触发Chrome Intent时TWA自动关闭,如何让CustomTWAActivity保持运行
解决方案:保持CustomTWAActivity持续运行不自动关闭
问题根因
自动关闭是TWA的LauncherActivity默认逻辑导致的:父类在onNewIntent中接收到ACTION_VIEW类型的意图并完成内置处理后,会自动调用finish()销毁当前Activity,直接退回到MainActivity。
解决方案
方案1:自行接管意图处理(推荐)
匹配到你需要处理的意图后直接执行自定义逻辑,跳过父类的默认处理流程,从根源避免自动关闭:
class CustomTWAActivity: LauncherActivity() { override fun onNewIntent(intent: Intent?) { Log.i("intent in launcher", intent?.dataString?: "no intent data received") // 匹配到目标意图就自行处理,不调用super.onNewIntent if (intent != null && intent.action === Intent.ACTION_VIEW) { val value = intent.dataString TWAUtils.onNewIntentReceived(value) // 如有需要,手动让当前TWA加载新地址 getTwaLauncher()?.launchUrl(this, Uri.parse(value)) return } // 其他非目标意图仍然交给父类处理 super.onNewIntent(intent) } }
方案2:拦截自动finish调用
如果你需要完整保留父类onNewIntent的处理逻辑,可以加标记位拦截处理意图过程中触发的自动finish:
class CustomTWAActivity: LauncherActivity() { private var isHandlingNewIntent = false override fun onNewIntent(intent: Intent?) { isHandlingNewIntent = true super.onNewIntent(intent) Log.i("intent in launcher", intent?.dataString?: "no intent data received") if (intent != null && intent.action === Intent.ACTION_VIEW) { val value = intent.dataString TWAUtils.onNewIntentReceived(value) } isHandlingNewIntent = false } override fun finish() { // 只拦截处理新意图时触发的自动关闭 if (isHandlingNewIntent) return super.finish() } }
注意事项
- 两种方案都不会影响用户主动按返回键退出TWA的正常逻辑
- 若处理新意图后需要TWA页面同步跳转,记得手动调用加载对应Uri的逻辑,否则页面不会自动更新
内容的提问来源于stack exchange,提问作者Dhruvam Sharma
相关产品推荐
相关产品推荐

