Локальные уведомления не срабатывают в новое время при переносе Flutter - PullRequest
0 голосов
/ 03 августа 2020

В своем приложении я использую плагин flutter_local_notifications: ^1.4.2 для локальных уведомлений. Пользователь выбирает, в какие дни недели запланировать alarm, и при сохранении я передаю объект alarm методу setSchedulerNotifications, чтобы установить уведомление для каждого дня в списке repeatWeekdays будильника. I l oop через список repeatWeekdays и установить уведомление для каждого l oop, с идентификатором, который передается в идентификаторе тревоги + номер l oop, чтобы быть инкрементным. Пока все работает, как ожидалось.

Теперь, когда тревога редактируется (другое время), при сохранении я передаю новую тревогу методу modifySchedulerNotification, который сначала вызывает метод deleteSchedulerNotifications (который имеет тот же l oop для вычисления идентификатора уведомления), а затем снова вызывает setSchedulerNotifications.

Распечатки показывают, что идентификаторы уведомлений в setSchedulerNotifications верны, и они согласованы в deleteSchedulerNotifications и втором вызове setSchedulerNotifications, но когда они установлены во второй раз (те же идентификаторы, что и в первый раз) уведомления не срабатывают в новое время, а срабатывают в старое время.

Можете ли вы заметить, что я делаю не так?

Способы уведомления:

Установить

Future<void> setSchedulerNotifications(Alarm alarm) async {
    print(
        '##### LocalNotificationRepository().setSchedulerNotifications called');
    print('##### sound to play is : ${alarm.sound.toLowerCase()}');
    for (int i = 0; i < alarm.repeatWeekdays.length; i++) {
      List<String> repeat = alarm.repeatWeekdays;
      int notificationId = int.parse(alarm.alarmId) + i;
      print('##### Scheduling local notification with id: $notificationId,\n'
          '###### for alarm with id ${alarm.alarmId}\n'
          '##### i = $i');
      String notificationChannelId = 'checkRoute_${alarm.sound}';
      String notificationChannelName = 'checkRoute_${alarm.alarmName}';
      String notificationChannelDescription =
          'Scherduled checking for route ${alarm.alarmName}';
      String sound = alarm.sound.toLowerCase();
      DateFormat dateFormat = DateFormat('HH:mm');
      var date = dateFormat.parse(alarm.time);
      int hour = date.hour;
      int minute = date.minute;
      Time time = Time(hour, minute, 0);

      var androidPlatformChannelSpecifics = AndroidNotificationDetails(
          notificationChannelId, //'show weekly channel id',
          notificationChannelName, //'show weekly channel name',
          notificationChannelDescription, //'show weekly channel description');
          priority: Priority.High,
          sound: RawResourceAndroidNotificationSound('$sound'));
      var iOSPlatformChannelSpecifics = IOSNotificationDetails(
          presentAlert: true, presentSound: true, presentBadge: true);
      var platformChannelSpecifics = NotificationDetails(
          androidPlatformChannelSpecifics, iOSPlatformChannelSpecifics);
      await flutterLocalNotificationsPlugin
          .showWeeklyAtDayAndTime(
              notificationId,
              sprintf(
                  AppLocalizations.instance
                      .text('ROUTE_CHECK_NOTIFICATION_TITLE'),
                  [alarm.alarmName]), //'show weekly title',
              AppLocalizations.instance.text(
                  'ROUTE_CHECK_NOTIFICATION_BODY'), //'show weekly subtitle',
              selectDay(repeat[i]),
              time,
              platformChannelSpecifics,
//          categoryIdentifier: "ROUTE_CHECK_CATEGORY",
              payload: alarm.routeName)
          .whenComplete(() {
        print('##### Scheduled local notification with id: $notificationId');
      });
    }
    print('##### LocalNotificationRepository().setWeeklyNotifications()\n'
        '##### all notifications for this route check are set');
  }

Удалить

  Future<void> deleteSchedulerNotifications(Alarm alarm) async {
    print(
        '@@@@ LocalNotificationRepository().deleteSchedulerNotifications called');

    for (int i = 0; i < alarm.repeatWeekdays.length; i++) {
      int id = int.parse(alarm.alarmId) + i;
      print('@@@@ Deleting local notification with id: $id,\n'
          '###### for alarm with id ${alarm.alarmId}\n'
          '##### i = $i');
      await flutterLocalNotificationsPlugin.cancel(id).catchError((e) {
        print(
            '@@@@ LocalNotificationRepository().deleteSchedulerNotifications error: $e');
      }).whenComplete(() {
        print('@@@@ Deleted local notification with id: $id');
        print('@@ LocalNotificationRepository().deleteWeeklyNotifications()\n'
            '@@ all notifications for this route check are deleted');
//        return;
      });
    }
  }

