升级到Android 12(SDK 31)后无法运行Trusted Web Activity(TWA)问题求助
适配Android 12后TWA启动失败问题解决方案
该报错的根因为Android 12(API 31)引入了强制规则:所有创建PendingIntent的场景必须显式指定FLAG_IMMUTABLE或FLAG_MUTABLE标记,你遇到的两次报错分别来自旧版androidx.browser库和2.2.2版本androidbrowserhelper库未适配该规则。
具体解决步骤
- 优先升级
com.google.androidbrowserhelper依赖到官方适配版本:将依赖配置implementation 'com.google.androidbrowserhelper:androidbrowserhelper:2.2.2'替换为implementation 'com.google.androidbrowserhelper:androidbrowserhelper:2.3.0',该版本已内置对Android 12 PendingIntent规则的适配,可直接解决两处报错,拉取不到新版本可检查项目根目录build.gradle是否配置了google()和mavenCentral()仓库。 - 若因业务约束暂时无法升级
androidbrowserhelper版本,可通过覆写问题类临时修复:在你的项目中创建和SDK完全相同的包路径com.google.androidbrowserhelper.trusted,复制原SDK中FocusActivity的全部代码到该路径下,找到创建PendingIntent的代码行,添加版本判断和对应标记:int pendingIntentFlag = 0; if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) { pendingIntentFlag = PendingIntent.FLAG_IMMUTABLE; } // 将原创建PendingIntent方法的第四个参数替换为上面定义的pendingIntentFlag - 确认
androidx.browser:browser依赖升级到1.4.0正式版及以上,避免CustomTabs相关逻辑出现同类报错。
内容的提问来源于stack exchange,提问作者david
相关产品推荐
相关产品推荐

