How to Cancel AlarmManager on a Scheduled time

2019-02-11 09:18发布

问题:

How can I cancel one AlarmManager on a scheduled time, which was already started. I am starting one AlarmManager like this.

I want to cancel it after 5 hours. How can I do this?

AlarmManager service = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
Intent i = new Intent(context, MyStartServiceReceiver.class);
PendingIntent pending = PendingIntent.getBroadcast(context, 0, i, PendingIntent.FLAG_CANCEL_CURRENT);
Calendar cal = Calendar.getInstance();
cal.add(Calendar.SECOND, 30);
service.setInexactRepeating(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(), REPEAT_TIME, pending);

回答1:

set a another alarm for 5 hours from now. when this alarm alarm goes off then cancel the first alarm.

AlarmManager service = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
Intent intentForCancelling = new Intent(context, ReceiverForCancelling.class);
PendingIntent pending = PendingIntent.getBroadcast(context, 0, intentForCancelling,
PendingIntent.FLAG_CANCEL_CURRENT);
Calendar cal = Calendar.getInstance();
cal.roll(Calendar.HOUR_OF_DAY, 5);
service.set(AlarmManager.RTC_WAKEUP,
cal.getTimeInMillis(), pending)

and, from ReceiverForCancelling you can cancel the first alarm.
edit::

AlarmManager service = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
Intent intent = new Intent(context, ReceiverForCancelling.class);
PendingIntent pending = PendingIntent.getBroadcast(context, 0, intent,
PendingIntent.FLAG_CANCEL_CURRENT);
service.cancel(pending);


回答2:

You can try below code

Intent intentstop = new Intent(this, RefreshFeedsReceiver.class);
PendingIntent senderstop = PendingIntent.getBroadcast(this,
                            0, intentstop, 0);
AlarmManager alarmManagerstop = (AlarmManager) getSystemService(ALARM_SERVICE);
alarmManagerstop.cancel(senderstop);


回答3:

Check below code to set and cancel alarm

 public void SetAlarm(Context context)
 {
     AlarmManager am=(AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
     Intent i = new Intent(context, Alarm.class);
     PendingIntent pi = PendingIntent.getBroadcast(context, 0, i, 0);
     am.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(), 1000 * 60 * 10, pi); // Millisec * Second * Minute
 }

 public void CancelAlarm(Context context)
 {
     Intent intent = new Intent(context, Alarm.class);
     PendingIntent sender = PendingIntent.getBroadcast(context, 0, intent, 0);
     AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
     alarmManager.cancel(sender);
 }