Expo-notifications通知响应事件在应用未后台运行/冷启动时无法触发
Expo SDK 40 冷启动通知响应捕获方案
问题原因
addNotificationResponseReceivedListener 仅监听应用完成启动后触发的通知点击事件,用户点击通知冷启动应用时的响应数据不会被该监听器捕获,会暂存在通知模块的缓存中,需要主动查询获取。
解决步骤
- 不需要额外配置权限,现有通知权限配置即可满足需求
- 抽离公共的通知响应处理逻辑,避免运行时和冷启动场景重复写代码
- 在应用根组件初始化阶段主动查询冷启动通知响应
示例代码
import { Notifications } from 'expo-notifications'; import axios from 'axios'; import { useEffect, useRef } from 'react'; export default function App() { const responseListener = useRef(); // 公共通知响应处理逻辑 const handleNotificationResponse = (response) => { axios.post("https://<logUrl.onOurServer.com>", { test: "background", }); }; useEffect(() => { // 原有运行时/后台场景监听器 responseListener.current = Notifications.addNotificationResponseReceivedListener(handleNotificationResponse); // 新增冷启动场景查询逻辑 const getInitialNotification = async () => { const initialResponse = await Notifications.getLastNotificationResponseAsync(); // 确认存在冷启动通知响应再处理 if (initialResponse) { handleNotificationResponse(initialResponse); } }; getInitialNotification(); // 组件卸载时移除监听器 return () => { responseListener.current && responseListener.current.remove(); }; }, []); // 其余应用逻辑 return <></>; }
注意事项
- 冷启动响应缓存默认10分钟有效期,超时后会自动清空,不会误处理历史通知点击事件
- 不需要修改app.json配置或新增原生权限,补充上述逻辑即可覆盖全场景通知点击事件
内容的提问来源于stack exchange,提问作者Ali Mert Çakar
相关产品推荐
相关产品推荐

