React Native集成Firebase功能及FCM数据消息手动处理咨询
嘿,刚好在React Native项目里折腾过FCM手动处理通知的需求,尤其是Android端的部分,给你梳理下完整的实现方案——其实不用纠结PushNotificationIOS的Android替代,React Native Firebase(RNFB)的Messaging模块本身就支持跨平台的手动消息处理,而且比单独的工具更统一。
RNFB的Messaging模块已经封装了Android和iOS的FCM底层逻辑,我们只需要通过它提供的监听方法,就能接管前台、后台甚至APP被杀死状态下的数据消息,完全自定义处理逻辑。
1. 基础配置:安装并初始化RNFB Messaging
首先确保你已经完成了RNFB的核心配置(比如添加google-services.json/GoogleService-Info.plist),然后安装Messaging模块:
npm install @react-native-firebase/core @react-native-firebase/messaging
Android端要确保gradle配置符合RNFB的初始化要求(官方步骤里的配置要走全)。
2. 请求必要的通知权限(Android 13+重点)
Android 13及以上需要单独申请POST_NOTIFICATIONS权限,结合RNFB的权限请求,代码示例如下:
import { PermissionsAndroid, Platform } from 'react-native'; import messaging from '@react-native-firebase/messaging'; async function setupNotificationPermissions() { // 请求FCM基础权限 const authStatus = await messaging().requestPermission(); const isFcmAuthorized = authStatus === messaging.AuthorizationStatus.AUTHORIZED || authStatus === messaging.AuthorizationStatus.PROVISIONAL; // 单独处理Android 13的POST_NOTIFICATIONS权限 if (Platform.OS === 'android' && Platform.Version >= 33) { const postNotificationGranted = await PermissionsAndroid.request( PermissionsAndroid.PERMISSIONS.POST_NOTIFICATIONS, { title: '通知权限申请', message: '我们需要权限向您发送自定义通知', buttonPositive: '同意', buttonNegative: '拒绝', }, ); return isFcmAuthorized && postNotificationGranted === PermissionsAndroid.RESULTS.GRANTED; } return isFcmAuthorized; }
在APP启动时调用这个函数即可。
3. 监听不同状态下的数据消息
RNFB提供了三个关键的监听方法,覆盖所有场景:
前台消息监听(APP正在前台运行)
在你的根组件里添加监听,收到消息后直接处理逻辑:
import { useEffect } from 'react'; import messaging from '@react-native-firebase/messaging'; function App() { useEffect(() => { const unsubscribe = messaging().onMessage(async remoteMessage => { console.log('前台收到数据消息:', remoteMessage); // 这里写你的自定义逻辑:比如更新UI、弹出Alert、创建本地通知 handleCustomNotificationLogic(remoteMessage.data); }); // 组件卸载时取消监听 return unsubscribe; }, []); // ...其他组件代码 }
后台/杀死状态下的消息处理
这个监听要放在App.js或index.js的顶层(不能放在组件内部),因为APP在后台时组件可能未挂载:
// index.js 顶部 import messaging from '@react-native-firebase/messaging'; // 后台消息处理器 messaging().setBackgroundMessageHandler(async remoteMessage => { console.log('后台收到数据消息:', remoteMessage); // 处理逻辑:比如存储消息到本地、触发本地通知 handleCustomNotificationLogic(remoteMessage.data); });
4. 自定义通知逻辑与本地通知显示
因为纯数据消息不会自动弹出系统通知,所以如果需要显示通知,得自己创建本地通知。可以用RNFB的Notifications模块,示例如下:
先创建Android通知渠道(必须)
Android 8.0+要求所有通知都属于某个渠道:
import notifications from '@react-native-firebase/notifications'; async function createCustomNotificationChannel() { if (Platform.OS === 'android') { const channel = new notifications.Android.Channel( 'custom_data_channel', '自定义数据通知', notifications.Android.Importance.High, ).setDescription('处理FCM数据消息的通知渠道'); await notifications().android.createChannel(channel); return 'custom_data_channel'; } return ''; }
显示本地通知
async function showCustomLocalNotification(title, body, data) { const channelId = await createCustomNotificationChannel(); await notifications().displayNotification({ title, body, channelId, data: { ...data }, // 携带自定义数据,方便点击通知时跳转 }); } // 在handleCustomNotificationLogic里调用 function handleCustomNotificationLogic(data) { // 比如根据数据类型处理业务 if (data.type === 'ORDER_UPDATE') { showCustomLocalNotification('订单更新', `您的订单${data.orderId}状态已变更`, { screen: 'OrderDetail', orderId: data.orderId }); // 其他逻辑:比如更新本地订单数据 } }
5. 处理通知点击事件
不管是后台收到的消息触发的通知,还是前台创建的本地通知,点击后都需要处理跳转逻辑:
// 在App组件的useEffect里 useEffect(() => { // APP在后台时点击通知打开 messaging().onNotificationOpenedApp(remoteMessage => { const { data } = remoteMessage; console.log('点击后台通知:', data); // 跳转到指定页面 navigation.navigate(data.screen, { orderId: data.orderId }); }); // APP被杀死后点击通知打开 messaging() .getInitialNotification() .then(remoteMessage => { if (remoteMessage) { const { data } = remoteMessage; console.log('点击杀死状态下的通知:', data); navigation.navigate(data.screen, { orderId: data.orderId }); } }); }, [navigation]);
- 区分数据消息和通知消息:FCM的消息分两种,如果你想完全手动处理,建议只发送纯数据消息(只填
data字段,不填notification字段),这样系统不会自动弹通知,全部由你的代码控制。 - 测试数据消息:在Firebase控制台的Cloud Messaging里,选择“发送测试消息”,然后在“自定义数据”里添加键值对,不要填通知标题/内容,这样就能测试纯数据消息的处理逻辑。
- Android清单文件:确保已经添加了必要的权限,比如
<uses-permission android:name="android.permission.INTERNET" />和<uses-permission android:name="android.permission.WAKE_LOCK" />,RNFB一般会自动配置,但如果遇到问题可以手动检查。
内容的提问来源于stack exchange,提问作者Jude Fernandes

