前言

本文根据Android 11,参阅《Android进阶解密》一书材料。了解Service的发动和绑定流程,以及Service的Context创立过程。

由于根据剖析流程,疏忽许多细节分支。各位在看源码的时分,要尽或许疏忽细节,剖析全体流程之后,还有精力的话再去看细节。例如有些特点是在后面赋值的,假如在前面追究,难哦。

另:阅读这种流程需求很大的耐心和意志。建议在心情愉悦想要学习的时分调配源码一起食用。

一、Service 的发动流程

1、ContextImpl.startService

发动一个Service,通常在Activity调用startService来发动。

@Override
public ComponentName startService(Intent service) {
    return startServiceCommon(service, false, mUser);
}

2、ContextImpl.startServiceCommon

startServiceCommon查看intent内容是否合法,然后做一些脱离当时进程的准备操作。调用 ActivityManager.getService()获得AMS的本地引证,并调用其startService函数。也便是说经过Binder机制跨进程通讯调用了AMSstartService函数。

private ComponentName startServiceCommon(Intent service, boolean requireForeground,
        UserHandle user) {
    try {
        //查看intent 的compant和package是否合法
        validateServiceIntent(service);
        ...
        ComponentName cn = ActivityManager.getService().startService(
                mMainThread.getApplicationThread(), service,
                service.resolveTypeIfNeeded(getContentResolver()), requireForeground,
                getOpPackageName(), getAttributionTag(), user.getIdentifier());
        ...
        return cn;
    } catch (RemoteException e) {
        throw e.rethrowFromSystemServer();
    }
}

经过 ActivityManager.getService()的完成。

    @UnsupportedAppUsage
    public static IActivityManager getService() {
        return IActivityManagerSingleton.get();
    }
    @UnsupportedAppUsage
    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;
                }
            };

3、AMS.startService

AMS.startService函数获取调用PidUid,然后调用ActiveServicestartServiceLocked函数。

@Override
public ComponentName startService(IApplicationThread caller, Intent service,
        String resolvedType, boolean requireForeground, String callingPackage,
        String callingFeatureId, int userId)
        throws TransactionTooLargeException {
    ...
    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, callingFeatureId, userId);
        } finally {
            Binder.restoreCallingIdentity(origId);
        }
        return res;
    }
}

4、ActiveService.startServiceLock

ActiveService.startServiceLock函数,对一些合法性的查看,例如前台Service的权限、限制性后台Service进行延迟运转(standby)。并将要发动的信息封装成ServiceRecord。然后调用了startServiceInnerLocked函数。

ComponentName startServiceLocked(IApplicationThread caller, Intent service, String resolvedType,
        int callingPid, int callingUid, boolean fgRequired, String callingPackage,
        @Nullable String callingFeatureId, final int userId)
        throws TransactionTooLargeException {
    return startServiceLocked(caller, service, resolvedType, callingPid, callingUid, fgRequired,
            callingPackage, callingFeatureId, userId, false);
}
ComponentName startServiceLocked(IApplicationThread caller, Intent service, String resolvedType,
        int callingPid, int callingUid, boolean fgRequired, String callingPackage,
        @Nullable String callingFeatureId, final int userId,
        boolean allowBackgroundActivityStarts) throws TransactionTooLargeException {
    final boolean callerFg;
    if (caller != null) {
        //获取调用Service的运用程序进程描绘
        final ProcessRecord callerApp = mAm.getRecordForAppLocked(caller);
        if (callerApp == null) {
          ...
        }
        callerFg = callerApp.setSchedGroup != ProcessList.SCHED_GROUP_BACKGROUND;
    } else {
        callerFg = true;
    }
    //检索ServiceRecord,包含同运用和其他运用
    ServiceLookupResult res =
        retrieveServiceLocked(service, null, resolvedType, callingPackage,
                callingPid, callingUid, userId, true, callerFg, false, false);
    ...
    //要发动的ServiceRecord
    ServiceRecord r = res.record;
    ...
    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;
}

5、ActiveServices.startServiceInnerLocker

调用了bringUpServiceLocked函数,会将ServiceRecord添加到ServiceMap类型的smap集合,进行缓存。

ComponentName startServiceInnerLocked(ServiceMap smap, Intent service, ServiceRecord r,
        boolean callerFg, boolean addToStarting) throws TransactionTooLargeException {
    r.callStart = false;
    ...
    String error = bringUpServiceLocked(r, service.getFlags(), callerFg, false, false);
    ...
    return r.name;
}

6、 ActiveService.bringUpServiceLocked

