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

FirebaseMessaging.onMessage.listen未触发:前台收广播无响应

解决Firebase Cloud Messaging前台接收消息无响应问题

针对后台能接收消息、前台onMessage.listen无输出但控制台有D/FLTFireMsgReceiver日志的问题,按以下步骤排查修复:

1. 确保Firebase初始化与监听顺序正确

必须在Firebase.initializeApp()完成后再注册消息监听,同时初始化Android通知通道(Android 8.0+必填):

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  // 初始化Firebase
  await Firebase.initializeApp();
  // 创建Android通知通道
  _createNotificationChannel();
  // 请求iOS通知权限(适配iOS时需添加)
  await FirebaseMessaging.instance.requestPermission(
    alert: true,
    badge: true,
    sound: true,
  );
  // 注册前台消息监听
  FirebaseMessaging.onMessage.listen((RemoteMessage message) {
    print('Got a message whilst in the foreground!');
    print('Message data: ${message.data}');

    if (message.notification != null) {
      print('Message also contained a notification: ${message.notification}');
    }
    // 前台需手动显示通知(FCM默认不自动弹出)
    FlutterLocalNotificationsPlugin().show(
      message.notification.hashCode,
      message.notification?.title,
      message.notification?.body,
      NotificationDetails(
        android: AndroidNotificationDetails(
          'high_importance_channel',
          '高优先级通知',
          channelDescription: '用于接收即时消息通知',
        ),
      ),
    );
  });
  runApp(MyApp());
}

void _createNotificationChannel() {
  if (Platform.isAndroid) {
    final channel = AndroidNotificationChannel(
      'high_importance_channel',
      '高优先级通知',
      description: '接收即时消息的通知通道',
      importance: Importance.high,
    );
    FlutterLocalNotificationsPlugin().createNotificationChannel(channel);
  }
}

2. 完善Android端配置

  • 在AndroidManifest.xml中添加必要权限:
    <uses-permission android:name="android.permission.INTERNET"/>
    <!-- Android 13+ 需添加通知权限 -->
    <uses-permission android:name="android.permission.POST_NOTIFICATIONS"/>
    
  • 确保firebase_messaging插件版本与其他Firebase插件版本兼容,建议使用pub上的最新稳定版。

3. 优化云函数消息发送配置

给消息设置Android高优先级,确保前台能及时接收,同时验证data字段类型:

message = messaging.Message(
    token=receiver_device_token,
    notification=messaging.Notification(
        title= '*****',
        body='test sent you a message!'
    ),
    data = {"name": "test" ,
            "imgURL" : "test_url" },
    # 设置Android高优先级
    android=messaging.AndroidConfig(
        priority='high',
    ),
)

可先测试仅发送data消息(去掉notification字段),看onMessage.listen是否触发,以此排查是通知消息还是数据消息的问题。

4. 检查iOS端配置(若适配iOS)

在Info.plist中添加后台推送权限:

<key>UIBackgroundModes</key>
<array>
  <string>remote-notification</string>
</array>

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.18 16:57:33