适配API 31后出现FLAG_IMMUTABLE相关崩溃但项目未用PendingIntent如何解决
问题根源
该崩溃并非由你自有代码触发,而是项目引入的第三方依赖内部使用了不符合Android 12(API 31)规则的PendingIntent导致,和你推测的FCM推送场景完全吻合:你当前使用的com.google.firebase:firebase-bom:26.1.1是2020年发布的版本,远早于Android 12正式版发布时间,其配套的firebase-messaging库内部创建通知对应的PendingIntent时,没有显式指定FLAG_IMMUTABLE或FLAG_MUTABLE标记,因此在API 31及以上系统上运行时会触发该规则报错。
解决方案
方案一(推荐):升级Firebase依赖版本
将Firebase BOM升级到29.0.0及以上的稳定版本,该版本及之后配套的firebase-messaging已经完成了Android 12的PendingIntent规则适配,无需修改自有代码即可解决崩溃问题:
implementation platform('com.google.firebase:firebase-bom:32.7.0') // 可替换为最新稳定版 implementation 'com.google.firebase:firebase-messaging'
方案二:自定义FCM通知处理逻辑
如果暂时无法升级Firebase依赖,可以自行实现FirebaseMessagingService的通知创建逻辑,拦截FCM的默认通知发送流程,自己构造PendingIntent时显式添加对应标记:
public class CustomFirebaseMessagingService extends FirebaseMessagingService { @Override public void onMessageReceived(RemoteMessage remoteMessage) { // 拦截默认通知,自行构造通知 if (remoteMessage.getNotification() != null) { Intent intent = new Intent(this, 你的首页Activity.class); intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); PendingIntent pendingIntent; if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) { pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_IMMUTABLE); } else { pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_ONE_SHOT); } // 后续构造Notification并使用NotificationManager展示的逻辑自行补充 } } }
同时需要在AndroidManifest.xml中注册你自定义的MessagingService,替代FCM默认的服务实现。
其他适配建议
你项目中另外两个依赖也存在API 31适配风险,建议同步升级避免后续出现其他崩溃:
com.android.billingclient:billing:3.0.2升级到4.0.0及以上版本com.google.android.play:core:1.10.2升级到1.10.3及以上版本,或迁移到拆分后的Play Core KTX依赖
内容的提问来源于stack exchange,提问作者Fat Monk
相关产品推荐
相关产品推荐

