说说PendingIntent的内部机制css
侯 亮html
在Android中,咱们经常使用PendingIntent来表达一种“留待往后处理”的意思。从这个角度来讲,PendingIntent能够被理解为一种特殊的异步处理机制。不过,单就命名而言,PendingIntent其实具备必定误导性,由于它既不继承于Intent,也不包含Intent,它的核心能够粗略地汇总成四个字——“异步激发”。java
很明显,这种异步激发经常是要跨进程执行的。好比说A进程做为发起端,它能够从系统“获取”一个PendingIntent,而后A进程能够将PendingIntent对象经过binder机制“传递”给B进程,再由B进程在将来某个合适时机,“回调”PendingIntent对象的send()动做,完成激发。android
在Android系统中,最适合作集中性管理的组件就是AMS(Activity Manager Service)啦,因此它责无旁贷地承担起管理全部PendingIntent的职责。这样咱们就能够画出以下示意图:数组
注意其中的第4步“递送相应的intent”。这一步递送的intent是从何而来的呢?简单地说,当发起端获取PendingIntent时,实际上是须要同时提供若干intent的。这些intent和PendingIntent只是配套的关系,而不是聚合的关系,它们会被缓存在AMS中。往后,一旦处理端将PendingIntent的“激发”语义传递到AMS,AMS就会尝试找到与这个PendingIntent对应的若干intent,并递送出去。缓存
固然,以上说的只是大概状况,实际的技术细节会更复杂一点儿。下面咱们就来谈谈细节。异步
咱们先要理解,所谓的“发起端获取PendingIntent”到底指的是什么。难道只是简单new一个PendingIntent对象吗?固然不是。此处的“获取”动做其实还含有向AMS“注册”intent的语义。函数
在PendingIntent.java文件中,咱们能够看到有以下几个比较常见的静态函数:学习
它们就是咱们经常使用的获取PendingIntent的动做了。ui
坦白说,这几个函数的命名可真不怎么样,因此咱们简单解释一下。上面的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实体。示意图以下:
那么PendingIntentRecord里又有什么信息呢?它的定义截选以下:
class PendingIntentRecord extends IIntentSender.Stub { final ActivityManagerService owner; final Key key; // 最关键的key域 final int uid; final WeakReference<PendingIntentRecord> 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(虽然通常状况下只会指定一个intent,但相似getActivities()这样的函数仍是能够指定多个intent的),然后者能够粗浅地理解为用户所指定的那个intent数组中的最后一个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不光承担着记录信息的做用,它还承担“键值”的做用。
在AMS中,管理着系统中全部的PendingIntentRecord节点,因此须要把这些节点组织成一张表:
final HashMap<PendingIntentRecord.Key, WeakReference<PendingIntentRecord>> mIntentSenderRecords
这张哈希映射表的键值类型就是刚才所说的PendingIntentRecord.Key。
之后每当咱们要获取PendingIntent对象时,PendingIntent里的mTarget是这样获得的:AMS会先查mIntentSenderRecords表,若是能找到符合的PendingIntentRecord节点,则返回之。若是找不到,就建立一个新的PendingIntentRecord节点。由于PendingIntentRecord是个binder实体,因此通过binder机制传递后,客户进程拿到的就是个合法的binder代理。如此一来,前文的示意图能够进一步修改为下图:
如今,咱们回过头继续说前文的getActivity(),以及其调用的getIntentSender()。咱们先列一遍getActivity()的原型:
public static PendingIntent getActivity(Context context, int requestCode, Intent intent, int flags, Bundle 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,表示这个PendingIntent激发时,是不须要发回什么回馈的。不过当咱们但愿获取类型为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能够根据这个ActivityRecord肯定出该向哪一个目标进程的哪一个Activity发出result语义。
resultWho参数和token参数息息相关,通常也是null啦。在createPendingResult()中,其值为Activity的mEmbeddedID字符串。
requestCode参数是个简单的整数,能够在获取PendingIntent时由用户指定,它能够起区分的做用。
intents数组参数是异步激发时但愿发出的intent。对于getActivity()、getBroadcast()和getService()来讲,都只会指定一个intent而已。只有getActivities()会尝试一次传入若干intent。
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等等。有时候,flags中还能够附带若干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的mAction域赋值:
1) 当srcIntent的mAction域值为null时;
2) 若是fillIn的flags参数里携带了FILL_IN_ACTION标志位,那么即使srcIntent的mAction已经有值了,此时也会用otherIntent的mAction域值强行替换掉srcIntent的mAction域值。
其余FILL_IN_标志位和FILL_IN_ACTION的处理方式相似,咱们再也不赘述。
options参数能够携带一些额外数据。
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); . . . . . . }
getIntentSender()函数中有一段逐条判断intents[]的代码,我用伪代码checkIntents(intents)来表示,这部分对应的实际代码以下:
for (int i=0; i<intents.length; i++) { Intent intent = intents[i]; if (intent != null) { if (intent.hasFileDescriptors()) { throw new IllegalArgumentException("File descriptors passed in Intent"); } if (type == ActivityManager.INTENT_SENDER_BROADCAST && (intent.getFlags()&Intent.FLAG_RECEIVER_BOOT_UPGRADE) != 0) { throw new IllegalArgumentException("Can't use FLAG_RECEIVER_BOOT_UPGRADE here"); } intents[i] = new Intent(intent); } }
这段代码说明在获取PendingIntent对象时,intent中是不能携带文件描述符的。并且若是这个PendingIntent是那种要发出广播的PendingIntent,那么intent中也不能携带FLAG_RECEIVER_BOOT_UPGRADE标识符。“BOOT_UPGRADE”应该是“启动并升级”的意思,它不能使用PendingIntent。
getIntentSender()中最核心的一句应该是调用getIntentSenderLocked()的那句。
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<PendingIntentRecord> 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<WeakReference<PendingIntentRecord>>(); } activity.pendingResults.add(rec.ref); } return rec; }
上面这段代码主要作的事情有:
1) 将传进来的多个参数信息整理成一个PendingIntentRecord.Key对象(key);
2) 尝试从mIntentSenderRecords总表中查找和key相符的PendingIntentRecord节点;
3) 根据flags参数所含有的意义,对获得的PendingIntentRecord进行加工。有时候修改之,有时候删除之。
4) 若是在总表中没有找到对应的PendingIntentRecord节点,或者根据flags的语义删除了刚找到的节点,那么此时的默认行为是建立一个新的PendingIntentRecord节点,并插入总表。除非flags中明确指定了FLAG_NO_CREATE,此时不会建立新节点。
从getIntentSenderLocked()的代码中,咱们终于搞明白了flags中那些特定比特值的意义了。咱们如今总结一下。
应该说这些flags比特值基本上都是在围绕着mIntentSenderRecords总表说事的。其中,FLAG_CANCEL_CURRENT的意思是,当咱们获取PendingIntent时,若是能够从总表中查到一个相符的已存在的PendingIntentRecord节点的话,那么须要把这个节点从总表中清理出去。而在没有指定FLAG_CANCEL_CURRENT的大前提下,若是用户指定了FLAG_UPDATE_CURRENT标识,那么会用新的intents参数替掉刚查到的PendingIntentRecord中的旧intents。
而不论是刚清理了已存在的PendingIntentRecord,仍是压根儿就没有找到符合的PendingIntentRecord,只要用户没有明确指定FLAG_NO_CREATE标识,系统就会尽力建立一个新的PendingIntentRecord节点,并插入总表。
至于FLAG_ONE_SHOT标识嘛,它并无在getIntentSenderLocked()中露脸儿。它的名字是“FLAG_ONE_SHOT”,也就是“只打一枪”的意思,那么很明显,这个标识起做用的地方应该是在“激发”函数里。在最终的激发函数(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; }
意思很简单,一进行激发就把相应的PendingIntentRecord节点从总表中清理出去,并且把PendingIntentRecord的canceled域设为true。这样,之后即使外界再调用send()动做都没用了,由于再也没法进入if (!canceled)判断了。
接下来getIntentSenderLocked()函数new了一个PendingIntentRecord节点,并将之插入mIntentSenderRecords总表中。
下面咱们来看PendingIntent的激发动做。在前文咱们已经说过,当须要激发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()才是真正作激发动做的函数。
sendInner()完成的主要逻辑动做有:
1) 若是当前PendingIntentRecord节点已经处于canceled域为true的状态,那么说明这个节点已经被取消掉了,此时sendInner()不会作任何实质上的激发动做,只是简单地return ActivityManager.START_CANCELED而已。
2) 若是当初在建立这个节点时,使用者已经指定了FLAG_ONE_SHOT标志位的话,那么此时sendInner()会把这个PendingIntentRecord节点从AMS中的总表中摘除,而且把canceled域设为true。然后的操做和普通激发时的动做是一致的,也就是说也会走下面的第3)步。
3) 关于普通激发时应执行的逻辑动做是,根据当初建立PendingIntentRecord节点时,用户指定的type类型,进行不一样的处理。这个type其实就是咱们前文所说的INTENT_SENDER_ACTIVITY、INTENT_SENDER_BROADCAST、INTENT_SENDER_SERVICE等类型啦,你们若有兴趣,可本身参考本文一开始所说的getActivity()、getBroadcast()、getService()等函数的实现代码。
如今还有一个问题是,既然咱们在当初获取PendingIntent时,已经指定了往后激发时须要递送的intent(或intent数组),那么为何send()动做里还有一个intent参数呢?它们的关系又是什么呢?我猜测,PendingIntent机制的设计者是但愿给激发端一个修改“待激发的intent”的机会。好比当初咱们获取PendingIntent对象时,若是在flags里设置了FILL_IN_ACTION标志位,那么就说明咱们容许往后在某个激发点,用新的intent的mAction域值,替换掉咱们最初给的intent的mAction域值。若是一开始没有设置FILL_IN_ACTION标志位,并且在最初的intent里已经有了非空的mAction域值的话,那么即便在激发端又传入了新intent,它也不可能修改用新intent的mAction域值替换旧intent的mAction域值。
细心的读者必定记得,当初获取PendingIntent对象时,咱们但是向AMS端传递了一个intent数组噢,虽然通常状况下这个数组里只有一个intent元素,但有时候咱们也是有可能一次性传递多个intent的。好比getActivities()函数就能够一次传递多个intent。但是如今激发动做send()却只能传递一个intent参数,这该如何处理呢?答案很简单,所传入的intent只能影响已有的intent数组的最后一个intent元素。你们能够看看sendInner里allIntents[allIntents.length-1] = finalIntent;一句。
Ok,intent说完了,下面就该作具体的激发了。咱们以简单的INTENT_SENDER_BROADCAST型PendingIntentRecord来讲明,此时的激发动做就是发送一个广播:
owner.broadcastIntentInPackage(key.packageName, uid, finalIntent, resolvedType, finishedReceiver, code, null, null, requiredPermission, (finishedReceiver != null), false, UserId.getUserId(uid));
至于其余类型的PendingIntentRecord的激发动做,你们能够自行查阅代码,它们的基本代码格局都是差很少的。
本文是基于我早先的一点儿笔记整理而成的。当时为了搞清楚PendingIntent的机理,也查阅了一些网上的相关文章,只是都不大知足个人要求,后来只好本身看代码,终于得了些本身的浅见。如今把我过去的一点儿认识整理出来,但愿能对学习PendingIntent的同窗有点儿帮助。