React Native Notifee安卓后台不显示通知求助(前台/杀死状态正常)
解决方案:安卓后台无法显示Notifee通知的问题
1. 将setBackgroundMessageHandler移到项目根目录的index.js
后台消息处理器必须在APP初始化阶段完成注册,放在Home/index.js这类组件文件中时,后台状态下组件未挂载,处理器不会生效。
修改根index.js:
import { getMessaging } from 'firebase/messaging'; import { DisplayNotificationData } from './android/app/src/utils/push_notification_helper'; import { AppRegistry } from 'react-native'; import App from './App'; import { name as appName } from './app.json'; const messaging = getMessaging(); // 注册后台消息处理器 messaging.setBackgroundMessageHandler(async remoteMessage => { try { console.log('后台消息已接收:', remoteMessage); await DisplayNotificationData(remoteMessage); console.log('后台通知已展示'); } catch (err) { console.error('后台消息处理失败:', err); } }); AppRegistry.registerComponent(appName, () => App);
2. 优化DisplayNotificationData函数
- 移除安卓环境下的权限请求:安卓后台无需请求通知权限,该异步操作会阻塞后台任务执行
- 提前创建通知频道:避免每次收到通知才创建频道,减少异步延迟
步骤2.1:提前创建通知频道(根index.js)
import notifee, { AndroidImportance } from '@notifee/react-native'; // 在APP启动时创建通知频道 async function initNotificationChannels() { await notifee.createChannel({ id: 'important', name: '重要通知', importance: AndroidImportance.HIGH, }); } // 在注册App前执行初始化 initNotificationChannels();
步骤2.2:修改DisplayNotificationData函数
import { Platform } from 'react-native'; import notifee from '@notifee/react-native'; export async function DisplayNotificationData(remoteMessage) { // 仅iOS前台需要请求权限 if (Platform.OS === 'ios') { await notifee.requestPermission(); } const { title, body } = remoteMessage.data; await notifee.displayNotification({ title: title, body: body, android: { channelId: 'important', // 使用提前创建的频道ID }, }); console.log('DisplayNotificationData 执行完成'); }
3. 检查安卓Manifest配置
确保android/app/src/main/AndroidManifest.xml中包含Firebase消息服务注册,否则后台消息无法被接收:
<service android:name="com.google.firebase.messaging.FirebaseMessagingService" android:exported="false"> <intent-filter> <action android:name="com.google.firebase.MESSAGING_EVENT" /> </intent-filter> </service>
4. 验证推送消息格式
发送纯data类型通知时,确保title和body字段存在于data对象中,示例格式:
{ "data": { "title": "测试标题", "body": "测试内容" }, "to": "你的设备FCM Token" }
5. 调整notifee.onBackgroundEvent逻辑
该事件主要处理通知交互(如点击动作),无需在其中重复调用DisplayNotificationData,避免冲突:
import { EventType } from '@notifee/react-native'; notifee.onBackgroundEvent(async ({ type, detail }) => { const { notification, pressAction } = detail; if (type === EventType.ACTION_PRESS && pressAction.id === 'mark-as-read') { await notifee.cancelNotification(notification.id); } });
内容的提问来源于stack exchange,提问作者Ahmet Ekiz
相关产品推荐
相关产品推荐

