如何取消AlarmManager在预定的时间(How to Cancel AlarmManager

2019-06-26 15:01发布

我怎样才能取消预定的时间,这是已经开始了一个AlarmManager。 我开始一个AlarmManager这样。

我想5小时后取消。 我怎样才能做到这一点?

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);

Answer 1:

从现在设置5小时,其他报警。 当此报警器报警熄灭然后取消第一报警。

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)

并且,从ReceiverForCancelling可以取消第一个报警。
编辑::

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);


Answer 2:

你可以试试下面的代码

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


Answer 3:

检查下面的代码来设置和取消报警

 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);
 }


文章来源: How to Cancel AlarmManager on a Scheduled time