Schedule tasks with alarms
Alarms用途
repeating alarms are a good choice for scheduling regular events or data lookups.
They let you fire Intents at set times and/or intervals.
You can use them in conjunction with broadcast receivers to start services and perform other operations.
They operate outside of your application, so you can use them to trigger events or actions even when your app is not running, and even if the device itself is asleep.
They help you to minimize your app's resource requirements. You can schedule operations without relying on timers or continuously running background services.
Note:For timing operations that are guaranteed to occurduring the lifetime of your application, instead consider using the Handler class in conjunction with Timer and Thread. This approach gives Android better control over system resources. 可以确认发生在应用生命期内的的定时操作,考虑使用Handler Timer 和 Thread来主动操作,避免了对于系统资源的访问
best practices in using alarms:
在接收到alarm触发的发出服务器请求事件与本地实际发出服务器请求之前,通过一些本地任务产生一些随机时间,避免集中访问服务器造成服务端异常
控制alarm的频率
谨慎选择alarm类型,涉及到是否 wake up device 的问题
谨慎选择alarm的精度,以求更好的利用Android系统的对齐唤醒机制
Avoid basing your alarm on clock time if possible.
set a repeating alarm
组成元素 alarm type, trigger time, interval, pending Intent
choose alarm type
There are two general clock types for alarms: "elapsed real time" and "real time clock" (RTC).
UTC setting an alarm based on the passage of time (for example, an alarm that fires every 30 seconds) since it isn't affected by time zone/locale
Used when simply need your alarm to fire at a particular interval
RTC The real time clock type is better suited for alarms that are dependent on current locale.
need your alarm to fire at a particular time of day
使用setInexactRepeating()控制唤醒alarm的精度,没必要所有的alarm请求都是精确的
Start an Alarm When the Device Boots
By default, all alarms are canceled when a device shuts down. To prevent this from happening, you can design your application to automatically restart a repeating alarm if the user reboots the device.
Set the RECEIVE_BOOT_COMPLETED permission -- "android:name="android.permission.RECEIVE_BOOT_COMPLETED"
实现一个广播监听 并在 manifest 中注册
Notice that in the manifest, the boot receiver is set to android:enabled="false". This means that the receiver will not be called unless the application explicitly enables it. This prevents the boot receiver from being called unnecessarily. 只有真正启动app并且授权开机的时候自动启动之后 才允许应用恢复注册上去的alarm
http://developer.android.com/reference/android/os/SystemClock.html 对于各个clock接口使用的说明
实际使用
在开发一加管理中心时,大量使用alarm作为定时任务的解决方案,完成了
定时校正当前使用流量
流量用尽自动断网的检查
低流量状态下的流量使用情况监控
替换Timer+service的实现方式