先簡單說明 AlarmManager 的機制:它是一個全局定時器(鬧鐘),會在指定時刻為我們廣播一個指定的 Intent,主要有兩種形式:一是在特定時刻到來時執行某項操作;二是以固定時間間隔週期性執行操作。
Android 提供了四種鬧鐘類型:
(1) ELAPSED_REALTIME:在指定延時後發送 Intent,但不喚醒設備。
(2) ELAPSED_REALTIME_WAKEUP:在指定延時後發送 Intent,並喚醒設備;延時會把開機以來的時間 SystemClock.elapsedRealtime() 計入。
(3) RTC:在指定時刻發送 Intent,但不喚醒設備。
(4) RTC_WAKEUP:在指定時刻發送 Intent,並喚醒設備。
set():註冊一個鬧鐘。
setRepeating():註冊一個會重複的鬧鐘。
setInexactRepeating():註冊不精確的重複鬧鐘,相對更節能,因為系統可能把幾個相近的鬧鐘合併執行、減少喚醒次數;內建的 interval 有 INTERVAL_FIFTEEN_MINUTES、INTERVAL_HALF_HOUR、INTERVAL_HOUR、INTERVAL_HALF_DAY、INTERVAL_DAY 等。
cancel():取消一個已註冊的鬧鐘。
setTimeZone()、setTime():設定時區與系統時鐘,需相應權限。
Intent 是一個意圖,描述想要啟動的 Activity、Broadcast 或 Service,並透過 startActivity、startService 或 sendBroadcast 來執行。
PendingIntent 則可視為對 Intent 的包裝,它持有所包裝的 Intent 與當前的 App Context,供本 App 或其他 App 呼叫。外部 App 執行 PendingIntent 時,其實是延時執行其中描述的 Intent;即使原 App 已不存在,也能透過 PendingIntent 裡的 Context 來執行 Intent。由於 PendingIntent 仍擁有原程式的權限,取得它時必須格外謹慎,最好在 Intent 中明確指定目標元件,以免 Intent 無處可去。
可以這樣理解:若你想在 A Activity 中啟動 B Activity,有兩種情況——一是配置好 Intent 後呼叫 startActivity() 立即跳轉;二是想延後(例如五分鐘後)才跳轉,此時可用 PendingIntent 包裝該 Intent,再交給 AlarmManager 定時觸發。取得 PendingIntent 的方式有 getActivity、getService、getBroadcast 三種系列方法。
PendingIntent 的幾個關鍵常量:FLAG_CANCEL_CURRENT 會取消目前 PendingIntent 並新建;FLAG_UPDATE_CURRENT 會以新的 Intent 更新既有 PendingIntent 的資料(如 Extras);FLAG_NO_CREATE 則在已存在時直接返回、不存在時返回 null。
以下以啟動 BroadcastReceiver 為例(原理與啟動 Activity、Service 相同)。MainActivity.java:
package com.test.Alarm;
import android.app.Activity;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.SystemClock;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
public class MainActivity extends Activity {
private Button msetButton;
private Button mcancelButton;
private TextView mTextView;
private final int REQUEST_CODE_0 = 0;
private final int REQUEST_CODE_1 = 1;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mTextView = (TextView) this.findViewById(R.id.mText);
msetButton = (Button) this.findViewById(R.id.setTimeButton);
mcancelButton = (Button) findViewById(R.id.cancelButton);
msetButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
AlarmManager alarmMgr = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
Intent intent = new Intent(getApplicationContext(), AlermReceiver.class);
intent.putExtra("flag", true);
PendingIntent setPendIntent0 = PendingIntent.getBroadcast(getApplicationContext(), REQUEST_CODE_0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
PendingIntent setPendIntent1 = PendingIntent.getBroadcast(getApplicationContext(), REQUEST_CODE_1, intent, PendingIntent.FLAG_UPDATE_CURRENT);
// 5 秒後發送廣播,之後每隔 10 秒重複
int triggerAtTime = (int) (SystemClock.elapsedRealtime() + 5 * 1000);
int interval = 10 * 1000;
alarmMgr.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP, triggerAtTime, interval, setPendIntent0);
alarmMgr.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP, triggerAtTime, interval, setPendIntent1);
}
});
mcancelButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
AlarmManager alarmMgr = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
Intent intent = new Intent(getApplicationContext(), AlermReceiver.class);
intent.putExtra("flag", false);
PendingIntent StopPendIntent0 = PendingIntent.getBroadcast(getApplicationContext(), REQUEST_CODE_0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
/* 若想更新 putExtra 中 flag 的值,必須先透過 alarmMgr 的 setxxx() 再註冊一次以更新既有 Intent,否則無法達到更新目的。 */
alarmMgr.cancel(StopPendIntent0);
// 以下僅為示範 PendingIntent 各常量的差異
PendingIntent StopPendIntent11 = PendingIntent.getBroadcast(getApplicationContext(), REQUEST_CODE_1, intent, PendingIntent.FLAG_NO_CREATE);
alarmMgr.cancel(StopPendIntent11);
PendingIntent StopPendIntent12 = PendingIntent.getBroadcast(getApplicationContext(), REQUEST_CODE_1, intent, PendingIntent.FLAG_CANCEL_CURRENT);
alarmMgr.cancel(StopPendIntent12);
PendingIntent StopPendIntent13 = PendingIntent.getBroadcast(getApplicationContext(), REQUEST_CODE_1, intent, PendingIntent.FLAG_ONE_SHOT);
alarmMgr.cancel(StopPendIntent13);
}
});
}
}