react-native - React Native - Expo - 在 Android 上一次抛出多个通知而不是单个通知的本地计划通知
问题描述
我正在尝试每小时创建一次具有通知功能的水提醒应用程序。我已经使用 scheduleLocalNotificationAsync 实现了通知。我的实现在 IOS 中按预期工作,但在 Android 中,当我打开应用程序时,应用程序同时发送 12 个通知,而不是在预定时间一一发送。
componentDidMount = () => {
this._sendNotifications();
};
_sendNotifications = async () => {
// Not to create duplicated notifications first cancel all notifications
await Notifications.cancelAllScheduledNotificationsAsync();
// beginning of notification part
const localnotification = {
title: 'Water Reminder',
body: "Don't forget to drink water!",
android: {
sound: true,
},
ios: {
sound: true,
},
};
// get the current date
let currentDate = Date.now();
currentDate = new Date(currentDate);
// get the day, month and year from current date to create time to schedule
let year = currentDate.getFullYear();
let month = currentDate.getMonth();
let date = currentDate.getDate();
// then create unix epoch number for eact date with number from notification section
// then we call notification function with each timestamp (not1)
if (this.state.switchStatus === false) {
await Notifications.cancelAllScheduledNotificationsAsync();
} else {
// Notification for nine
if (this.state.otherSwitchStatus.nine === true) {
let not0 = new Date(year, month, date, 9);
not0 = Date.parse(not0);
const schedulingOptions0 = { time: not0, repeat: 'day' };
// call the function to send notification at 9:00
await Notifications.scheduleLocalNotificationAsync(localnotification, schedulingOptions0);
}
// Notification for ten
if (this.state.otherSwitchStatus.ten === true) {
let not1 = new Date(year, month, date, 10);
not1 = Date.parse(not1);
const schedulingOptions1 = { time: not1, repeat: 'day' };
// call the function to send notification at 10:00
await Notifications.scheduleLocalNotificationAsync(localnotification, schedulingOptions1);
}
}
解决方案
我想我明白代码发生了什么。
正如您在我的代码中看到的那样,与一天中的当前时间无关,我调用 scheduleLocalNotificationAsync 15 次(从 09:00 到 23:00,每天重复选项)。但是,当我在 12:40 打开通知屏幕时,我会立即收到 4 个通知(09:00、10:00、11:00 和 12:00 各一个)。
我猜 expo 会立即调用通知函数 4 次。这不是 ios 的情况,但它正在发生在 Android 中。我想它需要在博览会方面进行修复。
在那之前,我通过检查当前时间并将其与要安排的时间进行比较来解决问题,如果通过了,我将其安排在明天。
let hour = currentDate.getHours();
// I changed the code below
// let not0 = new Date(year, month, date, 9)
// to this
let not0 = new Date(year, month, hour > 9 ? date + 1 : date, 9);
我还创建了一个问题博览会 github。 https://github.com/expo/expo/issues/3946
推荐阅读
- c# - 提取字符串的特定部分
- kubernetes-helm - 由于模板错误,无法从本地文件部署掌舵图
- swift - 如何从 Annotation Callout Xcode 9 设置警报
- c# - 实体框架上的 Min DateTime 可以返回 null,所以我使用的是 DateTime?保值
- php - Laravel Eloquent 返回 null
- c# - 如何在对话中处理是/否
- html - 如何更改实现 css sidenav 断点
- typescript - 关于 TypeScript 的展示有什么建议吗?
- python - Python 3.X:在嵌套 For 循环中调用外部变量
- javascript - 如何通过 node.js server-sent-event 发送命令行输出并在浏览器中显示