You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何检测Expo/React Native应用是否通过点击通知启动?

检测Expo/React Native应用是否通过点击通知打开

核心思路是利用expo-notifications提供的监听API,分别处理应用冷启动(完全关闭后点击通知打开)和应用后台/前台运行时点击通知两种场景,以下是具体实现步骤:

1. 先完成基础配置与权限请求

首先要确保用户授予了通知权限,并初始化通知处理逻辑:

import * as Notifications from 'expo-notifications';
import { Platform, useEffect } from 'react-native';

// 请求通知权限
async function requestNotificationPermissions() {
  const { status } = await Notifications.requestPermissionsAsync();
  if (status !== 'granted') {
    alert('请开启通知权限才能正常接收通知');
    return;
  }
}

// 配置通知展示规则(iOS必填,Android可选)
Notifications.setNotificationHandler({
  handleNotification: async () => ({
    shouldShowAlert: true,
    shouldPlaySound: false,
    shouldSetBadge: false,
  }),
});

// 在App组件挂载时执行初始化
useEffect(() => {
  requestNotificationPermissions();
}, []);

2. 处理冷启动场景

当应用完全关闭时,用户点击通知启动应用,需要在App初始化时获取启动通知:

useEffect(() => {
  // 获取冷启动触发的通知响应
  Notifications.getLastNotificationResponseAsync().then(response => {
    // 判断是否是用户点击通知默认行为(打开应用)
    if (response?.actionIdentifier === Notifications.DEFAULT_ACTION_IDENTIFIER) {
      console.log('应用通过点击通知冷启动');
      // 提取通知携带的自定义数据,用于后续业务处理(比如跳转页面)
      const notificationData = response.notification.request.content.data;
      if (notificationData) {
        // 示例:根据data中的参数跳转到指定页面
        // navigation.navigate(notificationData.targetScreen, { id: notificationData.id });
      }
    }
  });
}, []);

3. 处理后台/前台唤醒场景

当应用在后台或前台运行时,监听通知点击事件:

useEffect(() => {
  // 订阅通知点击事件
  const notificationSubscription = Notifications.addNotificationResponseReceivedListener(response => {
    if (response.actionIdentifier === Notifications.DEFAULT_ACTION_IDENTIFIER) {
      console.log('应用通过点击通知从后台唤醒');
      const notificationData = response.notification.request.content.data;
      // 处理自定义数据,比如页面跳转
      // navigation.navigate(notificationData.targetScreen);
    }
  });

  // 组件卸载时取消订阅,避免内存泄漏
  return () => notificationSubscription.remove();
}, []);

补充说明

  • 调度通知时,要把自定义业务数据放在content.data字段里,这样点击通知后才能拿到数据:
async function scheduleTestNotification() {
  await Notifications.scheduleNotificationAsync({
    content: {
      title: '测试通知',
      body: '点击打开应用',
      data: { targetScreen: 'UserDetail', id: 456 }, // 自定义数据
    },
    trigger: { seconds: 5 }, // 5秒后触发通知
  });
}
  • Notifications.DEFAULT_ACTION_IDENTIFIER 特指用户点击通知主体(而非自定义操作按钮)的行为,如果你的通知有自定义按钮,需要对应判断其他actionIdentifier

内容的提问来源于stack exchange,提问作者Ben

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.10 00:40:09