Search code examples
androidandroid-intentscheduled-tasksalarmmanagerandroid-pendingintent

Automatically assign requestCodes to PendingIntent.getBroadcast (using AlarmManager)


I am essentially providing an interface to another application inside my android app. The client requested a system where he can either schedule a new local notification to be displayed at a specific time but also the ability to cancel all the local scheduled notifications. Is there a way that automatically assigns (practically unlimited) requestCodes(/ids) to PendingIntent objects while using them with AlarmManager?

PendingIntent pendingIntent = PendingIntent.getBroadcast(this, requestCode, someNotificationIntent, PendingIntent.FLAG_UPDATE_CURRENT);
...
AlarmManager alarmManager = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
    alarmManager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, futureTimeInMillis, pendingIntent);

I also want to be able to cancel all these pending intents without keeping track of the requestCodes:

for(int requestCode : somehowGetAllUsedRequestCodes){
AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
    PendingIntent pendingIntent = PendingIntent.getBroadcast(this, requestCode, someNotificationIntent, PendingIntent.FLAG_UPDATE_CURRENT);
    pendingIntent.cancel();
    alarmManager.cancel(pendingIntent);
}

Is that thing even possible without manually keeping track of request codes?


Solution

  • You would need to keep track of the request codes in a database or whatever to be able to cancel them later. You can ensure the id is unique if you store the values in a database as well.