編輯:關於 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 這個參數代表鬧鐘會採用絕對時間,並能喚醒裝置。
接著要把 AlarmReceiver 註冊到 AndroidManifest.xml,並為它掛上對應的 action 過濾器:
<receiver android:name=".AlarmReceiver">
<intent-filter>
<action android:name="cn.pocketdigi.update.alarm" />
</intent-filter>
</receiver>
當鬧鐘到點,系統便會呼叫 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 等參數都必須與設定時一致,否則系統會認為這是兩個不同的鬧鐘,導致取消失敗。
除了用 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 系列,更適合只需要「相對時間間隔」的週期性任務。
Android 自定義 ViewGroup 佈局:onMeasure 與 onLayout 的實作要點
當系統內建的 LinearLayout、RelativeLayout 都無法滿足排列需求時,就得自己繼承 ViewGroup 寫一個佈局。自定義 ViewGroup 的核
深入解析 Android 官方 MVP 架構示例項目
本文就來具體看看官方示例究竟是如何實現 MVP 的。先從總體輪廓說起,業務代碼這裡僅列出任務詳情頁(taskDetail)的相關類,其他業務模組的組織方式類似。 基
Android 資料儲存入門:SQLiteDatabase 與 SQLiteOpenHelper 實務整理
SQLite 是 Android 常用的本機資料庫。本文整理 SQLiteDatabase 的開啟、建表、新增、修改、刪除、查詢,以及 SQLiteOpenHelper
Android Studio 系列教程(一):從下載安裝到第一個 HelloWorld
背景 Android Studio 是 Google 在 2013 年 I/O 大會上為 Android 開發推出的新一代 IDE,基於 IntelliJ IDEA 改造