Search code examples
androidalarmmanagerandroid-pendingintent

When deleting alarm from AlarmManager, should I also cancel PendingIntent?


I'm trying to delete alarm from AlarmManager. I just called AlarmManager.cancel(), and It seems to work fine. Should I also cancel PendingIntent and why?

PendingIntent p; // prepare a pending intent which matches target alarm's intent.
alarmManager.cancel(p);
p.cancel() // should I do that? 

Solution

  • It is not necessary to do this. But it matters upon your usage.

    A PendingIntent itself is simply a reference to a token maintained by the system describing the original data used to retrieve it. This means that, even if its owning application's process is killed, the PendingIntent itself will remain usable from other processes that have been given it. If the creating application later re-retrieves the same kind of PendingIntent (same operation, same Intent action, data, categories, and components, and same flags), it will receive a PendingIntent representing the same token if that is still valid, and can thus call cancel() to remove it.

    If you only need one PendingIntent active at a time for any of the Intents you will use, then you can alternatively use the flags FLAG_CANCEL_CURRENT or FLAG_UPDATE_CURRENT to either cancel or modify whatever current PendingIntent is associated with the Intent you are supplying.