Paul Cham
Paul Cham

Reputation: 425

Delete an Alarm using AlarmManager.cancel() not working

I'm trying to cancel an Alarm using AlarmManager.cancel() but apparently it is not working. I've read somewhere that I have to use PendingIntent.FLAG_UPDATE_CURRENT which as seen on the code, is what I used. In setting the alarm, I want the program to set an alarm automatically using code, hence the code below.

setAlarm Function:

public void setAlarm(DateTime date, String message) {
        Intent i = new Intent(AlarmClock.ACTION_SET_ALARM);
        i.putExtra(AlarmClock.EXTRA_MESSAGE, message);
        i.putExtra(AlarmClock.EXTRA_HOUR, date.getHourOfDay());
        i.putExtra(AlarmClock.EXTRA_MINUTES, date.getMinuteOfHour());
        i.putExtra(AlarmClock.EXTRA_SKIP_UI, true);
        PendingIntent pendingIntent = PendingIntent.getActivity(appContext.getApplicationContext(), 0, i, PendingIntent.FLAG_UPDATE_CURRENT);
        AlarmManager manager = (AlarmManager) appContext.getApplicationContext().getSystemService(Context.ALARM_SERVICE);
        manager.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(), pendingIntent);
        return;
    }

cancelAlarm Function:

public void cancelAlarm(DateTime date, String message) {
        Intent i = new Intent(AlarmClock.ACTION_SET_ALARM);
        i.putExtra(AlarmClock.EXTRA_MESSAGE, message);
        i.putExtra(AlarmClock.EXTRA_HOUR, date.getHourOfDay());
        i.putExtra(AlarmClock.EXTRA_MINUTES, date.getMinuteOfHour());
        i.putExtra(AlarmClock.EXTRA_SKIP_UI, true);
        PendingIntent pendingIntent = PendingIntent.getActivity(appContext.getApplicationContext(), 0, i, PendingIntent.FLAG_UPDATE_CURRENT);
        AlarmManager manager = (AlarmManager) appContext.getApplicationContext().getSystemService(Context.ALARM_SERVICE);
        manager.cancel(pendingIntent);
        return;
    }

Any ideas? I'm at my wit's end. Thanks in advance!

Upvotes: 0

Views: 901

Answers (1)

David Wasser
David Wasser

Reputation: 95578

When you set the alarm you do this:

manager.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(), pendingIntent);

This sets the alarm to go off at System.currentTimeMillis(), which will make the alarm go off immediately. Your call to cancel the alarm doesn't work because by the time you make the call to cancel, the alarm has already gone off and doesn't exist anymore.

Upvotes: 2

Related Questions