I’ve got a navigation app. I want to get position information that may not arrive for a while, depending on how long it takes GPS to lock up — or ever if reception is bad.
I was planning to use LocationManager.requestLocationUpdates() to request location information to be sent to a BroadcastReciever whenever it becomes available, and to also set a timeout via AlarmManager.set().
If the location update arrives, I want to cancel the timeout. If the timeout arrives, I want to cancel the location update. Assuming that my app could be killed before either happens, I’ll have lost the PendingIntent for the thing I want to cancel.
Is there a way to save the PendingIntent somehow, so I can use them to cancel the timeout and/or location update later? Or is there a better way to go about this?
You don’t need to save the PendingIntent instance itself. The documentation for AlarmManager.cancel(PendingIntent operation) says,
If you look at Intent.filterEquals(Intent), it says,
So you can just create a PendingIntent with the same action and do am.cancel() with that new pending intent, and it will cancel the previous pending intent as well.
Here’s a quick code sample:
And now you can call am.set() with the PendingIntent returned from the above function, and also call am.cancel() with the PendingIntent returned from the same function as well. It doesn’t matter whether the PendingIntent is the same instance or not, it just has to match the Intent.filterEquals() test (so basically just the Intent action has to match only).
So basically just use the same action to create the intent to set/cancel the alarm and it will work.