Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
您现在的位置: Android教程網 >> Android系統教程 >  >> Android 技術 >> Android 開發 >> 中階開發

PendingIntent 是什麼:與 Intent 的差異及源碼解析

編輯:中階開發

不少初學者會疑惑:既然已經有 Intent,為什麼還需要 PendingIntent?看看 Notification、SmsManager 的 sendMessage、AlarmManager 的 set 等方法,參數清單裡出現的都是 PendingIntent。兩者的定位其實完全不同。

一、Intent:描述「現在要做什麼」

Intent 位於 android.content.Intent,直接繼承 Object,內部保存一些字串、整數與輕量級陣列,方法多為賦值與取值。它是一次性的、當下的意圖描述。

二、PendingIntent:授權他人執行「我將來要做的事」

PendingIntent 被放在 android.app 而非 content 層,這已經暗示了它的定位——它屬於應用層的概念,代表一個尚未發生、但已授權可被觸發的操作。

最典型的例子是簡訊發送。從 GSM 通訊到 RIL,再到行動基站,整個過程很漫長。如果要在應用裡開一條 Thread 坐著等結果,既麻煩又耗資源。Android 的做法是把這件事交給框架層的 TelephonyManager 遠程服務去追蹤,最後透過 PendingIntent 把結果回傳給你。這也就是為什麼簡訊回執、發送成功或失敗的 callback 都長這個樣子。

三、源碼結構

public final class PendingIntent implements Parcelable {
    private final IIntentSender mTarget;

    public static final int FLAG_ONE_SHOT = 1 << 30;
    public static final int FLAG_NO_CREATE = 1 << 29;
    public static final int FLAG_CANCEL_CURRENT = 1 << 28;
    public static final int FLAG_UPDATE_CURRENT = 1 << 27;

    public static class CanceledException extends android.util.AndroidException { ... }

    public interface OnFinished {
        void onSendFinished(PendingIntent pendingIntent, Intent intent,
                int resultCode, String resultData, Bundle resultExtras);
    }

值得注意的第一點是它實作了 Parcelable——因為 PendingIntent 需要跨進程傳遞,底層靠 writeStrongBinder 把 mTarget 序列化過去。

第二點是 FinishedDispatcher,它繼承自 IIntentReceiver.Stub 並實作 Runnable。如果你了解 Android 的 RemoteService 或 Java RMI,這段就不難理解:它是一個跨進程的 callback 接收器,收到結果後再拋給 Handler 或直接呼叫 onSendFinished。

四、三個取得入口

// 用於啟動 Activity
public static PendingIntent getActivity(Context context, int requestCode,
        Intent intent, int flags)

// 用於送出廣播
public static PendingIntent getBroadcast(Context context, int requestCode,
        Intent intent, int flags)

// 用於啟動 Service
public static PendingIntent getService(Context context, int requestCode,
        Intent intent, int flags)

三者內部邏輯幾乎一致,差別只在傳給 ActivityManagerNative 的 INTENT_SENDER 型別常數不同。

五、那些 flag 的意義

FLAG_ONE_SHOT:只能觸發一次,之後自動失效。
FLAG_NO_CREATE:不存在就回傳 null,不要新建。
FLAG_CANCEL_CURRENT:若已存在同值的 PendingIntent,先取消再建新的。
FLAG_UPDATE_CURRENT:若已存在,則用新的 extras 更新它。

這幾個 flag 在搭配通知時特別重要。由於 PendingIntent 的相等性判斷只看 mTarget.asBinder(),不包含 extras,因此當你更新通知內容卻發現點進去還是舊資料時,通常就是忘了加上 UPDATE_CURRENT。

總結

PendingIntent 的實作本身並不複雜,本質上就是一個可跨進程傳遞、代表授權動作的 Binder 包裝。日常應用中多數場景用不到它,但一旦涉及通知、鬧鐘、簡訊回執或 AppWidget,它就是必備工具。

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