Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

Android 定時任務實作:用 AlarmManager 啟動與取消鬧鐘

編輯:關於 Android 程式設計

在 Android 開發中,若需要讓某段邏輯在指定時間被觸發、甚至週期性重複執行,AlarmManager 就是最經典的定時工具。它的運作方式是「到點發送一個 Intent」,再由對應的 BroadcastReceiver 接手處理。本文就來完整走一遍設定與取消的 both 流程。

一、送出定時廣播

首先要建立一個 Intent,明確指定要送達的接收者,再用 PendingIntent 把它包裝起來,最後交給 AlarmManager 排程:

Intent intent = new Intent("cn.pocketdigi.update.alarm");
intent.setClass(this, AlarmReceiver.class);

PendingIntent pi = PendingIntent.getBroadcast(this, 0, intent, 0);
// 建立一個 PendingIntent 物件,用來發送廣播
AlarmManager am = (AlarmManager) getSystemService(ALARM_SERVICE);
// 取得 AlarmManager 物件

// am.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + 3500, pi); // 只執行一次
am.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + 3500, 10000, pi); // 重複執行

這裡的關鍵在於兩組 API 的差異:set() 只觸發一次,而 setRepeating() 則會按照指定的間隔週期性重複觸發。以本例來說,它會在約 3.5 秒後首次觸發,之後每隔 10 秒再觸發一次。而 RTC_WAKEUP 這個參數代表鬧鐘會採用絕對時間,並能喚醒裝置。

二、在 manifest 中註冊接收者

接著要把 AlarmReceiver 註冊到 AndroidManifest.xml,並為它掛上對應的 action 過濾器:

<receiver android:name=".AlarmReceiver">
    <intent-filter>
        <action android:name="cn.pocketdigi.update.alarm" />
    </intent-filter>
</receiver>

三、撰寫 BroadcastReceiver

當鬧鐘到點,系統便會呼叫 AlarmReceiver 的 onReceive 方法。在這裡你可以印出日誌、處理業務,或甚至啟動一個 Activity:

public class AlarmReceiver extends BroadcastReceiver {
    private static final String TAG = "AlarmReceiver";

    @Override
    public void onReceive(Context context, Intent intent) {
        Log.v(TAG, "收到廣播");
        // Intent it = new Intent(context, AlarmActivity.class);
        // it.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        // context.startActivity(it);
    }
}

要特別注意的是:如果你打算在 onReceive 裡啟動 Activity,務必替 Intent 加上 Intent.FLAG_ACTIVITY_NEW_TASK 旗標,否則會因為缺乏合適的 Task 環境而拋出例外。

四、取消定時任務

想取消先前排好的鬧鐘,做法很直觀——用完全相同參數再建立一次 PendingIntent,然後呼叫 cancel():

Intent intent = new Intent("cn.pocketdigi.update.alarm");
intent.setClass(this, AlarmReceiver.class);

PendingIntent pi = PendingIntent.getBroadcast(this, 0, intent, 0);
AlarmManager alarm = (AlarmManager) getSystemService(ALARM_SERVICE);
alarm.cancel(pi);

這裡有個容易忽略的細節:PendingIntent 是靠一組「內在比對」來辨識彼此是否為同一個的,因此取消時的 Intent action、requestCode 等參數都必須與設定時一致,否則系統會認為這是兩個不同的鬧鐘,導致取消失敗。

五、另一種以 Intent 對象為導向的寫法

除了用 action 字串比對,也可以直接指定目標元件(Class),並搭配 ELAPSED_REALTIME_WAKEUP 這種基於「開機以來的經過時間」的鬧鐘型別:

Intent intent = new Intent(Main.this, alarmreceiver.class);
intent.setAction("repeating");
PendingIntent sender = PendingIntent.getBroadcast(Main.this, 0, intent, 0);

// 開始時間
long firstime = SystemClock.elapsedRealtime();

AlarmManager am = (AlarmManager) getSystemService(ALARM_SERVICE);
// 每 5 秒一個週期,不停地發送廣播
am.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP, firstime, 5 * 1000, sender);

這種寫法的好處是直接綁定目標元件、不必依賴 action 字串,語意更清晰;而 ELAPSED_REALTIME_WAKEUP 相對於 RTC 系列,更適合只需要「相對時間間隔」的週期性任務。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved