How to get and cancel a PendingIntent?

ninjasense picture ninjasense · Dec 3, 2010 · Viewed 22k times · Source

I have an alarmManager which I am using to send notifications to the user at specific times. Since there are multiple alarms, I have multiple pending intents that I am creating and giving a unique ID, However there are certain situations in which I will need to get all the pending intents and then cancel them, so I can reset the alarms. I have tried doing this and I still cant seem to get it right so I have a couple questions:

Is this how you would correctly get and cancel a PendingIntent?

Intent intent = new Intent(con, AppointmentNotificationReciever.class);
PendingIntent sender = PendingIntent.getBroadcast(con, id, intent,
        PendingIntent.FLAG_CANCEL_CURRENT);
AlarmManager am = (AlarmManager) con.getSystemService(Context.ALARM_SERVICE);
am.cancel(sender);

Does the intent need to exactly match that of the original pending intent(extras and all)?

Does the PendingIntent flag need to match that of the original pending intent?

Answer

ninjasense picture ninjasense · Dec 3, 2010

I found out that you do not actually "get" the pending intent...you have to recreate it exactly as it was when you first created it(Intent as well) and then pass it to the AlarmManager's cancel function. So the above code I posted really is not incorrect as long as thats how I first created it. Hopefully someone will find this helpful.