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