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

PendingIntent 深入解析:用法、典型場景與與 Intent 的差異

編輯:關於 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)的觸發動作等。共同點是——執行者不是你,而是系統或另一個進程。

二、場景一:狀態列通知

拖動狀態列即可展開查看通知。基本流程四步:

  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. 建立通知: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);
  • destinationAddress:對方手機號碼。
  • scAddress:簡訊中心號碼,一般傳 null。
  • text:簡訊內容。
  • sentIntent:判斷發送動作是否成功。沒有 SIM 卡、網路中斷等情況都可由此得知。注意它關心的是「有沒有發出去」,與對方是否收到無關。
  • 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 的四點差異

面向IntentPendingIntent
執行時機立即使用等事件發生後觸發,且可 cancel()
生命週期所屬程式結束後即失效程式結束後依然有效
Context需要在某個 Context 內運行自帶 Context
運行 Task在原本的 task 中運行在新的 task 中運行

這四點合起來解釋了 PendingIntent 的設計目的:它是一個「可以在條件滿足時被執行的 Intent」,而相比普通 Intent 的優勢在於自帶 Context,因此不必依賴某個 Activity 存在。

五、Token、權限與身分:進階但關鍵的機制

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 的意義:

  • 當你向系統索取 PendingIntent 時,若系統中已存在一個「與你描述的內容對等」的 PendingIntent,系統會直接回傳同一個 token 的 PendingIntent,而不是新建一個。
  • 帶上 FLAG_CANCEL_CURRENT,會先把舊的 cancel 掉,這樣取回的 PendingIntent 與其 token 都是全新的。
  • 帶上 FLAG_UPDATE_CURRENT,則用新的 Intent 內容更新既有 PendingIntent 中的 Intent 物件資料(例如更新 Extras),token 保持不變。
  • FLAG_ONE_SHOT 使這個 PendingIntent 只能被使用一次,之後自動失效。
  • FLAG_IMMUTABLE 標示其內容不可被接收方修改,是安全上的預設選擇。

需要時,也可以在原本的進程中呼叫 PendingIntent.cancel() 把它從系統中移除,讓後續的執行落空。

六、實務檢核清單

  • requestCode 要能區分不同 PendingIntent。若多個通知共用同一組 Intent 與 requestCode,系統會認為它們是同一個,導致點擊都跳到同一處。
  • Intent 要顯式或具備唯一 action,避免被其他 App 攔截。
  • Android 12+ 明確指定 mutability,預設用 IMMUTABLE,確需接收方填充內容時才用 MUTABLE。
  • 通知使用 PendingIntent.getActivity(),並注意不要在 PendingIntent 裡做長耗時操作——它被執行時已不在你的 UI 情境中了。
  • Android 5.0 起 Service 相關需留意,getService() 在新版本上行為受限,背景工作請改用 WorkManager 或前台服務。

一句話總結:Intent 描述的是「要做什麼」,PendingIntent 描述的是「授權誰、在什麼時候、以我的身分去做什麼」。理解這個授權模型,比記住幾個 API 參數重要得多。

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