MaikuB / flutter_local_notifications

A Flutter plugin for displaying local notifications on Android, iOS, macOS and Linux
2.47k stars 1.4k forks source link

Scheduling multiple notifications every few days #2277

Closed hirosz closed 8 months ago

hirosz commented 8 months ago

I want to send notifications every few days using the code below. Unfortunately, on Android, all notifications are sent at once after about 24 hours. Is this my mistake or the library's problem?

Future<void> showScheduledNotifications() async {
    tz.initializeTimeZones(); // Initializes the timezone database.
    tz.setLocalLocation(
        tz.getLocation('America/Detroit')); // Set your local timezone.

    var androidDetails = const AndroidNotificationDetails(
      'reading_reminder_channel',
      'Reading Reminders',
      channelDescription: 'Channel for reading reminder notifications',
      importance: Importance.max,
      priority: Priority.high,
    );

    var iOSDetails = const DarwinNotificationDetails();

    var platformChannelSpecifics = NotificationDetails(
      android: androidDetails,
      iOS: iOSDetails,
    );

    // Messages map with delays in days as keys
    Map<int, List<String>> messages = {
      2: [
        "It's time for a book. More stories await!",
        "It's time for your daily reading. What will you discover today?",
        "A few minutes of reading can make a big difference. Let's go!",
      ],
      4: [
        "4 days gone. Time for a new chapter?",
        "Stacks of books and audiobooks await your return.",
        "Time to pick up a book?",
        "Let's make today a reading day.",
      ],
      6: [
        "Check out more great books and audiobooks.",
        "Stories await. Dive back in!",
        "Feeling adventurous? A new story is ready for you.",
      ],
      7: [
        "Last message. We've missed you in the tales.",
        "These reminders don't seem to be working. We'll stop sending them for now.",
      ],
      20: [
        "Hey! Check free books and audiobooks",
        "Maybe it's time for a book?",
        "Books are uniquely portable magic. Ready to explore?",
      ],
      40: [
        "We miss you! Maybe it's time for a book?",
        "It's never too late to start a reading habit. Begin today!",
        "Looking for a sign to read more? This is it. Open the app!",
        "Revive your reading habit now.",
      ],
    };

    // Titles list
    List<String> titles = [
      "Time to Read",
      "Open a Book Today",
      "Reading Time!",
      "Pick Up Where You Left Off",
      "New Stories Await",
      "Grab Your Book",
      "Dive Back In",
      "Keep the Habit Going",
      "Your Book Misses You",
    ];

    final bool canScheduleExact = await flutterLocalNotificationsPlugin
        .resolvePlatformSpecificImplementation<
        AndroidFlutterLocalNotificationsPlugin>()
        ?.canScheduleExactNotifications() ?? false;

    // Decide on the scheduling mode based on the permission
    AndroidScheduleMode scheduleMode = canScheduleExact
        ? AndroidScheduleMode.exactAllowWhileIdle
        : AndroidScheduleMode.inexact;

    Random random = Random();
    messages.forEach((delay, messagesForDelay) {
      var scheduledTime =
          tz.TZDateTime.now(tz.local).add(Duration(days: delay));

      // // Debugging output
      // debugPrint("Scheduled time for delay of $delay days: $scheduledTime");

      // Select a random message from the list for the corresponding delay
      if (messagesForDelay.isNotEmpty) {
        String message =
            messagesForDelay[random.nextInt(messagesForDelay.length)];
        String title =
            titles[random.nextInt(titles.length)]; // Select a random title

        flutterLocalNotificationsPlugin.zonedSchedule(
          delay,
          title,
          message,
          scheduledTime,
          platformChannelSpecifics,
          payload: 'ReminderNotification$delay',
          uiLocalNotificationDateInterpretation:
              UILocalNotificationDateInterpretation.absoluteTime,
          androidScheduleMode: scheduleMode,
          matchDateTimeComponents: DateTimeComponents.time,
        );
      }
    });
  }
Aziz-cs commented 5 months ago

Did you resolve this issue or what happened? Thanks

hirosz commented 5 months ago

Did you resolve this issue or what happened? Thanks

Yes. Set: matchDateTimeComponents: DateTimeComponents.dateAndTime,