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

看懂 Android PendingIntent:它與 Intent 差在哪

編輯:關於 Android 程式設計

PendingIntent 這個名稱直譯是「待決定的 Intent」。字面上有個「pending」,意思就是:這個 Intent 什麼時候執行、由誰執行,都還沒定下來。

核心差異:執行時機與執行權

普通的 Intent 在被送出後立即執行,而且是在你自己的應用行程中執行。

PendingIntent 則是把一個 Intent 打包好交給別人保管,等到某個條件成立時,才由持有者代為執行。它執行的內容就是你傳進去的 Intent 所描述的操作,但執行權已經轉移出去了。

這個設計的價值在於:PendingIntent 內部保存了建立它的那個 Application 的 Context。因此即使你的應用行程此時已經被系統回收、已經不存在了,持有 PendingIntent 的一方(例如系統的通知服務)依然能靠著這個 Context 把 Intent 執行起來。

如何取得 PendingIntent

透過三個靜態方法建立,分別對應 Intent 的三種行為:

PendingIntent.getActivity(Context, int, Intent, int)   // 跳轉到 Activity
PendingIntent.getBroadcast(Context, int, Intent, int)  // 送出 Broadcast
PendingIntent.getService(Context, int, Intent, int)    // 啟動 Service

四個參數的重要性有先後:第一個 Context 與第三個 Intent 是必要的,分別決定「誰來執行」與「執行什麼」;第二與第四個參數則影響快取與比對行為。

常見使用場景

PendingIntent 最常出現在三個地方:通知(Notification)、簡訊發送(SmsManager)與鬧鐘(AlarmManager)。共同點是——這三個服務都運行在你的應用之外,需要一個能跨行程執行的「憑證」。

實例一:狀態列通知

Android 的狀態列通知需要使用者下拉才能查看完整內容。建立流程如下:

  1. 取得通知管理器 NotificationManager,它同樣是一個系統服務。
  2. 建立 Notification 物件。
  3. 為通知設定各項參數(提示音、震動、燈光閃爍等)。
  4. 把通知加入通知管理器。
// 1. 取得通知管理器
NotificationManager mNotificationManager =
        (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);

int icon = android.R.drawable.stat_notify_chat;
long when = System.currentTimeMillis();   // 通知發生的時間

// 2. 建立通知:參數依序為圖示、暫態提示文字、時間
Notification notification = new Notification(icon, null, when);

// 3. 設定參數
notification.defaults = Notification.DEFAULT_SOUND;        // 播放預設提示音
notification.flags |= Notification.FLAG_AUTO_CANCEL;       // 點擊後自動清除

// 4. 準備 PendingIntent:點擊通知時要執行的動作
Intent openintent = new Intent(this, OtherActivity.class);
PendingIntent contentIntent = PendingIntent.getActivity(this, 0, openintent, 0);

notification.setLatestEventInfo(this, "標題", "我是內容", contentIntent);

// 5. 發送通知,第一個參數為自訂的唯一識別碼
mNotificationManager.notify(0, notification);

重點在 setLatestEventInfo() 的最後一個參數——它是一個 PendingIntent。點擊通知時,系統會代你執行這個 PendingIntent,而此時你的應用可能早已不在記憶體中。

實例二:簡訊發送的狀態回呼

SmsManager 的送訊方法簽名如下:

sendTextMessage(destinationAddress, scAddress, text, sentIntent, deliveryIntent);
  • destinationAddress:對方手機號碼。
  • scAddress:簡訊中心號碼,一般設為 null。
  • text:簡訊內容。
  • sentIntent:用來判斷「送出」動作是否成功。若沒有 SIM 卡或網路中斷,可透過它得知。注意這裡強調的是「送出」這個動作的成敗,至於對方是否收到,是另一回事。
  • deliveryIntent:當簡訊真正送達收件人時觸發,強調的是「送出之後的結果」。

換句話說,只有在「簡訊成功送出」與「對方成功收到」這兩個時點,系統才會分別觸發這兩個 Intent。這本質上就是一種延遲執行。

小結

兩個例子都指向同一個結論:PendingIntent 是一個能在滿足特定條件時才執行的 Intent。相比普通 Intent,它的優勢在於自身攜帶 Context 物件,因此不必依附某個還活著的 Activity 就能存在與執行。

這也是為什麼凡是需要「跨行程、跨時間」觸發的機制,都繞不開 PendingIntent。

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