如何在收到推送通知时将Expo CLI开发的APP调至前台(含杀死状态)
实现Expo APP在杀死状态下通过推送唤醒至前台
Android 端实现
1. 配置高优先级推送参数
发送推送请求时,在android配置段设置高优先级,确保APP被杀死时系统能处理通知:
{ "to": "EXPO_PUSH_TOKEN", "title": "服务器异常", "body": "服务器负载过高,请查看", "android": { "priority": "high", "channelId": "your-notification-channel-id", "clickAction": "OPEN_APP" } }
priority: "high"是核心配置,能让通知突破后台限制被系统识别。
2. 监听通知点击事件
在APP初始化阶段注册通知打开监听器,用户点击通知时自动唤醒APP至前台:
import * as Notifications from 'expo-notifications'; Notifications.setNotificationHandler({ handleNotification: async () => ({ shouldShowAlert: true, shouldPlaySound: true, shouldSetBadge: false, }), }); // 监听通知点击动作 Notifications.addNotificationOpenedListener(async () => { // 此处可直接跳转至监控页面,Android系统会自动处理APP前台唤醒 });
3. 后台任务自动唤醒(可选)
若需要无需用户点击、收到通知就自动唤醒APP,可结合expo-task-manager注册后台任务(注意Android 12+对后台启动有严格限制,仅高优先级通知可触发):
- 定义并注册后台任务:
import * as TaskManager from 'expo-task-manager'; import * as Notifications from 'expo-notifications'; const BACKGROUND_NOTIFICATION_TASK = 'background-notification-task'; TaskManager.defineTask(BACKGROUND_NOTIFICATION_TASK, async ({ data }) => { if (data) { // 尝试触发APP前台唤醒逻辑,需适配厂商系统限制 console.log('收到后台通知,唤醒APP'); } }); Notifications.registerTaskAsync(BACKGROUND_NOTIFICATION_TASK);
- 推送时补充
contentAvailable配置:
{ "android": { "priority": "high", "contentAvailable": true, "channelId": "your-notification-channel-id" } }
iOS 端实现
iOS系统对后台唤醒有严格限制,仅支持用户点击通知唤醒APP,无法自动唤醒:
- 推送配置需包含
alert和contentAvailable:
{ "to": "EXPO_PUSH_TOKEN", "title": "服务器异常", "body": "服务器负载过高,请查看", "ios": { "sound": "default", "contentAvailable": true, "badge": 1 } }
- 注册通知打开监听器,用户点击后APP自动唤醒,可在回调中跳转至目标页面:
Notifications.addNotificationOpenedListener(async (notification) => { // 导航至服务器监控详情页,例如:navigation.navigate('ServerMonitor'); });
注意事项
- Android 13+需提前申请
POST_NOTIFICATIONS权限:
const { status } = await Notifications.requestPermissionsAsync({ android: { allowAlert: true, allowBadge: true, allowSound: true, allowVibrate: true, allowPostNotifications: true, }, });
- 部分Android厂商(小米、华为等)有额外后台限制,需引导用户开启APP的「自启动」「后台运行」权限,否则高优先级通知可能无法触发唤醒。
- iOS的
contentAvailable用于触发静默通知,但静默通知无弹窗,需搭配alert字段显示通知,用户点击后才会唤醒APP。
内容的提问来源于stack exchange,提问作者Alex Bleotu
相关产品推荐
相关产品推荐

