Android Service启动流程源码解析

相信大家都知道,Service的启动方式有两种:startService和bindService,今天我们就一起从源码的角度来学习下startService的启动流程。

启动一个Service的方式如下:

    Intent intent = new Intent(MainActivity.this, TestService.class);
    startService(intent);

我们跟进去startService方法去看下:

    #ContextWrapper
    @Override
    public ComponentName startService(Intent service) {
        return mBase.startService(service);
    }

可以看到,ContextWrapper中的startService方法直接调用到 mBase.startService,mBase是什么呢?它又是在什么时候被赋值的呢?其实mBase就是 ContextImpl实例,了解过Activity启动流程的朋友应该很清楚,在Activity实例创建后,会调用到activity.attach方法,正是在这个方法中将当前activity实例对应的ContextImpl对象赋值给 mBase成员变量。对Activity启动流程还不熟悉的朋友可以看下笔者的 《Activity启动流程源码解析》:https://www.jianshu.com/p/621ae18547b0;好了,我们接着跟进去ContextImpl中的 startService方法:

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

ContextImpl类中的startService方法中直接调用到 startServiceCommon方法:

    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());
            if (cn != null) {
                if (cn.getPackageName().equals("!")) {
                    throw new SecurityException(
                            "Not allowed to start service " + service
                            + " without permission " + cn.getClassName());
                } else if (cn.getPackageName().equals("!!")) {
                    throw new SecurityException(
                            "Unable to start service " + service
                            + ": " + cn.getClassName());
                } else if (cn.getPackageName().equals("?")) {
                    throw new IllegalStateException(
                            "Not allowed to start service " + service + ": " + cn.getClassName());
                }
            }
            return cn;
        } catch (RemoteException e) {
            throw e.rethrowFromSystemServer();
        }
    }

可以看到,在 startServiceCommon方法中直接调用到 ActivityManager.getService().startService方法,和Activity的启动流程一致,这里是由客户端进程向SystemServer进程发起的一次单向IPC操作,最终调用到 ActivityManagerService类的startService方法,我们跟进去看下:

    #ActivityManagerService
    @Override
    public ComponentName startService(IApplicationThread caller, Intent service,
            String resolvedType, boolean requireForeground, String callingPackage, int userId)
            throws TransactionTooLargeException {
        enforceNotIsolatedCaller("startService");
        // Refuse possible leaked file descriptors
        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;
        }
    }

在ActivityManagerService的startService方法中,直接调用到 mServices.startServiceLocked方法,mServices对象的类型为ActiveServices,简单来讲,ActiveServices是一个辅助AMS进行Service管理的类,包括Service的启动、绑定和停止等。我们跟进去mServices.startServiceLocked方法看下:

    #ActiveServices
    ComponentName startServiceLocked(IApplicationThread caller, Intent service, String resolvedType,
            int callingPid, int callingUid, boolean fgRequired, String callingPackage, final int userId)
            throws TransactionTooLargeException {

        ...
        //重点
        ComponentName cmp = startServiceInnerLocked(smap, service, r, callerFg, addToStarting);
        return cmp;
    }

    ...

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

    ...

     private String bringUpServiceLocked(ServiceRecord r, int intentFlags, boolean execInFg,
            boolean whileRestarting, boolean permissionsReviewRequired)
            throws TransactionTooLargeException {

        ...

        if (app != null && app.thread != null) {
                try {
                    app.addPackage(r.appInfo.packageName, r.appInfo.versionCode, 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);
                }

                // If a dead object exception was thrown -- fall through to
                // restart the application.
            }

        ...
    }

可以看到最终是调用到 realStartServiceLocked方法,从名字上看,这个方法应该是真正启动一个Service,我们跟进去看下:

private final void realStartServiceLocked(ServiceRecord r,
            ProcessRecord app, boolean execInFg) throws RemoteException {
     
        ...
 
        //标记当前Service对象是否成功创建
        boolean created = false;
        try {
            
            synchronized (r.stats.getBatteryStats()) {
                r.stats.startLaunchedLocked();
            }
            mAm.notifyPackageUse(r.serviceInfo.packageName,
                                 PackageManager.NOTIFY_PACKAGE_USE_SERVICE);
            app.forceProcessStateUpTo(ActivityManager.PROCESS_STATE_SERVICE);
            //1.发起SystemServer进程到客户端进程的单向IPC操作,创建Service对象并调用其onCreate方法
            app.thread.scheduleCreateService(r, r.serviceInfo,
                    mAm.compatibilityInfoForPackageLocked(r.serviceInfo.applicationInfo),
                    app.repProcState);
            r.postNotification();
            created = true;
        } catch (DeadObjectException e) {
            Slog.w(TAG, "Application dead when creating service " + r);
            mAm.appDiedLocked(app);
            throw e;
        } finally {
            if (!created) {
                // Keep the executeNesting count accurate.
                final boolean inDestroying = mDestroyingServices.contains(r);
                serviceDoneExecutingLocked(r, inDestroying, inDestroying);

                // Cleanup.
                if (newService) {
                    app.services.remove(r);
                    r.app = null;
                }

                // Retry.
                if (!inDestroying) {
                    scheduleServiceRestartLocked(r, false);
                }
            }
        }

        if (r.whitelistManager) {
            app.whitelistManager = true;
        }

        requestServiceBindingsLocked(r, execInFg);

        updateServiceClientActivitiesLocked(app, null, true);

        //2.同样为IPC操作,最终调用到Service对象的onStartCommand方法
        sendServiceArgsLocked(r, execInFg, true);

        ...
    }

