刚接触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