Cordova开发Android应用在Android12+后台接收FCM推送崩溃求助
解决Cordova Android应用在Android 12+后台接收FCM推送崩溃的问题
崩溃原因
这个问题的核心是Android 12(API 31)及以上版本强制要求创建PendingIntent时必须指定FLAG_IMMUTABLE或FLAG_MUTABLE标记,而当前使用的Firebase Messaging依赖或Cordova插件未适配该规则,导致后台接收推送时触发IllegalArgumentException崩溃。
解决方案
1. 更新FCM相关Cordova插件到最新版
如果使用的是主流FCM插件(比如cordova-plugin-fcm-with-dependecy-updated),新版本已经适配了Android 12+的要求:
- 卸载旧插件:
cordova plugin remove cordova-plugin-fcm-with-dependecy-updated - 安装最新版本:
cordova plugin add cordova-plugin-fcm-with-dependecy-updated
2. 手动指定兼容的Firebase依赖版本
若更新插件后问题仍存在,可在项目的config.xml中直接锁定适配的Firebase版本:
在<platform name="android">节点内添加以下配置:
<!-- 配置默认通知渠道(可选,但推荐添加) --> <config-file parent="/manifest/application" target="AndroidManifest.xml"> <meta-data android:name="com.google.firebase.messaging.default_notification_channel_id" android:value="@string/default_notification_channel_id" /> </config-file> <!-- 指定兼容的Gradle和Firebase版本 --> <preference name="GradlePluginGoogleServicesVersion" value="4.3.15" /> <preference name="FirebaseMessagingVersion" value="23.1.2" />
上述版本的Firebase Messaging已处理PendingIntent的标记要求。
3. 自定义通知逻辑的适配
如果应用有自定义推送通知处理代码,需确保创建PendingIntent时添加对应标记:
- 常规通知跳转(推荐使用):
PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT | PendingIntent.FLAG_IMMUTABLE); - 需要支持内联回复、气泡交互的场景:
PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT | PendingIntent.FLAG_MUTABLE);
验证修复
重新编译并安装应用到Android 12+设备:
cordova build android --release
后台运行应用后发送测试推送,确认崩溃问题不再出现。
内容的提问来源于stack exchange,提问作者Hasnain Rashid
相关产品推荐
相关产品推荐

