Reputation: 5362
I'm just looking at how to cancel an alarm and I came across these two methods. Which one should be used in what situation and why? Are they both the same?
I am currently doing this:
Intent alarmIntent = new Intent(ChangeAlarmActivity.this, AlarmReceiver.class);
PendingIntent pendingAlarmIntent = PendingIntent.getBroadcast(ChangeAlarmActivity.this, (int)alarm.getID(),
alarmIntent, 0);
pendingAlarmIntent.cancel();
How is that different to this below?
Intent alarmIntent = new Intent(ChangeAlarmActivity.this, AlarmReceiver.class);
PendingIntent pendingAlarmIntent = PendingIntent.getBroadcast(ChangeAlarmActivity.this, (int)alarm.getID(),
alarmIntent, 0);
AlarmManager alarmManager = (AlarmManager)getSystemService(ALARM_SERVICE);
alarmManager.cancel(pendingAlarmIntent);
Upvotes: 2
Views: 185
Reputation: 1007369
Are they both the same?
No.
If you want to cancel an alarm, call cancel()
on AlarmManager
.
cancel()
on PendingIntent
probably will appear to have the same effect -- whatever your alarm events were supposed to trigger no longer happens. However, you are then assuming that AlarmManager
will detect this and clean things up on its side, which is not guaranteed. Particularly for _WAKEUP
alarms, this could result in the device being woken up for no good reason, wasting battery life.
Which one should be used in what situation and why?
I am sure that cancel()
on PendingIntent
has use cases. I cannot name any concrete ones, as I have never seen it used. Typically when you are using a PendingIntent
, any "cancel" semantics are on the use of the PendingIntent
(e.g., you cancel()
the alarm via AlarmManager
, you cancel()
the notification via NotificationManager
), not on the PendingIntent
itself.
One place for cancel()
on PendingIntent
, therefore, would be some place where you pass off a PendingIntent
and there is no "cancel" to revert that, or you explicitly wish to use cancel()
as the revert mechanism. For example, if you are creating some sort of plugin mechanism, and the plugin sends a PendingIntent
to the host app, the plugin might use cancel()
to say "stop using that PendingIntent
", which the host app would find out about the next time it tried to send()
the PendingIntent
and got the exception. Personally, I'm not a huge fan of this -- much along the AlarmManager
lines, you don't know what resources might be used by the host app if it fails to properly handle this scenario. But, used properly, it could certainly work.
How is that different to this below?
The "below" one is what I would recommend that you use.
Upvotes: 1