System Server

System Server是Zygote fork的第一个Java进程,这个进程非常重要因为它提供很多的系统线程,提供android是什么手机牌子所有核心的系统服务,其实包括大事务性工作名鼎鼎的WindowManager, ActivityManager,它们都是运行在system_server的进程里。还有很多“Binder-x”的线程,它们是各个Service为了响应应用程序远程调用请求而创建的。除此之外,还有很多内部的线程,比如 ”UI thread”线程池核心参数,“InputReader”,“InputDispatch” 等等。

System Server启动

//Zygote通过forkSystemServer最终会执行到这里
public static void main(String[] args) {
    new SystemServer().run();
}

run()方法执行过程

private void run() {
    try {
        //处理系统时间,如果系统时间小于1970年则设置为1970年
        if (System.currentTimeMillis() < EARLIEST_SUPPORTED_TIME) {
            SystemClock.setCurrentTimeMillis(EARLIEST_SUPPORTED_TIME);
        }
        //设置默认时区GMT
        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", "");
        }
        //Binder事务发生阻塞时发出警告
        Binder.setWarnOnBlocking(true);
        //设置安全标签
        PackageItemInfo.setForceSafeLabels(true);
        SQLiteCompatibilityWalFlags.init(null);
        //系统时钟时间戳
        int uptimeMillis = (int) SystemClock.elapsedRealtime(); uptimeMillis);
        ....
        //设置虚拟机执行路径
        SystemProperties.set("persist.sys.dalvik.vm.lib.2", VMRuntime.getRuntime().vmLibrary());
        //清除虚拟机内存增长限制
        VMRuntime.getRuntime().clearGrowthLimit();
        //设置内存的可能有效使用率为0.8
        VMRuntime.getRuntime().setTargetHeapUtilization(0.8f);
        //定义指纹信息
        Build.ensureFingerprintProperty();
        //明确指定用户
        Environment.setUserRequired(true);
        //防止Bundle解析崩溃
        BaseBundle.setShouldDefuse(true);
        //设置Parcel异常追踪
        Parcel.setStackTraceParceling(true);
        //设置系统Binder运行在前台优先级
        BinderInternal.disableBackgroundScheduling(true);
        //设置最大的binder线程数(31个)
        BinderInternal.setMaxThreads(sMaxBinderThreads);
        //设置线程优先级、开始执行Looper
        android.os.Process.setThreadPriority(
            android.os.Process.THREAD_PRIORITY_FOREGROUND);
        android.os.Process.setCanSelfBackground(false);
        Looper.prepareMainLooper();
        Looper.getMainLooper().setSlowLogThresholdMs(
                SLOW_DISPATCH_THRESHOLD_MS, SLOW_DELIVERY_THRESHOLD_MS);
        //加载android_servers.so库        
        System.loadLibrary("android_servers");
        //检测上次关机过程是否失败,该方法可能不会返回
        performPendingShutdown();
        //初始化系统context
        createSystemContext();
        //创建系统服务管理类,SystemServerManager主要进行服务的管理和启动
        mSystemServiceManager = new SystemServiceManager(mSystemContext);
        mSystemServiceManager.setStartInfo(mRuntimeRestart,
                mRuntimeStartElapsedTime, mRuntimeStartUptime);
        //将mSystemServiceManager添加到本地服务的成员sLocalServiceObjects        
        LocalServices.addService(SystemServiceManager.class, mSystemServiceManager);
        //初始化执行各种系统服务的线程池
        SystemServerInitThreadPool.get();
    } finally {
        traceEnd();  // InitBeforeStartServices
    }
    //前面都是一些准备工作,这里开始启动各种服务
    try {
        startBootstrapServices();//启动引导服务
        startCoreServices();     //启动系统核心服务
        startOtherServices();    //启动其他服务
        SystemServerInitThreadPool.shutdown(); //关闭线程池
    } catch (Throwable ex) {
       ....
    } finally {
        traceEnd();
    }
    StrictMode.initVmDefaults(null);
    ....
    Looper.loop(); //开启looper循环
  ....
}

creatGoeSystemContext

private void createSystemContext() {
    //systemMain方法完成ActivityThread的创建和attach
    ActivityThread activityThread = ActivityThread.systemMain();
    //获取系统上下文、设置主题
    mSystemContext = activityThread.getSystemContext();
    mSystemContext.setTheme(DEFAULT_SYSTEM_THEME);
    final Context systemUiContext = activityThread.getSystemUiContext();
    systemUiContext.setTheme(DEFAULT_SYSTEM_THEME);
}

createSystemContext方法是进行ActivityThread的创建和attach并设置主题。

star事务的四个特性tBootstrapServices

