我正在尝试每小时创建一次带有通知功能的水提醒应用程序。我已经使用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);
我还创建了一个问题expo github。 https://github.com/expo/expo/issues/3946