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

React Native Firebase推送通知异常:前台不显示通知等问题

React Native Firebase 推送通知问题解决方案

问题1:应用前台时无顶部通知展示

messaging().onMessage仅负责接收通知数据,不会自动触发系统通知栏展示,需手动创建本地通知实现该功能。

解决步骤

  1. 安装通知模块:
npm install @react-native-firebase/notifications
# 或
yarn add @react-native-firebase/notifications
  1. 修改notificationservice.tsx,引入模块并在onMessage回调中构建本地通知:

问题2:getInitialNotification始终返回null

可能原因及修复方案

  • payload格式错误:确保推送的是包含notification字段的通知消息,纯数据消息无法被getInitialNotification捕获。
  • 初始化时机过晚:在App启动入口(如App.tsx的useEffect或index.js)立即调用notificationListener,避免延迟初始化导致错过冷启动通知。
  • Android配置遗漏:检查AndroidManifest.xml,确保主Activity的launchMode设为singleTop/singleTask,并添加intent filter:
<intent-filter>
  <action android:name="FLUTTER_NOTIFICATION_CLICK" />
  <category android:name="android.intent.category.DEFAULT" />
</intent-filter>
  • 测试方式错误:冷启动需完全关闭App(划掉后台进程)后点击通知打开,热重启无法触发该逻辑。

完整修改后的notificationservice.tsx

import messaging from '@react-native-firebase/messaging';
import AsyncStorage from '@react-native-async-storage/async-storage';
import notifications from '@react-native-firebase/notifications';

// 请求通知权限
export async function requestUserPermission() {
  try {
    const authStatus = await messaging().requestPermission();
    const enabled =
      authStatus === messaging.AuthorizationStatus.AUTHORIZED ||
      authStatus === messaging.AuthorizationStatus.PROVISIONAL;

    if (enabled) {
      console.log('Authorization status:', authStatus);
      await getFcmToken();
      // Android 8.0+ 需请求通知频道权限
      await notifications().requestPermission();
    } else {
      console.log('Notification permission denied.');
    }
  } catch (error) {
    console.error('Error requesting permission:', error);
  }
}

// 获取FCM Token
const getFcmToken = async () => {
  try {
    let fcmToken = await AsyncStorage.getItem('fcmToken');
    console.log('Stored FCM Token:', fcmToken);

    if (!fcmToken) {
      const newFcmToken = await messaging().getToken();
      if (newFcmToken) {
        console.log('New FCM Token generated:', newFcmToken);
        await AsyncStorage.setItem('fcmToken', newFcmToken);
      }
    }
  } catch (error) {
    console.error('Error getting or setting FCM Token:', error);
  }
}

// 监听通知事件
export const notificationListener = async () => {
  // 后台点击通知打开App
  messaging().onNotificationOpenedApp(remoteMessage => {
    console.log('Notification opened from background state:', remoteMessage.notification);
  });

  // 前台接收通知并展示
  messaging().onMessage(async remoteMessage => {
    console.log('Received notification in foreground state:', remoteMessage);
    
    const notification = notifications().buildNotification()
      .setTitle(remoteMessage.notification?.title || '系统通知')
      .setBody(remoteMessage.notification?.body || '您有一条新消息')
      .setSound('default')
      .setData(remoteMessage.data || {});
    
    await notifications().displayNotification(notification);
  });

  // 冷启动时检查是否由通知打开
  messaging()
    .getInitialNotification()
    .then(remoteMessage => {
      if (remoteMessage) {
        console.log('Notification caused app to open from quit state:', remoteMessage.notification);
      } else {
        console.log('No initial notification found.');
      }
    })
    .catch(error => {
      console.error('Error getting initial notification:', error);
    });
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.13 20:34:56