Android 通过切换按钮取消后警报未打开
我的MainActivity的OnCreate方法调用scheduleAlarm方法,我在另一个名为PollReceiver的类中实现了该方法。其中包含以下代码:Android 通过切换按钮取消后警报未打开,android,android-intent,broadcastreceiver,alarmmanager,android-pendingintent,Android,Android Intent,Broadcastreceiver,Alarmmanager,Android Pendingintent,我的MainActivity的OnCreate方法调用scheduleAlarm方法,我在另一个名为PollReceiver的类中实现了该方法。其中包含以下代码: Intent iWeekly = new Intent(context, ScheduledWeeklyService.class); PendingIntent piWeekly = PendingIntent.getBroadcast(context, 0, iWeekly, 0); AlarmManag
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代码如下所示:
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");
}
}
现在,一切正常。因此,当我退出应用程序并再次打开它时,上面的代码会再次被触发&它会重新安排报警时间,效果也很好
我试图通过下面的代码来避免警报的重新调度,但它不起作用。非常感谢您的任何想法或帮助。如果我关闭切换按钮并将其打开,则不会安排报警,因为不知何故,它不满足以下条件,也不满足以下条件。有什么线索或想法如何做到这一点吗
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);
}
此代码用于检查是否已计划报警:
boolean weeklyAlarmUp = (PendingIntent.getBroadcast(context, 0, new Intent(context,
ScheduledWeeklyService.class), PendingIntent.FLAG_NO_CREATE) != null);
无法工作,因为您依赖的是现有的pendingent
。当您取消报警时,您没有取消挂起内容
,因此它仍然存在,即使报警已被取消
要解决此问题,请确保在取消报警时也取消了pendingent
,如下所示:
// cancel alarm
alarmMgrWeekly.cancel(piWeekly);
// Cancel PendingIntent
piWeekly.cancel();