react native 推送实现
集成 Firebase Cloud Messaging (FCM)
安装 Firebase 依赖库并配置 Android/iOS 项目。对于 Android,需在 android/app/build.gradle 中添加 Firebase SDK 依赖。iOS 需通过 CocoaPods 安装 Firebase 并配置 GoogleService-Info.plist 文件。
yarn add @react-native-firebase/app @react-native-firebase/messaging
请求推送权限
在应用启动时请求用户通知权限(iOS 需显式调用,Android 默认授予)。使用 messaging().requestPermission() 检查权限状态,并在权限授予后获取设备 token。
import messaging from '@react-native-firebase/messaging';
async function requestUserPermission() {
const authStatus = await messaging().requestPermission();
const enabled =
authStatus === messaging.AuthorizationStatus.AUTHORIZED ||
authStatus === messaging.AuthorizationStatus.PROVISIONAL;
if (enabled) {
const token = await messaging().getToken();
console.log('FCM Token:', token);
}
}
处理前台和后台消息
通过 messaging().onMessage 监听前台通知,使用 setBackgroundMessageHandler 处理后台消息。需在 index.js 中注册后台处理器。
// 前台消息处理
messaging().onMessage(async remoteMessage => {
console.log('Foreground Message:', remoteMessage);
});
// 后台消息处理(需在 index.js 中注册)
messaging().setBackgroundMessageHandler(async remoteMessage => {
console.log('Background Message:', remoteMessage);
});
处理通知点击
使用 messaging().getInitialNotification() 获取应用关闭时点击的通知数据,通过 messaging().onNotificationOpenedApp 监听应用处于后台时的点击事件。
// 检查初始通知
messaging().getInitialNotification().then(remoteMessage => {
if (remoteMessage) {
console.log('Launched by notification:', remoteMessage);
}
});
// 监听通知点击
messaging().onNotificationOpenedApp(remoteMessage => {
console.log('Notification clicked:', remoteMessage);
});
测试推送通知
通过 Firebase 控制台或 Postman 调用 FCM API 发送测试通知。需使用设备 token 和服务器密钥(可在 Firebase 项目设置中获取)。

# 示例 cURL 命令
curl -X POST \
-H "Authorization: key=<SERVER_KEY>" \
-H "Content-Type: application/json" \
-d '{
"to": "<DEVICE_TOKEN>",
"notification": {
"title": "Test Title",
"body": "Test Body"
}
}' \
https://fcm.googleapis.com/fcm/send
注意事项
- Android 配置:确保
android/app/src/main/AndroidManifest.xml包含正确的intent-filter和service声明。 - iOS 证书:需在 Apple Developer 后台配置 APNs 证书并上传至 Firebase。
- 调试:使用
adb logcat或 Xcode 控制台查看推送日志。






