我在Android上通过AlarmManager禁用警报时遇到了一个小问题。
我在这里阅读了几篇文章和答案 并且不知道为什么我的cancel()报警不起作用。
我甚至用静态变量改变了我的代码......(但仍然不起作用) 代码存储在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)第二次点击按钮和日志说警报已尝试禁用但未禁用: - (
有任何线索吗?
答案 0 :(得分:0)
由于使用以下方法检查警报是否正在运行,我无法正常工作: (PendingIntent.getService(aContext,ID_FOR_STOP_ALARM,aiStopMyApp,PendingIntent.FLAG_NO_CREATE)== null)
我只是简单地改为:
1)当运行警报时,我在Prefs中存储alarmRunning = true以知道警报处于活动状态
2)取消闹钟时我在Prefs中设置alarmRunning = false以知道闹钟被禁用
启动时我知道Prefs的最后一个状态,我可以在必要时重新创建警报
这个解决方法有缺陷但有效,它只是假设当设置警报时,它必须由系统保持,无论什么[直到启动],但它应该如此: - )
在接下来的Q中见。 诉
答案 1 :(得分:0)
您可以使用以下方法检查闹钟是否处于活动状态:
PendingIntent.getService(aContext, ID_FOR_STOP_ALARM,aiStopMyApp,
PendingIntent.FLAG_NO_CREATE) != null
您与null
的比较是错误的。 PendingIntent.FLAG_NO_CREATE
的文档不正确。如果没有匹配的null
,则返回PendingIntent
,否则返回匹配的PendingIntent
。