0

I want to use AlarmService to trigger a notification at a certain time. Think of it as something similar as a calendar app that is showing a reminder as notification for an upcoming event.

The code to schedule the intent (via alarm service) looks like this:

fun scheduleNotification(event : CalendarEvent)
    val startTime : Instant = event.startTime

    val intent = buildPendingIntent(event)

    val notificationTime = startTime.minusMillis(TimeUnit.MINUTES.toMillis(10)) // 10 Minutes earlier

    if (Build.VERSION.SDK_INT < 23) {
      alarmService().setExact(AlarmManager.RTC_WAKEUP,
          notificationTime.toEpochMilli(), intent)
    } else {
      alarmService().setExactAndAllowWhileIdle(AlarmManager.RTC_WAKEUP,
          notificationTime.toEpochMilli(), intent)
    }
  }

fun buildPendingIntent(event : CalendarEvent){
       val intent = Intent(context, NotificationReceiver::class.java)
       intent.putExtra(EVENT_ID, event.id)
       return PendingIntent.getBroadcast(context, 0, realIntent, 0)
}

class NotificationReceiver : WakefulBroadcastReceiver() {

   override fun onReceive(context: Context, intent: Intent) {
      // build and display the notification
  }

}

So 1 of 10 times the notification is tirggered and shown (by NotificationReceiver) correctly, also at the desired time. So I think the scheduling part is working properly.

Which leads me to another question: Whenever the user creates a new CalendarEvent the method scheduleNotification(newEvent) is called. It seems to me that AlarmService is internally updating the PendingIntents of existing and that this is the reason why 1 of 10 (usually the first scheduled PendingIntent) is triggered, but the others are not.

How many alarms can I schedule for an Android App? Do you spot any other issue with my code?

sockeqwe
  • 15,574
  • 24
  • 88
  • 144
  • Maybe flag issue, last parameter here: `PendingIntent.getBroadcast(context, 0, realIntent, 0)` ? – Jemshit Aug 31 '17 at 14:29
  • This answer says you need to give unique Request Code for each alarm: https://stackoverflow.com/a/10090378/3736955 – Jemshit Aug 31 '17 at 14:33
  • ah, yeah, this sounds reasonable. I will give it a try. Thanks! – sockeqwe Aug 31 '17 at 14:45
  • Possible duplicate of [how to set multiple alarms using android alarm manager](https://stackoverflow.com/questions/8469705/how-to-set-multiple-alarms-using-android-alarm-manager) – sockeqwe Sep 01 '17 at 00:25

0 Answers0