private void startBootstrapServices() {
    ....
    //阻塞等待与installd建立socket通道
    Installer installer = mSystemServiceManager.startService(Installer.class);
    ....
    // 启动 DeviceIdentifiersPolicyService,该服务定义了访问设备标识符的策略
    mSystemServiceManager.startService(DeviceIdentifiersPolicyService.class);
    ....
    //启动AMS
    mActivityManagerService = mSystemServiceManager.startService(
            ActivityManagerService.Lifecycle.class).getService();
    mActivityManagerService.setSystemServiceManager(mSystemServiceManager);
    mActivityManagerService.setInstaller(installer);
    ....
    //启动PowerManagerService
    mPowerManagerService = mSystemServiceManager.startService(PowerManagerService.class);
    //初始化power management
    mActivityManagerService.initPowerManagement();
    //启动RecoverySystemService
    mSystemServiceManager.startService(RecoverySystemService.class);
    ....
    RescueParty.noteBoot(mSystemContext);
    ....
    //启动LightsService
    mSystemServiceManager.startService(LightsService.class);
    ....
    //启动DisplayManagerService
    mDisplayManagerService = mSystemServiceManager.startService(DisplayManagerService.class);
    ....
    //设置BootPhase为100,BootPhase将启动阶段进行了分类
    mSystemServiceManager.startBootPhase(SystemService.PHASE_WAIT_FOR_DEFAULT_DISPLAY);
    ....
    //启动PackageManagerService
    mPackageManagerService = PackageManagerService.main(mSystemContext, installer,
            mFactoryTestMode != FactoryTest.FACTORY_TEST_OFF, mOnlyCore);
    mFirstBoot = mPackageManagerService.isFirstBoot();
    mPackageManager = mSystemContext.getPackageManager();
    ....
    //启动UserManagerService
    mSystemServiceManager.startService(UserManagerService.LifeCycle.class);
    AttributeCache.init(mSystemContext);
    //设置AMS
    mActivityManagerService.setSystemProcess();
    mDisplayManagerService.setupSchedulerPolicies();
    //启动OverlayManagerService
    mSystemServiceManager.startService(new OverlayManagerService(mSystemContext, installer));
    //通过单独的线程执行SensorService
    mSensorServiceStart = SystemServerInitThreadPool.get().submit(() -> {
        ....
        startSensorService();
        ....
    }, START_SENSOR_SERVICE);
}

startBootstrapServices方法是来启动系统的各种关键服务,包线程池的工作原理Installer DeviceIdentifiersPolicyService ActivityManagerService PowerManagerService RecoverySystemService LightsService StartSidekickService Display事务所所长npcManagerService``PackageManagerServiceUserManagerServiceOverlayManagerServicewebview2控件SensorService,同时设置了BootPhase为100来标记服务的启动阶段。

startCoreServices

private void startCoreServices() {
    //启动BatteryService
    mSystemServiceManager.startService(BatteryService.class);
    //启动UsageStatsService
    mSystemServiceManager.startService(UsageStatsService.class);
    mActivityManagerService.setUsageStatsManager(
            LocalServices.getService(UsageStatsManagerInternal.class));
    //根据条件判断是否要启动WebView更新服务
    if (mPackageManager.hasSystemFeature(PackageManager.FEATURE_WEBVIEW)) {
        mWebViewUpdateService = mSystemServiceManager.startService(WebViewUpdateService.class);
    }
    //启动BinderCallsStatsService
    BinderCallsStatsService.start();
}

sgoogletartCoreServices方法启动了BatteryServiceUsageStatsServiceWebViewUpd线程池的使用ateServiceBinderCallsStatsService四个服务。

startOtherSe枸杞rvices

sta事务所是干什么的rtOtherServices方法涉及到很多的服务,代线程池码量也比较大,这里指列举几个我们平时了解的比较多的线程池面试题

private void startOtherServices() {
   ....
   //AlarmManagerService,定闹钟的
   mSystemServiceManager.startService(AlarmManagerService.class);
   //InputManagerService,处理点击事件的
   inputManager = new InputManagerService(context);
   //WindowManagerService,并且与InputManagerService建立关联
   wm = WindowManagerService.main(context, inputManager,
        mFactoryTestMode != FactoryTest.FACTORY_TEST_LOW_LEVEL,
        !mFirstBoot, mOnlyCore, new PhoneWindowManager());
   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);
   //AMS再与WindowManagerService(WMS)建立关联 
   mActivityManagerService.setWindowManager(wm);  
   //启动InputManagerService
   inputManager.setWindowManagerCallbacks(wm.getInputMonitor());
   inputManager.start();
   ....
   // 480 
   mSystemServiceManager.startBootPhase(SystemService.PHASE_LOCK_SETTINGS_READY);
   // 500 
   mSystemServiceManager.startBootPhase(SystemService.PHASE_SYSTEM_SERVICES_READY);
   // 准备好window, power, package, display服务 wm.systemReady(); 
   mPowerManagerService.systemReady(...); 
   mPackageManagerService.systemReady(); 
   mDisplayManagerService.systemReady(...);
   ....
}

startOtherServices方法启动了各种各样龚俊的服务,启动服务的过程中设置了多个阶段信息。

SystemService.PHASE_LOCK_SETTINGS_READY             // 480
SystemService.PHASE_SYSTEM_SERVICES_READY           // 500
SystemService.PHASE_DEVICE_SPECIFIC_SERVICES_READY  // 520
SystemService.PHASE_ACTIVITY_MANAGER_READY          // 550
SystemService.PHASE_THIRD_PARTY_APPS_CAN_START      // 600

整体可归纳为Gityuan大神画的这张webview更新

System Server工作流程
到此为止,system_seandroid平板电脑价格rver进程的主要工作就算完成了,之后会进入 Looper.loop() 状态,等待其他android什么意思线程通过 Handler 发送消息到主线程并处理。

总结

System Server启动会涉及大量的系统服务来支持系统的运行,这其中就包括我们常见的AMS、事务所WMS、IMS等服务,各种系统服务共同维持着系统和app的运行。

参考文章
gityuan.com/2016/02/20/…
/事务所所长npcpost/684490…