Search code examples
androidpush-notificationkotlinandroid-pendingintent

Android - What is the correct way of keeping track of multiple PendingIntents?


I'll explain briefly what I need to achieve, I have used the PendingIntent in combination with AlarmManager.setRepeating() to notify the user every week.

val notificationAlarmManager = getSystemService(Context.ALARM_SERVICE) as AlarmManager
val notificationIntent = Intent(this, ReminderBroadcastReceiver::class.java)
val pendingNotificationIntent = PendingIntent.getBroadcast(this, 549078, notificationIntent,
        PendingIntent.FLAG_UPDATE_CURRENT)
 myCalendar.set(Calendar.HOUR_OF_DAY, 10)
 notificationAlarmManager.setRepeating(AlarmManager.RTC_WAKEUP, myCalendar.timeInMillis, notificationOffset(sub.cycle),
                    pendingNotificationIntent)

As you can see now I am forcing the 549078 as a resultCode in the PendingIntent.getBroadcast().

What is the correct way to differenciate between the result codes, so that I not only can have multiple notifications (since the same resultCode will be overwritten when I create a new one) but I also need a way to keep track of the result code, because I may want to delete it before it is being shown.


Solution

  • It is not possible to query the AlarmManager for the PendingIntents. You must store the resultCode and other information to recreate the PendingIntent in order to delete it.

    For example in SharedPreferences or in a database like SqliteDB or Room. Then you can recreate the PendingIntent to cancel it.

    See how to cancel PendingIntent.

    See How does android compare pending intents for details on what fields are important when comparing the intents for deletion.