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

最新更新