如何通过代码将启动页Activity的noHistory属性设为false?
解决启动页noHistory="true"下从CustomTab返回应用关闭的问题
方案一:移除Manifest的noHistory,主动控制启动页生命周期(推荐)
把Manifest里启动页的noHistory="true"删掉,然后在启动页逻辑里区分场景处理:
- 正常启动流程(如跳转到主页面):启动目标Activity后主动调用
finish(),模拟noHistory的效果 - 打开CustomTab场景:直接启动CustomTab,不调用
finish(),让启动页留在任务栈中,返回时能回到原页面
示例代码:
// 正常启动主页面的逻辑 Intent mainIntent = new Intent(this, MainActivity.class); startActivity(mainIntent); finish(); // 主动销毁启动页,和noHistory效果一致 // 点击链接打开CustomTab的逻辑 CustomTabsIntent customTabsIntent = new CustomTabsIntent.Builder().build(); customTabsIntent.launchUrl(this, Uri.parse("你的链接地址")); // 这里不调用finish(),启动页会保留在任务栈
方案二:保留Manifest的noHistory,通过PendingIntent在返回时重启启动页
如果必须保留Manifest中的noHistory="true",可以在创建CustomTabIntent时设置关闭后的PendingIntent,让系统在关闭CustomTab时重新启动启动页:
示例代码:
// 创建返回启动页的Intent Intent backToSplashIntent = new Intent(this, SplashActivity.class); backToSplashIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP); PendingIntent pendingIntent = PendingIntent.getActivity( this, 0, backToSplashIntent, PendingIntent.FLAG_IMMUTABLE // 适配Android 12+ ); // 构建CustomTabIntent并设置关闭回调 CustomTabsIntent customTabsIntent = new CustomTabsIntent.Builder() .setPendingIntentOnClose(pendingIntent) .build(); customTabsIntent.launchUrl(this, Uri.parse("你的链接地址"));
注意:这种方式会重新创建启动页实例,而非回到原来的页面,适合对启动页状态无要求的场景。
内容的提问来源于stack exchange,提问作者KCD
相关产品推荐
相关产品推荐

