Search code examples
androidalarmmanager

Delete specific ALARM from AlarmManger in Android


I am building a reminder app using alarmManger but I don't know how to delete a specific alarm.

AlarmManager manager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);

Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(System.currentTimeMillis());
calendar.set(Calendar.HOUR_OF_DAY, 10);
calendar.set(Calendar.MINUTE, 30);

Intent intent = new Intent(MainActivity.this, AlarmReceiver.class);
PendingIntent alarmIntent = PendingIntent.getBroadcast(getApplicationContext(), 0, intent, 0);
manager.set(AlarmManager.RTC_WAKEUP,calendar.getTimeInMillis(),pendingIntent);

The Receiver is a normal and simple Receiver.

My problem is that I want to edit/remove an alarm that has been added. I know conceptually how to remove an alarm, but I can't remove a specific alarm in alarmManger when several have been added.


Solution

  • by Id that you set in alarm manager you can access specific alarm, in your code:

    AlarmManager manager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
    
    Calendar calendar = Calendar.getInstance();
    calendar.setTimeInMillis(System.currentTimeMillis());
    calendar.set(Calendar.HOUR_OF_DAY, 10);
    calendar.set(Calendar.MINUTE, 30);
    
    Intent intent = new Intent(MainActivity.this, AlarmReceiver.class);
    

    at this line choose ID separate from each other , then you can get specific alarm by it's id

    PendingIntent alarmIntent = PendingIntent.getBroadcast(getApplicationContext(), ID, intent, 0);
    manager.set(AlarmManager.RTC_WAKEUP,calendar.getTimeInMillis(),pendingIntent);