简体   繁体   English

取消在Android中重复闹钟

[英]Cancel repeating Alarm in Android

I've created a repeating Alarm that goes off every minute. 我创建了一个重复警报,每分钟响一次。 I created a class with 2 static functions to start and cancel the alarm. 我创建了一个具有2个静态函数的类,以启动和取消警报。 I did this so I can start and cancel it from multiple places. 我这样做是为了可以从多个地方开始和取消它。 Starting the alarm works fine, but canceling is doesn't. 发出警报可以正常工作,但不能取消。 The context I use when calling startAlarm and cancelAlarm is getApplicationContext() . 我在调用startAlarmcancelAlarm时使用的上下文是getApplicationContext() I think it might be a problem with the context but I'm not sure. 我认为这可能与上下文有关,但我不确定。 Any ideas? 有任何想法吗?

This is my class 这是我的课

public class Alarm {

  public  static PendingIntent pendingIntent;
  public static  AlarmManager manager;
  public static Intent alarmIntent;

    public static void startAlarm(Context context) {

    Log.e("ALARM", "------------STARTED----------------");
    alarmIntent = new Intent((context), AlarmReceiver.class);
    alarmIntent.setAction("NOTIFICATION_ALARM");
    pendingIntent = PendingIntent.getBroadcast(context, 0, alarmIntent, 0);
    manager = (AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
    int alarmType = AlarmManager.RTC_WAKEUP;
    Calendar cal = Calendar.getInstance();


    long intervalTime = 1 * 60 * 1000;
    manager.setRepeating(alarmType, cal.getTimeInMillis(), intervalTime, pendingIntent);

  }

    public static void cancelAlarm(Context context) {

      alarmIntent = new Intent(context, AlarmReceiver.class);
      pendingIntent = PendingIntent.getBroadcast(context, 0, alarmIntent, 0);
      manager = (AlarmManager)     context.getSystemService(Context.ALARM_SERVICE);
      if (manager != null) {
          Log.e("ALARM", "------------STOPPED----------------");
          manager.cancel(pendingIntent);
      }
    }
}

Use the cancel() on AlarmManager with its PendingIntent to the one you used with setRepeating(): AlarmManagercancel()PendingIntent与setRepeating()一起使用:

Intent intent = new Intent(this, AlarmReceive.class);
PendingIntent sender = PendingIntent.getBroadcast(this, 0, intent, 0);
AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);

The Intent on the PendingIntent you're canceling needs to match that which you used to set the alarm, as defined by the Intent#filterEquals(Intent) method. 根据Intent Intent#filterEquals(Intent)方法的定义,要取消的PendingIntent上的Intent需要与设置警报时使用的Intent#filterEquals(Intent) That is, you need to call alarmIntent.setAction("NOTIFICATION_ALARM"); 也就是说,您需要调用alarmIntent.setAction("NOTIFICATION_ALARM"); in the cancelAlarm() method, as well. cancelAlarm()方法中也是如此。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM