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()已经不保证精确性。