AlarmManager 定时周期不精确
使用AlarmManager启动循环任务,代码如下
almgr = (AlarmManager)getSystemService(ALARM_SERVICE);
Intent intent = new Intent(tag);
pi = PendingIntent.getBroadcast(this, 1, intent, PendingIntent.FLAG_UPDATE_CURRENT);
almgr.setInexactRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(), 2000, pi);
定时周期是2000 ms,但是实际测试结果,receiver接受到的周期是1 min左右
12-10 16:13:52.882 24628-24628/com.example.tg.testalarmmanager D/MainService: onReceive
12-10 16:14:52.881 24628-24628/com.example.tg.testalarmmanager D/MainService: onReceive
12-10 16:15:52.880 24628-24628/com.example.tg.testalarmmanager D/MainService: onReceive
12-10 16:16:52.881 24628-24628/com.example.tg.testalarmmanager D/MainService: onReceive
12-10 16:17:52.881 24628-24628/com.example.tg.testalarmmanager D/MainService: onReceive
12-10 16:18:52.880 24628-24628/com.example.tg.testalarmmanager D/MainService: onReceive
12-10 16:19:52.881 24628-24628/com.example.tg.testalarmmanager D/MainService: onReceiveNote: Beginning with API 19 (KITKAT) alarm delivery is inexact: the OS will shift alarms in order to minimize wakeups and battery use. There are new APIs to support applications which need strict delivery guarantees; see setWindow(int, long, long, PendingIntent) and setExact(int, long, PendingIntent). Applications whose targetSdkVersion is earlier than API 19 will continue to see the previous behavior in which all alarms are delivered exactly when requested.
参考
API 19开始,使用Alarm.set()和Alarm.setRepeating()已经不保证精确性。
本文探讨了使用Android的AlarmManager进行循环任务调度时遇到的实际周期与预期不符的问题。通过示例代码展示了设置2000ms重复周期的任务实际上每隔约1分钟才被触发的现象,并解释了从API19开始,系统为了节省电量而对AlarmManager的定时精度进行了调整。
2776

被折叠的 条评论
为什么被折叠?



