React Native(Expo)本地通知无法显示问题求助
Expo本地通知在Android模拟器不显示的排查方案(含setNotificationHandler位置验证)
先明确setNotificationHandler的正确位置
它必须在App启动时尽早初始化,不能嵌套在按钮回调、条件渲染或非顶层组件中。正确的做法是放在App根组件的useEffect(空依赖数组)里,或者组件函数体的最顶部,确保App启动后立刻完成配置。
示例代码:
import { useEffect } from 'react'; import * as Notifications from 'expo-notifications'; import { View, Button } from 'react-native'; export default function App() { useEffect(() => { // 核心:初始化通知处理器,必须在App启动时执行 Notifications.setNotificationHandler({ handleNotification: async () => ({ shouldShowAlert: true, shouldPlaySound: true, shouldSetBadge: false, }), }); // 同步请求通知权限 async function requestNotifyPermission() { const { status } = await Notifications.requestPermissionsAsync(); if (status !== 'granted') { alert('请开启通知权限以接收通知'); } } requestNotifyPermission(); }, []); // 触发本地通知的函数 const sendTestNotification = async () => { await Notifications.scheduleNotificationAsync({ content: { title: '测试通知', body: '这是一条本地测试通知内容', }, trigger: { seconds: 1 }, // 延迟1秒发送,避免立即触发的兼容性问题 }); }; return ( <View style={{ flex: 1, justifyContent: 'center', alignItems: 'center' }}> <Button title="发送测试通知" onPress={sendTestNotification} /> </View> ); }
其他必查项
- 确认通知权限已授予:Android模拟器默认可能关闭应用通知权限,除了代码中请求,也可以手动进入模拟器「设置-应用-你的应用-通知」开启权限。
- 检查模拟器免打扰模式:下拉模拟器状态栏,确认没有开启免打扰,否则通知会被屏蔽。
- 验证依赖版本匹配:确保
package.json中expo-notifications的版本与你的Expo SDK版本对应(比如SDK 49对应expo-notifications ~0.20.1),版本不兼容会导致功能失效。 - 检查app.json配置:确保
expo.plugins中正确添加了expo-notifications插件,示例配置:
{ "expo": { "plugins": [ [ "expo-notifications", { "icon": "./assets/notification-icon.png", "color": "#4287f5" } ] ] } }
- 清除缓存重启项目:执行
npx expo start -c清除缓存,同时重启Android模拟器,避免配置未生效的情况。
内容的提问来源于stack exchange,提问作者filip_j
相关产品推荐
相关产品推荐

