Android: Get all PendingIntents set with AlarmManager

后端 未结 3 1917
傲寒
傲寒 2020-11-27 10:55

I\'m setting an alarm like this:

alarmManager.set(AlarmManager.RTC_WAKEUP, alarmTime, pendingEvent);

I\'m interested in removing all the al

3条回答
  •  無奈伤痛
    2020-11-27 11:24

    You don't have to keep reference to it. Just define a new PendingIntent like exactly the one that you defined in creating it.

    For example:

    if I created a PendingIntent to be fired off by the AlarmManager like this:

    Intent alarmIntent = new Intent(getApplicationContext(), AlarmBroadcastReceiver.class);
    alarmIntent.setData(Uri.parse("custom://" + alarm.ID));
    alarmIntent.setAction(String.valueOf(alarm.ID));
    AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
    
    PendingIntent displayIntent = PendingIntent.getBroadcast(getApplicationContext(), 0, alarmIntent, 0);
    
    alarmManager.set(AlarmManager.RTC_WAKEUP, alarmDateTime, displayIntent);
    

    Then somewhere in your other code (even another activity) you can do this to cancel:

    Intent alarmIntent = new Intent(getApplicationContext(), AlarmBroadcastReceiver.class);
    alarmIntent.setData(Uri.parse("custom://" + alarm.ID));
    alarmIntent.setAction(String.valueOf(alarm.ID));
    AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
    
    PendingIntent displayIntent = PendingIntent.getBroadcast(getApplicationContext(), 0, alarmIntent, 0);
    
    alarmManager.cancel(displayIntent);
    

    The important thing here is to set the PendingIntent with exactly the same data and action, and other criteria as well as stated here http://developer.android.com/reference/android/app/AlarmManager.html#cancel%28android.app.PendingIntent%29

提交回复
热议问题