使用Notifee时,应用被杀死状态下FCM推送通知无法正常工作
解决应用杀死状态下无法接收FCM通知的问题
针对你遇到的应用杀死后无法接收FCM通知的情况,主要可以从以下几个方面排查和修复:
1. 确认FCM消息的结构类型
FCM消息分为两种类型,不同类型在应用杀死状态下的处理逻辑不同:
- 纯数据消息:仅包含
data字段,应用杀死时Android系统不会自动触发setBackgroundMessageHandler,需要依赖后台服务唤醒应用。 - 混合消息:同时包含
notification和data字段,系统会直接显示通知栏消息,点击后再将数据传递给应用,这种方式在杀死状态下更可靠。
建议发送混合消息,示例结构如下:
{ "to": "你的设备Token", "notification": { "title": "通知标题", "body": "通知内容" }, "data": { "customKey": "customValue" }, "priority": "high", "content_available": true }
2. 配置Android后台消息服务
React Native Firebase虽然封装了消息处理,但部分安卓设备需要手动配置自定义Firebase消息服务来确保杀死状态下的消息处理:
- 在Android项目的
android/app/src/main/java/[你的包名]/目录下创建MyFirebaseMessagingService.java文件:
import com.google.firebase.messaging.FirebaseMessagingService; import com.google.firebase.messaging.RemoteMessage; import io.invertase.firebase.messaging.ReactNativeFirebaseMessagingService; public class MyFirebaseMessagingService extends ReactNativeFirebaseMessagingService { @Override public void onMessageReceived(RemoteMessage remoteMessage) { super.onMessageReceived(remoteMessage); // 确保消息被正确转发给RN层处理 } }
- 在
AndroidManifest.xml中注册该服务:
<service android:name=".MyFirebaseMessagingService" android:exported="false"> <intent-filter> <action android:name="com.google.firebase.MESSAGING_EVENT" /> </intent-filter> </service>
3. 提前创建通知渠道
你的代码中是在收到消息时才创建通知渠道,但应用杀死状态下,消息到达时可能还没执行创建渠道的逻辑,导致通知无法显示。建议在应用启动时就创建渠道:
在App组件的初始化逻辑中添加:
import notifee, { AndroidImportance } from '@notifee/react-native'; // 在App启动时执行 useEffect(() => { const createNotificationChannel = async () => { await notifee.createChannel({ id: 'important', name: 'Important Notifications', importance: AndroidImportance.HIGH, }); }; createNotificationChannel(); }, []);
4. 检查权限和系统设置
- 确保
AndroidManifest.xml中添加了必要权限:
<uses-permission android:name="android.permission.INTERNET" /> <uses-permission android:name="android.permission.POST_NOTIFICATIONS" /> <uses-permission android:name="android.permission.WAKE_LOCK" />
- 部分安卓厂商的电池优化会阻止后台唤醒,需要引导用户关闭应用的电池优化设置,确保FCM能正常唤醒应用处理消息。
5. 确认消息发送优先级
发送FCM消息时必须设置priority: "high"(Android)和content_available: true(iOS),这样才能确保系统在应用杀死时优先处理消息。
内容的提问来源于stack exchange,提问作者Mishen Thakshana
相关产品推荐
相关产品推荐

