原文来自于 Gityuan startService启动过程分析 和 Service 流程分析 源码更新于 AndroidCodeSearch (现在是 Android 11) ,老版本代码查看于 opersys
一、概述 经历了之前的 无 Binder 不 Android ,相信对 Binder 架构有了较深地理解。Binder 的地位是非常之重要,整个 Java framework 的提供ActivityManagerService 、PackageManagerService 等服务都是基于 Binder 架构来通信的,另外 Handle 消息机制 在进程内的通信使用非常多。本文将开启对 ActivityManagerService 的分析。
ActivityManagerService 是 Android 的 Java framework 的服务框架最重要的服务之一。
对于 Andorid 的 Activity、Service、Broadcast、ContentProvider 四剑客的管理,包含其生命周期都是通过 ActivityManagerService 来完成的。
1.1 ActivityManagerService 介绍 缩写
AMP: ActivityManagerProxy
AMN: ActivityManagerNative
AMS: ActivityManagerService
AT: ApplicationThread
ATP: ApplicationThreadProxy
ATN: ApplicationThreadNative
IAM: IActivityManager
IAT: IApplicationThread
ACF: AppComponentFactory
CW: ContextWrapper
CI: ContextImpl
LA: LoadeAPK
Android 7.0 Android7 之前(包括7.0、7.1),AMS 是通过自己实现代理类来完成 Binder
与 AMS 通信是基于其代理 AMP(通过 ActivityManagerNative. getDefault 得到其内部类 ActivityManagerProxy 的单例对象,即 AMS 在客户端(用户进程)的代理对象)
Activity 的直接管理者是 ActivityManager,但最终管理者是 AMS:
Client 端发起启动 Service 请求;
AM 会通过 ActivityManagerNative 的 getDefault 来得到其内部类 ActivityManagerProxy 的单例对象,即 AMS 在客户端(用户进程)的代理对象;
作为代理类,AMP 中含有 AMS 的引用,AMN 和 AMP 都实现了 IActivityManager ;
IActivityManager 继承了 IInterface(实现 Binder 通信的必备条件),所以 AMP 具备了 Binder 通信能力;
startService 最终会通过 AMP 中的 AMS 引用来调用 AMS 的 transact 方法;
向 AMS 发送启动 Service 请求,并将序列化数据传递给 AMS ,随后 AMS 的子类 AMN 的 onTransact 会执行,它会将具体的启动工作交给 ActivityStater 来负责;
Android 8.0 8.0 开始,AMS 通过 AIDL 完成 Binder 通信
AMS 中主要涉及这三个数据结构:ActivityRecord、TaskRecord 和 ActivityStack ;
ActivityRecord: 存储 Activity 的相关信息,比如 AndroidMainifes 的节点信息,启动 Activity 的包名,所在进程,图标主题标识符,当前 Activity 状态,所属 TaskRecord 等;
TaskRecord: 描述一个 Activity 任务栈,主要维护了一个按历史顺序排列的 ArrayList<ActivityRecord>,并包含此任务栈所属的 ActivityStack 等;
ActivityStack: 一个管理系统中所有 Activity 的管理类,真实交由 ActivityStackSupervisor 管理,内部维护了 Activity 的所有状态,并对不同状态的 Activity 进行分类管理,如最近启动的 Activity,正在暂停的 Activity 等。
IActivityManager.java 就是 ADIL 文件所对应的 java 文件,里面包含了 Proxy 和 Stub 类
1.2 ApplicationThread Android 7.0 Android 7 之前(包括7.0、7.1),AT 是通过自己实现代理类来完成 Binder
与 IActivityManager 的 binder 通信原理一样,ApplicationThreadProxy 作为 binder 通信的客户端,ApplicationThreadNative 作为 Binder 通信的服务端,其中ApplicationThread 继承 ApplicationThreadNative 类,覆写其中的部分方法。
Android 8.0 8.0 开始,AT 通过 AIDL 完成 Binder 通信
IApplivation.Thread.Stub 代替 ApplicationThreadNative
IApplivation.Thread.Stub.Proxy 代替 ApplicationThreadProxy
1.3 启动服务流程图 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 frameworks/base/services/core/java/com/android/server/am/ - ActivityManagerService.java - ActiveServices.java - ServiceRecord.java - ProcessRecord.java out/soong/.intermediates/frameworks/base/framework-minus-apex/android_common/xref30/srcjars.xref/android/app/ - IActivityManager.java (AIDL 文件生成的,内含 Proxy 和 Stub) - IApplicationThread.java (AIDL 文件生成的,内含 Proxy 和 Stub) frameworks/base/core/java/android/app/ - ActivityManager.java - IApplicationThread.java - ActivityThread.java (内含 ApplicationThread ) - ContextImpl.java - LoadedApk.java frameworks/base/core/java/android/content/ - ContextWrapper.java
接下来,我们正式从代码角度来分析服务启动的过程。
二、startService 源码 2.1 CW.startService 1 2 3 4 5 6 ContextWrapper.java @Override public ComponentName startService (Intent service) { return mBase.startService(service); }
2.2 CI.startService 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 ContextImpl.java @Override public ComponentName startService (Intent service) { warnIfCallingFromSystemProcess(); return startServiceCommon(service, false , mUser); } private ComponentName startServiceCommon (Intent service, boolean requireForeground, UserHandle user) { try { validateServiceIntent(service); service.prepareToLeaveProcess(this ); ComponentName cn = ActivityManager.getService().startService( mMainThread.getApplicationThread(), service, service.resolveTypeIfNeeded( getContentResolver()), requireForeground, getOpPackageName(), user.getIdentifier()); return cn; } catch (RemoteException e) { throw e.rethrowFromSystemServer(); } }
2.3 AM.getService 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 ActivityManager.java public static IActivityManager getService () { return IActivityManagerSingleton.get(); } Singleton.java @UnsupportedAppUsage public final T get () { synchronized (this ) { if (mInstance == null ) { mInstance = create(); } return mInstance; } } ActivityManager.java private static final Singleton<IActivityManager> IActivityManagerSingleton = new Singleton<IActivityManager>() { @Override protected IActivityManager create () { final IBinder b = ServiceManager.getService(Context.ACTIVITY_SERVICE); final IActivityManager am = IActivityManager.Stub.asInterface(b); return am; } }; IActivityManager.java public static android.app.IActivityManager asInterface (android.os.IBinder obj) { if ((obj==null )) { return null ; } android.os.IInterface iin = obj.queryLocalInterface(DESCRIPTOR); if (((iin!=null )&&(iin instanceof android.app.IActivityManager))) { return ((android.app.IActivityManager)iin); } return new android.app.IActivityManager.Stub.Proxy(obj); }
create 方法返回的是 AIDL 生成的代理类,IActivityManager.Stub.Proxy, 那么下一步调用 IActivityManager.Stub.Proxy.startService 方法。
通过 Binder 通信过程中,
提供了一个 IActivityManager 服务接口(继承于 android.os.IInterface)
IActivityManager.Stub.Proxy 类实现了 IActivityManager 接口
IActivityManager.Stub 继承 Binder 并且实现 IActivityManager 接口
ActivityManagerService 继承自 IActivityManager.Stub
这里可以看出 IActivityManager.Stub.Proxy 是 Binder 通信的客户端,ActivityManagerService 是 Binder 通信的服务端,那么IActivityManager.Proxy.startService() 最终调用的是 ActivityManagerService.startService()
2.3.1 IAM.Stub.Proxy.startService 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 @Override public android.content.ComponentName startService (android.app.IApplicationThread caller, android.content.Intent service, java.lang.String resolvedType, boolean requireForeground, java.lang.String callingPackage, java.lang.String callingFeatureId, int userId) throws android.os.RemoteException { android.os.Parcel _data = android.os.Parcel.obtain(); android.os.Parcel _reply = android.os.Parcel.obtain(); android.content.ComponentName _result; try { _data.writeInterfaceToken(DESCRIPTOR); _data.writeStrongBinder((((caller!=null ))?(caller.asBinder()):(null ))); if ((service!=null )) { _data.writeInt(1 ); service.writeToParcel(_data, 0 ); } else { _data.writeInt(0 ); } _data.writeString(resolvedType); _data.writeInt(((requireForeground)?(1 ):(0 ))); _data.writeString(callingPackage); _data.writeString(callingFeatureId); _data.writeInt(userId); boolean _status = mRemote.transact(Stub.TRANSACTION_startService, _data, _reply, 0 ); if (!_status) { if (getDefaultImpl() != null ) { return getDefaultImpl().startService(caller, service, resolvedType, requireForeground, callingPackage, callingFeatureId, userId); } } _reply.readException(); if ((0 !=_reply.readInt())) { _result = android.content.ComponentName.CREATOR.createFromParcel(_reply); } else { _result = null ; } } finally { _reply.recycle(); _data.recycle(); } return _result; }
2.3.2 IAM.Stub.onTransact(Client -> Service) 到这里,借助 IAM 这个 AIDL ,便完成了从 Service 所在的进程(Client 的进程)到了 system_server 进程(服务进程)的调用过程。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 @Override public boolean onTransact (int code, android.os.Parcel data, android.os.Parcel reply, int flags) throws android.os.RemoteException { switch (code) ... case TRANSACTION_startService: { data.enforceInterface(descriptor); android.app.IApplicationThread _arg0; _arg0 = android.app.IApplicationThread.Stub.asInterface(data.readStrongBinder()); android.content.Intent _arg1; if ((0 !=data.readInt())) { _arg1 = android.content.Intent.CREATOR.createFromParcel(data); } else { _arg1 = null ; } java.lang.String _arg2; _arg2 = data.readString(); boolean _arg3; _arg3 = (0 !=data.readInt()); java.lang.String _arg4; _arg4 = data.readString(); java.lang.String _arg5; _arg5 = data.readString(); int _arg6; _arg6 = data.readInt(); android.content.ComponentName _result = this .startService(_arg0, _arg1, _arg2, _arg3, _arg4, _arg5, _arg6); reply.writeNoException(); if ((_result!=null )) { reply.writeInt(1 ); _result.writeToParcel(reply, android.os.Parcelable.PARCELABLE_WRITE_RETURN_VALUE); } else { reply.writeInt(0 ); } return true ; } }
在整个调用过程涉及两个进程,令 startService 的发起进程记为进程 A ,ServiceManagerService 记为进程 B ;那么进程 A 通过 Binder 机制(采用 IActivityManager 接口)向进程B发起请求服务,进程 B 则通过 Binder 机制(采用 IApplicationThread 接口)向进程 A 发起请求服务。也就是说进程 A 与进程 B 能相互间主动发起请求,进程通信。
2.4 AMS.startService 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 @Override public ComponentName startService (IApplicationThread caller, Intent service, String resolvedType, boolean requireForeground, String callingPackage, int userId) throws TransactionTooLargeException { enforceNotIsolatedCaller("startService" ); if (service != null && service.hasFileDescriptors() == true ) { throw new IllegalArgumentException("File descriptors passed in Intent" ); } if (callingPackage == null ) { throw new IllegalArgumentException("callingPackage cannot be null" ); } if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "*** startService: " + service + " type=" + resolvedType + " fg=" + requireForeground); synchronized (this ) { final int callingPid = Binder.getCallingPid(); final int callingUid = Binder.getCallingUid(); final long origId = Binder.clearCallingIdentity(); ComponentName res; try { res = mServices.startServiceLocked(caller, service, resolvedType, callingPid, callingUid, requireForeground, callingPackage, userId); } finally { Binder.restoreCallingIdentity(origId); } return res; } }
参数说明
caller: IApplicationThread 类型,复杂处理
service: Intent 类型,包含需要运行的 service 信息
*resolvedType: * String 类型
callingPackage: String 类型,调用该方法的 package
userId: int 类型,用户的 id
2.5 AS.startServiceLocked 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 ComponentName startServiceLocked (IApplicationThread caller, Intent service, String resolvedType, int callingPid, int callingUid, boolean fgRequired, String callingPackage, final int userId) throws TransactionTooLargeException { final boolean callerFg; if (caller != null ) { final ProcessRecord callerApp = mAm.getRecordForAppLocked(caller); if (callerApp == null ) { throw new SecurityException("" ); } callerFg = callerApp.setSchedGroup != ProcessList.SCHED_GROUP_BACKGROUND; } else { callerFg = true ; } ServiceLookupResult res = retrieveServiceLocked(service, resolvedType, callingPackage, callingPid, callingUid, userId, true , callerFg, false , false ); if (res == null ) { return null ; } if (res.record == null ) { return new ComponentName("!" , res.permission != null ? res.permission : "private to package" ); } ServiceRecord r = res.record; if (!mAm.mUserController.exists(r.userId)) { Slog.w(TAG, "Trying to start service with non-existent user! " + r.userId); return null ; } r.lastActivity = SystemClock.uptimeMillis(); r.startRequested = true ; r.delayedStop = false ; r.fgRequired = fgRequired; r.pendingStarts.add(new ServiceRecord.StartItem(r, false , r.makeNextStartId(), service, neededGrants, callingUid)); ComponentName cmp = startServiceInnerLocked(smap, service, r, callerFg, addToStarting); return cmp; }
有一种重要的标记符 callerFg , 用于标记是前台还是后台:
当发起方进程不等于 ProcessList.SCHED_GROUP_BACKGROUND ,或者发起方为空, 则 callerFg= true ;
否则,callerFg= false;
2.6 AS.startServiceInnerLocked 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 ComponentName startServiceInnerLocked (ServiceMap smap, Intent service, ServiceRecord r, boolean callerFg, boolean addToStarting) throws TransactionTooLargeException { ServiceState stracker = r.getTracker(); if (stracker != null ) { stracker.setStarted(true , mAm.mProcessStats.getMemFactorLocked(), r.lastActivity); } r.callStart = false ; synchronized (r.stats.getBatteryStats()) { r.stats.startRunningLocked(); } String error = bringUpServiceLocked(r, service.getFlags(), callerFg, false , false ); if (error != null ) { return new ComponentName("!!" , error); } if (r.startRequested && addToStarting) { boolean first = smap.mStartingBackground.size() == 0 ; smap.mStartingBackground.add(r); r.startingBgTimeout = SystemClock.uptimeMillis() + mAm.mConstants.BG_START_TIMEOUT; if (DEBUG_DELAYED_SERVICE) { RuntimeException here = new RuntimeException("here" ); here.fillInStackTrace(); Slog.v(TAG_SERVICE, "Starting background (first=" + first + "): " + r, here); } else if (DEBUG_DELAYED_STARTS) { Slog.v(TAG_SERVICE, "Starting background (first=" + first + "): " + r); } if (first) { smap.rescheduleDelayedStartsLocked(); } } else if (callerFg || r.fgRequired) { smap.ensureNotStartingBackgroundLocked(r); } return r.name; }
2.7 AS.bringUpServiceLocked 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 private String bringUpServiceLocked (ServiceRecord r, int intentFlags, boolean execInFg, boolean whileRestarting, boolean permissionsReviewRequired) throws TransactionTooLargeException { if (r.app != null && r.app.thread != null ) { sendServiceArgsLocked(r, execInFg, false ); return null ; } if (!whileRestarting && mRestartingServices.contains(r)) { return null ; } if (mRestartingServices.remove(r)) { clearRestartingIfNeededLocked(r); } if (r.delayed) { if (DEBUG_DELAYED_STARTS) Slog.v(TAG_SERVICE, "REM FR DELAY LIST (bring up): " + r); getServiceMapLocked(r.userId).mDelayedStartList.remove(r); r.delayed = false ; } if (!mAm.mUserController.hasStartedUserState(r.userId)) { String msg = "Unable to launch app " + r.appInfo.packageName + "/" + r.appInfo.uid + " for service " + r.intent.getIntent() + ": user " + r.userId + " is stopped" ; Slog.w(TAG, msg); bringDownServiceLocked(r); return msg; } try { AppGlobals.getPackageManager().setPackageStoppedState( r.packageName, false , r.userId); } catch (RemoteException e) { } catch (IllegalArgumentException e) { Slog.w(TAG, "Failed trying to unstop package " + r.packageName + ": " + e); } final boolean isolated = (r.serviceInfo.flags&ServiceInfo.FLAG_ISOLATED_PROCESS) != 0 ; final String procName = r.processName; String hostingType = "service" ; ProcessRecord app; if (!isolated) { app = mAm.getProcessRecordLocked(procName, r.appInfo.uid, false ); if (DEBUG_MU) Slog.v(TAG_MU, "bringUpServiceLocked: appInfo.uid=" + r.appInfo.uid + " app=" + app); if (app != null && app.thread != null ) { try { app.addPackage(r.appInfo.packageName, r.appInfo.longVersionCode, mAm.mProcessStats); realStartServiceLocked(r, app, execInFg); return null ; } catch (TransactionTooLargeException e) { throw e; } catch (RemoteException e) { Slog.w(TAG, "Exception when starting service " + r.shortName, e); } } } else { app = r.isolatedProc; if (WebViewZygote.isMultiprocessEnabled() && r.serviceInfo.packageName.equals(WebViewZygote.getPackageName())) { hostingType = "webview_service" ; } } if (app == null && !permissionsReviewRequired) { if ((app=mAm.startProcessLocked(procName, r.appInfo, true , intentFlags, hostingType, r.name, false , isolated, false )) == null ) { bringDownServiceLocked(r); return msg; } if (isolated) { r.isolatedProc = app; } } if (r.fgRequired) { mAm.tempWhitelistUidLocked(r.appInfo.uid,SERVICE_START_FOREGROUND_TIMEOUT, "fg-service-launch" ); } if (!mPendingServices.contains(r)) { mPendingServices.add(r); } if (r.delayedStop) { r.delayedStop = false ; if (r.startRequested) { stopServiceLocked(r); } } return null ; }
当目标进程已存在,则直接执行 realStartServiceLocked();
当目标进程不存在,则先执行 startProcessLocked(过程待更新 Android四大组件与进程启动的关系 ) 创建进程, 经过层层调用最后会调用到 AMS.attachApplicationLocked, 然后再执行 realStartServiceLocked() 。
对于非前台进程调用而需要启动的服务,如果已经有其他的后台服务正在启动中,那么我们可能希望延迟其启动。这是用来避免启动同时启动过多的进程(非必须的)。
2.7.1 AMS.attachApplicationLocked 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 private final boolean attachApplicationLocked (IApplicationThread thread, int pid) { ... thread.bindApplication(processName, appInfo, providers, app.instrumentationClass, profilerInfo, app.instrumentationArguments, app.instrumentationWatcher, app.instrumentationUiAutomationConnection, testMode, enableOpenGlTrace, isRestrictedBackupMode || !normalMode, app.persistent, new Configuration(mConfiguration), app.compat, getCommonServicesLocked(app.isolated), mCoreSettingsObserver.getCoreSettingsLocked()); ... if (!badApp) { try { didSomething |= mServices.attachApplicationLocked(app, processName); } catch (Exception e) { badApp = true ; } } ... return true ; }
2.7.2 AS.attachApplicationLocked 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 boolean attachApplicationLocked (ProcessRecord proc, String processName) throws RemoteException { boolean didSomething = false ; if (mPendingServices.size() > 0 ) { ServiceRecord sr = null ; try { for (int i=0 ; i<mPendingServices.size(); i++) { sr = mPendingServices.get(i); if (proc != sr.isolatedProc && (proc.uid != sr.appInfo.uid || !processName.equals(sr.processName))) { continue ; } mPendingServices.remove(i); i--; proc.addPackage(sr.appInfo.packageName, sr.appInfo.longVersionCode,mAm.mProcessStats); realStartServiceLocked(sr, proc, sr.createdFromFg); didSomething = true ; if (!isServiceNeededLocked(sr, false , false )) { bringDownServiceLocked(sr); } } } catch (RemoteException e) { Slog.w(TAG, "Exception in new application when starting service " + sr.shortName, e); throw e; } } if (mRestartingServices.size() > 0 ) { ServiceRecord sr; for (int i=0 ; i<mRestartingServices.size(); i++) { sr = mRestartingServices.get(i); if (proc != sr.isolatedProc && (proc.uid != sr.appInfo.uid || !processName.equals(sr.processName))) { continue ; } mAm.mHandler.removeCallbacks(sr.restarter); mAm.mHandler.post(sr.restarter); } } return didSomething; }
当需要创建新进程,则创建后经历过 attachApplicationLocked,则会再调用 realStartServiceLocked();
当不需要创建进程,即在上一步中直接就进入了 realStartServiceLocked();
2.8 AS.realStartServiceLocked 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 private final void realStartServiceLocked (ServiceRecord r, ProcessRecord app, boolean execInFg) throws RemoteException { if (app.thread == null ) { throw new RemoteException(); } r.app = app; r.restartTime = r.lastActivity = SystemClock.uptimeMillis(); final boolean newService = app.services.add(r); bumpServiceExecutingLocked(r, execInFg, "create" ); mAm.updateLruProcessLocked(app, false , null ); updateServiceForegroundLocked(r.app, false ); mAm.updateOomAdjLocked(); boolean created = false ; try { if (LOG_SERVICE_START_STOP) { String nameTerm; int lastPeriod = r.shortName.lastIndexOf('.' ); nameTerm = lastPeriod >= 0 ? r.shortName.substring(lastPeriod) : r.shortName; EventLogTags.writeAmCreateService( r.userId, System.identityHashCode(r), nameTerm, r.app.uid, r.app.pid); } synchronized (r.stats.getBatteryStats()) { r.stats.startLaunchedLocked(); } mAm.notifyPackageUse(r.serviceInfo.packageName, PackageManager.NOTIFY_PACKAGE_USE_SERVICE); app.forceProcessStateUpTo(ActivityManager.PROCESS_STATE_SERVICE); app.thread.scheduleCreateService(r, r.serviceInfo, mAm.compatibilityInfoForPackageLocked(r.serviceInfo.applicationInfo), app.repProcState); r.postNotification(); created = true ; } catch (DeadObjectException e) { mAm.appDiedLocked(app); throw e; } finally { if (!created) { final boolean inDestroying = mDestroyingServices.contains(r); serviceDoneExecutingLocked(r, inDestroying, inDestroying); if (newService) { app.services.remove(r); r.app = null ; } if (!inDestroying) { scheduleServiceRestartLocked(r, false ); } } } if (r.whitelistManager) { app.whitelistManager = true ; } requestServiceBindingsLocked(r, execInFg); updateServiceClientActivitiesLocked(app, null , true ); if (r.startRequested && r.callStart && r.pendingStarts.size() == 0 ) { r.pendingStarts.add(new ServiceRecord.StartItem(r, false , r.makeNextStartId(),null , null , 0 )); } sendServiceArgsLocked(r, execInFg, true ); if (r.delayed) { getServiceMapLocked(r.userId).mDelayedStartList.remove(r); r.delayed = false ; } if (r.delayedStop) { r.delayedStop = false ; if (r.startRequested) { stopServiceLocked(r); } } }
2.8.1 AS.bumpServiceExecutingLocked 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 private final void bumpServiceExecutingLocked (ServiceRecord r, boolean fg, String why) { boolean timeoutNeeded = true ; if ((mAm.mBootPhase < SystemService.PHASE_THIRD_PARTY_APPS_CAN_START) && (r.app != null ) && (r.app.pid == android.os.Process.myPid())) { timeoutNeeded = false ; } if (r.executeNesting == 0 ) { } else if (r.app != null && fg && !r.app.execServicesFg) { r.app.execServicesFg = true ; if (timeoutNeeded) { scheduleServiceTimeoutLocked(r.app); } } }
2.8.2 AS.scheduleServiceTimeoutLocked 1 2 3 4 5 6 7 8 9 10 11 void scheduleServiceTimeoutLocked (ProcessRecord proc) { if (proc.executingServices.size() == 0 || proc.thread == null ) { return ; } Message msg = mAm.mHandler.obtainMessage( ActivityManagerService.SERVICE_TIMEOUT_MSG); msg.obj = proc; mAm.mHandler.sendMessageDelayed(msg, proc.execServicesFg ? SERVICE_TIMEOUT : SERVICE_BACKGROUND_TIMEOUT); }
发送延时消息 `SERVICE_TIMEOUT_MSG 延时时长:
对于前台服务,则超时为 SERVICE_TIMEOUT,即 timeout=20s;
对于后台服务,则超时为 SERVICE_BACKGROUND_TIMEOUT,即 timeout=200s;
2.9 IAT.Stub.Proxy.scheduleCreateService 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 @Override public void scheduleCreateService (android.os.IBinder token, android.content.pm.ServiceInfo info, android.content.res.CompatibilityInfo compatInfo, int processState) throws android.os.RemoteException { android.os.Parcel _data = android.os.Parcel.obtain(); try { _data.writeInterfaceToken(DESCRIPTOR); _data.writeStrongBinder(token); if ((info!=null )) { _data.writeInt(1 ); info.writeToParcel(_data, 0 ); } else { _data.writeInt(0 ); } if ((compatInfo!=null )) { _data.writeInt(1 ); compatInfo.writeToParcel(_data, 0 ); } else { _data.writeInt(0 ); } _data.writeInt(processState); boolean _status = mRemote.transact(Stub.TRANSACTION_scheduleCreateService, _data, null , android.os.IBinder.FLAG_ONEWAY); if (!_status) { if (getDefaultImpl() != null ) { getDefaultImpl().scheduleCreateService(token, info, compatInfo, processState); return ; } } } finally { _data.recycle(); } }
2.9.1 IAT.Stub.onTransact (Service -> Client) 到这里,借助 IAT 这个 AIDL ,便完成了从 system_server 进程(服务进程)到了 Service 所在的进程(Client 的进程)的调用过程。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 @Override public boolean onTransact (int code, android.os.Parcel data, android.os.Parcel reply, int flags) throws android.os.RemoteException { switch (code) ... case TRANSACTION_scheduleCreateService: { data.enforceInterface(descriptor); android.os.IBinder _arg0; _arg0 = data.readStrongBinder(); android.content.pm.ServiceInfo _arg1; if ((0 !=data.readInt())) { _arg1 = android.content.pm.ServiceInfo.CREATOR.createFromParcel(data); } else { _arg1 = null ; } android.content.res.CompatibilityInfo _arg2; if ((0 !=data.readInt())) { _arg2 = android.content.res.CompatibilityInfo.CREATOR.createFromParcel(data); } else { _arg2 = null ; } int _arg3; _arg3 = data.readInt(); this .scheduleCreateService(_arg0, _arg1, _arg2, _arg3); return true ; } }
2.9.2 AT.scheduleCreateService 1 2 3 4 5 6 7 8 9 10 11 12 public final void scheduleCreateService (IBinder token, ServiceInfo info, CompatibilityInfo compatInfo, int processState) { updateProcessState(processState, false ); CreateServiceData s = new CreateServiceData(); s.token = token; s.info = info; s.compatInfo = compatInfo; sendMessage(H.CREATE_SERVICE, s); } final H mH = new H();
H 是 ActivityThread 的内部类,继承 Handler
2.10 AT.H.handleMessage 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 void sendMessage (int what, Object obj) { sendMessage(what, obj, 0 , 0 , false ); } private void sendMessage (int what, Object obj, int arg1, int arg2, boolean async) { Message msg = Message.obtain(); msg.what = what; msg.obj = obj; msg.arg1 = arg1; msg.arg2 = arg2; if (async) { msg.setAsynchronous(true ); } mH.sendMessage(msg); } class H extends Handler { public void handleMessage (Message msg) { switch (msg.what) { case CREATE_SERVICE: handleCreateService((CreateServiceData)msg.obj); break ; case BIND_SERVICE: handleBindService((BindServiceData)msg.obj); break ; case UNBIND_SERVICE: handleUnbindService((BindServiceData)msg.obj); break ; case SERVICE_ARGS: handleServiceArgs((ServiceArgsData)msg.obj); break ; case STOP_SERVICE: handleStopService((IBinder)msg.obj); break ; } } }
2.11 AT.handleCreateService 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 private void handleCreateService (CreateServiceData data) { unscheduleGcIdler(); LoadedApk packageInfo = getPackageInfoNoCheck(data.info.applicationInfo, data.compatInfo); Service service = null ; try { java.lang.ClassLoader cl = packageInfo.getClassLoader(); service = packageInfo.getAppFactory().instantiateService(cl, data.info.name, data.intent); } catch (Exception e) { } try { ContextImpl context = ContextImpl.createAppContext(this , packageInfo); context.setOuterContext(service); Application app = packageInfo.makeApplication(false , mInstrumentation); service.attach(context, this , data.info.name, data.token, app,ActivityManager.getService()); service.onCreate(); mServices.put(data.token, service); try { ActivityManager.getService().serviceDoneExecuting(data.token, SERVICE_DONE_EXECUTING_ANON, 0 , 0 ); } catch (RemoteException e) { } } catch (Exception e) { } }
2.11.1 packageInfo.getAppFactory() 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 public AppComponentFactory getAppFactory () { return mAppComponentFactory; } private AppComponentFactory createAppFactory (ApplicationInfo appInfo, ClassLoader cl) { if (appInfo.appComponentFactory != null && cl != null ) { try { return (AppComponentFactory) cl.loadClass(appInfo.appComponentFactory) .newInstance(); } catch (InstantiationException | IllegalAccessException | ClassNotFoundException e) { Slog.e(TAG, "Unable to instantiate appComponentFactory" , e); } } return AppComponentFactory.DEFAULT; }
2.12 ACF.instantiateService 1 2 3 4 5 6 public @NonNull Service instantiateService (@NonNull ClassLoader cl, @NonNull String className, @Nullable Intent intent) throws InstantiationException, IllegalAccessException, ClassNotFoundException { return (Service) cl.loadClass(className).newInstance(); }
2.13 Service.attach/onCreate 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 public abstract class Service extends ContextWrapper implements ComponentCallbacks2 { public final void attach ( Context context, ActivityThread thread, String className, IBinder token, Application application, Object activityManager) { attachBaseContext(context); mThread = thread; mClassName = className; mToken = token; mApplication = application; mActivityManager = (IActivityManager)activityManager; mStartCompatibility = getApplicationInfo().targetSdkVersion < Build.VERSION_CODES.ECLAIR; } public void onCreate () { } }
最终调用 Service.onCreate() 方法,对于目标服务都是继承于 Service ,并覆写该方式,调用目标服务的 onCreate() 方法。拨云见日,到此总算是进入了 Service 的生命周期。
2.14 AMS.serviceDoneExecuting 1 2 3 4 5 6 public void serviceDoneExecuting (IBinder token, int type, int startId, int res) { synchronized (this ) { mServices.serviceDoneExecutingLocked((ServiceRecord)token, type, startId, res); } }
由 2.8.1 的 bumpServiceExecutingLocked 发送一个延时消息 SERVICE_TIMEOUT_MSG
2.14.1 AS.serviceDoneExecutingLocked 1 2 3 4 5 6 7 8 9 10 11 12 void serviceDoneExecutingLocked (ServiceRecord r, int type, int startId, int res) { boolean inDestroying = mDestroyingServices.contains(r); if (r != null ) { final long origId = Binder.clearCallingIdentity(); serviceDoneExecutingLocked(r, inDestroying, inDestroying); Binder.restoreCallingIdentity(origId); } else { } }
2.14.2 AS.serviceDoneExecutingLocked 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 private void serviceDoneExecutingLocked (ServiceRecord r, boolean inDestroying,boolean finishing) { r.executeNesting--; if (r.executeNesting <= 0 ) { if (r.app != null ) { r.app.execServicesFg = false ; r.app.executingServices.remove(r); if (r.app.executingServices.size() == 0 ) { mAm.mHandler.removeMessages(ActivityManagerService.SERVICE_TIMEOUT_MSG, r.app); } else if (r.executeFg) { } if (inDestroying) { mDestroyingServices.remove(r); r.bindings.clear(); } mAm.updateOomAdjLocked(r.app, true ); } r.executeFg = false ; if (finishing) { if (r.app != null && !r.app.persistent) { r.app.services.remove(r); if (r.whitelistManager) { updateWhitelistManagerLocked(r.app); } } r.app = null ; } } }
handleCreateService() 执行后便会移除服务启动超时的消息 SERVICE_TIMEOUT_MSG。Service 启动过程出现 ANR ,”executing service [发送超时serviceRecord信息]”, 这往往是 service 的 onCreate() 回调方法执行时间过长。
在 2.8 AS.realStartServiceLocked 方法在完成 onCreate 操作,解析来便是进入 onStartCommand 方法.
2.15 AS.sendServiceArgsLocked 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 private final void sendServiceArgsLocked (ServiceRecord r, boolean execInFg, boolean oomAdjusted) throws TransactionTooLargeException { final int N = r.pendingStarts.size(); if (N == 0 ) { return ; } ArrayList<ServiceStartArgs> args = new ArrayList<>(); while (r.pendingStarts.size() > 0 ) { ServiceRecord.StartItem si = r.pendingStarts.remove(0 ); if (si.intent == null && N > 1 ) { continue ; } si.deliveredTime = SystemClock.uptimeMillis(); r.deliveredStarts.add(si); si.deliveryCount++; if (si.neededGrants != null ) { mAm.grantUriPermissionUncheckedFromIntentLocked(si.neededGrants, si.getUriPermissionsLocked()); } mAm.grantEphemeralAccessLocked(r.userId, si.intent, r.appInfo.uid, UserHandle.getAppId(si.callingId)); bumpServiceExecutingLocked(r, execInFg, "start" ); if (!oomAdjusted) { oomAdjusted = true ; mAm.updateOomAdjLocked(r.app, true ); } if (r.fgRequired && !r.fgWaiting) { } int flags = 0 ; if (si.deliveryCount > 1 ) { flags |= Service.START_FLAG_RETRY; } if (si.doneExecutingCount > 0 ) { flags |= Service.START_FLAG_REDELIVERY; } args.add(new ServiceStartArgs(si.taskRemoved, si.id, flags, si.intent)); } ParceledListSlice<ServiceStartArgs> slice = new ParceledListSlice<>(args); slice.setInlineCountLimit(4 ); Exception caughtException = null ; try { r.app.thread.scheduleServiceArgs(r, slice); } catch (Exception e) { caughtException = e; } if (caughtException != null ) { final boolean inDestroying = mDestroyingServices.contains(r); for (int i = 0 ; i < args.size(); i++) { serviceDoneExecutingLocked(r, inDestroying, inDestroying); } if (caughtException instanceof TransactionTooLargeException) { throw (TransactionTooLargeException)caughtException; } } }
三、bindService 源码
3.1 CW.bindService 1 2 3 4 5 6 7 ContextWrapper.java @Override public boolean bindService (Intent service, ServiceConnection conn, int flags) { return mBase.bindService(service, conn, flags); }
3.2 CI.bindService 1 2 3 4 5 6 7 8 ContextImpl.java @Override public boolean bindService (Intent service, ServiceConnection conn, int flags) { warnIfCallingFromSystemProcess(); return bindServiceCommon(service, conn, flags, mMainThread.getHandler(), getUser()); }
3.3 CI.bindServiceCommon 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 private boolean bindServiceCommon (Intent service, ServiceConnection conn, int flags, String instanceName, Handler handler, Executor executor, UserHandle user) { IServiceConnection sd; if (conn == null ) { throw new IllegalArgumentException("connection is null" ); } if (handler != null && executor != null ) { throw new IllegalArgumentException("Handler and Executor both supplied" ); } if (mPackageInfo != null ) { if (executor != null ) { sd = mPackageInfo.getServiceDispatcher(conn, getOuterContext(), executor, flags); } else { sd = mPackageInfo.getServiceDispatcher(conn, getOuterContext(), handler, flags); } } else { throw new RuntimeException("Not supported in system context" ); } validateServiceIntent(service); try { IBinder token = getActivityToken(); if (token == null && (flags&BIND_AUTO_CREATE) == 0 && mPackageInfo != null && mPackageInfo.getApplicationInfo().targetSdkVersion < android.os.Build.VERSION_CODES.ICE_CREAM_SANDWICH) { flags |= BIND_WAIVE_PRIORITY; } service.prepareToLeaveProcess(this ); int res = ActivityManager.getService().bindIsolatedService( mMainThread.getApplicationThread(), getActivityToken(), service, service.resolveTypeIfNeeded(getContentResolver()), sd, flags, instanceName, getOpPackageName(), user.getIdentifier()); if (res < 0 ) { throw new SecurityException("Not allowed to bind to service " + service); } return res != 0 ; } catch (RemoteException e) { throw e.rethrowFromSystemServer(); } }
注意: 在这里需要注意以上注释的地方,因为绑定 Service 最终客户端要回调 ServiceConnection 对象的 onServiceConnected() 方法,mPackageInfo.getServiceDispatcher() 就是将我们调用 bindService() 方法传递的 ServiceConnection 对象封装成 IServiceConnection(实现类为LoadedApk.ServiceDispatcher.InnerConnection) 。这是一个 aidl 接口,这是因为 Service 启动和绑定时跨进程的,普通的 ServiceConnection 是不能款进程传输的,所以需要进行封装与转换成 aidl 类型。
ActivityManager.getService().bindIsolatedService 这里不做过多讲解,上面已经讲过了,最终调用的是 AMS 的 bindIsolatedService
3.4 AMS.bindIsolatedService 1 2 3 4 5 6 7 8 9 10 11 public int bindIsolatedService (IApplicationThread caller, IBinder token, Intent service, String resolvedType, IServiceConnection connection, int flags, String instanceName, String callingPackage, int userId) throws TransactionTooLargeException { synchronized (this ) { return mServices.bindServiceLocked(caller, token, service, resolvedType, connection, flags, instanceName, callingPackage, userId); } }
3.5 AS.bindServiceLocked 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 int bindServiceLocked (IApplicationThread caller, IBinder token, Intent service, String resolvedType, final IServiceConnection connection, int flags, String instanceName, String callingPackage, final int userId) throws TransactionTooLargeException { ServiceLookupResult res = retrieveServiceLocked(service, instanceName, resolvedType, callingPackage, callingPid, callingUid, userId, true , callerFg, isBindExternal, allowInstant); ServiceRecord s = res.record; try { AppBindRecord b = s.retrieveAppBindingLocked(service, callerApp); ConnectionRecord c = new ConnectionRecord(b, activity, connection, flags, clientLabel, clientIntent, callerApp.uid, callerApp.processName, callingPackage); IBinder binder = connection.asBinder(); s.addConnection(binder, c); b.connections.add(c); if (activity != null ) { activity.addConnection(c); } b.client.connections.add(c); c.startAssociationIfNeeded(); if ((flags&Context.BIND_AUTO_CREATE) != 0 ) { s.lastActivity = SystemClock.uptimeMillis(); if (bringUpServiceLocked(s, service.getFlags(), callerFg, false , permissionsReviewRequired) != null ) { return 0 ; } } } finally { Binder.restoreCallingIdentity(origId); } return 1 ; }
注意,上面注释部分,绑定服务时,我们将连接对象保存到了 ServiceRecord 中。
3.6 AS.bringUpServiceLocked 绑定服务到这里,后面调用 attach() 和 onCreate() 方法就和启动服务时一样的了 见 startService 2.7 ,在 bringUpServiceLocked() 中 调用realStartServiceLocked() 方法,接着继续往下调用。
1 2 3 4 5 6 7 8 9 10 private String bringUpServiceLocked (ServiceRecord r, int intentFlags, boolean execInFg, boolean whileRestarting, boolean permissionsReviewRequired) throws TransactionTooLargeException { realStartServiceLocked(r, app, execInFg); return null ; }
3.7 AS.realStartServiceLocked 这一步,和启动 Service 不一样的是,在 realStartServiceLocked() 方法中会调用 requestServiceBindingsLocked() 方法,处理绑定服务的过程 (其他过程请看 startService 2.8)
1 2 3 4 5 6 7 8 9 10 private final void realStartServiceLocked (ServiceRecord r, ProcessRecord app, boolean execInFg) throws RemoteException { requestServiceBindingsLocked(r, execInFg); sendServiceArgsLocked(r, execInFg, true ); }
流程图中 [8 -13] 对应 startService 中的 [9 - 14]
这里省略 3.8 - 3.13
3.14 AS.requestServiceBindingsLocked 1 2 3 4 5 6 7 8 9 10 private final void requestServiceBindingsLocked (ServiceRecord r, boolean execInFg) throws TransactionTooLargeException { for (int i=r.bindings.size()-1 ; i>=0 ; i--) { IntentBindRecord ibr = r.bindings.valueAt(i); if (!requestServiceBindingLocked(r, ibr, execInFg, false )) { break ; } } }
根据是否有连接对象判断是否需要调用 ActiveServices 中的requestServiceBindingLocked() 方法(和当前方法差了个 s,bindings),绑定 Service 在 ActiveServices 中的 bindServiceLocked() 方法中添加了,所以集合肯定不会为空
3.15 AS.requestServiceBindingLocked 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 private final boolean requestServiceBindingLocked (ServiceRecord r, IntentBindRecord i, boolean execInFg, boolean rebind) throws TransactionTooLargeException { if ((!i.requested || rebind) && i.apps.size() > 0 ) { try { bumpServiceExecutingLocked(r, execInFg, "bind" ); r.app.forceProcessStateUpTo(ActivityManager.PROCESS_STATE_SERVICE); r.app.thread.scheduleBindService(r, i.intent.getIntent(), rebind, r.app.getReportedProcState()); if (!rebind) { i.requested = true ; } i.hasBound = true ; i.doRebind = false ; } catch (TransactionTooLargeException e) { final boolean inDestroying = mDestroyingServices.contains(r); serviceDoneExecutingLocked(r, inDestroying, inDestroying); throw e; } catch (RemoteException e) { final boolean inDestroying = mDestroyingServices.contains(r); serviceDoneExecutingLocked(r, inDestroying, inDestroying); return false ; } } return true ; }
[15 - 17] 就是 Service 端到 Client 端的调用,类似 startService 的 [2.9 - 2.10]
这里省略 3.16 - 3.17
3.18 AT.handleBindService 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 private void handleBindService (BindServiceData data) { Service s = mServices.get(data.token); if (s != null ) { try { data.intent.setExtrasClassLoader(s.getClassLoader()); data.intent.prepareToEnterProcess(); try { if (!data.rebind) { IBinder binder = s.onBind(data.intent); ActivityManager.getService().publishService( data.token, data.intent, binder); } else { s.onRebind(data.intent); ActivityManager.getService().serviceDoneExecuting( data.token, SERVICE_DONE_EXECUTING_ANON, 0 , 0 ); } } catch (RemoteException ex) { throw ex.rethrowFromSystemServer(); } } catch (Exception e) { if (!mInstrumentation.onException(s, e)) { } } } }
3.19 onBind/onRebind 在上面的方法中我们已经看到了 Service 的 onBind() 或者 onRebind() 方法已经被调用了,那么对于Service类来说已经执行完成了。但是我们绑定Service,客户端需要拿到 IBinder 对象,这个对象是在 ServiceConnection 对象的回调 onServiceConnected() 方法取到的,所以我们继续看看这个过程是怎样的。
四、bindService 回调 4.1 LA.getServiceDispatcher 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 @UnsupportedAppUsage public final IServiceConnection getServiceDispatcher (ServiceConnection c, Context context, Handler handler, int flags) { return getServiceDispatcherCommon(c, context, handler, null , flags); } private IServiceConnection getServiceDispatcherCommon (ServiceConnection c, Context context, Handler handler, Executor executor, int flags) { synchronized (mServices) { LoadedApk.ServiceDispatcher sd = null ; ArrayMap<ServiceConnection, LoadedApk.ServiceDispatcher> map = mServices.get(context); if (map != null ) { if (DEBUG) Slog.d(TAG, "Returning existing dispatcher " + sd + " for conn " + c); sd = map.get(c); } if (sd == null ) { if (executor != null ) { sd = new ServiceDispatcher(c, context, executor, flags); } else { sd = new ServiceDispatcher(c, context, handler, flags); } if (DEBUG) Slog.d(TAG, "Creating new dispatcher " + sd + " for conn " + c); if (map == null ) { map = new ArrayMap<>(); mServices.put(context, map); } map.put(c, sd); } else { sd.validate(context, handler, executor); } return sd.getIServiceConnection(); } }
4.2 AMS.publishService 1 2 3 4 5 6 7 8 9 10 public void publishService (IBinder token, Intent intent, IBinder service) { synchronized (this ) { if (!(token instanceof ServiceRecord)) { throw new IllegalArgumentException("Invalid service token" ); } mServices.publishServiceLocked((ServiceRecord)token, intent, service); } }
4.3 AS.publishServiceLocked 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 void publishServiceLocked (ServiceRecord r, Intent intent, IBinder service) { final long origId = Binder.clearCallingIdentity(); try { if (r != null ) { Intent.FilterComparison filter = new Intent.FilterComparison(intent); IntentBindRecord b = r.bindings.get(filter); if (b != null && !b.received) { b.binder = service; b.requested = true ; b.received = true ; ArrayMap<IBinder, ArrayList<ConnectionRecord>> connections = r.getConnections(); for (int conni = connections.size() - 1 ; conni >= 0 ; conni--) { ArrayList<ConnectionRecord> clist = connections.valueAt(conni); for (int i=0 ; i<clist.size(); i++) { ConnectionRecord c = clist.get(i); if (!filter.equals(c.binding.intent.intent)) { continue ; } try { c.conn.connected(r.name, service, false ); } catch (Exception e) { } } } } serviceDoneExecutingLocked(r, mDestroyingServices.contains(r), false ); } } finally { Binder.restoreCallingIdentity(origId); } }
4.4 LA.ServiceDispatcher.InnerConnection 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 private static class InnerConnection extends IServiceConnection .Stub { @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553) final WeakReference<LoadedApk.ServiceDispatcher> mDispatcher; InnerConnection(LoadedApk.ServiceDispatcher sd) { mDispatcher = new WeakReference<LoadedApk.ServiceDispatcher>(sd); } public void connected (ComponentName name, IBinder service, boolean dead) throws RemoteException { LoadedApk.ServiceDispatcher sd = mDispatcher.get(); if (sd != null ) { sd.connected(name, service, dead); } } }
4.5 LA.ServiceDispatcher.connected 1 2 3 4 5 6 7 8 9 10 11 12 public void connected (ComponentName name, IBinder service, boolean dead) { if (mActivityExecutor != null ) { mActivityExecutor.execute(new RunConnection(name, service, 0 , dead)); } else if (mActivityThread != null ) { mActivityThread.post(new RunConnection(name, service, 0 , dead)); } else { doConnected(name, service, dead); } }
4.6LA.ServiceDispatcher.RunConnection 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 private final class RunConnection implements Runnable { RunConnection(ComponentName name, IBinder service, int command, boolean dead) { mName = name; mService = service; mCommand = command; mDead = dead; } public void run () { if (mCommand == 0 ) { doConnected(mName, mService, mDead); } else if (mCommand == 1 ) { doDeath(mName, mService); } } final ComponentName mName; final IBinder mService; final int mCommand; final boolean mDead; }
4.7 LA.ServiceDispatcher.doConnected 1 2 3 4 5 6 7 8 9 10 11 12 13 public void doConnected (ComponentName name, IBinder service, boolean dead) { ServiceDispatcher.ConnectionInfo old; ServiceDispatcher.ConnectionInfo info; if (service != null ) { mConnection.onServiceConnected(name, service); } else { mConnection.onNullBinding(name); } }
mConnection 就是客户端的 ServiceConnection 对象,在前面 ContextImpl 的 bindServiceCommon() 方法说明时有注释进行说明了。
五、解绑 Service
六、停止 Service
startService启动过程分析
Android Service 流程分析
ActivityManagerService 通信浅析