剖析一:初次发动Service时,在履行bringUpServiceLocked函数,ServiceRecord是归于新创立的,而非从AMS的缓存mServices中检索而来,所以此时的ServiceRecordProcessRecord类型appIApplicationThread类型thread都是null。只有发动过后的ServiceRecord才有值,才会履行sendServiceArgsLocked函数,重复调用Service的生命周期onStartCommand,而不调用onCreate函数。

  private String bringUpServiceLocked(ServiceRecord r, int intentFlags, boolean execInFg,
            boolean whileRestarting, boolean permissionsReviewRequired)
            throws TransactionTooLargeException {
        //剖析一:未发动过的ServiceRecord两者都是null,重复发动会履行该函数,
        //会重复调用service的onStartCommand函数。
        if (r.app != null && r.app.thread != null) {
            sendServiceArgsLocked(r, execInFg, false);
            return null;
        }
		...
        final boolean isolated = (r.serviceInfo.flags&ServiceInfo.FLAG_ISOLATED_PROCESS) != 0;
        final String procName = r.processName;
        HostingRecord hostingRecord = new HostingRecord("service", r.instanceName);
        ProcessRecord app;
        if (!isolated) {
        	////经过AMS获取service地点进程的ProcessRecord。ProcessList=>MyProcessMap=》会缓存已创立过进程的ProcessRecord
            app = mAm.getProcessRecordLocked(procName, r.appInfo.uid, false);
            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.shortInstanceName, e);
                }
            }
        }
        //假如service地点的进程未发动,经过AMS发动该进程,可以参阅运用进程的发动流程
          if (app == null && !permissionsReviewRequired) {
            if ((app=mAm.startProcessLocked(procName, r.appInfo, true, intentFlags,
                    hostingRecord, ZYGOTE_POLICY_FLAG_EMPTY, false, isolated, false)) == null) {;
                bringDownServiceLocked(r);
                return msg;
            }
            if (isolated) {
                r.isolatedProc = app;
            }
        }
        //等候进程发动结束重启发动
        if (!mPendingServices.contains(r)) {
            mPendingServices.add(r);
        }
		...
        return null;
    }

7、ActiveService.realStartServiceLocked

   private final void realStartServiceLocked(ServiceRecord r,
            ProcessRecord app, boolean execInFg) throws RemoteException {
        //将ProcessRecord设置给ServiceRecord
        r.setProcess(app);
		//挂号当ServiceRecord到ProcessRecordd的数组mServices,表明Service现已发动(实际未发动)
        final boolean newService = app.startService(r);
        boolean created = false;
        try {
			...
            app.thread.scheduleCreateService(r, r.serviceInfo,
                    mAm.compatibilityInfoForPackage(r.serviceInfo.applicationInfo),
                    app.getReportedProcState());
          	...
        } catch (DeadObjectException e) {
            Slog.w(TAG, "Application dead when creating service " + r);
            mAm.appDiedLocked(app, "Died when creating service");
            throw e;
        } 
        //会调用Service的onStartCommand函数
         sendServiceArgsLocked(r, execInFg, true);
        ...
    }

经过ProcessRecord目标的IApplicationThread引证,经过Binder机制调用了运用程序的ApplicationThreadscheduleCreateService函数。

8、ApplicationThread.scheduleCreateService

ServiceInfo等相关信息封装到CreateServiceData中,并发送给ActivityThreadH类型的mH目标。

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);
}

9、H.handleMesssage

调用了ActivityThreadhandleCreateService函数。

case CREATE_SERVICE:
    handleCreateService((CreateServiceData)msg.obj);
    break;

10、ActivityThread.handleCreateService

    private void handleCreateService(CreateServiceData data) {
        ...
        //获取当时运用的描绘信息LoadedApk
        LoadedApk packageInfo = getPackageInfoNoCheck(
                data.info.applicationInfo, data.compatInfo);
        Service service = null;
        try {
           //创立Service的上下问文
           ContextImpl context = ContextImpl.createAppContext(this, packageInfo);
           //获取当时运用Applcation目标
            Application app = packageInfo.makeApplication(false, mInstrumentation);
            //经过反射创立Service目标
            java.lang.ClassLoader cl = packageInfo.getClassLoader();
            service = packageInfo.getAppFactory()
                    .instantiateService(cl, data.info.name, data.intent);
           //初始化资源
            context.getResources().addLoaders(
                    app.getResources().getLoaders().toArray(new ResourcesLoader[0]));
		   //context 与service彼此绑定
            context.setOuterContext(service);
            service.attach(context, this, data.info.name, data.token, app,
                    ActivityManager.getService());
            //调用Service的生命周期onCreate函数,意味Service创立结束
            service.onCreate();
            //缓存Service
            mServices.put(data.token, service);
            try {
                ActivityManager.getService().serviceDoneExecuting(
                        data.token, SERVICE_DONE_EXECUTING_ANON, 0, 0);
            } catch (RemoteException e) {
                throw e.rethrowFromSystemServer();
            }
        } catch (Exception e) {
            if (!mInstrumentation.onException(service, e)) {
                throw new RuntimeException(
                    "Unable to create service " + data.info.name
                    + ": " + e.toString(), e);
            }
        }
    }

