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

React Native中Firebase后台推送通知自定义处理问题

解决Firebase主题推送后台重复通知及自动唤起应用问题

问题根源

当FCM主题推送包含notification字段时:

  • 后台状态下,FCM会自动生成系统通知,即便你在setBackgroundMessageHandler中处理消息,也会出现系统通知+自定义本地通知的重复问题。
  • 这类推送的通知被点击时,FCM会自动唤起应用,不符合你的预期逻辑。

解决方案

1. 调整推送消息结构

将原本放在notification字段的内容迁移到data字段,示例推送Payload:

{
  "to": "/topics/your_topic",
  "data": {
    "title": "自定义通知标题",
    "body": "自定义通知内容",
    // 可添加自定义字段用于后续导航逻辑
    "targetScreen": "OrderDetail"
  }
}

通过这种方式,FCM不会自动生成系统通知,消息会完全交由你的客户端代码处理。

2. 修改监听代码

export const NotificationListener = navigation => {
  // 处理后台状态下点击通知唤起应用的逻辑
  messaging().onNotificationOpenedApp(remoteMessage => {
    console.log('后台点击通知打开应用', remoteMessage.data);
    const targetScreen = remoteMessage.data.targetScreen;
    if (targetScreen) {
      navigation.navigate(targetScreen);
    }
  });

  // 处理应用杀死状态下点击通知唤起应用的逻辑
  messaging()
    .getInitialNotification()
    .then(remoteMessage => {
      if (remoteMessage) {
        console.log('杀死状态点击通知打开应用', remoteMessage.data);
        const targetScreen = remoteMessage.data.targetScreen;
        if (targetScreen && navigation) {
          navigation.navigate(targetScreen);
        }
      }
    });

  // 后台消息处理:完全自定义本地通知
  messaging().setBackgroundMessageHandler(async remoteMessage => {
    console.log('后台处理推送消息', remoteMessage.data);
    const { title, body } = remoteMessage.data;
    PushNotification.localNotification({
      channelId: 'burque_channel_id',
      title: title,
      message: body,
      // 携带自定义数据,用于点击通知时的逻辑处理
      userInfo: remoteMessage.data
    });
  });

  // 前台消息处理:自定义本地通知
  messaging().onMessage(async remoteMessage => {
    console.log('前台处理推送消息', remoteMessage.data);
    const { title, body } = remoteMessage.data;
    PushNotification.localNotification({
      channelId: 'burque_channel_id',
      title: title,
      message: body,
      userInfo: remoteMessage.data
    });
  });
};

关键说明

  • 改用data字段后,FCM不会自动干预通知展示,彻底避免重复通知问题。
  • 后台接收推送时仅会触发setBackgroundMessageHandler生成自定义本地通知,不会自动唤起应用,只有用户主动点击通知才会触发后续导航逻辑。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.10 16:22:34