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. 可以確認(rèn)發(fā)生在應(yīng)用生命期內(nèi)的的定時(shí)操作,考慮使用Handler Timer 和 Thread來主動(dòng)操作,避免了對(duì)于系統(tǒng)資源的訪問
best practices in using alarms:
在接收到alarm觸發(fā)的發(fā)出服務(wù)器請求事件與本地實(shí)際發(fā)出服務(wù)器請求之前,通過一些本地任務(wù)產(chǎn)生一些隨機(jī)時(shí)間,避免集中訪問服務(wù)器造成服務(wù)端異常
控制alarm的頻率
謹(jǐn)慎選擇alarm類型,涉及到是否 wake up device 的問題
謹(jǐn)慎選擇alarm的精度,以求更好的利用Android系統(tǒng)的對(duì)齊喚醒機(jī)制
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()控制喚醒a(bǔ)larm的精度,沒必要所有的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"
實(shí)現(xiàn)一個(gè)廣播監(jiān)聽 并在 manifest 中注冊
<receiver android:name=".SampleBootReceiver"?android:enabled="false">
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. 只有真正啟動(dòng)app并且授權(quán)開機(jī)的時(shí)候自動(dòng)啟動(dòng)之后 才允許應(yīng)用恢復(fù)注冊上去的alarm
http://developer.android.com/reference/android/os/SystemClock.html 對(duì)于各個(gè)clock接口使用的說明
實(shí)際使用
在開發(fā)一加管理中心時(shí),大量使用alarm作為定時(shí)任務(wù)的解決方案,完成了
定時(shí)校正當(dāng)前使用流量
流量用盡自動(dòng)斷網(wǎng)的檢查
低流量狀態(tài)下的流量使用情況監(jiān)控
替換Timer+service的實(shí)現(xiàn)方式