我需要每10分钟计划一次任务.
因为在Lollipop和更高版本setRepeating()
是不精确的,我使用setExact()
和(在警报发射)我在10分钟内设置新的确切警报.
private void setAlarm(long triggerTime, PendingIntent pendingIntent) {
int ALARM_TYPE = AlarmManager.ELAPSED_REALTIME_WAKEUP;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
alarmManager.setExact(ALARM_TYPE, triggerTime, pendingIntent);
} else {
alarmManager.set(ALARM_TYPE, triggerTime, pendingIntent);
}
}
Run Code Online (Sandbox Code Playgroud)
triggerTime
计算 SystemClock.elapsedRealtime() + 600_000;
当警报触发时,首先我计划新警报,然后我才会执行我的计划任务.
setAlarm();
mySheduledTask;
Run Code Online (Sandbox Code Playgroud)
WAKE_LOCK
我的清单中有权限.
当我在Android 4上测试它时 - 它工作得很完美(偏差可能是12-15 毫秒).
但是当我在小米Redmi Note 3 Pro(5.1.1)上运行应用程序时 - 偏差可能长达15秒!
例如,我在我的日志文件中看到:第一次运行是在1467119934477(RTC时间),第二次是在1467120541683.差异是607_206毫秒,而不是600_000,因为它是计划好的!
我错过了什么?什么是模拟系统警报行为的方法(它是可以描述我的大头钉的最接近的用例)?
PS.我使用IntentServicePendingIntent = PendingIntent.getService(context, 0, myIntent, 0);