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

Android 系列:Alarm 定時提醒的使用方式

編輯:Android 開發實例

Alarm 的設計目的是「在預定時間觸發一個 Intent」,它是一套獨立於應用程式之外的提醒機制。當鬧鐘時間到,系統會廣播這個 Intent;即使你的應用程式當時沒有在跑,也會被喚醒啟動,不需要應用程式事先開著或處於活動狀態。

所有的 Alarm 都由 AlarmManager 統一管理。

基本寫法

 1  // 1. 建立 Intent 與 PendingIntent
 2  Intent intent = new Intent(this, OneShotAlarm.class);
 3  PendingIntent sender = PendingIntent.getBroadcast(this, 0, intent, 0);
 4
 5  // 2. 設定鬧鐘時間(這裡是 30 秒後)
 6  Calendar calendar = Calendar.getInstance();
 7  calendar.setTimeInMillis(System.currentTimeMillis());
 8  calendar.add(Calendar.SECOND, 30);
 9
10  // 除了 Calendar,也可以用 SystemClock.elapsedRealtime()
11  long firstTime = SystemClock.elapsedRealtime();
12
13  AlarmManager am = (AlarmManager) getSystemService(ALARM_SERVICE);
14
15  // 只響一次
16  am.set(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), sender);
17
18  // 重複響,每 15 秒一次
19  am.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP, firstTime, 15 * 1000, sender);
20
21  // 取消:只要拿著同一個 PendingIntent 即可
22  am.cancel(sender);

幾個關鍵點

為什麼要用 PendingIntent 而不是直接傳 Intent? PendingIntent 授權別的應用程式(這裡是系統的 Alarm 服務)以你的身分執行一段操作。它也讓「取消」變得可能——因為系統是靠 PendingIntent 來識別每一個已註冊的鬧鐘,cancel() 時必須給它同一個物件(相同的 requestCode 與 Intent 比對特徵)才會生效。

兩組時間基準不要搞混: RTC_WAKEUP 系列走真實世界時鐘,會受使用者手動改時間影響,並會喚醒裝置;ELAPSED_REALTIME_WAKEUP 則從開機後開始累計,不受改時鐘影響,同樣會喚醒裝置。若加上 _WAKEUP 以外的變體(如 ELAPSED_REALTIME),到點時裝置若休眠中,會等到醒來才觸發。

精準度:基於電量考量,系統在較新版本中會把非精確的 Alarm 批次處理,實際觸發時間可能晚於設定值。需要精準(例如鬧鐘類應用)時應改用 setExact()/setExactAndAllowWhileIdle()。

注意:Alarm 是透過廣播 Intent 觸發的,所以 BroadcastReceiver、Activity、Service 都收得到它的 Intent 並加以處理——最常見的組合是配一個 BroadcastReceiver,收到後再決定要發通知、啟動 Service 還是更新資料。

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