我在服务上设置了重复警报,并决定从被调用的服务中重置警报最方便。原因是该服务已经有代码来检查它是否在用户定义的时间表(时间范围)内。当超出时间范围时,它会将警报重置为在用户选择的未来时间开始。也许我正在接近这个错误,但我会把这个问题放在那里,看看你的想法。
活动通过创建重复警报来启动服务:
//Activity
Calendar cal = Calendar.getInstance();
Intent intent = new Intent(getApplicationContext(), MyService.class);
intent.setData(Uri.parse("MyService://identifier"));
PendingIntent pIntent = PendingIntent.getService(getApplicationContext(), 0, intent, 0);
AlarmManager alarm = (AlarmManager)getSystemService(ALARM_SERVICE);
alarm.setInexactRepeating(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(),
intervalInMins*60000, pIntent);
该服务有这样的东西:
//Service
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Uri Action = intent.getData();
try {
if (Action.equals(Uri.parse("MyService://identifier"))) {
//Simplifying the code here: CalculatedOffset is determined from the current time
//and scheduled start time. intervalInMins is read from settings.
if (!WithinSchedule()) {
Calendar cal = Calendar.getInstance();
PendingIntent pIntent = PendingIntent.getService(getApplicationContext(), 0, intent, 0);
AlarmManager alarm = (AlarmManager)getSystemService(ALARM_SERVICE);
alarm.setInexactRepeating(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis() + CalculatedOffset,
intervalInMins*60000, pIntent);
}
}
} catch (NullPointerException np) {
np.printStackTrace();
}
return Service.START_REDELIVER_INTENT;
}
我希望重新使用意图来重置重复警报。使用这个新代码,我看到多个警报在开始时间到来时连续快速触发。它不应该像那样乱跑,而是应该像在调度重置之前那样定期触发。我需要在调试器中捕获它,但还不能确定确切的条件。我对警报的理解完全在这里吗?有一个更好的方法吗?
附录:其中一个问题是我正在使用 RootTools 来获得超级用户权限,以便在 Android 4.2 的飞行模式下工作。在调度之前这不是问题,但是我怀疑 su 在警报堆积时是否阻塞了很长时间。