我试图阻止重复警报。
我已经在网上寻找解决方案,但我的代码似乎很好......
它仍然没有停止警报......
这是一些代码(FM是文件写入对象)
public void StartAlarm() {
Intent intent = new Intent(getApplicationContext(), AlarmReciever.class);
PendingIntent sender = PendingIntent.getBroadcast(getApplicationContext(), 0, intent, 0);
AlarmManager am = (AlarmManager) getSystemService(ALARM_SERVICE);
Calendar alarm = Calendar.getInstance();
alarm.setTimeInMillis(System.currentTimeMillis());
alarm.set(Calendar.HOUR_OF_DAY, 15);
alarm.set(Calendar.MINUTE, 0);
long alarmCal=alarm.getTimeInMillis();
if (alarmCal<=new Date().getTime()) {
alarm.add(Calendar.DAY_OF_MONTH, 1);
}
am.setRepeating(AlarmManager.RTC_WAKEUP, alarm.getTimeInMillis(), AlarmManager.INTERVAL_DAY, sender);
FM.Write("startAlarm()");
}
public void StopAlarm() {
if (isAlarmRunning()) {
Intent intent = new Intent(getApplicationContext(), AlarmReciever.class);
PendingIntent sender = PendingIntent.getBroadcast(getApplicationContext(), 0, intent, 0);
AlarmManager alarmManager = (AlarmManager)getSystemService(ALARM_SERVICE);
alarmManager.cancel(sender);
FM.Write("alarm canceled");
isAlarmRunning();
}
public boolean isAlarmRunning() {
Intent intentToCheck = new Intent(getApplicationContext(),AlarmReciever.class);
boolean alarm = PendingIntent.getBroadcast(getApplicationContext(), 0, intentToCheck,
PendingIntent.FLAG_NO_CREATE) != null;
FM.Write("alarm = "+alarm);
if (!alarm) {
return false;
}
else
return true;
}
谢谢!
答案 0 :(得分:2)
您如何确认警报仍然存在?您需要使用等效的PendingIntent
(相同的意图,相同的标志)来停止警报,它确实有效。顺便说一句,您的isAlarmRunning()
方法检查是否存在PendingIntent
,这与正在注册的警报不同。即使警报已被删除,它也可以返回true
。
答案 1 :(得分:1)
在两个函数
中使用它PendingIntent sender = PendingIntent.getBroadcast(getApplicationContext(), 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
答案 2 :(得分:0)
完全同意Nokolay Elenkov,回答;正如问题注释中提到的那样,用户根据ToggleButton
是否处于活动状态来设置PendingIntent
。这与警报是否仍然注册有所不同。
要同时满足这两个条件,您必须同时取消它们;即取消闹钟,然后取消PendingIntent
。
Intent intent = new Intent(getApplicationContext(), AlarmReciever.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(getApplicationContext(), 0, intent, PendingIntent.FLAG_NO_CREATE);
myToggleButton.setChecked(pendingIntent != null);
// Setting the alarm
AlarmManager alarmManager = (AlarmManager) this.getSystemService(ALARM_SERVICE);
alarmManager.setRepeating();
// Canceling the alarm
alarmManager.cancel(pendingIntent);
// canceling the pendingIntent
PendingIntent.getBroadcast(getApplicationContext(), 0, intent, PendingIntent.FLAG_NO_CREATE).cancel();