Android之AlarmManager

本文探讨了使用Android的AlarmManager进行循环任务调度时遇到的实际周期与预期不符的问题。通过示例代码展示了设置2000ms重复周期的任务实际上每隔约1分钟才被触发的现象,并解释了从API19开始,系统为了节省电量而对AlarmManager的定时精度进行了调整。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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: onReceive

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

AlarmManager triger time设置成过去的时间,当set之后,会立即触发该事件

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值