Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
您现在的位置: Android教程網 >> Android系統教程 >  >> Android 技術 >> Android 開發實例

AlarmManager 實戰:全局定時器,延遲一次或週期性執行任務

編輯:Android 開發實例

AlarmManager 有人叫它全局定時器,有人叫它鬧鐘。從實際使用感受出發,「全局定時器」這個名字更貼切——因為它能在自己的應用程式之外觸發,即使 Activity 已經不在前景,約定的時間到了照樣會送出訊號。

它的定位與 Timer 相似,都支援兩種模式:延遲指定時長後執行一次,或以固定週期重複執行。差別在於 AlarmManager 搭配 Intent 運作,因此可以定時啟動 Activity、發送 Broadcast,或拉起 Service。

模式一:指定時長後執行一次

// 目標:五秒後發送一個廣播,由接收器跳出 Toast
Intent intent = new Intent(Main.this, alarmreceiver.class);
intent.setAction("short");

PendingIntent sender = PendingIntent.getBroadcast(Main.this, 0, intent, 0);

Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(System.currentTimeMillis());
calendar.add(Calendar.SECOND, 5);

AlarmManager alarm = (AlarmManager) getSystemService(ALARM_SERVICE);
alarm.set(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), sender);

// 也可以直接寫成:
// alarm.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + 5 * 1000, sender);

Toast.makeText(Main.this, "五秒後 alarm 開啟", Toast.LENGTH_LONG).show();

對應的廣播接收器(別忘了在 manifest 註冊):

public static class alarmreceiver extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        if ("short".equals(intent.getAction())) {
            Toast.makeText(context, "short alarm", Toast.LENGTH_LONG).show();
        } else {
            Toast.makeText(context, "repeating alarm", Toast.LENGTH_LONG).show();
        }
    }
}

模式二:週期性執行

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 秒為週期,從 firstime 開始反覆觸發
am.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP,
        firstime, 5 * 1000, sender);

看懂兩組時間型別的意義

AlarmManager 的 type 參數決定了「時間怎麼算」,選錯會導致行為不符預期:

  • RTC_WAKEUP:以真實世界時鐘為基準,會喚醒裝置。適合「在下午三點提醒我」這類真實時刻。
  • RTC:同上但不喚醒裝置,裝置睡著時會延後到醒來才觸發。
  • ELAPSED_REALTIME_WAKEUP:以開機後經過的時間為基準,不受使用者改系統時間影響,會喚醒裝置。適合「每 5 秒輪詢一次」這類相對間隔。
  • ELAPSED_REALTIME:同上但不喚醒裝置。

因此上例的兩種模式分別選了不同的 type:絕對時刻用 RTC,週期輪詢用 ELAPSED_REALTIME。這不是隨手挑的,而是由語意決定。

取消與實務注意事項

要取消已排定的鬧鐘,用相同參數重建 PendingIntent 再取消:

alarm.cancel(sender);
sender.cancel();

這裡有個關鍵細節:PendingIntent 的相等性由「Intent 的 action、data、type、類別」決定,不包含 extras。也就是說兩個 action 相同、extras 不同的 Intent 會被視為同一個 PendingIntent,後者會覆蓋前者的內容。若需要多組並存,務必讓 action 或 data 有所區別。

另外三點值得牢記:

  • 不要用 AlarmManager 做高頻(秒級以下)排程,它天生是為「省電的低頻喚醒」設計的,短間隔請用 Handler。
  • 從 Android 5.0 起系統引入了 Doze 與 App Standby,長時間閒置時鬧鐘會被延後批次處理;需要精準對時的場景應改用 setExactAndAllowWhileIdle() 或 WorkManager。
  • 從 Android 12 開始,設定精確鬧鐘需要 SCHEDULE_EXACT_ALARM 權限,使用者也可在系統設定中撤銷。

把這幾點放進來,你就擁有一個真正可靠的背景排程方案,而不只是能跑起來的示例。

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