Search code examples
androidalarmmanager

How to cancel an AlarmManager


I have setup an alarmManager as follows:

    Intent intent = new Intent(TopActivity.this, RecordActivity.class);
    intent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
    intent.putExtra(Utils.KEY_RECORD_TIME, recordLength);
    intent.putExtra(Utils.KEY_REC_START_TIME, start);

    saveTimeAndLength(start, recordLength);

    PendingIntent pintent = PendingIntent.getActivity(TopActivity.this, 0, intent, 0);
    AlarmManager alarm = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
    alarm.set(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(), pintent);

The following is supposed to cancel it, but it always fail. What am I missing?

 AlarmManager alarmManager = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
Intent intent = new Intent(TopActivity.this, RecordActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
intent.putExtra(Utils.KEY_RECORD_TIME, start);
intent.putExtra(Utils.KEY_REC_START_TIME, recordLength);

PendingIntent pintent = PendingIntent.getActivity(TopActivity.this, 0, intent, 0);
try {
    alarmManager.cancel(pintent);
    Log.e(TAG, "Cancelling all pending intents");
} catch (Exception e) {
    Log.e(TAG, "AlarmManager update was not canceled. " + e.toString());
}

I have read lots of answers on StackOverflow but still could not figure out what's the problem.
Thanks in advance!


Solution

  • I will post my answer here hoping that would help others saving some time.
    Somehow adding the flag PendingIntent.FLAG_UPDATE_CURRENT in both sides solve the problem.

    PendingIntent pintent = PendingIntent.getActivity(TopActivity.this, 0, intent,PendingIntent.FLAG_UPDATE_CURRENT);
    

    solved the problem.
    Setting Alarm

     Intent intent = new Intent(TopActivity.this, RecordActivity.class);
        intent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
        intent.putExtra(Utils.KEY_RECORD_TIME, recordLength);
        intent.putExtra(Utils.KEY_REC_START_TIME, start);
    
        saveTimeAndLength(start, recordLength);
    
        PendingIntent pintent = PendingIntent.getActivity(TopActivity.this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
        AlarmManager alarm = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
        alarm.set(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(), pintent);
    

    Cancel Alarm

    AlarmManager alarmManager = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
    Intent intent = new Intent(TopActivity.this, RecordActivity.class);
    
    PendingIntent pintent = PendingIntent.getActivity(TopActivity.this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
    try {
        alarmManager.cancel(pintent);
        Log.e(TAG, "Cancelling all pending intents");
    } catch (Exception e) {
        Log.e(TAG, "AlarmManager update was not canceled. " + e.toString());
    }