Java+Firebase聊天APP FCM通知收发故障排查求助
FCM聊天通知收发失败排查方案
一、基础配置校验
- 确认Firebase控制台项目配置正确,
google-services.json已放置在app模块根目录,文件内包名与APP包名完全一致。 - 检查AndroidManifest.xml中是否正确注册
NotifyFirebaseMessaging服务:<service android:name=".NotifyFirebaseMessaging" android:exported="false"> <intent-filter> <action android:name="com.google.firebase.MESSAGING_EVENT" /> </intent-filter> </service> - 验证设备FCM令牌有效性:重写
FirebaseMessagingService的onNewToken方法打印令牌,或调用FirebaseMessaging.getInstance().getToken()获取,确保发送消息时使用的是目标设备的正确令牌。
二、消息发送格式确认
你的代码依赖remoteMessage.getData()获取字段,说明发送的是数据消息,需满足以下要求:
- 发送端必须携带
sent、user、title、body、icon所有字段,缺少任意一个都会导致通知构建失败。 - 禁止发送通知消息(包含
notification字段):后台状态下FCM会直接展示该类通知,不会触发onMessageReceived,导致你的代码无法拦截处理。
三、代码逻辑问题排查
1. 条件拦截导致通知被过滤
代码中两层条件判断可能直接跳过通知发送:
if(firebaseUser != null && sent.equals(firebaseUser.getUid())) { if (!currentUser.equals(user)) { // 发送通知逻辑 } }
- 检查
sent字段值是否等于目标用户的UID:若发送端设置的sent不是接收方UID,会直接跳过通知。 - 临时注释
!currentUser.equals(user)判断:测试是否能收到通知,排除“当前正在聊天时不发通知”的逻辑影响。
2. 通知构建错误
- 图标参数异常:
setSmallIcon(Integer.parseInt(icon))中,若icon传入的不是有效资源ID(比如图片URL、错误字符串),会导致通知无法显示。建议替换为固定应用图标ID(如R.mipmap.ic_launcher)测试。 - PendingIntent请求码冲突:
int j = Integer.parseInt(user.replaceAll("[\\D]", ""))会将非数字用户ID转为0,导致多个通知使用同一请求码,出现覆盖或不显示问题。改用user.hashCode()作为请求码可避免冲突。 - Android O+通知渠道缺失:确认
OreoNotification类已正确创建通知渠道,无渠道则通知无法展示。示例渠道创建代码:public class OreoNotification { private NotificationManager notificationManager; private Context context; public OreoNotification(Context context) { this.context = context; createNotificationChannel(); } private void createNotificationChannel() { NotificationChannel channel = new NotificationChannel("chat_channel", "聊天消息通知", NotificationManager.IMPORTANCE_DEFAULT); channel.setDescription("接收好友聊天消息的通知渠道"); notificationManager = context.getSystemService(NotificationManager.class); if (notificationManager != null) { notificationManager.createNotificationChannel(channel); } } public Notification.Builder getOreoNotification(String title, String body, PendingIntent pendingIntent, Uri sound) { return new Notification.Builder(context, "chat_channel") .setContentTitle(title) .setContentText(body) .setSmallIcon(R.mipmap.ic_launcher) .setSound(sound) .setContentIntent(pendingIntent) .setAutoCancel(true); } }
3. 前台消息接收验证
在onMessageReceived方法开头添加日志,确认FCM消息是否到达设备:
Log.d("FCM_DEBUG", "接收到消息数据:" + remoteMessage.getData().toString());
通过Logcat查看日志,判断消息是否成功送达。
四、设备系统设置检查
- 确认设备未开启免打扰模式,且APP通知权限已启用:进入系统设置→应用管理→你的APP→通知,开启所有通知权限。
- 部分国产ROM(小米、华为等)需将APP加入后台保护白名单,避免FCM服务被系统杀死导致无法接收消息。
内容的提问来源于stack exchange,提问作者user13389781
相关产品推荐
相关产品推荐

