如何在预定时间内取消AlarmManager

时间:2012-07-31 05:36:56

标签: android broadcastreceiver alarmmanager

如何在已经开始的预定时间取消一个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);

3 个答案:

答案 0 :(得分: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);

答案 1 :(得分:0)

您可以尝试以下代码

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

答案 2 :(得分:0)

检查以下代码以设置和取消警报

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