You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Android 12设备上Firebase推送通知失效问题求助

解决Android 12上FCM推送后台不工作的PendingIntent错误

问题原因

Android 12(API 31+)强制要求创建PendingIntent时必须指定FLAG_IMMUTABLE或FLAG_MUTABLE标记。后台推送失效主要源于两个问题:

  • 代码中版本判断逻辑不准确(当前判断API≥23,但该要求仅从API31开始生效)
  • 使用的Firebase Messaging SDK版本过旧,内部创建PendingIntent时未适配Android 12规则

解决方案

1. 升级Firebase Messaging依赖

确保项目中firebase-messaging依赖版本至少为23.0.0(该版本开始适配Android 12的PendingIntent要求)。在Module级别的build.gradle中更新:

dependencies {
    // 其他依赖...
    implementation 'com.google.firebase:firebase-messaging:23.0.0+'
}

2. 修正PendingIntent创建逻辑

将版本判断条件改为Build.VERSION_CODES.S(对应API31),确保仅在Android 12及以上设备添加必要标记:

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
    pendingIntent = PendingIntent.getActivity(this,
            0, intent, PendingIntent.FLAG_UPDATE_CURRENT | PendingIntent.FLAG_IMMUTABLE);
} else {
    pendingIntent = PendingIntent.getActivity(this,
            0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
}
  • 除非通知需要支持内联回复或气泡功能,否则优先使用FLAG_IMMUTABLE(官方推荐)。

3. 适配API33+通知权限

若应用目标SDK为33及以上,需在AndroidManifest.xml中添加通知权限,并在运行时申请:

<uses-permission android:name="android.permission.POST_NOTIFICATIONS" />

运行时申请代码示例:

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
    if (ContextCompat.checkSelfPermission(this, Manifest.permission.POST_NOTIFICATIONS) != PackageManager.PERMISSION_GRANTED) {
        registerForActivityResult(new ActivityResultContracts.RequestPermission(), isGranted -> {
            // 处理权限申请结果
        }).launch(Manifest.permission.POST_NOTIFICATIONS);
    }
}

验证步骤

  1. 清理项目缓存并重新构建
  2. 在Android 12设备上测试后台推送
  3. 查看日志确认IllegalArgumentException是否消失

内容的提问来源于stack exchange,提问作者Bhaskar Jyoti Dutta

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.23 12:18:07