基于Expo的React-Native安卓/iOS应用FCM本地与远程推送实现求助
Expo React Native 本地+FCM远程推送通知解决方案
一、工具选择建议
- Expo Notifications:官方原生适配工具,无需 eject,完美兼容 Expo 托管/裸工作流,本地、远程推送全覆盖,FCM 集成链路更顺畅,优先推荐。
- Notifee:需搭配 Expo Modules 使用(托管流需额外配置),功能更偏向自定义通知样式、渠道管理等进阶场景,适合有个性化需求的项目。
你之前未完全实现功能,大概率是配置环节遗漏,以下是完整环境搭建与核心步骤:
二、完整环境搭建与核心实现
1. 前置准备
- 更新 Expo 项目到最新版本:
expo update - 配置 Firebase 项目:
- 安卓:下载
google-services.json放到项目根目录,在app.json中添加:"android": { "googleServicesFile": "./google-services.json" } - iOS:下载
GoogleService-Info.plist放到项目根目录,在app.json中添加:"ios": { "googleServicesFile": "./GoogleService-Info.plist" }
- 安卓:下载
2. Expo Notifications 实现步骤
(1)安装依赖
expo install expo-notifications expo-device
(2)权限申请与 FCM 令牌获取
import * as Notifications from 'expo-notifications'; import * as Device from 'expo-device'; async function setupNotifications() { if (!Device.isDevice) { alert('仅支持真实设备测试推送'); return; } // 申请通知权限 const { status: existingStatus } = await Notifications.getPermissionsAsync(); let finalStatus = existingStatus; if (existingStatus !== 'granted') { const { status } = await Notifications.requestPermissionsAsync(); finalStatus = status; } if (finalStatus !== 'granted') { alert('需开启通知权限才能接收推送'); return; } // 获取并上报FCM令牌到你的服务器 const token = (await Notifications.getExpoPushTokenAsync()).data; console.log('FCM令牌:', token); // 这里调用你的服务器接口存储令牌 }
(3)本地推送实现
async function triggerLocalNotification() { await Notifications.scheduleNotificationAsync({ content: { title: '本地通知', body: '这是一条定时触发的本地推送', data: { customKey: '自定义数据' }, }, trigger: { seconds: 3 }, // 3秒后触发 }); }
(4)FCM 远程推送配置
服务器端使用存储的令牌,通过 FCM API 发送通知,请求格式示例:
- 请求地址:
https://fcm.googleapis.com/fcm/send - 请求头:
Authorization: key=你的FCM服务器密钥 - 请求体:
{ "to": "获取到的FCM令牌", "notification": { "title": "远程通知", "body": "来自服务器的FCM推送内容" }, "data": { "page": "home", "id": "123" } }
3. 常见问题排查
- 令牌获取失败:检查 Firebase 配置文件路径是否正确,设备是否联网,权限是否授予。
- 本地通知不显示:必须用真实设备测试,模拟器可能不支持;应用后台/前台状态均需测试。
- 远程通知无响应:确认 FCM 服务器密钥有效,令牌未过期,推送格式符合 Expo 要求(需包含
notification或data字段)。
三、Notifee 适配补充
若你坚持使用 Notifee,需注意以下关键配置:
- 安装依赖:
expo install @notifee/react-native - 安卓必须创建通知渠道:
import notifee from '@notifee/react-native'; async function createNotificationChannel() { await notifee.createChannel({ id: 'default', name: '默认通知渠道', sound: 'default', }); } - 本地推送示例:
async function showNotifeeNotification() { await notifee.displayNotification({ title: 'Notifee通知', body: '自定义推送内容', android: { channelId: 'default' }, }); }
内容的提问来源于stack exchange,提问作者Lubron
相关产品推荐
相关产品推荐

