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

PendingIntent 的內部機制全解析

編輯:關於 Android 程式設計

一、概述

在 Android 開發中,我們經常用 PendingIntent 來表達一種「留待日後處理」的語義。從這個角度看,它可以被理解為一種特殊的異步處理機制。不過單看名字,PendingIntent 其實頗具誤導性——它既不繼承自 Intent,也不包含 Intent,其核心用四個字概括最為貼切:異步激發。

這種異步激發往往需要跨進程執行。舉例來說,A 進程作為發起端,可以從系統「獲取」一個 PendingIntent,再通過 Binder 機制把它「傳遞」給 B 進程,由 B 進程在未來某個合適的時機「回調」PendingIntent 的 send() 動作,完成激發。

在 Android 系統中,最適合做集中管理的組件莫過於 AMS(Activity Manager Service),於是由它義不容辭地承擔起管理所有 PendingIntent 的職責。示意圖如下:

請注意其中的第 4 步「遞送相應的 intent」。這裡遞送的 intent 從何而來?簡單說,當發起端獲取 PendingIntent 時,其實需要同時提供若干 intent。這些 intent 與 PendingIntent 只是配套關係,而非聚合關係,它們會被緩存在 AMS 中。日後一旦處理端把「激發」語義傳到 AMS,AMS 就會設法找到與該 PendingIntent 對應的若干 intent 並遞送出去。

以上只是大致輪廓,真實的技術細節會更複雜一些,下面我們逐一拆解。

二、PendingIntent 的技術細節

2.1 發起端獲取 PendingIntent

先要理解「發起端獲取 PendingIntent」到底指什麼。難道只是簡單 new 一個對象嗎?当然不是。此處的「獲取」還含有向 AMS「註冊」intent 的語義。

在 PendingIntent.java 中,可以看到幾個常見的靜態方法:

  • public static PendingIntent getActivity(Context context, int requestCode, Intent intent, int flags)
  • public static PendingIntent getBroadcast(Context context, int requestCode, Intent intent, int flags)
  • public static PendingIntent getService(Context context, int requestCode, Intent intent, int flags)
  • public static PendingIntent getActivities(Context context, int requestCode, Intent[] intents, int flags)
  • public static PendingIntent getActivities(Context context, int requestCode, Intent[] intents, int flags, Bundle options)

它們就是我們常用的獲取 PendingIntent 的動作。

坦白說,這幾個方法的命名並不理想,我們簡單解釋一下。getActivity() 的意思是:獲取一個 PendingIntent,且它日後激發時要做的事是啟動一個新 Activity,也就是執行類似 Context.startActivity() 的動作。相應地,getBroadcast() 與 getService() 獲取的 PendingIntent 在激發時,會分別執行類似 Context.sendBroadcast() 和 Context.startService() 的動作。至於最後兩個 getActivities(),用得較少,激發時可以一次啟動多個 Activity。

我們以 getActivity() 的代碼為例說明:

 public static PendingIntent getActivity(Context context, int requestCode, Intent intent, int flags, Bundle options) { String packageName = context.getPackageName(); String resolvedType = intent != null ? intent.resolveTypeIfNeeded(context.getContentResolver()) : null; try { intent.setAllowFds(false); IIntentSender target = ActivityManagerNative.getDefault().getIntentSender( ActivityManager.INTENT_SENDER_ACTIVITY, packageName, null, null, requestCode, new Intent[] { intent }, resolvedType != null ? new String[] { resolvedType } : null, flags, options); return target != null ? new PendingIntent(target) : null; } catch (RemoteException e) {} return null; }

其中 new PendingIntent(target) 創建了 PendingIntent 對象,重要性不言而喻。但這個對象的內部核心,其實來自上面的 getIntentSender() 方法。這個 IIntentSender 核心才是我們真正要關注的東西。

說穿了,IIntentSender 是個 Binder 代理,它對應的 Binder 實體是 AMS 中的 PendingIntentRecord 對象。PendingIntent 構造時,IIntentSender 代理作為參數傳入,並記錄在 PendingIntent 的 mTarget 域。日後當 PendingIntent 執行異步激發時,內部就是靠這個 mTarget 域向 AMS 傳遞語義的。

前面說過,PendingIntent 常常會經由 Binder 機制傳到另一個進程。而 Binder 機制可以保證,目標進程拿到的 PendingIntent 的 mTarget 域同樣是合法的 IIntentSender 代理,並且與發起端的 IIntentSender 代理對應著同一個 PendingIntentRecord 實體。示意圖如下:

