Search code examples
androidandroid-alarms

Cancelling alarm from other class that the one which initiated it


I set alarm from one class using this code

Intent myIntent = new Intent(ClassOne.this, AlarmService.class);
pendingIntent = PendingIntent.getService(ClassOne.this, 0, myIntent, 0);

AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(currentDate.getTime());
long when = calendar.getTimeInMillis();
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, when, (7 * 24 * 60 * 60) * 1000, pendingIntent);

Now I need to cancel the pending alarms from another class. Can I just use this code?

Intent myIntent = new Intent(ClassTwo.this, AlarmService.class);
PendingIntent pendingIntent = PendingIntent.getService(ClassTwo.this, 0, myIntent, 0);
AlarmManager alarmManagerCancel = (AlarmManager) getSystemService(ALARM_SERVICE);
alarmManagerCancel.cancel(pendingIntent);

Or there is a better/proper way to cancel pending alarms?


Solution

  • As long as the PendingIntent are equivalent as the one you used to register the alarm, it doesn't matter where you call cancel() from. Two PendingIntents are equivalent (equals() returns true) if the underlying intents and request codes are the equivalent.