经过ContextImpl.createAppContext创立Service的上下文context,经过packageInfo.getAppFactory().instantiateService反射获得当时Service目标service,将contextservice彼此绑定。然后调用service.onCreate。至此,Service创立结束。

二、Service的绑定

1、 ContextImpl.bindService

public boolean bindService(Intent service, ServiceConnection conn, int flags) {
	//系统进程调用绑定服务或发送播送都会宣布警告
    warnIfCallingFromSystemProcess();
    return bindServiceCommon(service, conn, flags, null, mMainThread.getHandler(), null,
            getUser());
}

2、ContextImpl.bindServiceCommon

在剖析一,主要判别入参Executor executorUserHandle user哪个为null,总有一个为null,但终究都是调用了LoadedApkgetServiceDispatcherCommon函数来获取ServiceDispathcer类型sd。影响仅仅回调代码是在主线程履行,还是线程池。这儿传入ActivityThreadH目标,意味着后续衔接成功回调onServiceConnected是在主线程。

剖析二:经过Binder机制调用AMSbindIsolatedService函数。

private boolean bindServiceCommon(Intent service, ServiceConnection conn, int flags,
        String instanceName, Handler handler, Executor executor, UserHandle user) {
    // Keep this in sync with DevicePolicyManager.bindDeviceAdminServiceAsUser.
    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) {//剖析一:无论哪个分支,都是获得ServiceConnect的本地引证sd,两者终究都是
        //调用LoadedApk的getServiceDispatcherCommon
            sd = mPackageInfo.getServiceDispatcher(conn, getOuterContext(), executor, flags);
        } else {
            //正常运用走这个分支
            sd = mPackageInfo.getServiceDispatcher(conn, getOuterContext(), handler, flags);
        }
    } else {
        throw new RuntimeException("Not supported in system context");
    }
    //查看compant and package is null ?
    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);
        //剖析二:调用AMS.bindIsolatedService
        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();
    }
}

IServiceConnection衔接的创立会先从缓存中获取,防止每次都要新建。剖析一:经过executorhandler创立ServiceDispatcher类型的sd,含有静态内部类InnerConnection的引证mIServiceConnection。承继自IServiceConnection.Stub,也便是InnerConnection是完成者,远程调用代理在其他进程,例如SystemServer进程中的ActiveService

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) {
            sd = map.get(c);
        }
        if (sd == null) {
        	//剖析一:经过executor或handler创立ServiceDispatcher
            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();
    }
}

3、AMS.bindIsolatedService

AMS经过两次重载函数bindIsolatedService调用,简略查看相关合法性。然后调用ActiveService类型的mServicebindServiceLocked函数。

4、ActiveService.bindServiceLocked

int bindServiceLocked(IApplicationThread caller, IBinder token, Intent service,
        String resolvedType, final IServiceConnection connection, int flags,
        String instanceName, String callingPackage, final int userId)
        throws TransactionTooLargeException {
    //建议绑定service的app进程描绘
    final ProcessRecord callerApp = mAm.getRecordForAppLocked(caller);
    ...
    ServiceLookupResult res =
        retrieveServiceLocked(service, instanceName, resolvedType, callingPackage,
                Binder.getCallingPid(), Binder.getCallingUid(), userId, true,
                callerFg, isBindExternal, allowInstant);
    ...
    ServiceRecord s = res.record;
    ...
        //描绘Service和运用程序进程之间的相关,内部保护Service、进程、IntentFilter以及一切绑定信息。
        AppBindRecord b = s.retrieveAppBindingLocked(service, callerApp);
        //描绘运用程序与service建立的一次通讯(绑定)
        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();
        ...
        //发动Service,可以参阅Service的发动
        if ((flags&Context.BIND_AUTO_CREATE) != 0) {
            s.lastActivity = SystemClock.uptimeMillis();
            if (bringUpServiceLocked(s, service.getFlags(), callerFg, false,
                    permissionsReviewRequired) != null) {
                return 0;
            }
        }
        ...
        //表明Service已发动,且已回来binder,可以经过binder访问接口
        if (s.app != null && b.intent.received) {
            // Service is already running, so we can immediately
            // publish the connection.
            try {
                //建立衔接
                c.conn.connected(s.name, b.intent.binder, false);
            } catch (Exception e) {
                Slog.w(TAG, "Failure sending service " + s.shortInstanceName
                        + " to connection " + c.conn.asBinder()
                        + " (in " + c.binding.client.processName + ")", e);
            }
            //第一个绑定该Service的进程,且要重绑
            if (b.intent.apps.size() == 1 && b.intent.doRebind) {
                requestServiceBindingLocked(s, b.intent, callerFg, true);
            }
        } else if (!b.intent.requested) {//初次绑定,履行此次
            requestServiceBindingLocked(s, b.intent, callerFg, false);
        }
        ...
}

