SystemServer 理解


总体流程

在这里插入图片描述

在Android系统启动过程中,需要经历几个流程:

  1. 启动Init进程
  2. 启动Zygote进程
  3. 启动SystemService
  4. 启动Launcher

本文主要了解Zygote进程和SystemService进程启动、系统服务流程。

Zygote进程意思为受精卵进程,由app_process启动。Zygote进程启动之后,会绑定一个端口,作为Socket的Server端,接收着其他进程请求创建> 新的进程。 应用进程通过Binder请求SystemServer进程,SystemServer进程发送socket消息给Zygote进程,最后由Zygote进程创建fork出来的。

SystemServer进程,运行多个服务的线程,应用进程通过Binder使用SystemService中的服务

ZygoteInit

public static void main(String argv[]) {
    // 1. 启动 ZygnoteServer
    ZygoteServer zygoteServer = new ZygoteServer();
    
    ...
    Os.setpgid(0, 0);

    try {
        // 开启ddms
        RuntimeInit.enableDdms();

        boolean startSystemServer = false;
        String socketName = "zygote";
        String abiList = null;
        // 解析启动参数
        boolean enableLazyPreload = false;
        for (int i = 1; i < argv.length; i++) {
            if ("start-system-server".equals(argv[i])) {
                startSystemServer = true;
            } else if ("--enable-lazy-preload".equals(argv[i])) {
                enableLazyPreload = true;
            } else if (argv[i].startsWith(ABI_LIST_ARG)) {
                abiList = argv[i].substring(ABI_LIST_ARG.length());
            } else if (argv[i].startsWith(SOCKET_NAME_ARG)) {
                socketName = argv[i].substring(SOCKET_NAME_ARG.length());
            } else {
                throw new RuntimeException("Unknown command line argument: " + argv[i]);
            }
        }
        // 2.启动zynote socket
        zygoteServer.registerServerSocket(socketName);
        // 3.预加载资源
        if (!enableLazyPreload) {
            preload(bootTimingsTraceLog);
        } 
		...
		// 4. 启动 SystemServer
        if (startSystemServer) {
            startSystemServer(abiList, socketName, zygoteServer);
        }
        // 5. zygote 启动循环监听
        zygoteServer.runSelectLoop(abiList);
        // 6. 关闭socket
        zygoteServer.closeServerSocket();
    }
}

init进程启动的时候,会调用zygoteInit的main方法

总体的流程是:

  1. 启动一个socket,并循环监听
  2. 预加载资源
  3. 启动systemServer

SystemServer

SystemServer 运行在一个独立的进程,其中上面运行了多个系统服务线程。

// ZygoteInit
private static boolean startSystemServer(String abiList, String socketName, ZygoteServer zygoteServer)
            throws Zygote.MethodAndArgsCaller, RuntimeException {
    String args[] = {
            "--setuid=1000",
            "--setgid=1000",
            "--setgroups=1001,1002,1003,1004,1005,1006,1007,1008,1009,1010,1018,1021,1023,1032,3001,3002,3003,3006,3007,3009,3010",
            "--capabilities=" + capabilities + "," + capabilities,
            "--nice-name=system_server",
            "--runtime-args",
            "com.android.server.SystemServer",
    };
    ZygoteConnection.Arguments parsedArgs = null;

    int pid;

    try {
        parsedArgs = new ZygoteConnection.Arguments(args);
        ZygoteConnection.applyDebuggerSystemProperty(parsedArgs);
        ZygoteConnection.applyInvokeWithSystemProperty(parsedArgs);

        /* Request to fork the system server process */
        pid = Zygote.forkSystemServer(
                    parsedArgs.uid, parsedArgs.gid,
                    parsedArgs.gids,
                    parsedArgs.debugFlags,
                    null,
                    parsedArgs.permittedCapabilities,
                    parsedArgs.effectiveCapabilities);
    } catch (IllegalArgumentException ex) {
        throw new RuntimeException(ex);
    }

    /* For child process */
    if (pid == 0) {
    // 线程启动成功
        if (hasSecondZygote(abiList)) {
            waitForSecondaryZygote(socketName);
        }
		// 子线程关闭socket
        zygoteServer.closeServerSocket();
        handleSystemServerProcess(parsedArgs);
    }
    return true;
}

Zygote 创建fork一个进程,并启动了SystemServer

// SystemServer
public static void main(String[] args) {
    new SystemServer().run();
}

private void run() {
    try {
       // 设置系统化属性
       String timezoneProperty =  SystemProperties.get("persist.sys.timezone");
       if (timezoneProperty == null || timezoneProperty.isEmpty()) {
                SystemProperties.set("persist.sys.timezone", "GMT");
       }

       if (!SystemProperties.get("persist.sys.language").isEmpty()) {
           final String languageTag = Locale.getDefault().toLanguageTag();

           SystemProperties.set("persist.sys.locale", languageTag);
           SystemProperties.set("persist.sys.language", "");
           SystemProperties.set("persist.sys.country", "");
           SystemProperties.set("persist.sys.localevar", "");
        }

        // The system server should never make non-oneway calls
        Binder.setWarnOnBlocking(true);
        SystemProperties.set("persist.sys.dalvik.vm.lib.2", VMRuntime.getRuntime().vmLibrary());
        // 启动一个looper
        Looper.prepareMainLooper();
        // 加载native层的libandroid_servers
        // Initialize native services.
        System.loadLibrary("android_servers");
        // 创建System的context
        createSystemContext();

        //创建mSystemServiceManager,负责启动系统服务
        mSystemServiceManager = new SystemServiceManager(mSystemContext);
        mSystemServiceManager.setRuntimeRestarted(mRuntimeRestart);
        LocalServices.addService(SystemServiceManager.class, mSystemServiceManager);
        // Prepare the thread pool for init tasks that can be parallelized
        SystemServerInitThreadPool.get();
   } 
   // 启动服务
   try {
        traceBeginAndSlog("StartServices");
        startBootstrapServices();
        startCoreServices();
        startOtherServices();
        SystemServerInitThreadPool.shutdown();
    } 
    // 开启循环loop
    Looper.loop();
    throw new RuntimeException("Main thread loop unexpectedly exited");
}

