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

FirebaseMessaging前台监听器无法接收API发送的Data消息

Firebase Cloud Messaging Legacy API 前台无法接收Data消息的解决方法

问题根源

你的监听代码仅处理了notification字段存在的消息,而Data类型消息的notification字段为null,当前代码不会触发任何Data消息的逻辑;另外你的Data消息结构不符合Legacy API的参数规范,导致推送优先级不达标,前台无法捕获。

解决步骤

  1. 修改监听代码,兼容Data消息
    补充对message.data的判断逻辑,确保Data消息能被捕获和处理:

    FirebaseMessaging.onMessage.listen((RemoteMessage message) {
      print('收到前台消息!');
      // 处理带notification的消息
      if (message.notification != null) {
        print('通知消息标题: ${message.notification?.title}');
      }
      // 处理纯Data消息
      if (message.data.isNotEmpty) {
        print('Data消息内容: ${message.data}');
        // 在这里添加本地通知的展示逻辑,比如用flutter_local_notifications库
      }
    });
    
  2. 修正Data消息的结构(Legacy API要求)
    在Legacy API中,content_available和priority是全局参数,不能放在data子字段内,否则无法生效。调整后的消息结构如下:

    {
      "to": "fHBcTCNttkyrt-....",
      "data": {
        "foo": "bar"
      },
      "content_available": true,
      "priority": "high"
    }
    
  3. 确认客户端权限配置

    • Android端:确保AndroidManifest.xml中配置了默认通知通道,且通道优先级设为高:
      <meta-data
          android:name="com.google.firebase.messaging.default_notification_channel_id"
          android:value="@string/default_notification_channel_id"/>
      
      同时在代码中创建高优先级通知通道:
      // 示例:创建通知通道
      const AndroidNotificationChannel channel = AndroidNotificationChannel(
        'high_importance_channel', // id
        'High Importance Notifications', // name
        description: 'This channel is used for important notifications.', // description
        importance: Importance.high,
      );
      final FlutterLocalNotificationsPlugin flutterLocalNotificationsPlugin =
          FlutterLocalNotificationsPlugin();
      await flutterLocalNotificationsPlugin
          .resolvePlatformSpecificImplementation<
              AndroidFlutterLocalNotificationsPlugin>()
          ?.createNotificationChannel(channel);
      
    • iOS端:在Info.plist中添加禁用代理的配置,并确保已请求推送权限:
      <key>FirebaseAppDelegateProxyEnabled</key>
      <false/>
      
      请求权限代码:
      await FirebaseMessaging.instance.requestPermission(
        alert: true,
        badge: true,
        sound: true,
      );
      

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.11 19:39:51