javaandroidalarmmanager

Android AlarmManager cancel not works


I've created an alarm manager and it works well, but i cannot cancel it. I created a intent in same code as used in create alarm manager and cancel alarm but dosent works. An alarm is sitll working very well...

Create Alarm

Intent intent = new Intent(context, AlarmReciver.class);
intent.putExtra("alarm", id);
intent.putExtra("h", h);
intent.putExtra("m", m);
intent.putExtra("sound", sound);
intent.putExtra("vibration", vibration);
intent.putExtra("name", name);
intent.putExtra("problem_type", problem_type);

PendingIntent pendingIntent =
        PendingIntent.getBroadcast(
                context,
                id,
                intent,
                PendingIntent.FLAG_UPDATE_CURRENT | PendingIntent.FLAG_IMMUTABLE);

AlarmManager alarmManager = (AlarmManager) context.getSystemService(ALARM_SERVICE);
alarmManager.setExactAndAllowWhileIdle(
        AlarmManager.RTC_WAKEUP,
        calendar.getTimeInMillis(),
        pendingIntent
);

Cancel alarm

Intent intent = new Intent(context, AlarmReciver.class);
Alarm alarm = getAlarm(id);
intent.putExtra("alarm", id);
intent.putExtra("h", alarm.h);
intent.putExtra("m", alarm.m);
intent.putExtra("sound", alarm.sound);
intent.putExtra("vibration", alarm.vibration);
intent.putExtra("name", alarm.name);
intent.putExtra("problem_type", alarm.problem_type);

PendingIntent pendingIntent = // 등록했을 때의 인텐트랑 같아야 삭제됨
        PendingIntent.getBroadcast(
                context,
                id,
                intent,
                PendingIntent.FLAG_NO_CREATE | PendingIntent.FLAG_IMMUTABLE);

AlarmManager alarmManager = (AlarmManager) context.getSystemService(ALARM_SERVICE);
alarmManager.cancel(pendingIntent);

Solution

  • It looks like the case where your id is different while creating and cancelling the alarm.

    PendingIntent pendingIntent =
        PendingIntent.getBroadcast(
                context,
                id, // should be same for both, creating and cancelling
                intent,
                PendingIntent.FLAG_NO_CREATE | PendingIntent.FLAG_IMMUTABLE);
    

    The id value should be same in both cases. Hope it helps.