Изменить

  Future<void> modifySchedulerNotification(Alarm alarm) async {
    print(
        '## LocalNotificationRepository().modifyWeeklyNotifications() called\n'
        '## for alarm ${alarm.toMap().toString()}');
    await deleteSchedulerNotifications(alarm).whenComplete(() async {
      print('## LocalNotificationRepository().modifyWeeklyNotifications()\n'
          '## old notifications for alarm ${alarm.toMap().toString()} have been deleted.\n'
          '## are there new notifications to be set? ${alarm.enabled}');
      if (alarm.enabled == true) {
        await setSchedulerNotifications(alarm).whenComplete(() {
          print('## LocalNotificationRepository().modifyWeeklyNotifications()\n'
              '## new notifications for alarm ${alarm.toMap().toString()} are set');
          return;
        });
      }
    });

    print(
        'modifyWeeklyNotifications() all notifications for this route check are modified');
  }

Печать:

Первое сохранение

I/flutter ( 1520): SetNotification received
I/flutter ( 1520): SchedulerRepository().saveAlarm() calledfor alarm: {alarmId: 815816479, alarmName: test, enabled: true, repeatWeekdays: ["Monday","Tuesday","Wednesday","Thursday","Friday"], time: 21:05, sound: fixitTheme, routeName: test}
I/flutter ( 1520): ##### LocalNotificationRepository().setSchedulerNotifications called
I/flutter ( 1520): ##### sound to play is : fixittheme
I/flutter ( 1520): ##### Scheduling local notification with id: 815816479,
I/flutter ( 1520): ###### for alarm with id 815816479
I/flutter ( 1520): ##### i = 0
I/flutter ( 1520): ##### Scheduled local notification with id: 815816479
I/flutter ( 1520): ##### Scheduling local notification with id: 815816480,
I/flutter ( 1520): ###### for alarm with id 815816479
I/flutter ( 1520): ##### i = 1
I/flutter ( 1520): ##### Scheduled local notification with id: 815816480
I/flutter ( 1520): ##### Scheduling local notification with id: 815816481,
I/flutter ( 1520): ###### for alarm with id 815816479
I/flutter ( 1520): ##### i = 2
I/flutter ( 1520): ##### Scheduled local notification with id: 815816481
I/flutter ( 1520): ##### Scheduling local notification with id: 815816482,
I/flutter ( 1520): ###### for alarm with id 815816479
I/flutter ( 1520): ##### i = 3
I/flutter ( 1520): ##### Scheduled local notification with id: 815816482
I/flutter ( 1520): ##### Scheduling local notification with id: 815816483,
I/flutter ( 1520): ###### for alarm with id 815816479
I/flutter ( 1520): ##### i = 4
I/flutter ( 1520): ##### Scheduled local notification with id: 815816483
I/flutter ( 1520): ##### LocalNotificationRepository().setWeeklyNotifications()
I/flutter ( 1520): ##### all notifications for this route check are set

Изменить сохранить

