Android の AlarmManager からアラームを無効にする際に問題があります。
ここでいくつかの記事と回答を読みましたが、アラームのキャンセル()が機能しない理由がわかりません。
静的変数を使用して、コードをこれに変更しました...(それでも機能しません)コードは、メソッドを呼び出すもの以外の Utility.class に格納されます。
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);
}
}
そして、それは単に機能せず、アラームを有効にし、無効にすることはできません:-(
他のアクティビティのボタンは次のようなコードを実行します:
boolean alarmUpStop = Utilities.toggleAlarmToStopMyApp(getApplicationContext());
1) 上のボタンを最初に押すと、アラームが適切にスケジュールされ、ログはサービスがトリガーされたことを示します
2) ボタンとログへの 2 回目のヒットは、アラームが無効にされようとしたが無効にならなかったことを示しています :-(
どんな手掛かり?