「Android 研习社」深刻研究源码:Android10.0系统启动流程(四):SystemServer

前言java

Android源码启动篇终于到了最后一个重要的内容--SystemServer(系统服务),接下来咱们就来看看SystemServer为何这么重要吧android

福利活动bash

Android研习社机械工业出版社联合发起的赠书活动正在进行中,欢迎你们点击连接参与app

正文

SystemServer是Android基本服务的提供者,是Android系统运行的最基本需求,全部service运行在一个叫system_server的进程中,system_server进程是Android中Java虚拟机中的第一个进程,能够说,整个Android系统的业务都是围绕system_server而展开的socket

前情提要

SystemServer是由Zygotefork出来的第一个进程,咱们在上篇文章中也提到了,这里咱们再来回顾下,在ZygoteInit类的main函数中,经过调用forkSystemServer(),内部采用硬编码的方式建立相关参数,启动SystemServer,由此正式进入SystemServer的相关业务逻辑中函数

ZygoteInit.javaoop

private static Runnable forkSystemServer(String abiList, String socketName,
            ZygoteServer zygoteServer) {
		...
        /* Hardcoded command line to start the system server */
        // "经过硬编码的方式提供相关的参数"
        String args[] = {
                "--setuid=1000", //用户id
                "--setgid=1000",//用户组id
                "--setgroups=1001,1002,1003,1004,1005,1006,1007,1008,1009,1010,1018,1021,1023,"
                        + "1024,1032,1065,3001,3002,3003,3006,3007,3009,3010",
                "--capabilities=" + capabilities + "," + capabilities, //进程权能
                "--nice-name=system_server", //进程niceName
                "--runtime-args", 
                "--target-sdk-version=" + VMRuntime.SDK_VERSION_CUR_DEVELOPMENT, 
                "com.android.server.SystemServer", //须要启动的类
        };
        ZygoteArguments parsedArgs = null; 

        int pid; //processId,进程id

        try {
            parsedArgs = new ZygoteArguments(args); //"建立ZygoteArguments对象,把args解析为须要的参数"
            Zygote.applyDebuggerSystemProperty(parsedArgs);
            Zygote.applyInvokeWithSystemProperty(parsedArgs);

            boolean profileSystemServer = SystemProperties.getBoolean(
                    "dalvik.vm.profilesystemserver", false);  
            if (profileSystemServer) { 
                parsedArgs.mRuntimeFlags |= Zygote.PROFILE_SYSTEM_SERVER;
            }

            /* Request to fork the system server process */
            pid = Zygote.forkSystemServer( // "fork建立SystemServer"
                    parsedArgs.mUid, parsedArgs.mGid,
                    parsedArgs.mGids,
                    parsedArgs.mRuntimeFlags,
                    null,
                    parsedArgs.mPermittedCapabilities,
                    parsedArgs.mEffectiveCapabilities);
        } catch (IllegalArgumentException ex) {
            throw new RuntimeException(ex);
        }
        ...
    }
复制代码

SystemServer的主要流程

咱们先来看一下总体的梳理 源码分析

从上面这张流程图能够看到,SystemServer的主要流程其实仍是比较简单的:

  1. 设置相关系统属性,并作一些准备工做post

  2. 对Vm进行相关设置ui

  3. 建立主线程Looper

  4. 建立SystemServiceManager

  5. 建立ActivityThread及系统上下文Context

  6. 开启各类服务

    //使用ServiceManger开启服务,并对这些服务进行管理
    startBootstrapServices(); //引导服务
    startCoreServices();//核心服务
    startOtherServices(); //其余服务
    复制代码
  7. 进入Looper.loop的无限循环中

咱们来看看SystemServer具体开启了哪些服务

能够看到这里面开启了不少的服务,因此,分红了三个函数类分类进程开启,

  1. 引导服务
  2. 核心服务
  3. 其余服务

这些服务,是经过调用SystemServiceManger.startServeice(),获取到参数传递的Class对象,使用反射的方式,获取到该类的构造器,建立该类的实例对象,并把该service对象添加到一个ArrayList列表中进行维护,最终调用service.onstart(),完成服务的开启任务

这里还要说一下,全部的服务,都是SystemService的子类对象,SystemService是一个抽象类,内部的onstart()是一个抽象方法,最终真正执行的逻辑是其子类对象本身去定义的