I/flutter ( 1520): ModifyNotification received
I/flutter ( 1520): SchedulerRepository().saveAlarm() calledfor alarm: {alarmId: 815816479, alarmName: test, enabled: true, repeatWeekdays: ["Monday","Tuesday","Wednesday","Thursday","Friday"], time: 21:07, sound: fixitTheme, routeName: test}
I/flutter ( 1520): ## LocalNotificationRepository().modifyWeeklyNotifications() called
I/flutter ( 1520): ## for alarm {alarmId: 815816479, alarmName: test, enabled: true, repeatWeekdays: ["Monday","Tuesday","Wednesday","Thursday","Friday"], time: 21:05, sound: fixitTheme, routeName: test}
I/flutter ( 1520): @@@@ LocalNotificationRepository().deleteSchedulerNotifications called
I/flutter ( 1520): @@@@ Deleting local notification with id: 815816479,
I/flutter ( 1520): ###### for alarm with id 815816479
I/flutter ( 1520): ##### i = 0
I/flutter ( 1520): @@@@ Deleted local notification with id: 815816479
I/flutter ( 1520): @@ LocalNotificationRepository().deleteWeeklyNotifications()
I/flutter ( 1520): @@ all notifications for this route check are deleted
I/flutter ( 1520): @@@@ Deleting local notification with id: 815816480,
I/flutter ( 1520): ###### for alarm with id 815816479
I/flutter ( 1520): ##### i = 1
I/flutter ( 1520): @@@@ Deleted local notification with id: 815816480
I/flutter ( 1520): @@ LocalNotificationRepository().deleteWeeklyNotifications()
I/flutter ( 1520): @@ all notifications for this route check are deleted
I/flutter ( 1520): @@@@ Deleting local notification with id: 815816481,
I/flutter ( 1520): ###### for alarm with id 815816479
I/flutter ( 1520): ##### i = 2
I/flutter ( 1520): @@@@ Deleted local notification with id: 815816481
I/flutter ( 1520): @@ LocalNotificationRepository().deleteWeeklyNotifications()
I/flutter ( 1520): @@ all notifications for this route check are deleted
I/flutter ( 1520): @@@@ Deleting local notification with id: 815816482,
I/flutter ( 1520): ###### for alarm with id 815816479
I/flutter ( 1520): ##### i = 3
I/flutter ( 1520): @@@@ Deleted local notification with id: 815816482
I/flutter ( 1520): @@ LocalNotificationRepository().deleteWeeklyNotifications()
I/flutter ( 1520): @@ all notifications for this route check are deleted
I/flutter ( 1520): @@@@ Deleting local notification with id: 815816483,
I/flutter ( 1520): ###### for alarm with id 815816479
I/flutter ( 1520): ##### i = 4
I/flutter ( 1520): @@@@ Deleted local notification with id: 815816483
I/flutter ( 1520): @@ LocalNotificationRepository().deleteWeeklyNotifications()
I/flutter ( 1520): @@ all notifications for this route check are deleted
I/flutter ( 1520): ## LocalNotificationRepository().modifyWeeklyNotifications()
I/flutter ( 1520): ## old notifications for alarm {alarmId: 815816479, alarmName: test, enabled: true, repeatWeekdays: ["Monday","Tuesday","Wednesday","Thursday","Friday"], time: 21:05, sound: fixitTheme, routeName: test} have been deleted.
I/flutter ( 1520): ## are there new notifications to be set? true
I/flutter ( 1520): ##### LocalNotificationRepository().setSchedulerNotifications called
I/flutter ( 1520): ##### sound to play is : fixittheme
I/flutter ( 1520): ##### Scheduling local notification with id: 815816479,
I/flutter ( 1520): ###### for alarm with id 815816479
I/flutter ( 1520): ##### i = 0
I/flutter ( 1520): ##### Scheduled local notification with id: 815816479
I/flutter ( 1520): ##### Scheduling local notification with id: 815816480,
I/flutter ( 1520): ###### for alarm with id 815816479
I/flutter ( 1520): ##### i = 1
I/flutter ( 1520): ##### Scheduled local notification with id: 815816480
I/flutter ( 1520): ##### Scheduling local notification with id: 815816481,
I/flutter ( 1520): ###### for alarm with id 815816479
I/flutter ( 1520): ##### i = 2
I/flutter ( 1520): ##### Scheduled local notification with id: 815816481
I/flutter ( 1520): ##### Scheduling local notification with id: 815816482,
I/flutter ( 1520): ###### for alarm with id 815816479
I/flutter ( 1520): ##### i = 3
I/flutter ( 1520): ##### Scheduled local notification with id: 815816482
I/flutter ( 1520): ##### Scheduling local notification with id: 815816483,
I/flutter ( 1520): ###### for alarm with id 815816479
I/flutter ( 1520): ##### i = 4
I/flutter ( 1520): ##### Scheduled local notification with id: 815816483
I/flutter ( 1520): ##### LocalNotificationRepository().setWeeklyNotifications()
I/flutter ( 1520): ##### all notifications for this route check are set
I/flutter ( 1520): ## LocalNotificationRepository().modifyWeeklyNotifications()
I/flutter ( 1520): ## new notifications for alarm {alarmId: 815816479, alarmName: test, enabled: true, repeatWeekdays: ["Monday","Tuesday","Wednesday","Thursday","Friday"], time: 21:05, sound: fixitTheme, routeName: test} are set
I/flutter ( 1520): modifyWeeklyNotifications() all notifications for this route check are modified
I/flutter ( 1520): LocalNotificationBLoc._modifySchedulerNotification() notifications have been modified

1 Ответ

0 голосов
/ 05 августа 2020

Наконец-то обнаружена ошибка .. Я передавал старый объект Alarm методу modifySchedulerNotification.

...