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

Spring Boot集成FCM推送通知:代码执行正常但设备未收到

问题分析与解决方案

你遇到的核心问题是:Spring Boot服务端发送的是FCM Data类型消息,但Flutter客户端未处理该类型消息的展示逻辑。

关键差异对比

你的服务端代码仅通过putData()添加了数据字段,这属于FCM的Data Message;而Firebase控制台和Postman请求中使用的是notification字段,属于Notification Message:

  • Notification Message:由FCM SDK自动在设备系统通知栏展示,无需客户端额外编码
  • Data Message:需要客户端手动编写逻辑解析数据并展示通知

解决方案(二选一)

方案1:修改Spring Boot服务端,发送Notification Message

直接在消息构建时添加Notification内容,这样FCM会自动推送系统通知:

@Service
public class ChatNotificationService implements IChatNotificationsService{
    @Override
    public void notify(User sender, User receiver) {
        // 构建Notification内容
        Notification notification = Notification.builder()
                .setTitle("新消息提醒")
                .setBody("你收到了来自@" + sender.getUsername() + "的消息")
                .build();

        Message msg = Message.builder()
                .setToken(receiver.getNotificationDeviceID())
                .setNotification(notification)
                // 可选:同时携带自定义数据
                .putData("senderId", sender.getId().toString())
                .putData("senderName", sender.getUsername())
                .build();
        try{
            FirebaseMessaging.getInstance().send(msg);
        }catch (Exception e){
            e.printStackTrace(); // 建议打印异常便于排查
        }
    }
}

方案2:修改Flutter客户端,处理Data Message

如果需要保留Data Message的方式,需在Flutter端添加Data消息的监听和通知展示逻辑(示例使用firebase_messaging包):

// 在FirebaseMessaging初始化后添加监听
FirebaseMessaging.onMessage.listen((RemoteMessage message) {
  Map<String, String>? data = message.data;

  // 处理Data消息
  if (data != null && data.isNotEmpty) {
    // 展示本地通知
    FlutterLocalNotificationsPlugin().show(
      0,
      "新消息提醒",
      "你收到了来自@${data['senderName']}的消息",
      NotificationDetails(
        android: AndroidNotificationDetails(
          "chat_channel",
          "聊天通知",
          importance: Importance.high,
        ),
      ),
    );
  }
});

额外排查点

  • 确认Flutter端firebase_messaging版本与服务端FCM SDK版本兼容
  • 检查设备后台状态下的消息接收逻辑(FCM对前后台消息的处理规则有差异)

内容的提问来源于stack exchange,提问作者Lucas Tomic

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.08 21:44:54