19

When using a PendingIntent in an AppWidgetProvider, I'm using the following code:

views.setOnClickPendingIntent( viewId,
                PendingIntent.getBroadcast( context, 0, intent,
                PendingIntent.FLAG_UPDATE_CURRENT ) );

So currently there's no reference kept to the PendingIntent returned by the getBroadcast method. In a specific situation I now want to cancel the PendingIntent. Is there any way of getting the PendingIntent back from the View? Or is the only way to call the cancel method of the PendingIntent afterwards by keeping a reference to it?

Alex Lockwood
  • 83,063
  • 39
  • 206
  • 250
Roger Rapid
  • 956
  • 1
  • 8
  • 28

1 Answers1

33

Where you want to cancel it, you would do the following (somewhere else in your code base):

PendingIntent.getBroadcast(context, 0, intent, 
                           PendingIntent.FLAG_UPDATE_CURRENT).cancel();

where intent is the same one as referenced in your code above. PendingIntent.getBroadcast(...) using the PendingIntent.FLAG_UPDATE_CURRENT will return a reference to the existing one already created, or create one if it doesn't currently exist.

Alex Lockwood
  • 83,063
  • 39
  • 206
  • 250
Chris Knight
  • 24,333
  • 24
  • 88
  • 134
  • 3
    does getBroadcast return the same object *reference* in case i use this flag? – lysergic-acid May 31 '13 at 18:19
  • Hi, does it care about the extra you put into the intent? Should it be exactly the same (intent target, action and extras)? – Neon Warge Aug 09 '18 at 03:57
  • 2
    From https://developer.android.com/reference/android/app/PendingIntent A common mistake people make is to create multiple PendingIntent objects with Intents that only vary in their "extra" contents, expecting to get a different PendingIntent each time. This does not happen. The parts of the Intent that are used for matching are the same ones defined by Intent#filterEquals(Intent) – juanlugm Mar 03 '20 at 21:22