0

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. 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(). 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);
      }
    }
}
Flexo
  • 87,323
  • 22
  • 191
  • 272
Jason Lie
  • 159
  • 3
  • 12

1 Answers1

0

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. That is, you need to call alarmIntent.setAction("NOTIFICATION_ALARM"); in the cancelAlarm() method, as well.

Mike M.
  • 38,532
  • 8
  • 99
  • 95