0

I can't seem to be able to cancel my alarm. I have looked at other posts on Stack Overflow but none of them have worked for me.

Here is my code:

AddAlarm class:

public void setAlarm(){
    AlarmManager am = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
    Intent i = new Intent(AddAlarm.this, AlarmReceiver.class);
    PendingIntent pi = PendingIntent.getBroadcast(AddAlarm.this, 0, i, PendingIntent.FLAG_UPDATE_CURRENT);

    calAlarm = Calendar.getInstance();
    Calendar calNow = Calendar.getInstance();
    Date date = new Date();

    calNow.setTime(date);
    calAlarm.setTime(date);
    calAlarm.set(Calendar.HOUR_OF_DAY, pickHour);
    calAlarm.set(Calendar.MINUTE, pickMinute);
    calAlarm.set(Calendar.SECOND, 0);

    if (calAlarm.before(calNow) || calAlarm == calNow){
        calAlarm.add(Calendar.DATE, 1);
    }

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
        am.setExact(AlarmManager.RTC_WAKEUP, calAlarm.getTimeInMillis(), pi);
    } else {
        am.set(AlarmManager.RTC_WAKEUP, calAlarm.getTimeInMillis(), pi);
    }
}

public void cancelAlarm(){
    AlarmManager am = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
    Intent i = new Intent(AddAlarm.this, AlarmReceiver.class);
    PendingIntent pi = PendingIntent.getBroadcast(AddAlarm.this, 0, i, PendingIntent.FLAG_UPDATE_CURRENT);

    am.cancel(pi);
}

Do you guys have any suggestions? Thanks!

Kevin Li
  • 195
  • 2
  • 14

2 Answers2

1

try to use this

PendingIntent.FLAG_CANCEL_CURRENT 

instead of

PendingIntent.FLAG_UPDATE_CURRENT

like

PendingIntent pi = PendingIntent.getBroadcast(AddAlarm.this, 0, i, PendingIntent.FLAG_CANCEL_CURRENT);
Michael
  • 113
  • 3
  • 13
Love Garg
  • 406
  • 1
  • 5
  • 17
  • Hi, I have already tried that. Unfortunately, it didn't work. – Kevin Li Jan 01 '16 at 04:14
  • Are you sure you are using same type of intent both time for details check this http://developer.android.com/reference/android/content/Intent.html#filterEquals(android.content.Intent) . – Love Garg Jan 01 '16 at 04:23
1

I think you are not canceling pending intent, try below snippet

 private void cancelAlarm(int alarmId)
{
    Intent intent = new Intent(this, AlarmManagerBroadcastReceiver.class);
    PendingIntent sender = PendingIntent.getBroadcast(this, alarmId,
            intent, 0);
    AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
    alarmManager.cancel(sender);
    sender.cancel();
}

Call cancelAlarm(0) method to cancel your alarm

Mohit Suthar
  • 8,725
  • 10
  • 37
  • 67