我使用 AlarmManager 编写了一个具有多个警报的应用程序。我还有一种方法可以取消所有当前/待处理的警报。它工作得很好,但是如果用户从最近的应用程序中关闭应用程序(警报仍然处于 Activity 状态,如预期),我的取消警报方法将不再工作(应用程序崩溃)。有什么办法解决这个问题吗?用户关闭应用程序后如何取消闹钟?
这就是我的闹钟的样子:
ArrayList<PendingIntent> intentArray = new ArrayList<PendingIntent>();
AlarmManager am = (AlarmManager) this.getSystemService(Context.ALARM_SERVICE);
...
Intent intent = new Intent(this, AlertReceiver.class);
Long cal = new GregorianCalendar().getTimeInMillis() + sms_in_x_minutes * 60 * 1000;
PendingIntent i1 = PendingIntent.getBroadcast(this, intent_id++, intent, 0);
am.set(AlarmManager.RTC_WAKEUP, cal, i1);
intentArray.add(i1);
这就是我的取消方法:
private void cancelAlarms(){
if(intentArray.size()>0){
for(int i=0; i<intentArray.size(); i++){
am.cancel(intentArray.get(i));
}
intentArray.clear();
}
}
我的猜测是,关闭应用程序后 intentArray
和 am
为空,并且 PendingIntents
未保存。但我不知道如何解决这个问题。
最佳答案
不要保留一系列待处理的 Intent 。正如您正确诊断的那样,应用程序关闭后您的数组为空,这会在您尝试再次访问它们时导致崩溃。
仅设置最早的警报。将警报 ID 保存到临时存储(例如 SharedPreferences
)。 (如果更容易,您还可以使用 ID 的常量值,因为您现在只需考虑一个警报)
当闹钟响起时,您可以将下一个最早的闹钟设置为执行的第一个任务。
如果您想取消闹钟并在 SharedPreferences
中保存 ID 值,请使用它重新创建 AlarmManager
并取消闹钟。如果没有 ID 值,则不会设置警报,也不需要取消。
关于java - 如何在应用程序关闭后取消闹钟,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31677171/