如何用Expo-Notification设置周期性提醒?Android报错求助
解决方案
核心问题
Android平台不支持Expo中type: "weekly"/"monthly"这类calendar类型的触发器,需改用跨平台兼容的重复触发方式:通过date指定首次触发时间,搭配repeatInterval定义重复周期。
权限前置
在调度通知前,务必先请求通知权限:
import { Notifications } from 'expo-notifications'; async function requestNotificationPermissions() { const { status } = await Notifications.requestPermissionsAsync(); if (status !== 'granted') { alert('需要开启通知权限才能使用此功能'); return false; } return true; }
不同周期的通知实现
1. 每日重复通知
async function scheduleDailyNotification() { const hasPermission = await requestNotificationPermissions(); if (!hasPermission) return; // 设置首次触发时间为今日的14:38 const triggerDate = new Date(); triggerDate.setHours(14, 38, 0, 0); // 如果当前时间已过14:38,设置为明天的14:38 if (triggerDate < new Date()) { triggerDate.setDate(triggerDate.getDate() + 1); } try { await Notifications.scheduleNotificationAsync({ content: { title: "EnergieM - Pripomienka", body: "Spravte si novy odpocet", sound: "default", }, trigger: { date: triggerDate, repeatInterval: 'day', }, }); } catch (error) { console.error('调度通知失败:', error); } }
2. 每周特定某天重复通知(例:每周三14:38)
async function scheduleWeeklyNotification(targetWeekday = 3) { const hasPermission = await requestNotificationPermissions(); if (!hasPermission) return; const today = new Date(); const triggerDate = new Date(today); // 计算距离下一个目标周几的天数(周日为0,周一为1,...,周六为6) const daysUntilTarget = (targetWeekday - today.getDay() + 7) % 7; // 如果今天就是目标周几且已过时间,设置为下周的同一天 if (daysUntilTarget === 0 && triggerDate.getHours() >= 14 && triggerDate.getMinutes() >= 38) { triggerDate.setDate(triggerDate.getDate() + 7); } else { triggerDate.setDate(triggerDate.getDate() + daysUntilTarget); } triggerDate.setHours(14, 38, 0, 0); try { await Notifications.scheduleNotificationAsync({ content: { title: "EnergieM - Pripomienka", body: "Spravte si novy odpocet", sound: "default", }, trigger: { date: triggerDate, repeatInterval: 'week', }, }); } catch (error) { console.error('调度通知失败:', error); } }
3. 每月特定某天重复通知(例:每月15号14:38)
async function scheduleMonthlyNotification(targetDay = 15) { const hasPermission = await requestNotificationPermissions(); if (!hasPermission) return; const today = new Date(); const triggerDate = new Date(today); triggerDate.setDate(targetDay); triggerDate.setHours(14, 38, 0, 0); // 如果当前日期已过目标日,设置为下个月的目标日 if (triggerDate < today) { triggerDate.setMonth(triggerDate.getMonth() + 1); } try { await Notifications.scheduleNotificationAsync({ content: { title: "EnergieM - Pripomienka", body: "Spravte si novy odpocet", sound: "default", }, trigger: { date: triggerDate, repeatInterval: 'month', }, }); } catch (error) { console.error('调度通知失败:', error); } }
注意事项
repeatInterval支持的值包括'minute'、'hour'、'day'、'week'、'month'、'year',跨平台兼容。- 务必用
try/catch包裹调度代码,避免未处理的Promise拒绝。 - 周几的数值需注意:JavaScript中
getDay()返回0(周日)到6(周六),需根据你的需求调整对应关系。
内容的提问来源于stack exchange,提问作者martin
相关产品推荐
相关产品推荐