2.2 AMS 裡的 PendingIntentRecord

那 PendingIntentRecord 裡又存了什麼信息呢?定義截選如下:

 class PendingIntentRecord extends IIntentSender.Stub { final ActivityManagerService owner; final Key key; // 最關鍵的key域 final int uid; final WeakReference ref; boolean sent = false; boolean canceled = false; String stringName; . . . . . . }

請注意那個 key 域。Key 是 PendingIntentRecord 的內嵌類,定義截選如下:

 final static class Key { final int type; final String packageName; final ActivityRecord activity; final String who; final int requestCode; final Intent requestIntent; // 注意! final String requestResolvedType; final Bundle options; Intent[] allIntents; // 注意!記錄了當初獲取PendingIntent時,用戶所指定的所有intent String[] allResolvedTypes; final int flags; final int hashCode; . . . . . . . . . . . . }

請特別留意 allIntents[] 數組域與 requestIntent 域。前者記錄了當初獲取 PendingIntent 時用戶指定的所有 intent(一般只會指定一個,但類似 getActivities() 這樣的方法可以指定多個),後者則可粗略理解為那個 intent 數組中最後一個。現在大家應該清楚,異步激發時用到的 intent 都存在哪裡了吧。

Key 的構造函數截選如下:

 Key(int _t, String _p, ActivityRecord _a, String _w, int _r, Intent[] _i, String[] _it, int _f, Bundle _o) { type = _t; packageName = _p; activity = _a; who = _w; requestCode = _r; requestIntent = _i != null ? _i[_i.length-1] : null; // intent數組中的最後一個 requestResolvedType = _it != null ? _it[_it.length-1] : null; allIntents = _i; // 所有intent allResolvedTypes = _it; flags = _f; options = _o; . . . . . . }

Key 不僅承擔記錄信息的作用,還肩負著「鍵值」的職責。

2.3 AMS 中的 PendingIntentRecord 總表

AMS 管理著系統中所有的 PendingIntentRecord 節點,需要把它們組織成一張表:

 final HashMap mIntentSenderRecords;

這張哈希映射表的鍵值類型,正是剛才提到的 PendingIntentRecord.Key。

以後每當我們獲取 PendingIntent 時,其 mTarget 是這樣得到的:AMS 先查 mIntentSenderRecords 表,若能找到匹配的 PendingIntentRecord 節點就返回它;找不到就新建一個節點。由於 PendingIntentRecord 是個 Binder 實體,經過 Binder 機制傳遞後,客戶進程拿到的就是合法的 Binder 代理。如此一來,前面的示意圖可以進一步完善為下圖:

2.4 AMS 裡的 getIntentSender() 方法

回到前面的 getActivity() 及其調用的 getIntentSender()。先列出 getActivity() 的原型:

 public static PendingIntent getActivity(Context context, int requestCode, Intent intent, int flags, Bundle options)
  • context 是調用方的上下文。
  • requestCode 是個簡單整數,起區分作用。
  • intent 是異步激發時將發出的 intent。
  • flags 可以包含一些既有標識,比如 FLAG_ONE_SHOT、FLAG_NO_CREATE、FLAG_CANCEL_CURRENT、FLAG_UPDATE_CURRENT 等,後文會細說。
  • options 可以攜帶一些額外數據。

getActivity() 的代碼很簡單,參數基本都轉發給了 getIntentSender()。

 IIntentSender target = ActivityManagerNative.getDefault().getIntentSender(. . . . . .)

getIntentSender() 的原型大致如下:

 public IIntentSender getIntentSender(int type, String packageName, IBinder token, String resultWho, int requestCode, Intent[] intents, String[] resolvedTypes, int flags, Bundle options) throws RemoteException;

它的參數比 getActivity() 多一些,我們逐一說明。

type 參數表明 PendingIntent 的類型。getActivity() 與 getActivities() 指定 INTENT_SENDER_ACTIVITY,getBroadcast() 與 getService() 分別指定 INTENT_SENDER_BROADCAST 和 INTENT_SENDER_SERVICE。此外在 Activity.java 中還有一個 createPendingResult() 方法,表達發起方 Activity 日後希望得到 result 回饋,其內部調用 getIntentSender() 時指定的類型為 INTENT_SENDER_ACTIVITY_RESULT。

packageName 表示發起端所屬的包名。

token 是個指代回饋目標方的代理。我們常用的 getActivity()、getBroadcast()、getService() 都把它簡單設為 null,表示激發時不需要發回回饋。而當我們希望獲取類型為 INTENT_SENDER_ACTIVITY_RESULT 的 PendingIntent 時,就需要指定 token 了,具體可參考 createPendingResult() 的代碼:

 public PendingIntent createPendingResult(int requestCode, Intent data, int flags) { String packageName = getPackageName(); try { data.setAllowFds(false); IIntentSender target = ActivityManagerNative.getDefault().getIntentSender( ActivityManager.INTENT_SENDER_ACTIVITY_RESULT, packageName, mParent == null ? mToken : mParent.mToken, mEmbeddedID, requestCode, new Intent[] { data }, null, flags, null); return target != null ? new PendingIntent(target) : null; } catch (RemoteException e) { // Empty } return null; }

看到了嗎?傳入的 token 是 Activity 的 mToken 或其 mParent.mToken。簡單說,AMS 內部可以根據這個 token 找到對應的 ActivityRecord,日後 PendingIntent 激發時,AMS 就能依此確定該向哪個目標進程的哪個 Activity 發出 result 語義。

resultWho 參數與 token 息息相關,一般也是 null。在 createPendingResult() 中,其值為 Activity 的 mEmbeddedID 字符串。

requestCode 是個簡單整數,可由用戶在獲取 PendingIntent 時指定,起區分作用。

intents 數組參數是異步激發時希望發出的 intent。對於 getActivity()、getBroadcast()、getService() 來說都只指定一個 intent,只有 getActivities() 會一次傳入多個。

resolvedTypes 參數基本與 intent 相關,通常是這樣得到的:

 String resolvedType = intent != null ? intent.resolveTypeIfNeeded( context.getContentResolver()) : null;

這個值常與 intent 內部的 mData URI 有關,比如最終可能是 URI 對應的 MIME 類型。

flags 參數可以指定 PendingIntent 的一些行為特點,取值是若干既有比特標識的組合。目前可用的標識有 FLAG_ONE_SHOT、FLAG_NO_CREATE、FLAG_CANCEL_CURRENT、FLAG_UPDATE_CURRENT 等,有時還會附帶若干 FILL_IN_XXX 標識。常見標識定義列舉如下:

【PendingIntent 中】

 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;

【Intent 中】

 public static final int FILL_IN_ACTION = 1<<0; public static final int FILL_IN_DATA = 1<<1; public static final int FILL_IN_CATEGORIES = 1<<2; public static final int FILL_IN_COMPONENT = 1<<3; public static final int FILL_IN_PACKAGE = 1<<4; public static final int FILL_IN_SOURCE_BOUNDS = 1<<5; public static final int FILL_IN_SELECTOR = 1<<6; public static final int FILL_IN_CLIP_DATA = 1<<7;

這些以 FILL_IN_ 打頭的標志位,主要在 intent 對象的 fillIn() 方法裡起作用:

 public int fillIn(Intent other, int flags)

以 FILL_IN_ACTION 為例,當執行類似 srcIntent.fillIn(otherIntent, ...) 的句子時,如果 otherIntent 的 mAction 域不為 null,那麼 fillIn() 會在兩種情況下用 otherIntent 的 mAction 為 srcIntent 賦值:一是 srcIntent 的 mAction 本就為 null;二是 fillIn 的 flags 參數攜帶了 FILL_IN_ACTION 標志位,此時即便 srcIntent 的 mAction 已有值,也會被 otherIntent 的 mAction 強行替換。其他 FILL_IN_ 標志位處理方式類似,不再贅述。

options 參數可以攜帶一些額外數據。

2.4.1 getIntentSender() 方法

getIntentSender() 摘錄如下:

 public IIntentSender getIntentSender(int type, String packageName, IBinder token, String resultWho, int requestCode, Intent[] intents, String[] resolvedTypes, int flags, Bundle options) { . . . . . . // 先判斷intents數組,可以用偽代碼checkIntents(intents)來表示 // checkIntents(intents); . . . . . . int callingUid = Binder.getCallingUid(); . . . . . . if (callingUid != 0 && callingUid != Process.SYSTEM_UID) { int uid = AppGlobals.getPackageManager().getPackageUid(packageName, UserId.getUserId(callingUid)); if (!UserId.isSameApp(callingUid, uid)) { . . . . . . throw new SecurityException(msg); } } . . . . . . return getIntentSenderLocked(type, packageName, Binder.getOrigCallingUid(), token, resultWho, requestCode, intents, resolvedTypes, flags, options); . . . . . . }

這段逐條判斷 intents[] 的代碼(我用偽代碼 checkIntents(intents) 表示)說明:獲取 PendingIntent 時,intent 中不能攜帶文件描述符;而且如果這個 PendingIntent 是要發出廣播的那種,intent 中也不能攜帶 FLAG_RECEIVER_BOOT_UPGRADE 標識符。「BOOT_UPGRADE」應該是「啟動並升級」的意思,它不能使用 PendingIntent。

getIntentSender() 中最核心的一句,是調用 getIntentSenderLocked() 的那句。

2.4.2 getIntentSenderLocked() 方法

【frameworks/base/services/java/com/android/server/am/ActivityManagerService.java】

 IIntentSender getIntentSenderLocked(int type, String packageName, int callingUid, IBinder token, String resultWho, int requestCode, Intent[] intents, String[] resolvedTypes, int flags, Bundle options) { . . . . . . // 如果是INTENT_SENDER_ACTIVITY_RESULT類型,那麼要判斷token所 // 代表的activity是否還在activity棧中 . . . . . . // 整理flags中的信息 . . . . . . PendingIntentRecord.Key key = new PendingIntentRecord.Key(type, packageName, activity, resultWho, requestCode, intents, resolvedTypes, flags, options); // 盡力從哈希映射表中查找key對應的PendingIntentRecord,如果找不到就創建一個新的節點。 WeakReference ref; ref = mIntentSenderRecords.get(key); PendingIntentRecord rec = ref != null ? ref.get() : null; if (rec != null) { // 找到了匹配的PendingIntent,現在考慮要不要更新它,或者取消它。 if (!cancelCurrent) { if (updateCurrent) { // 如果明確指定了FLAG_UPDATE_CURRENT,那麼更新找到的節點 if (rec.key.requestIntent != null) { rec.key.requestIntent.replaceExtras(intents != null ? intents[intents.length - 1] : null); } if (intents != null) { intents[intents.length-1] = rec.key.requestIntent; rec.key.allIntents = intents; rec.key.allResolvedTypes = resolvedTypes; } else { rec.key.allIntents = null; rec.key.allResolvedTypes = null; } } // 凡是能找到對應的節點,而且又不取消該節點的,那麼就return這個節點 return rec; } // 如果PendingIntent的標志中帶有FLAG_CANCEL_CURRENT,則從哈希映射表中刪除之 rec.canceled = true; mIntentSenderRecords.remove(key); } if (noCreate) { // 如果明確表示了不創建新節點,也就是說標志中帶有FLAG_NO_CREATE, // 那麼不管是不是Cancel了PendingIntent,此時一概直接返回。 return rec; } // 從哈希映射表中找不到,而且又沒有寫明FLAG_NO_CREATE,此時創建一個新節點 rec = new PendingIntentRecord(this, key, callingUid); mIntentSenderRecords.put(key, rec.ref); if (type == ActivityManager.INTENT_SENDER_ACTIVITY_RESULT) { // 如果intent需要返回結果,那麼修改token對應的ActivityRecord // 的pendingResults域。 if (activity.pendingResults == null) { activity.pendingResults = new HashSet(); } activity.pendingResults.add(rec.ref); } return rec; }

這段代碼主要做了幾件事:一是把傳入的參數整理成一個 PendingIntentRecord.Key 對象;二是嘗試從 mIntentSenderRecords 總表中查找與 key 相符的節點;三是根據 flags 的語義對找到的節點進行加工,或修改或刪除;四是如果沒找到、或根據 flags 語義刪掉了剛找到的節點,則默認創建一個新節點並插入總表,除非 flags 明確指定了 FLAG_NO_CREATE。

2.4.3 說說 flags

從 getIntentSenderLocked() 的代碼中,我們終於搞明白了那些特定比特值的意義。這些 flags 基本都圍繞著 mIntentSenderRecords 總表說事。FLAG_CANCEL_CURRENT 的意思是:獲取 PendingIntent 時,若能從總表中查到相符的已存在節點,就把這個節點清理出去。而在沒有指定 FLAG_CANCEL_CURRENT 的前提下,如果指定了 FLAG_UPDATE_CURRENT,則會用新的 intents 參數替掉剛查到的節點中的舊 intents。

不管是剛清理了已存在的節點,還是壓根沒找到相符節點,只要用戶沒明確指定 FLAG_NO_CREATE,系統都會盡力創建一個新節點並插入總表。

至於 FLAG_ONE_SHOT,它並沒在 getIntentSenderLocked() 中露面。顧名思義,它就是「只打一槍」的意思,起作用的地方應該在「激發」方法裡。在最終的激發方法 sendInner() 中,可以看到下面的代碼:

【frameworks/base/services/java/com/android/server/am/PendingIntentRecord.java】

 int sendInner(int code, Intent intent, String resolvedType, IIntentReceiver finishedReceiver, String requiredPermission, IBinder resultTo, String resultWho, int requestCode, int flagsMask, int flagsValues, Bundle options) { synchronized(owner) { if (!canceled) { sent = true; if ((key.flags & PendingIntent.FLAG_ONE_SHOT) != 0) { owner.cancelIntentSenderLocked(this, true); canceled = true; } . . . . . . . . . . . . } } return ActivityManager.START_CANCELED; }

意思很簡單:一激發就把相應節點從總表中清理出去,並把 canceled 域設為 true。這樣日後即便外界再調用 send() 也沒用了,因為再也進不了 if (!canceled) 判斷。

2.4.4 將 PendingIntentRecord 節點插入總表

接著 getIntentSenderLocked() 新建了一個 PendingIntentRecord 節點,並把它插入 mIntentSenderRecords 總表中。

2.5 PendingIntent 的激發動作

下面來看激發動作。前面說過,激發主要通過調用 PendingIntent 的 send() 完成。PendingIntent 提供了多個形式的 send(),但內部其實調用的是同一個 send(),原型如下:

 public void send(Context context, int code, Intent intent, OnFinished onFinished, Handler handler, String requiredPermission) throws CanceledException

該方法內部最關鍵的一句是:

 int res = mTarget.send(code, intent, resolvedType, onFinished != null ? new FinishedDispatcher(this, onFinished, handler) : null, requiredPermission);

前面介紹過 mTarget 域,它對應著 AMS 中的某個 PendingIntentRecord,所以要看 PendingIntentRecord 一側的 send():

 public int send(int code, Intent intent, String resolvedType, IIntentReceiver finishedReceiver, String requiredPermission) { return sendInner(code, intent, resolvedType, finishedReceiver, requiredPermission, null, null, 0, 0, 0, null); }

其中 sendInner() 才是真正做激發的方法,主要邏輯動作有:

1)如果當前節點已處於 canceled 為 true 的狀態,說明已被取消,sendInner() 不做任何實質激發,只簡單返回 START_CANCELED。

2)如果當初創建節點時指定了 FLAG_ONE_SHOT,則此時會把節點從 AMS 總表中摘除,並把 canceled 設為 true,之後的操作與普通激發一致,也會走第 3)步。

3)普通激發時,根據當初指定的 type 類型進行不同處理,也就是 INTENT_SENDER_ACTIVITY、INTENT_SENDER_BROADCAST、INTENT_SENDER_SERVICE 等,有興趣可參考本文開頭提到的 getActivity()、getBroadcast()、getService() 等方法的實現。

還有一個問題:既然獲取時已經指定了日後要遞送的 intent,為什麼 send() 裡還有一個 intent 參數?我猜想,設計者是希望給激發端一個修改「待激發 intent」的機會。比如獲取時在 flags 裡設置了 FILL_IN_ACTION,就允許日後在激發點用新 intent 的 mAction 替換最初給的 mAction;反之若一開始沒設 FILL_IN_ACTION,且最初的 intent 已有非空 mAction,那麼即便激發端傳入新 intent,也無法替換舊的 mAction。

細心的讀者一定記得,獲取時我們向 AMS 傳了一個 intent 數組,雖然一般只有一個元素,但有時也可能一次性傳多個(比如 getActivities())。可是現在 send() 只能傳一個 intent 參數,怎麼辦?答案很簡單:所傳入的 intent 只能影響已有數組的最後一個元素,可以看看 sendInner 裡 allIntents[allIntents.length-1] = finalIntent; 這一句。

intent 說完,就該做具體激發了。以簡單的 INTENT_SENDER_BROADCAST 型 PendingIntentRecord 為例,此時激發動作就是發送一個廣播:

 owner.broadcastIntentInPackage(key.packageName, uid, finalIntent, resolvedType, finishedReceiver, code, null, null, requiredPermission, (finishedReceiver != null), false, UserId.getUserId(uid));

至於其他類型的激發動作,大家可以自行查閱代碼,基本格局都差不多。

三、小結

本文基於我早先的一點筆記整理而成。當初為了搞清 PendingIntent 的機理,我也查過不少網絡文章,只是都不太滿足需求,後來只好自己啃代碼,終於有了些粗淺的認識。如今整理出來,希望能給學習 PendingIntent 的同學一點幫助。

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