Android应用前台运行时无法处理FCM通知问题求助
问题原因及修复方案
- 未适配Android 8.0+通知渠道要求
你代码中虽然定义了CHANNEL_ID常量,但没有主动创建通知渠道,Android 8.0及以上系统所有通知都必须绑定合法渠道才能展示,前台运行时通知会被系统直接拦截。
修复方法:在Application初始化或者发送通知前添加渠道创建逻辑
- 未适配Android 8.0+通知渠道要求
// 放在Application的onCreate方法中,或者发通知前先执行 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { CharSequence name = "FCM通知渠道"; String description = "接收FCM推送的通知"; int importance = NotificationManager.IMPORTANCE_DEFAULT; NotificationChannel channel = new NotificationChannel(CHANNEL_ID, name, importance); channel.setDescription(description); NotificationManager notificationManager = getSystemService(NotificationManager.class); notificationManager.createNotificationChannel(channel); }
- PendingIntent未适配Android 12+规则
Android 12(API 31)及以上系统要求PendingIntent必须显式指定FLAG_IMMUTABLE或FLAG_MUTABLE标记,你代码中传入的标记为0,会导致PendingIntent创建失败,通知构建异常无法展示。
修复方法:修改PendingIntent创建代码
- PendingIntent未适配Android 12+规则
// 根据你的业务需求选标记,不需要修改PendingIntent内容就用FLAG_IMMUTABLE int flag = Build.VERSION.SDK_INT >= Build.VERSION_CODES.M ? PendingIntent.FLAG_IMMUTABLE : 0; PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, flag);
- 未申请Android 13+通知权限
Android 13(API 33)新增了POST_NOTIFICATIONS运行时权限,未主动申请获得权限的情况下,所有通知都无法展示。
修复方法:在应用启动的首个Activity中添加权限申请逻辑
- 未申请Android 13+通知权限
// 先判断版本,再申请权限 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) { if (ContextCompat.checkSelfPermission(this, Manifest.permission.POST_NOTIFICATIONS) != PackageManager.PERMISSION_GRANTED) { ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.POST_NOTIFICATIONS}, 1001); } }
同时需要在AndroidManifest.xml中添加权限声明:
<uses-permission android:name="android.permission.POST_NOTIFICATIONS" />
- 未处理空指针异常
你代码中直接调用remoteMessage.getNotification().getTitle(),如果推送的是FCM数据消息,或者通知字段为空,会触发空指针异常导致通知构建失败。
修复方法:添加空值判断
- 未处理空指针异常
if(remoteMessage.getNotification() != null){ String title = remoteMessage.getNotification().getTitle() != null ? remoteMessage.getNotification().getTitle() : "新通知"; String body = remoteMessage.getNotification().getBody() != null ? remoteMessage.getNotification().getBody() : "您收到一条新消息"; // 后续构建通知用上面的title和body变量 }
- 检查AndroidManifest.xml服务注册配置
确认你已经在Manifest中正确注册了FirebaseMessagingService,配置错误会导致onMessageReceived方法不会被回调:
- 检查AndroidManifest.xml服务注册配置
<service android:name=".你的FirebaseMessagingService类名" android:exported="false"> <intent-filter> <action android:name="com.google.firebase.MESSAGING_EVENT" /> </intent-filter> </service>
内容的提问来源于stack exchange,提问作者aziz laroussi
相关产品推荐
相关产品推荐