那么咱们这里就能够先思考下,若是咱们想添加一个自定义的系统服务,应该如何去作?这里先不作深究

具体源码

"ssm"中根据Class对象反射建立指定的Service对象

public <T extends SystemService> T startService(Class<T> serviceClass) {
        try {
            final String name = serviceClass.getName();
            Slog.i(TAG, "Starting " + name);
            Trace.traceBegin(Trace.TRACE_TAG_SYSTEM_SERVER, "StartService " + name);

            // Create the service.
            if (!SystemService.class.isAssignableFrom(serviceClass)) {
                throw new RuntimeException("Failed to create " + name
                        + ": service must extend " + SystemService.class.getName());
            }
            final T service;
            try {
                Constructor<T> constructor = serviceClass.getConstructor(Context.class);
                service = constructor.newInstance(mContext);
            } catch (InstantiationException ex) {
                throw new RuntimeException("Failed to create service " + name
                        + ": service could not be instantiated", ex);
            } catch (IllegalAccessException ex) {
                throw new RuntimeException("Failed to create service " + name
                        + ": service must have a public constructor with a Context argument", ex);
            } catch (NoSuchMethodException ex) {
                throw new RuntimeException("Failed to create service " + name
                        + ": service must have a public constructor with a Context argument", ex);
            } catch (InvocationTargetException ex) {
                throw new RuntimeException("Failed to create service " + name
                        + ": service constructor threw an exception", ex);
            }

            startService(service);
            return service;
        } finally {
            Trace.traceEnd(Trace.TRACE_TAG_SYSTEM_SERVER);
        }
    }
复制代码

添加到mServices的列表中进行维护,并维护这些服务的生命中周期事件,执行该服务的onStart()函数

// Services that should receive lifecycle events.
private final ArrayList<SystemService> mServices = new ArrayList<SystemService>();

public void startService(@NonNull final SystemService service) {
        // Register it.
        mServices.add(service);
        // Start it.
        long time = SystemClock.elapsedRealtime();
        try {
            service.onStart();
        } catch (RuntimeException ex) {
            throw new RuntimeException("Failed to start service " + service.getClass().getName()
                    + ": onStart threw an exception", ex);
        }
        warnIfTooLong(SystemClock.elapsedRealtime() - time, service, "onStart");
    }
复制代码

SystemServer相关的主要系统服务

ActivityManagerService是如何启动的

ActivityManagerService是在startBootstrapServices函数中开启的服务,咱们来具体看下,它是如何被建立和启动的

这里主要涉及到了三个类,ActivityTaskManagerServiceActivityManagerServiceSystemServiceManager

private void startBootstrapServices() {
        ...
        //此处是经过"ssm"反射建立"atm"的静态内部类对象,并经过"Lifecycle"提供的"getService()"获取到"atm"实例对象
        ActivityTaskManagerService atm = mSystemServiceManager.startService(
                ActivityTaskManagerService.Lifecycle.class).getService();
        //调用"ams"的静态内部类的静态方法"startService"函数,把"ssm""atm"传递过去
        mActivityManagerService = ActivityManagerService.Lifecycle.startService(
                mSystemServiceManager, atm);//内部仍是使用"ssm"来建立的"ams"
        ...
}
复制代码

具体如何启动的上面的代码注释已经解释的很清楚了,其中ATM和AMS中有着类似的设计,都是经过静态内部类Lifecycle来建立和获取本类对象,即当前系统服务的,关于AMS和Lifecycle咱们后面有机会再作深究

WindowManagerServices是如何启动的

WMS是经过调用startOtherServices在其余服务中开启的, 能够看出来这里的开启方式跟AMS不太同样了,这里并非使用SSM的StartService()函数来开启的,而是先经过WMS的静态工厂函数main()先建立出WMS对象,再经过ServiceManageraddService()函数,经过Binder机制进行进程间通讯,把WMS注册到系统的服务表中

建立WMS对象并添加到ServiceManger

private void startOtherServices() {
// WMS needs sensor service ready
            ConcurrentUtils.waitForFutureNoInterrupt(mSensorServiceStart, START_SENSOR_SERVICE);
            mSensorServiceStart = null;
            wm = WindowManagerService.main(context, inputManager, !mFirstBoot, mOnlyCore,
                    new PhoneWindowManager(), mActivityManagerService.mActivityTaskManager);
            ServiceManager.addService(Context.WINDOW_SERVICE, wm, /* allowIsolated= */ false,
                    DUMP_FLAG_PRIORITY_CRITICAL | DUMP_FLAG_PROTO);
            ServiceManager.addService(Context.INPUT_SERVICE, inputManager,
                    /* allowIsolated= */ false, DUMP_FLAG_PRIORITY_CRITICAL);
}
复制代码

