在 Android 中要做定時啟動,最常見的做法就是 AlarmManager:註冊一個時間點與一個 Intent 到系統,時間一到,系統就替你送出廣播、啟動服務或打開頁面。
這裡的「要執行的動作」通常用 PendingIntent 包裝。可以把它理解成 Intent 的封裝包,也就是「未來要執行的 Intent」。兩者的差別在於:Intent 還需要你自行呼叫 startActivity、startService 或 sendBroadcast 才會生效;PendingIntent 已經把這個動作包在裡面,可以直接交給系統執行。
// 啟動 service
Intent intent = new Intent(instance, RecommendService.class);
intent.putExtra("userInfoBody", userInfoBody);
intent.putExtra("isDynamic", true);
intent.putExtra("content", comment);
if (!TextUtils.isEmpty(sayhiOrCollect)) {
intent.putExtra("sayhiOrCollect", sayhiOrCollect);
}
PendingIntent sender = PendingIntent.getService(instance, 1, intent, PendingIntent.FLAG_UPDATE_CURRENT);
// 四個參數依序為 context、區分不同 PendingIntent 的 requestCode、intent,以及重複時的處理策略
long firstTime = SystemClock.elapsedRealtime();
firstTime += 1 * 1000;
// 排定鬧鐘
AlarmManager am = (AlarmManager) getSystemService(ALARM_SERVICE);
am.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP, firstTime, 10 * 60 * 1000, sender);
注意:兩個 PendingIntent 是否「相同」,取決於 operation 是否一致,且 Intent 的 action、data、categories、components、flags 都相同;但 Extra 可以不同。這正是 intent 攜帶內容無法更新的根源,解法就是加上 PendingIntent.FLAG_UPDATE_CURRENT。
getService() 最後一個參數常用的常數有:
· FLAG_CANCEL_CURRENT:若系統已有相同的 PendingIntent,先取消舊的再重建。
· FLAG_NO_CREATE:若目前不存在相同的 PendingIntent,就不建立,直接回傳 null。
· FLAG_ONE_SHOT:只用一次,send() 觸發後會自動 cancel(),再呼叫 send() 將丟出 SendIntentException。
· FLAG_UPDATE_CURRENT:若存在對等的 PendingIntent,沿用該物件,但用新的 Intent 內容(例如 Extras)更新它。
(1)set(int type, long startTime, PendingIntent pi):設定一次性鬧鐘。
(2)setRepeating(int type, long startTime, long intervalTime, PendingIntent pi):設定固定間隔的重複鬧鐘。
(3)setInexactRepeating(int type, long startTime, long intervalTime, PendingIntent pi):同樣是重複鬧鐘,但間隔不保證精準,換取更省電的排程。
int type(鬧鐘類型),常用值有五種:
· ELAPSED_REALTIME:使用相對時間(自開機起算),裝置睡眠時不會觸發,值為 3。
· ELAPSED_REALTIME_WAKEUP:使用相對時間,睡眠時會喚醒裝置並執行,值為 2。
· RTC:使用絕對時間(當前系統時間),睡眠時不觸發,值為 1。
· RTC_WAKEUP:使用絕對時間,睡眠時會喚醒裝置,值為 0。
· POWER_OFF_WAKEUP:使用絕對時間,關機狀態下也能提示,值為 4;但此狀態受 SDK 版本影響,部分版本並不支援。
long startTime:第一次執行的時間,單位毫秒。它必須與 type 搭配:相對時間用 SystemClock.elapsedRealtime(),絕對時間用 System.currentTimeMillis()。
long intervalTime:相鄰兩次執行的間隔,單位毫秒,僅後兩個方法需要。
PendingIntent pi:綁定的執行動作。取用方式必須與實作手段一致——用服務就用 getService(),用廣播就用 getBroadcast(),用 Activity 就用 getActivity()。三者用錯不會報錯,但提示永遠不出現,這是最容易浪費時間的地方。
public class RecommendService extends IntentService {
@Override
protected void onHandleIntent(Intent intent) {
}
}
IntentService 的優勢在於:多次定時觸發送來的 intent 會依序處理,而且不必自己開子執行緒,因為它已經為每個 intent 準備好 worker thread。