I have a hudge problem with disabling alarms form AlarmManager on Android.
I have read several articles and answers here and no clue why my cancel() for alarm does not work.
I have even changed my code to this, with static variables... (and still does not work) the code is stored in Utility.class other than the one which calls the method.
public class Utilities {
public static final int ID_FOR_STOP_ALARM = 770;
private static PendingIntent piStopMyApp;
private static Intent aiStopMyApp;
private static Context aContext;
public static boolean toggleAlarmToStopMyApp(Context context) {
if(aContext == null){
aContext = context;
}
if (aiStopMyApp == null) {
aiStopMyApp = new Intent(aContext, MyAppServiceStop.class);
}
PendingIntent piStopMyAppCheck = PendingIntent.getService(aContext,
ID_FOR_STOP_ALARM, aiStopMyApp, PendingIntent.FLAG_UPDATE_CURRENT);
AlarmManager alarm = (AlarmManager) aContext
.getSystemService(Context.ALARM_SERVICE);
if (piStopMyApp == null) {
piStopMyApp = PendingIntent.getService(aContext, ID_FOR_STOP_ALARM,
aiStopMyApp, PendingIntent.FLAG_UPDATE_CURRENT);
}
if (piStopMyAppCheck == null) {
SharedPreferences p = aContext.getSharedPreferences(
Utilities.APP_SHARED_PREFS, Context.MODE_PRIVATE);
int h = p.getInt(Utilities.ALARM_STOP_H, 23);
int m = p.getInt(Utilities.ALARM_STOP_M, 0);
Calendar cur_cal = new GregorianCalendar();
cur_cal.setTimeInMillis(System.currentTimeMillis());
Calendar cal = new GregorianCalendar();
cal.set(Calendar.YEAR, cur_cal.get(Calendar.YEAR));
cal.set(Calendar.MONTH, cur_cal.get(Calendar.MONTH));
cal.set(Calendar.DAY_OF_MONTH, cur_cal.get(Calendar.DAY_OF_MONTH));
cal.set(Calendar.HOUR_OF_DAY, h);
cal.set(Calendar.MINUTE, m);
cal.set(Calendar.SECOND, 0);
cal.set(Calendar.MILLISECOND, 0);
if (isLoggingEnabled) {
Log.d(TAG, "Enable ALARM for STOP " + cal.toString());
}
alarm.setRepeating(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(),
AlarmManager.INTERVAL_DAY, piStopMyApp);
} else {
alarm.cancel(piStopMyApp);
if (isLoggingEnabled) {
Log.d(TAG, "Disable ALARM for STOP = "
+ (PendingIntent.getService(aContext,
ID_FOR_STOP_ALARM,aiStopMyApp,
PendingIntent.FLAG_NO_CREATE) == null));
}
}
piStopMyAppCheck = null;
return (PendingIntent.getService(aContext, ID_FOR_STOP_ALARM, aiStopMyApp,
PendingIntent.FLAG_NO_CREATE) != null);
}
}
and it simply does not work, enables alarm and cannot disable it :-(
button in other activity runs such code:
boolean alarmUpStop = Utilities.toggleAlarmToStopMyApp(getApplicationContext());
1) the first hit to the button above and Alarms are scheduled properly, logs shows service triggered
2) the second hit to the button and logs say that alarm was tried to disable but it wasn't disabled :-(
Any clue?