经过addServcie添加到ServiceManager

public static void addService(String name, IBinder service, boolean allowIsolated,
            int dumpPriority) {
        try {
            getIServiceManager().addService(name, service, allowIsolated, dumpPriority);//获取到ServiceManger对象并把`WMS`添加进去
        } catch (RemoteException e) {
            Log.e(TAG, "error in addService", e);
        }
    
复制代码

加餐

经过上面的源码分析,咱们得知,有两种开启服务的方式,下面咱们就来具体分析下

SystemServiceManager详解

SSM这个类,目的是对系统服务「com.android.server.SystemService」的生命周期事件(建立,开启和其余事件)进行管理

SystemService生命周期

既然是对其生命周期进行管理,那先来看看系统服务都有哪些生命周期的方法 跟Activty的生命周期同样,SystemService的生命周期方法也是onxxx()的函数命名的

  • onStart()
  • onBootPhase()
  • onStartUser()
  • onUnlockUser()
  • onSwitchUser()
  • onStopUser()
  • onCleanupUser() 这些生命周期的做用咱们在这里就不展开分析了,你们能够去查看具体源码,源码注释中也写的很清楚了

经过SystemServiceManager管理SystemService的生命周期

AMS的系统服务是经过SystemServiceManagerstartService()函数,建立并开启指定className的系统服务,咱们来看下具体的代码

/**
	 * 经过Classname建立(或者说开启)一个系统服务
     * Starts a service by class name.
     *
     * @return The service instance.
     */
    @SuppressWarnings("unchecked")
    public SystemService startService(String className) {
        //反射建立系统服务
        final Class<SystemService> serviceClass;
        try {
            serviceClass = (Class<SystemService>)Class.forName(className);
        } catch (ClassNotFoundException ex) {
            Slog.i(TAG, "Starting " + className);
            throw new RuntimeException("Failed to create service " + className
                    + ": service class not found, usually indicates that the caller should "
                    + "have called PackageManager.hasSystemFeature() to check whether the "
                    + "feature is available on this device before trying to start the "
                    + "services that implement it", ex);
        }
        return startService(serviceClass);  //启动建立好的系统服务
    }
复制代码

启动服务,调用系统服务的onStart()生命周期方法

public void startService(@NonNull final SystemService service) {
        // Register it.
        mServices.add(service);
        // Start it.
        long time = SystemClock.elapsedRealtime();
        try {
            service.onStart(); //调用已建立好的系统服务的onStart方法,完成初始化工做
        } catch (RuntimeException ex) {
            throw new RuntimeException("Failed to start service " + service.getClass().getName()
                    + ": onStart threw an exception", ex);
        }
        warnIfTooLong(SystemClock.elapsedRealtime() - time, service, "onStart");
    }
复制代码

其余的生命周期方法调用也是在SystemServiceManager中进行调用的,这里再也不具体分析

ServiceManger详解

总体分析

ServiceManger中主要的函数有

  • addService() 添加系统服务
  • getServerce() 获取系统服务
  • checkService() 从service manager中检索指定name的系统服务是否存在
  • listServices() 返回正在运行的全部服务

经过这些函数能够看到,ServiceManger是对全部的系统服务进行管理,而SystemServiceManager是对单个系统服务的建立和生命周期进行管理

思考

咱们其实还能够进一步来思考下,为何AMS经过SystemServiceManager来添加,而WMS是经过ServiceManger来添加呢?这里先卖个关子,你们能够在评论中提出本身的见解

写在最后

启动篇的源码分析断断续续作了一个多月的时间,写到这里咱们就把Android源码启动篇彻底分析完了,能够先告一段落了,接下来,会对AMS,WMS,以及Binder相关内容进行详尽的源码分析。因为水平有限,写的不对的还请各位多多指教

原创不易,坚持更难

若是你想继续看到我接下来的分享,请经过点赞的方式告诉我,你的鼓励是我继续创做的最大动力!

郑重声明

本文版权归Android研习社全部,侵权必究!

相关文章
相关标签/搜索