Android Training Scheduling tasks

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 中注冊

<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. 只有真正啟動app并且授權開機的時候自動啟動之后 才允許應用恢復注冊上去的alarm

http://developer.android.com/reference/android/os/SystemClock.html 對于各個clock接口使用的說明

實際使用

在開發一加管理中心時,大量使用alarm作為定時任務的解決方案,完成了

定時校正當前使用流量

流量用盡自動斷網的檢查

低流量狀態下的流量使用情況監控

替換Timer+service的實現方式

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容