React Native后台或关闭时无法接收FCM通知问题咨询
嘿,我碰到过类似的情况,咱们先理清楚核心问题:当应用后台或者完全关闭时,RN的JS环境已经销毁了(也就是你说的ReactInstanceManager.detachViewFromInstance()被调用),这时候FCM通知得靠Android原生层来处理,而不是RN的JS代码。下面是一步步的排查和解决方法:
先检查原生FCM服务的实现
这是最关键的一步,因为后台/关闭状态下的通知是由Android系统直接接管的,必须确保原生服务配置正确:
1. 自定义FirebaseMessagingService类
在你的Android项目里(路径大概是android/app/src/main/java/com/你的包名/)创建一个MessagingService.java文件,内容如下:
package com.你的包名; import com.google.firebase.messaging.FirebaseMessagingService; import com.google.firebase.messaging.RemoteMessage; import com.evollu.react.fcm.FCMEventService; public class MessagingService extends FirebaseMessagingService { @Override public void onMessageReceived(RemoteMessage remoteMessage) { // 调用react-native-fcm的处理逻辑,让系统弹出通知 FCMEventService.getInstance(this).sendMessage(remoteMessage); } @Override public void onNewToken(String token) { // 可选:把新的token同步到你的服务器 FCMEventService.getInstance(this).sendTokenRefresh(token); } }
然后在AndroidManifest.xml的<application>标签里注册这个服务:
<service android:name=".MessagingService" android:exported="false"> <intent-filter> <action android:name="com.google.firebase.MESSAGING_EVENT" /> </intent-filter> </service>
2. 配置Android 8.0+的通知渠道
Android 8.0及以上版本强制要求通知渠道,否则后台通知不会显示。你可以在MainActivity的onCreate方法或者自定义的Application类里添加这段代码:
import android.os.Build; import android.app.NotificationChannel; import android.app.NotificationManager; // 在onCreate方法里 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { String channelId = "default_notification_channel"; String channelName = "默认通知渠道"; NotificationChannel channel = new NotificationChannel(channelId, channelName, NotificationManager.IMPORTANCE_DEFAULT); NotificationManager notificationManager = getSystemService(NotificationManager.class); notificationManager.createNotificationChannel(channel); }
发送FCM通知时,记得在notification字段里指定channel_id为上面的default_notification_channel。
检查FCM消息的Payload格式
后台/关闭状态下,FCM必须发送包含notification字段的消息,不能只发data字段——如果只有data,系统不会自动弹出通知,得你自己在onMessageReceived里手动构建。
正确的Payload示例(服务器端发送):
{ "to": "你的设备Token", "notification": { "title": "新消息提醒", "body": "这是一条测试通知", "channel_id": "default_notification_channel" }, "data": { "custom_key": "custom_value" } }
确认react-native-fcm的链接配置
RN 0.57.5虽然支持自动链接,但最好手动检查一下配置是否正确:
settings.gradle里应该有:
include ':react-native-fcm' project(':react-native-fcm').projectDir = new File(rootProject.projectDir, '../node_modules/react-native-fcm/android')
app/build.gradle的dependencies里要包含:
implementation project(':react-native-fcm') implementation 'com.google.firebase:firebase-messaging:17.6.0' // 这个版本和react-native-fcm@16.2.4兼容,别乱升级
测试步骤
- 先测试应用前台状态下能否接收通知,确认FCM基础配置没问题;
- 退到后台,发送通知,看系统是否弹出;
- 完全关闭应用(从最近任务划掉),再发送通知测试。
如果还是不行,去Android Studio的Logcat里过滤FirebaseMessaging或者FCM关键词,看看有没有报错信息,比如“Failed to show notification”,这能帮你定位具体问题。
内容的提问来源于stack exchange,提问作者Dev bluCursor

