基于Expo的React Native:如何为全球各时区用户定时发送20点通知?
在Expo中实现全球时区用户当地晚8点接收通知
完全可以实现,针对你的需求,优先选本地通知,原因和具体操作如下:
一、选本地还是推送?
- 本地通知:首选方案。不需要依赖服务器,直接基于用户设备的系统时区计算触发时间,离线状态也能正常触发,逻辑简单,完美匹配固定当地时间的定时通知需求。
- 推送通知:适合需要动态修改通知内容、统计推送数据或发布紧急公告的场景,但需要服务器存储用户时区信息、逐个计算用户的触发时间,复杂度高,对你的需求来说没必要使用。
二、本地通知实现步骤
1. 安装依赖
先安装Expo通知相关的核心包:
npx expo install expo-notifications expo-device
2. 请求通知权限
App启动时需先获取用户的通知授权:
import * as Notifications from 'expo-notifications'; import * as Device from 'expo-device'; import { Platform } from 'react-native'; async function requestNotificationPermissions() { // Android需先创建通知渠道,否则通知无法正常显示 if (Platform.OS === 'android') { await Notifications.setNotificationChannelAsync('daily-reminder', { name: '每日提醒', importance: Notifications.AndroidImportance.MAX, vibrationPattern: [0, 250, 250, 250], lightColor: '#FF231F7C', }); } if (Device.isDevice) { const { status: existingStatus } = await Notifications.getPermissionsAsync(); let finalStatus = existingStatus; if (existingStatus !== 'granted') { const { status } = await Notifications.requestPermissionsAsync(); finalStatus = status; } if (finalStatus !== 'granted') { alert('需要开启通知权限才能接收定时提醒'); return; } } else { alert('请使用真实设备测试通知功能,模拟器存在兼容性问题'); } }
3. 计算当地晚8点的触发时间
编写函数计算距离当前时间最近的当地20:00时间戳,若当前时间已过8点,则自动设置为次日的20:00:
function getTonight8PMTimestamp() { const now = new Date(); const tonight = new Date(now.getFullYear(), now.getMonth(), now.getDate(), 20, 0, 0); if (now > tonight) { tonight.setDate(tonight.getDate() + 1); } return tonight.getTime(); }
4. 调度每日重复通知
完成权限请求后,设置每日重复触发的本地通知:
async function scheduleDaily8PMNotification() { await requestNotificationPermissions(); const trigger = { timestamp: getTonight8PMTimestamp(), repeats: true, repeatInterval: 'day', }; await Notifications.scheduleNotificationAsync({ content: { title: '每日提醒', body: '当地时间晚上8点啦!', sound: true, }, trigger, }); }
5. 可选:处理通知点击事件
如果需要用户点击通知后跳转到App内指定页面,可添加监听逻辑:
// 配置通知的显示行为 Notifications.setNotificationHandler({ handleNotification: async () => ({ shouldShowAlert: true, shouldPlaySound: true, shouldSetBadge: false, }), }); // 监听通知点击事件 Notifications.addNotificationResponseReceivedListener(response => { // 此处可添加页面跳转逻辑,例如 navigation.navigate('TargetScreen') console.log('通知被点击', response); });
三、注意事项
- iOS设备卸载App后,已设置的本地通知会被清空,重装App后需重新调度
- Android设备需确保App拥有后台运行权限,否则可能无法正常触发通知
- 必须使用真实设备测试通知功能,模拟器的通知兼容性较差
内容的提问来源于stack exchange,提问作者Niitron
相关产品推荐
相关产品推荐