上述代码重点部分已经做了标注,我们首先来看下 1 处,可以看到 1 处调用到app.thread.scheduleCreateService方法,由SystemServer进程向客户端进程发起单向IPC操作,最终调用到 ApplicationThread 的scheduleCreateService方法,我们跟进去看下:

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

我们都知道ApplicationThread为SystemServer进程到客户端进程单向通信对应的Binder实现类,类中的方法都是运行在客户端的Binder线程池中,所以在scheduleCreateService方法的最后调用到sendMessage方法,由mH(Handler实例)发送了一条CREATE_SERVICE 类型的Message,最终调用到 ActivityThread类的 handleCreateService方法,我们跟进去看下:

    private void handleCreateService(CreateServiceData data) {
        // If we are getting ready to gc after going to the background, well
        // we are back active so skip it.
        unscheduleGcIdler();

        LoadedApk packageInfo = getPackageInfoNoCheck(
                data.info.applicationInfo, data.compatInfo);
        Service service = null;
        try {
            //1.通过类加载器创建Service实例
            java.lang.ClassLoader cl = packageInfo.getClassLoader();
            service = (Service) cl.loadClass(data.info.name).newInstance();
        } catch (Exception e) {
            if (!mInstrumentation.onException(service, e)) {
                throw new RuntimeException(
                    "Unable to instantiate service " + data.info.name
                    + ": " + e.toString(), e);
            }
        }

        try {
            if (localLOGV) Slog.v(TAG, "Creating service " + data.info.name);
            //2.创建ContextImpl实例
            ContextImpl context = ContextImpl.createAppContext(this, packageInfo);
            context.setOuterContext(service);
            //3.获取到当前Application实例
            Application app = packageInfo.makeApplication(false, mInstrumentation);
            //4.调用当前Service对象的attach方法,进行关联操作
            service.attach(context, this, data.info.name, data.token, app,
                    ActivityManager.getService());
            //5.调用当前Service对象的onCreate方法
            service.onCreate();
            //6.将当前Service对象添加到mServices中
            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);
            }
        }
    }

可以看到在 handleCreateService方法中完成了Service对象的创建以及其 onCreate生命周期方法的调用。

好了,我们回到 realStartServiceLocked方法的 2 处,继续向下分析,可以看到 2 处调用到 sendServiceArgsLocked方法,我们跟进去看下:

    #ActiveServices
    private final void sendServiceArgsLocked(ServiceRecord r, boolean execInFg,
            boolean oomAdjusted) throws TransactionTooLargeException {

      ...
   
      try {
            //重点
            r.app.thread.scheduleServiceArgs(r, slice);
        } catch (TransactionTooLargeException e) {
            if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "Transaction too large for " + args.size()
                    + " args, first: " + args.get(0).args);
            Slog.w(TAG, "Failed delivering service starts", e);
            caughtException = e;
        } catch (RemoteException e) {
            // Remote process gone...  we'll let the normal cleanup take care of this.
            if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "Crashed while sending args: " + r);
            Slog.w(TAG, "Failed delivering service starts", e);
            caughtException = e;
        } catch (Exception e) {
            Slog.w(TAG, "Unexpected exception", e);
            caughtException = e;
        }

        ...
    }

在sendServiceArgsLocked方法中调用到 r.app.thread.scheduleServiceArgs方法,同样为SystemServer进程到应用程序进程的单向IPC操作,最终调用到 ApplicationThread的scheduleServiceArgs方法,我们跟进去看下:

    #ApplicationThread
    public final void scheduleServiceArgs(IBinder token, ParceledListSlice args) {
            List list = args.getList();

            for (int i = 0; i < list.size(); i++) {
                ServiceStartArgs ssa = list.get(i);
                ServiceArgsData s = new ServiceArgsData();
                s.token = token;
                s.taskRemoved = ssa.taskRemoved;
                s.startId = ssa.startId;
                s.flags = ssa.flags;
                s.args = ssa.args;

                sendMessage(H.SERVICE_ARGS, s);
            }
        }

我们可以看到,scheduleServiceArgs方法中发送了一条 SERVICE_ARGS类型的Message,最终调用到 ActivityThread类的 handleServiceArgs方法,我们跟进去看下:

   #ActivityThread
   private void handleServiceArgs(ServiceArgsData data) {
        //1.获取到当前Service对象
        Service s = mServices.get(data.token);
        if (s != null) {
            try {
                if (data.args != null) {
                    data.args.setExtrasClassLoader(s.getClassLoader());
                    data.args.prepareToEnterProcess();
                }
                int res;
                if (!data.taskRemoved) {
                    //2.重点,调用到当前Service对象的 onStartCommand方法
                    res = s.onStartCommand(data.args, data.flags, data.startId);
                } else {
                    s.onTaskRemoved(data.args);
                    res = Service.START_TASK_REMOVED_COMPLETE;
                }

                QueuedWork.waitToFinish();

                try {
                    ActivityManager.getService().serviceDoneExecuting(
                            data.token, SERVICE_DONE_EXECUTING_START, data.startId, res);
                } catch (RemoteException e) {
                    throw e.rethrowFromSystemServer();
                }
                ensureJitEnabled();
            } catch (Exception e) {
                if (!mInstrumentation.onException(s, e)) {
                    throw new RuntimeException(
                            "Unable to start service " + s
                            + " with " + data.args + ": " + e.toString(), e);
                }
            }
        }
    }

可以看到在 handleServiceArgs方法的 2 处调用到当前 Service对象的 onStartCommand方法。

到这里,Service的启动流程就分析完毕了。

你可能感兴趣的:(Android Service启动流程源码解析)