升级targetSdkVersion至31后React Native应用在Android 12崩溃
React Native 升级 targetSdkVersion 到31后 Android12崩溃的修复方案
问题根源
Android 12(API 31)开始强制要求创建PendingIntent时必须指定FLAG_IMMUTABLE或FLAG_MUTABLE,旧系统没有这个强制校验规则,所以之前版本的应用不会触发崩溃。
具体修复步骤
1. 升级核心依赖
- React Native版本:至少升级到
0.68.0及以上,这个版本开始官方已适配API 31的PendingIntent要求 - AndroidX Core库:在
android/app/build.gradle中,将androidx.core:core-ktx或androidx.core:core版本升级至1.7.0以上,该版本提供了兼容新旧系统的PendingIntent创建方法
修改示例:dependencies { // 保留其他原有依赖 implementation 'androidx.core:core-ktx:1.10.1' // 推荐使用最新稳定版 }
2. 修复第三方库的PendingIntent问题
如果升级核心依赖后仍崩溃,大概率是第三方库(如推送、通知、定位类库)创建PendingIntent时未添加指定flag:
- 查看崩溃堆栈找到对应的第三方库,去其官方仓库确认是否有适配API 31的新版本,直接升级即可
- 若库已停止维护,可fork仓库后手动修改:找到创建
PendingIntent的代码块,添加兼容flag
仅当你的应用需要PendingIntent可变(如支持内回复、气泡功能)时,才用// 旧代码 PendingIntent pendingIntent = PendingIntent.getActivity(context, requestCode, intent, 0); // 修改后(兼容新旧系统) int flags = Build.VERSION.SDK_INT >= Build.VERSION_CODES.S ? PendingIntent.FLAG_IMMUTABLE : 0; PendingIntent pendingIntent = PendingIntent.getActivity(context, requestCode, intent, flags);FLAG_MUTABLE替换FLAG_IMMUTABLE。
3. 检查自定义原生代码
如果项目中存在自行编写的创建PendingIntent的原生代码,同样按照上述方式添加兼容flag:
// Kotlin示例 val flags = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) { PendingIntent.FLAG_IMMUTABLE } else { 0 } val pendingIntent = PendingIntent.getActivity(context, requestCode, intent, flags)
验证方法
- 在Android 12+的真机或模拟器上运行应用,触发之前崩溃的场景(如接收推送、页面跳转),确认不再崩溃
- 同时测试Android 12以下的设备,确保兼容性不受影响
内容的提问来源于stack exchange,提问作者ASH Uddin
相关产品推荐
相关产品推荐

