React Native - Expo - локальное уведомление о расписании, отправляющее сразу несколько уведомлений вместо одного на Android - PullRequest
0 голосов
/ 08 апреля 2019

Я пытаюсь создать приложение для напоминания о воде с функцией уведомления один раз в час. Я реализовал уведомления с 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);
  }
}

1 Ответ

0 голосов
/ 14 апреля 2019

Полагаю, я понимаю, что происходит с кодом.

Поскольку, как вы можете видеть из моего кода, независимо от текущего времени дня, я вызываю 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

...