我的MainActivity的OnCreate方法调用了scheduleAlarm方法,我在另一个名为PollReceiver的类中实现了该方法。它的代码如下:
Intent iWeekly = new Intent(context, ScheduledWeeklyService.class);
PendingIntent piWeekly = PendingIntent.getBroadcast(context, 0, iWeekly, 0);
AlarmManager alarmMgrWeekly = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
alarmMgrWeekly.setRepeating(AlarmManager.RTC_WAKEUP, scheduleTime, Constants.PERIOD_WEEKLY, piWeekly);
我的应用程序还有一个togglebutton来启用或禁用警报。
togglebutton代码如下所示:
public void enableDisableScheduler(View v){
if (btnEnableDisableScheduler.isChecked()) {
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(ctx);
SharedPreferences.Editor editor = prefs.edit();
editor.putBoolean("toggleButton", tb.isChecked());
editor.commit();
// Enable all alarms
PollReceiver.scheduleAlarms(this);
Log.i(TAG, "alarm is turned on");
} else {
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(ctx);
SharedPreferences.Editor editor = prefs.edit();
editor.putBoolean("toggleButton", tb.isChecked());
editor.commit();
// Cancel all alarms
Intent iWeekly = new Intent(context, ScheduledWeeklyService.class);
PendingIntent piWeekly = PendingIntent.getBroadcast(context, 0, iWeekly, 0);
AlarmManager alarmMgrWeekly = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
try {
alarmMgrWeekly.cancel(piWeekly);
} catch (Exception e) {
Log.e(TAG, "alarm is not cancelled");
}
Log.i(TAG, "alarm is turned off");
}
}
现在,一切正常。所以,当我退出app&重新打开它,上面的代码再次被解雇&它重新安排了那些效果很好的警报。
我试图通过放下代码来避免重新安排警报,但它不起作用。非常感谢任何想法或帮助。如果我关闭切换按钮&把它打开警报没有按计划进行,因为不知何故它不满足以下条件&如果条件不符合以下条件。任何线索或想法如何做到这一点?
boolean weeklyAlarmUp = (PendingIntent.getBroadcast(context, 0, new Intent(context, ScheduledWeeklyService.class), PendingIntent.FLAG_NO_CREATE) != null);
if (!weeklyAlarmUp) {
Intent iWeekly = new Intent(context, ScheduledWeeklyService.class);
PendingIntent piWeekly = PendingIntent.getBroadcast(context, 0, iWeekly, 0);
AlarmManager alarmMgrWeekly = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
alarmMgrWeekly.setRepeating(AlarmManager.RTC_WAKEUP, scheduleTime, Constants.PERIOD_WEEKLY, piWeekly);
}
答案 0 :(得分:0)
此代码用于检查警报是否已安排:
boolean weeklyAlarmUp = (PendingIntent.getBroadcast(context, 0, new Intent(context,
ScheduledWeeklyService.class), PendingIntent.FLAG_NO_CREATE) != null);
不起作用,因为您依赖PendingIntent
的现有内容。当您取消闹钟时,即使闹钟已被取消,您也不会取消PendingIntent
,因此它仍然存在。
要解决此问题,请确保在取消闹钟时取消PendingIntent
,如下所示:
// cancel alarm
alarmMgrWeekly.cancel(piWeekly);
// Cancel PendingIntent
piWeekly.cancel();