Android端Firebase离线推送异常:仅收到最后一条通知求助
解决Android端Firebase离线后仅收到最后一条通知的问题
可能的原因及对应解决方案
1. 避免重复的collapse_key导致通知折叠
Firebase的collapse_key字段会将同key的通知合并,设备离线时多条同key的通知只会保留最后一条。
- 发送通知时,给每条通知生成唯一的
collapse_key,比如用UUID或业务ID+时间戳:{ "to": "DEVICE_TOKEN", "collapse_key": "order_notify_1698765432", "notification": { "title": "新订单提醒", "body": "您有一笔新订单待处理" } } - 若无需折叠通知,直接**不设置
collapse_key**即可,FCM会默认不合并同类型通知。
2. 确保本地通知ID唯一
Android端显示通知时,重复的通知ID会让新通知直接覆盖旧通知。
- 在
FirebaseMessagingService的onMessageReceived方法中,生成唯一ID,比如用系统时间戳:@Override public void onMessageReceived(RemoteMessage remoteMessage) { // 生成唯一通知ID int notificationId = (int) System.currentTimeMillis(); NotificationCompat.Builder builder = new NotificationCompat.Builder(this, "CHANNEL_ID") .setContentTitle(remoteMessage.getNotification().getTitle()) .setContentText(remoteMessage.getNotification().getBody()) .setSmallIcon(R.drawable.ic_notification); NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); notificationManager.notify(notificationId, builder.build()); }
3. 使用数据消息替代通知消息
FCM的notification类型消息在离线时由服务器暂存,默认可能触发折叠逻辑;而data类型消息会完整保留所有离线消息,需客户端自行处理显示。
- 发送端改用数据消息格式:
{ "to": "DEVICE_TOKEN", "data": { "title": "系统通知", "body": "您的账户已完成实名认证", "type": "account" } } - 客户端接收后自行构建通知:
@Override public void onMessageReceived(RemoteMessage remoteMessage) { if (!remoteMessage.getData().isEmpty()) { String title = remoteMessage.getData().get("title"); String body = remoteMessage.getData().get("body"); int notificationId = (int) System.currentTimeMillis(); NotificationCompat.Builder builder = new NotificationCompat.Builder(this, "CHANNEL_ID") .setContentTitle(title) .setContentText(body) .setSmallIcon(R.drawable.ic_notification); NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); notificationManager.notify(notificationId, builder.build()); } }
4. 检查消息存活时间设置
FCM默认保留离线消息4周,但如果设置了过短的time_to_live,会导致旧消息被提前丢弃。确保该值设置合理:
{ "to": "DEVICE_TOKEN", "time_to_live": 604800, // 设为7天,最大值为2419200秒(4周) "notification": { "title": "活动提醒", "body": "限时折扣即将结束" } }
内容的提问来源于stack exchange,提问作者Krishan chand tiwari
相关产品推荐
相关产品推荐

