編輯:關於 Android 程式設計
PendingIntent 的字面意思是「待定的、未決定的 Intent」。它是 Android 裡一個容易被誤解、卻又幾乎無法迴避的元件——只要做通知、簡訊回報、鬧鐘、桌面捷徑、App Widget,就一定會遇到它。
取得 PendingIntent 的方式是 PendingIntent 的三個靜態工廠方法,分別對應 Intent 的三種行為:
PendingIntent.getActivity(Context, int requestCode, Intent intent, int flags) // 啟動 Activity PendingIntent.getBroadcast(Context, int requestCode, Intent intent, int flags) // 送出廣播 PendingIntent.getService(Context, int requestCode, Intent intent, int flags) // 啟動 Service
四個參數的重要性大致是:Intent 與 Context 必填(沒有 Intent 就無從談起,沒有 Context 也無法解析),接著是 flags,最後是 requestCode。
PendingIntent 是一種特殊的 Intent。兩者最大的差異在於執行時機:Intent 是立刻使用的,而 PendingIntent 代表的是「一個授權給他人、在未來某個條件滿足時才執行的操作」。
換個角度理解:PendingIntent 是對 Intent 的包裝,它主要持有兩樣東西——被包裝的 Intent,以及當前 Application 的 Context。正因為它把 Application Context 一起帶走了,即使產生它的那個 App 進程此時已經不存在,系統依然能憑這份 Context 把 Intent 執行起來。這也是它與普通 Intent 最關鍵的能力差異。
典型使用場合:通知(Notification)的點擊跳轉、簡訊(SmsManager)的發送與送達回呼、鬧鐘(AlarmManager)的觸發動作等。共同點是——執行者不是你,而是系統或另一個進程。
拖動狀態列即可展開查看通知。基本流程四步:
NotificationManager(同樣是系統服務)。
// 1. 取得通知管理器
NotificationManager mNotificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
int icon = android.R.drawable.stat_notify_chat;
long when = System.currentTimeMillis();
// 2. 建立通知:icon、暫態提示標題、時間
Notification notification = new Notification(icon, null, when);
// 3. 設定行為
notification.defaults = Notification.DEFAULT_SOUND; // 預設提示音
notification.flags |= Notification.FLAG_AUTO_CANCEL; // 點擊後自動清除
// 4. 準備點擊後要執行的動作
Intent openIntent = new Intent(this, OtherActivity.class);
PendingIntent contentIntent = PendingIntent.getActivity(this, 0, openIntent, 0);
notification.setLatestEventInfo(this, "標題", "我是內容", contentIntent);
mNotificationManager.notify(0, notification); // 參數 0 為通知唯一標識
整段程式碼的重點是 setLatestEventInfo() 的最後一個參數——它是一個 PendingIntent。少了它,使用者點擊通知就不會有任何反應。
另一個使用寫法(搭配 flag):
NotificationManager nm = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); int icon = android.R.drawable.stat_notify_chat; long when = System.currentTimeMillis() + 2000; Notification n = new Notification(icon, "通知欄 demo 提醒", when); n.defaults = Notification.DEFAULT_SOUND; n.flags |= Notification.FLAG_AUTO_CANCEL; Intent openIntent = new Intent(this, DemoList.class); PendingIntent pi = PendingIntent.getActivity(this, 0, openIntent, PendingIntent.FLAG_CANCEL_CURRENT); n.setLatestEventInfo(this, "通知欄 demo 提醒 title", "通知欄 demo 提醒 text", pi); nm.notify(0, n);
補充:這套 new Notification(...) + setLatestEventInfo() 的寫法在 API 11 之後已被棄用,新專案請改用 Notification.Builder(或 NotificationCompat.Builder),並記得建立通知管道、處理 Android 8.0 起的通知渠道要求與 Android 13 起的通知執行權限。但 PendingIntent 的角色完全沒變。
SmsManager 的發送方法本身就是 PendingIntent 的教科書案例:
sendTextMessage(destinationAddress, scAddress, text, sentIntent, deliveryIntent);
也就是說,只有在「發送成功」與「對方收到」這兩個時點,系統才會分別激活這兩個 PendingIntent——本質上就是延遲執行 Intent。
完整範例:
private final static String SEND_ACTION = "send";
private final static String DELIVERED_ACTION = "delivered";
private void sendSms(String receiver, String text) {
SmsManager s = SmsManager.getDefault();
PendingIntent sentPI = PendingIntent.getBroadcast(
this, 0, new Intent(SEND_ACTION), PendingIntent.FLAG_CANCEL_CURRENT);
PendingIntent deliveredPI = PendingIntent.getBroadcast(
this, 0, new Intent(DELIVERED_ACTION), PendingIntent.FLAG_CANCEL_CURRENT);
// 發送完成
registerReceiver(new BroadcastReceiver() {
@Override public void onReceive(Context context, Intent intent) {
switch (getResultCode()) {
case Activity.RESULT_OK:
Toast.makeText(getBaseContext(), "Send Success!", Toast.LENGTH_SHORT).show();
break;
case SmsManager.RESULT_ERROR_GENERIC_FAILURE:
Toast.makeText(getBaseContext(), "Send Failed: generic failure.", Toast.LENGTH_SHORT).show();
break;
case SmsManager.RESULT_ERROR_NO_SERVICE:
Toast.makeText(getBaseContext(), "Send Failed: no service.", Toast.LENGTH_SHORT).show();
break;
case SmsManager.RESULT_ERROR_NULL_PDU:
Toast.makeText(getBaseContext(), "Send Failed: null pdu.", Toast.LENGTH_SHORT).show();
break;
case SmsManager.RESULT_ERROR_RADIO_OFF:
Toast.makeText(getBaseContext(), "Send Failed: radio off.", Toast.LENGTH_SHORT).show();
break;
default:
Toast.makeText(getBaseContext(), "Send Failed.", Toast.LENGTH_SHORT).show();
break;
}
}
}, new IntentFilter(SEND_ACTION));
// 對方接收完成
registerReceiver(new BroadcastReceiver() {
@Override public void onReceive(Context context, Intent intent) {
if (getResultCode() == Activity.RESULT_OK) {
Toast.makeText(getBaseContext(), "Delivered Success!", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(getBaseContext(), "Delivered Failed!", Toast.LENGTH_SHORT).show();
}
}
}, new IntentFilter(DELIVERED_ACTION));
// 送出簡訊,sentPI 與 deliveredPI 會分別在上述兩個時機被廣播
s.sendTextMessage(receiver, null, text, sentPI, deliveredPI);
}
實作提醒:動態注册的 receiver 記得在 onDestroy() 中反注册,避免記憶體洩漏;Android 8.0 起隱含廣播的注册限制也需要留意(此例屬App 內部的自訂 action,通常不受影響,但仍建議改用更精確的 API)。
| 面向 | Intent | PendingIntent |
|---|---|---|
| 執行時機 | 立即使用 | 等事件發生後觸發,且可 cancel() |
| 生命週期 | 所屬程式結束後即失效 | 程式結束後依然有效 |
| Context | 需要在某個 Context 內運行 | 自帶 Context |
| 運行 Task | 在原本的 task 中運行 | 在新的 task 中運行 |
這四點合起來解釋了 PendingIntent 的設計目的:它是一個「可以在條件滿足時被執行的 Intent」,而相比普通 Intent 的優勢在於自帶 Context,因此不必依賴某個 Activity 存在。
PendingIntent 用於描述 Intent 及其最終行為。你可以透過上述三個 get 系列方法向系統索取一個 PendingIntent,把它交給別的應用程式,由對方在稍後執行其中描述的動作。
這裡有一個非常重要的特性:當你把 PendingIntent 交給其他程式處理時,它仍然保有名義上原程式的權限與身分(with the same permissions and identity)。也就是說,系統是以「你的身分」去執行這個 Intent 的。這正是它能繞過進程生命週期的原因,同時也是安全風險的來源——隨意把權限高超的 PendingIntent 交出去,等於把自己的權限借給別人。
因此取得 PendingIntent 時務必謹慎。實務上的建議:若 Intent 的目的地是你自己的元件(Activity / Service / BroadcastReceiver),最好顯式指定目標元件名稱,確保 Intent 能送達預期位置;同時明確傳遞 FLAG_IMMUTABLE(Android 12 起強制要求),避免對方能任意填充 Intent 內容。
再往下一層:一個 PendingIntent 就是 Android 系統中某個 token 的物件引用,它描述了將來要用來比對的資料(也就是 Intent 及其最終行為)。這意味著即使原本的進程已結束,PendingIntent 本身依然存在,可在其他進程中繼續使用。
而 token 的存在也解釋了 requestCode 與 flags 的意義:
FLAG_CANCEL_CURRENT,會先把舊的 cancel 掉,這樣取回的 PendingIntent 與其 token 都是全新的。FLAG_UPDATE_CURRENT,則用新的 Intent 內容更新既有 PendingIntent 中的 Intent 物件資料(例如更新 Extras),token 保持不變。FLAG_ONE_SHOT 使這個 PendingIntent 只能被使用一次,之後自動失效。FLAG_IMMUTABLE 標示其內容不可被接收方修改,是安全上的預設選擇。需要時,也可以在原本的進程中呼叫 PendingIntent.cancel() 把它從系統中移除,讓後續的執行落空。
getService() 在新版本上行為受限,背景工作請改用 WorkManager 或前台服務。一句話總結:Intent 描述的是「要做什麼」,PendingIntent 描述的是「授權誰、在什麼時候、以我的身分去做什麼」。理解這個授權模型,比記住幾個 API 參數重要得多。
Android 開發實戰:實現應用的前後台切換效果
本文將介紹如何在 Android 中實現類似 QQ 的應用前後台切換效果——當應用退到後台時在通知欄顯示圖標,點擊即可返回原界面。在動手之前,先理清 Activity 與
仿微信底部菜單欄:用TabHost實現未讀消息紅點提示
底部菜單欄幾乎是所有應用的標配。這裡用 TabHost 做了一個通用版本,重點是能像微信那樣在圖標上顯示未讀消息數量。之前也做過類似功能,但佈局嵌套層數太多顯得臃腫,這次
Android 用 WindowManager 實現懸浮按鈕與懸浮菜單
簡介 本文模仿實現的是 360 手機衛士的「內存球」效果:桌面上懸著一個小窗,點一下能展開菜單。實現它並不需要什麼黑科技,核心只有一個 API——WindowManage
Android 多執行緒下載實作:仿下載助手與斷點續傳
先釐清一個常見誤會:本文的「多執行緒下載」不是指用多個執行緒共同下載同一個檔案,而是每個執行緒負責一個檔案,透過執行緒池統一調度。範例的互動是:點擊開始下載並顯示進度,完