3

I'm making an alarm clock app using PendingIntent and AlarmManager. I know in order to cancel a PendingIntent, you need to recreate it exactly. In my app, much like many other alarm clock apps, there is a list of alarms with a switch to toggle each alarm on/off. When toggled off, I currently recreate the PendingIntent and cancel it using the following:

Intent intent = new Intent(context, MyBroadcastReceiver.class);
String id = this.getId().replaceAll("[^0-9]+", "");
PendingIntent alarmIntent = PendingIntent.getBroadcast(context, id, intent, 0);
alarmIntent.cancel();

The first 3 lines of the code above I believe are unnecessary. When I toggle the alarm, I have access to the custom alarm object which contains the id along with many other details of the alarm. When I'm creating a new alarm, if I store the newly created PendingIntent in the alarm object, I can have access to the PendingIntent used to create the alarm, and just retrieve it and cancel it in 1 line, like this:

this.getPendingIntent().cancel();

I wouldn't have to recreate the intent, get the id, or recreate the PendingIntent from the code shown earlier. This would ultimately save time and resources (not much but it's good practice), so I have a couple questions:

1) Is there anything wrong with storing the PendingIntent in an object and use it later instead of recreating it? It seems like a straightforward answer but I haven't seen anyone do this before.

2) Is there an advantage to recreating the PendingIntent that I'm not aware of?

Thanks!

Michael
  • 3,093
  • 7
  • 39
  • 83

1 Answers1

2

Is there anything wrong with storing the PendingIntent in an object and use it later instead of recreating it?

Assuming that the underlying Intent doesn't have some massive payload (e.g., Bitmap in an extra), you should be OK.

It seems like a straightforward answer but I haven't seen anyone do this before.

https://github.com/commonsguy/cw-omnibus/tree/v8.7/AlarmManager/Simple, though it's a trivial example.

Is there an advantage to recreating the PendingIntent that I'm not aware of?

It works for cases where you do not have the PendingIntent. Your process does not live forever. If you want to use a cached PendingIntent as an optimization, that's fine, but you need to be in position to create the PendingIntent if it is needed.

CommonsWare
  • 986,068
  • 189
  • 2,389
  • 2,491
  • Thanks for the help! And not sure how to message someone on SO but can you take a look at my other question: https://stackoverflow.com/questions/45381092/how-to-stop-alarm-from-executing-after-pendingintent-has-been-received-android – Michael Sep 08 '17 at 15:55