AppBindRecord 描绘运用程序进程和Service的相关,包含谁绑定了ServiceProcessRecord,绑定信息IntentBindRecord,当时服务ServiceRecord,当时运用进程的一切衔接记录connections

5、requestServiceBindingLocked

调用了ApplicationThreadscheduleBindService函数。

private final boolean requestServiceBindingLocked(ServiceRecord r, IntentBindRecord i,
        boolean execInFg, boolean rebind) throws TransactionTooLargeException {
           ...
            r.app.thread.scheduleBindService(r, i.intent.getIntent(), rebind, r.app.getReportedProcState());
           ...
}

6、ApplicationThread.scheduleBindService

将数据封装BindServiceData,发送个ActivityThread的H类型的mH处理。

public final void scheduleBindService(IBinder token, Intent intent,
        boolean rebind, int processState) {
    updateProcessState(processState, false);
    BindServiceData s = new BindServiceData();
    s.token = token;
    s.intent = intent;
    s.rebind = rebind;
    sendMessage(H.BIND_SERVICE, s);
}

7 、 H.handleMessage

case BIND_SERVICE:
    handleBindService((BindServiceData)msg.obj);

8、ActivityThread.handleBindService

handleBindService函数有两个分支,即是否从头绑定。

假如当时进程第一个与Service绑定,且调用过了onUbBinder办法,那么这儿的data.rebind将为true,直接履行ServiceonRebind函数即可。另外一种便是没有绑定过,那么需求履行ServiceonBind函数。然后还要履行AMSpublishService函数。

private void handleBindService(BindServiceData data) {
    Service s = mServices.get(data.token);
    if (s != null) {
           ...
            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();
            }
        ...
    }
}

9、AMS.publishService

public void publishService(IBinder token, Intent intent, IBinder service) {
    // Refuse possible leaked file descriptors
    if (intent != null && intent.hasFileDescriptors() == true) {
        throw new IllegalArgumentException("File descriptors passed in Intent");
    }
    synchronized(this) {
        if (!(token instanceof ServiceRecord)) {
            throw new IllegalArgumentException("Invalid service token");
        }
        mServices.publishServiceLocked((ServiceRecord)token, intent, service);
    }
}

10、ActiveService.publishServiceLocked

剖析一:可见在第4步bindServiceLocked函数,IntentBindRecord目标的特点binderrequestedreceived都是false

ServiceRecord的一切衔接记录connections中,经过intent查找对应之前现已保存的ConnectionRecord,并调用其IServiceConnectionconnected函数。

在第2步的时分调用bindServiceCommon函数时,会创立ServiceDispatcher时,内部持有InnerConnection实例,这儿的IServiceConnection代理引证指向该InnerConnection实例,这儿会调用其connected函数。

    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) {//剖析1
                    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) {
                                Slog.w(TAG, "Failure sending service " + r.shortInstanceName
                                      + " to connection " + c.conn.asBinder()
                                      + " (in " + c.binding.client.processName + ")", e);
                            }
                        }
                    }
                }
                serviceDoneExecutingLocked(r, mDestroyingServices.contains(r), false);
            }
        } finally {
            Binder.restoreCallingIdentity(origId);
        }
    }

11、InnerConnection.connected

private static class InnerConnection extends IServiceConnection.Stub {
    @UnsupportedAppUsage
    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);
        }
    }
}

12、ServiceDispatcher.connected

这儿调用了 mActivityThread.post(new RunConnection(name, service, 0, dead)),履行RunConnectionrun函数。这儿的话run函数履行代码又回到了运用进程的主线程。

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);
    }
}

13、RunConnection.run

RunConnectionServiceDispatcher的内部类,这儿履行SDdoConnected函数。

public void run() {
    if (mCommand == 0) {
        doConnected(mName, mService, mDead);
    } else if (mCommand == 1) {
        doDeath(mName, mService);
    }
}

