Cordova应用在Android 12/13上无法显示Firebase通知问题求助
解决Cordova FirebaseX插件Android 12/13推送通知异常问题
核心问题分析
Android 12+(API 31+)引入了更严格的通知权限、PendingIntent规则和后台启动限制,你当前使用的cordova-android@9.1.0(目标SDK 30)和cordova-plugin-firebasex@12.1.0对这些新特性适配不足,导致通知不显示、后台崩溃。
解决方案步骤
1. 升级Cordova Android平台版本
cordova-android@9.1.0的目标SDK为30,不支持Android 12/13的新特性,必须升级到至少11.x版本(目标SDK 33,适配Android 13):
# 移除旧版本 cordova platform remove android # 安装适配Android 12/13的版本 cordova platform add android@11.0.0
2. 添加Android 13通知权限
Android 13要求显式申请POST_NOTIFICATIONS权限,在config.xml中添加:
<platform name="android"> <config-file parent="/manifest" target="AndroidManifest.xml"> <uses-permission android:name="android.permission.POST_NOTIFICATIONS" /> </config-file> </platform>
同时在应用启动时动态申请权限:
document.addEventListener('deviceready', () => { if (cordova.platformId === 'android' && parseInt(device.version) >= 13) { window.FirebasePlugin.requestPermission( () => console.log('通知权限已获取'), error => console.error('通知权限申请失败:', error) ); } });
3. 配置并确保通知渠道生效
Android 8+需要通知渠道,Android 12+对渠道的要求更严格,必须确保推送消息关联正确的渠道ID:
document.addEventListener('deviceready', () => { // 创建默认通知渠道 window.FirebasePlugin.createNotificationChannel({ id: "default_notification_channel", name: "默认通知", description: "接收应用推送通知", importance: 4, // HIGH级别,确保通知能弹出 visibility: 1, // 公开显示通知内容 sound: "default" }, () => {}, error => console.error('创建渠道失败:', error)); // 接收消息时强制指定渠道ID window.FirebasePlugin.onMessageReceived(message => { // 后台收到通知时,若消息未指定渠道,手动触发系统通知 if (message.notification && !message.notification.android_channel_id) { window.FirebasePlugin.showNotification({ title: message.notification.title, body: message.notification.body, channelId: "default_notification_channel", data: message.data }); } }); });
4. 修复PendingIntent导致的后台崩溃
Android 12+要求PendingIntent必须指定FLAG_IMMUTABLE或FLAG_MUTABLE,旧版本FirebaseX插件未适配此规则,可通过两种方式解决:
- 升级FirebaseX插件:更新到最新版本(如v16.x),该版本已适配Android 12+的PendingIntent规则:
cordova plugin remove cordova-plugin-firebasex cordova plugin add cordova-plugin-firebasex@latest - 手动修改原生代码:若无法升级插件,找到插件的
FirebaseMessagingService.java文件,修改PendingIntent创建代码:// 原代码 PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT); // 修改为 PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT | PendingIntent.FLAG_IMMUTABLE);
5. 优化后台消息处理逻辑
Android 12+限制后台应用的UI操作,后台接收通知时避免直接执行DOM修改、弹窗等操作,仅通过系统通知栏提示,让用户点击通知后再处理业务逻辑。
验证步骤
- 重新构建Android应用:
cordova build android - 在Firebase控制台发送测试通知,指定
android_channel_id为你创建的渠道ID - 分别测试前台、后台状态下的通知接收和应用稳定性
内容的提问来源于stack exchange,提问作者d512
相关产品推荐
相关产品推荐