SystemServer启动大致的流程:

  1. 设置系统时间、属性
  2. 初始化looper
  3. 加载native的android_server
  4. 创建system Context
  5. 创建mSystemServiceManager
  6. 启动系统服务
  7. looper开启循环

SystemServiceManager

顾名思义,SystemServiceManager 负责启动各个具体的SystemService线程

// SystemServiceManager
public SystemService startService(String className) {
    final Class<SystemService> serviceClass;
    try {
        serviceClass = (Class<SystemService>)Class.forName(className);
    } catch (ClassNotFoundException ex) {
    }
    return startService(serviceClass);
}

public <T extends SystemService> T startService(Class<T> serviceClass) {
    try {
        final String name = serviceClass.getName();
        // 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);
        } 
        startService(service);
        return service;
    }
}

public void startService(@NonNull final SystemService service) {
    // Register it.
    mServices.add(service);
    // Start it.
    long time = System.currentTimeMillis();
    try {
        service.onStart();
    } catch (RuntimeException ex) {
    }
    warnIfTooLong(System.currentTimeMillis() - time, service, "onStart");
}

SystemServiceManager启动systemService的历程并不难,主要是通过反射构造出service,再调用service的onStart()方法

这里有个疑问,systemService不是运行在独立的线程吗?

    // 启动三种服务
    startBootstrapServices();
    startCoreServices();
    startOtherServices();

系统服务启动分为三类

  1. startBootstrapServices()
  2. startCoreServices()
  3. startOtherServices()
startBootstrapServices:
  1. 启动Installer服务
  2. 启动ActivityManagerService,Installer赋给AMS
  3. 启动PowerManagerService
  4. 启动LightsService
  5. 启动PackageManagerService
  6. 启动SensorService
startCoreServices:
  1. 启动BatteryService
  2. 启动UsageStatsService
  3. AMS setUsageStatsManager
startOtherServices:
  1. 启动SchedulingPolicyService
  2. 启动TelecomLoaderService
  3. 启动TelephonyRegistry
  4. 启动CameraService
  5. 启动AccountManagerService
  6. 启动ContentService
  7. 启动VibratorService
  8. 启动ConsumerIrService
  9. 启动AlarmManagerService
  10. 初始化WatchDog与AMS相关
  11. 启动WindowManagerService
  12. 启动InputManagerService
  13. 启动AccessibilityManagerService
  14. 启动LockSettingsService
  15. 启动DeviceIdleController
  16. 启动StatusBarManagerService
  17. 启动ClipboardService
  18. 启动ConnectivityService
  19. 启动NotificationManagerService
  20. 启动JobSchedulerService
  21. 启动LauncherAppsService

具体来看startBootstrapServices如何启动服务

private void startBootstrapServices() {
    
     Installer installer = mSystemServiceManager.startService(Installer.class);
     
     mSystemServiceManager.startService(DeviceIdentifiersPolicyService.class);

     mActivityManagerService = mSystemServiceManager.startService(
                ActivityManagerService.Lifecycle.class).getService();
     mActivityManagerService.setSystemServiceManager(mSystemServiceManager);
     mActivityManagerService.setInstaller(installer);
     
     
     mPowerManagerService = mSystemServiceManager.startService(PowerManagerService.class);
}

我们拿PowerManagerService来看启动服务的流程:

// PowerManagerService
public final class PowerManagerService extends SystemService
        implements Watchdog.Monitor {


public PowerManagerService(Context context) {
        super(context);
        mContext = context;
        mHandlerThread = new ServiceThread(TAG,
                Process.THREAD_PRIORITY_DISPLAY, false /*allowIo*/);
        mHandlerThread.start();

}

启动了一个独立的线程ServiceThread,他是HandlerThread的子类。

// PowerManagerService
@Override
public void onStart() {
    publishBinderService(Context.POWER_SERVICE, new BinderService());
    publishLocalService(PowerManagerInternal.class, new LocalService());

    Watchdog.getInstance().addMonitor(this);
    Watchdog.getInstance().addThread(mHandler);
}

继续发布PowerManagerService

// SystemServer
    protected final void publishBinderService(String name, IBinder service) {
        publishBinderService(name, service, false);
    }
    
    protected final void publishBinderService(String name, IBinder service,
            boolean allowIsolated, int dumpPriority) {
        ServiceManager.addService(name, service, allowIsolated, dumpPriority);
    }
    protected final <T> void publishLocalService(Class<T> type, T service) {
        LocalServices.addService(type, service);
    }
WatchDog

在上面有两句代码:

    Watchdog.getInstance().addMonitor(this);
    Watchdog.getInstance().addThread(mHandler);

watchDog是什么?

WatchDog类作为看门狗来监控SystemServer中的线程。一旦发现问题,WatchDog会杀死SystemServer进程。

SystemServer的父进程Zygote接收到SystemServer的死亡信号后,会杀死自己。Zygote进程死亡的信号传递到Init进程后,Init进程会杀死Zygote进程所有的子进程并重启Zygote。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值