Search code examples
androidalarmmanager

Cannot cancel repeating alarm


I am using targetSdkVersion 24. I set up an alarm like this:

    alarmMgr = (AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
    Intent intent = new Intent(context, AlarmReceiver.class);
    intent.putExtra("REQUEST_CODE", CHEW_REQ_CODE);
    intent.putExtra("CHEW_TEXT", chewText);
    PendingIntent pIntent = PendingIntent.getBroadcast(context, CHEW_REQ_CODE, intent, PendingIntent.FLAG_UPDATE_CURRENT);

    alarmMgr.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + interval, interval, pIntent);

where interval is 15 x 60 x 1000 = 15 min. This alarm is set in a check box in the preferences. On a HTC One running API 23 the alarm goes off as expected. However, when I cancel this alarm by unchecking the preference, the alarm keeps going off. This is my cancel code:

    if (alarmMgr != null) {
        Intent intent = new Intent(context, AlarmReceiver.class);
        intent.putExtra("REQUEST_CODE", CHEW_REQ_CODE);
        intent.putExtra("CHEW_TEXT", chewText);
        PendingIntent pIntent = PendingIntent.getBroadcast(context, CHEW_REQ_CODE, intent, PendingIntent.FLAG_UPDATE_CURRENT);
        alarmMgr.cancel(pIntent);
    }

What am I missing?


Solution

  • Thanks to Blehi, I found that the code was not called. The part was this:

        if (alarmMgr != null) {
            alarmMgr.cancel(chewIntent);
    
        }
    

    AlarmReceived is implemented as Singleton, while the AlarmManager is instantiated in my setAlarm. So alarmMgr was null when the alarm was canceled.