React Native应用后台/杀死状态下点击Notifee通知无法启动的解决方法
React Native Notifee:后台/杀死状态下点击通知无法启动应用的解决方案
Android 端处理步骤
- 配置通知 Intent 与启动 Flags
创建通知时必须指定正确的启动组件,同时添加必要的 Intent Flags,确保应用能从后台/杀死状态唤醒。示例代码:await notifee.displayNotification({ title: '通知标题', body: '通知内容', android: { channelId: 'your_channel_id', intent: { action: 'OPEN_APP', component: { packageName: 'com.your.app.package', className: 'com.your.app.package.MainActivity', }, flags: ['FLAG_ACTIVITY_CLEAR_TOP', 'FLAG_ACTIVITY_SINGLE_TOP'], }, }, }); - 修改 AndroidManifest.xml
确保 MainActivity 的launchMode设置为singleTask,并添加匹配通知 action 的 Intent Filter:<activity android:name=".MainActivity" android:launchMode="singleTask"> <intent-filter> <action android:name="OPEN_APP" /> <category android:name="android.intent.category.DEFAULT" /> </intent-filter> </activity> - 注册 Headless Task
应用处于杀死状态时,Android 需要通过 Headless Task 处理通知点击事件。在项目入口文件(如index.js)添加:import { AppRegistry } from 'react-native'; import notifee from '@notifee/react-native'; notifee.registerHeadlessTask(async ({ notification, pressAction }) => { // 处理通知点击逻辑,比如初始化必要数据 return Promise.resolve(); }); AppRegistry.registerComponent(appName, () => App);
iOS 端处理步骤
- 开启 Xcode 后台权限
打开 Xcode 项目,进入Signing & Capabilities面板:- 启用
Push Notifications - 启用
Background Modes并勾选Remote notifications
- 启用
- 配置 AppDelegate
在AppDelegate.m(或AppDelegate.swift)中添加通知点击处理逻辑,确保应用被唤醒时能响应:// Objective-C 示例 #import <NotifeeCore/NotifeeCore.h> - (void)userNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:(UNNotificationResponse *)response withCompletionHandler:(void (^)(void))completionHandler { [Notifee didReceiveNotificationResponse:response withCompletionHandler:completionHandler]; // 可添加自定义跳转逻辑 } - (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler { [Notifee didReceiveRemoteNotification:userInfo fetchCompletionHandler:completionHandler]; } - 确保通知 Payload 配置正确
发送的通知 payload 需包含aps字段,保证点击能唤醒应用:{ "aps": { "alert": { "title": "通知标题", "body": "通知内容" }, "content-available": 1 }, "data": { "key": "value" } }
通用注意事项
- 重新注册通知监听器
在应用启动时(比如App.js的useEffect中)重新注册onNotificationPress监听器,避免杀死状态重启后监听器丢失:useEffect(() => { const unsubscribe = notifee.onNotificationPress(async ({ notification, pressAction }) => { // 处理页面跳转等逻辑 navigation.navigate('TargetScreen'); }); return unsubscribe; }, [navigation]); - 使用真实设备测试
iOS 模拟器对后台通知支持有限,建议用真实设备测试后台/杀死状态下的通知点击行为。
内容的提问来源于stack exchange,提问作者Ardentous T
相关产品推荐
相关产品推荐