14、ServiceDispatcher.doConnected

这儿调用了ServiceConnection目标的onServiceConnected函数,也便是我们建议绑定,调用context.bindService的参数。

public void doConnected(ComponentName name, IBinder service, boolean dead) {
        ...
        mConnection.onServiceConnected(name, service);
        ...
}

到此,Service的绑定流程剖析结束。

三、Service的Context

在第一节Service的发动流程最终函数调用了ActivityThreadhandleCreateService函数。

    private void handleCreateService(CreateServiceData data) {
        unscheduleGcIdler();
		//运用的描绘信息
        LoadedApk packageInfo = getPackageInfoNoCheck(
                data.info.applicationInfo, data.compatInfo);
        Service service = null;
        try {
			//剖析一
            ContextImpl context = ContextImpl.createAppContext(this, packageInfo);
            Application app = packageInfo.makeApplication(false, mInstrumentation);
            java.lang.ClassLoader cl = packageInfo.getClassLoader();
            service = packageInfo.getAppFactory()
                    .instantiateService(cl, data.info.name, data.intent);
            context.getResources().addLoaders(
                    app.getResources().getLoaders().toArray(new ResourcesLoader[0]));
			//剖析二
            context.setOuterContext(service);
            //剖析三
            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) {
                throw e.rethrowFromSystemServer();
            }
        } catch (Exception e) {
            if (!mInstrumentation.onException(service, e)) {
                throw new RuntimeException(
                    "Unable to create service " + data.info.name
                    + ": " + e.toString(), e);
            }
        }
    }

剖析一:经过ContextImpl静态函数createAppContext回来了一个ContextImpl类型的contextcreateAppContext又调用了重载函数createAppContext。直接新建了ContextImpl实例context,结构函数传递了ActivityThread类型的mainThread和LoadedApk类型的packageInfo。并给context设置了资源环境和是否Syetem特点。

static ContextImpl createAppContext(ActivityThread mainThread, LoadedApk packageInfo) {
    return createAppContext(mainThread, packageInfo, null);
}
static ContextImpl createAppContext(ActivityThread mainThread, LoadedApk packageInfo,
        String opPackageName) {
    if (packageInfo == null) throw new IllegalArgumentException("packageInfo");
    ContextImpl context = new ContextImpl(null, mainThread, packageInfo, null, null, null, null,
            0, null, opPackageName);
    context.setResources(packageInfo.getResources());
    context.mIsSystemOrSystemUiContext = isSystemOrSystemUI(context);
    return context;
}

ContextImpl类有一个Context类型的mOuterContext特点,在结构函数时指向了自己。

回到handleCreateService函数的剖析二,在创立好Service目标service之后,将service作为参数传递给了context.setOuterContext函数。Service本身承继自ContextWrapper,ContextWrapper又是Context的子类。这时分的setOuterContext函数将service设置给了contextmOuterContext特点。意味着当时上下文context持有当时新建的service引证。

在剖析三,调用了service.attach函数,context并作为第一个参数被传入。attach函数又调用了attachBaseContext函数。

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;
    setContentCaptureOptions(application.getContentCaptureOptions());
}

attachBaseContext调用了父类ContextWrapperattachBaseContext函数

@Override
protected void attachBaseContext(Context newBase) {
    super.attachBaseContext(newBase);
    if (newBase != null) {
        newBase.setContentCaptureOptions(getContentCaptureOptions());
    }
}

ContextWrapper将一路传递过来的上下文base设置给你了mBase特点。

protected void attachBaseContext(Context base) {
    if (mBase != null) {
        throw new IllegalStateException("Base context already set");
    }
    mBase = base;
}

也便是说,我们在发动Service时,会一起创立Service的上下文context,并将其存储到Service的父类ContextWrappermBases特点中,一起context也会有当时Service引证,存储在mOuterContext变量中。

四、总结

  • Service的发动和绑定从AMS转移到ActiveService
  • Service的发动,会先判别进程是否创立,提早发动进程,再发动自己。
  • Service重复发动,会重复调用onStratCommand及后续生命周期函数。
  • Service的绑定,会先走一趟Service的发动流程,再绑定。
  • 运用进程与SytemServer进程(AMS、ActiveService)的交互式经过Binder机制进行,经过AIDL各持有两边接口。运用进程经过H目标,将现成从头切回主线程(一切运用夸进程通讯应如此)。
  • Service在运用和AMS两边都会做缓存,以便快速在找到运用。运用程序存储在ArrayMap<IBinder, Service>类型的mServices;ActiveService则是ArraySet<ServiceRecord>类型的mServices