闹钟(Alarm)

刚接触android开发的时候,我是用定时器(Timer)来实现定时任务,产品发布后,部分用户反馈定时任务没有执行。很长一段时间之后,才意识到cpu休眠之后,timer也是不起作用的。执行定时任务要用到闹钟(Alarm)。


引用stackoverflow的回答

A Timer will start a thread that will keep track of when to start your code. If the device goes asleep, so will the timer thread and your code won't be executed on time. AlarmManager's alarms, on the other hand, are kernel-level. Depending on how you register them, you can request to wake up the device, or execute the next time something wakes up the device. Alarm's are generally preferable and use less resources

http://stackoverflow.com/questions/14579034/difference-between-timer-and-alarmmanager


Alarm需要知道几个要点


闹钟类型

ELAPSED_REALTIME      设备启动运行多少时间后,执行闹钟任务。如果cpu处于休眠,则推迟至cpu唤醒时执行。

ELAPSED_REALTIME_WAKEUP 同ELAPSED_REALTIME,差别在于它会唤醒cpu,执行任务。

RTC            具体某个时间点上运行任务,比如早上七点执行闹钟。如果cpu处于休眠,则推迟至cpu唤醒时执行。

RTC_WAKEUP        同RTC,差别在于它会唤醒cpu,执行任务。


时间精确度

AlarmManager#setRepeating        精确,cpu被唤醒的频次增加,电量损耗相对大

AlarmManager#setInexactRepeating    非精确,这是较常用的方法。几个时间间隔相差不大的闹钟任务一起执行,仅需要唤醒一次cpu

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值