欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  移动技术

Zygote家的大儿子 —— SystemServer

程序员文章站 2024-01-26 21:12:10
本文基于 Android 9.0 , 代码仓库地址 : "android_9.0.0_r45" 文中源码链接: "SystemServer.java" "SystemServiceManager.java" "SystemService.java" 首先来回顾一下上篇文章 "Java 世界的盘古和女 ......

本文基于 android 9.0 , 代码仓库地址 :

文中源码链接:

systemserver.java

systemservicemanager.java

systemservice.java

首先来回顾一下上篇文章 java 世界的盘古和女娲 —— zygote ,主要介绍了 android 世界中的第一个 java 进程 zygote,它的主要工作流程如下:

  1. registerserversocketfromenv(), 注册服务端 socket,用于和客户端进程通信
  2. preload(),预加载一系列资源,提高应用启动速度
  3. forksystemserver(),创建 system_server 进程
  4. 功成身退,调用 runselectloop() 等待响应客户端请求,创建应用进程

本篇文章的主角 system_server 进程是 zygote 进程 fork 出的第一个进程,它负责管理和启动整个 framework 层。

再来看看 gityuan 的这张图片,找一下 system server 的位置,它承载了各类系统服务的创建和启动。关于 system_server 进程的创建流程,上篇文章中已经做了详细介绍,这里再简单看一下流程图:

Zygote家的大儿子 —— SystemServer

最终会调用到 systemserver.main() 方法。下面就以此为起点,来具体分析 systemserver 都做了些什么。

systemserver 启动流程

public static void main(string[] args) {
    new systemserver().run();
}

接着看 run() 方法。

private void run() {
    try {
        ......
        // 如果设备时间早于 1970 年,很多 api 处理负数时会 crash。所以直接设置为 1970 年 1 月 1 日
        if (system.currenttimemillis() < earliest_supported_time) {
            slog.w(tag, "system clock is before 1970; setting to 1970.");
            systemclock.setcurrenttimemillis(earliest_supported_time);
        }

        // 未设置时区的话默认设为 gmt
        string timezoneproperty =  systemproperties.get("persist.sys.timezone");
        if (timezoneproperty == null || timezoneproperty.isempty()) {
            slog.w(tag, "timezone not set; setting to gmt.");
            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);
        // the system server should always load safe labels
        packageiteminfo.setforcesafelabels(true);

        // default to full within the system server.
        sqliteglobal.sdefaultsyncmode = sqliteglobal.sync_mode_full;

        // deactivate sqlitecompatibilitywalflags until settings provider is initialized
        sqlitecompatibilitywalflags.init(null);

        // here we go!
        slog.i(tag, "entered the android system server!");
        int uptimemillis = (int) systemclock.elapsedrealtime();
        eventlog.writeevent(eventlogtags.boot_progress_system_run, uptimemillis);
        if (!mruntimerestart) {
            metricslogger.histogram(null, "boot_system_server_init", uptimemillis);
        }

        // 设置虚拟机运行库路径
        systemproperties.set("persist.sys.dalvik.vm.lib.2", vmruntime.getruntime().vmlibrary());

        // mmmmmm... more memory!
        // 清除虚拟机内存增长限制,允许应用申请更多内存
        vmruntime.getruntime().cleargrowthlimit();

        // 设置堆内存的有效利用率为 0.8,(可能被忽略)
        vmruntime.getruntime().settargetheaputilization(0.8f);

        // 确保指纹信息已经定义
        build.ensurefingerprintproperty();

        // within the system server, it is an error to access environment paths without
        // explicitly specifying a user.
        environment.setuserrequired(true);

        // within the system server, any incoming bundles should be defused
        // to avoid throwing badparcelableexception.
        basebundle.setshoulddefuse(true);

        // within the system server, when parceling exceptions, include the stack trace
        parcel.setstacktraceparceling(true);

        // 确保系统的 binder 调用总是运行在前台优先级
        binderinternal.disablebackgroundscheduling(true);

        // increase the number of binder threads in system_server
        binderinternal.setmaxthreads(smaxbinderthreads);

        // prepare the main looper thread (this thread).
        android.os.process.setthreadpriority(
            android.os.process.thread_priority_foreground);
            android.os.process.setcanselfbackground(false);
        // 1. 创建主线程 looper
        looper.preparemainlooper();
        looper.getmainlooper().setslowlogthresholdms(
                slow_dispatch_threshold_ms, slow_delivery_threshold_ms);

        // 初始化 native 服务,加载 libandroid_servers.so
        system.loadlibrary("android_servers");

        // 检查上次关机是否失败,可能不会有返回值
        performpendingshutdown();

        // 2. 初始化系统上下文
        createsystemcontext();

        // 3. 创建系统服务管理 systemservicemanager
        // 并将 msystemservicemanager 注册到 slocalserviceobjects 中
        msystemservicemanager = new systemservicemanager(msystemcontext);
        msystemservicemanager.setstartinfo(mruntimerestart,
                mruntimestartelapsedtime, mruntimestartuptime);
        localservices.addservice(systemservicemanager.class, msystemservicemanager);
        // prepare the thread pool for init tasks that can be parallelized
        systemserverinitthreadpool.get();
    } finally {
        traceend();  // initbeforestartservices
    }

    // start services.
    try {
        tracebeginandslog("startservices");
        startbootstrapservices(); // 4. 启动系统引导服务
        startcoreservices();      // 5. 启动系统核心服务
        startotherservices();     // 6. 启动其他服务
        systemserverinitthreadpool.shutdown();
    } catch (throwable ex) {
        slog.e("system", "******************************************");
        slog.e("system", "************ failure starting system services", ex);
        throw ex;
    } finally {
        traceend();
    }

    strictmode.initvmdefaults(null);

    if (!mruntimerestart && !isfirstbootorupgrade()) {
        int uptimemillis = (int) systemclock.elapsedrealtime();
        metricslogger.histogram(null, "boot_system_server_ready", uptimemillis);
        final int max_uptime_millis = 60 * 1000;
        if (uptimemillis > max_uptime_millis) {
            slog.wtf(system_server_timing_tag,
                    "systemserver init took too long. uptimemillis=" + uptimemillis);
        }
    }

    // 7. loop forever.
    looper.loop();
    throw new runtimeexception("main thread loop unexpectedly exited");
}

代码虽然比较长,但是逻辑很清晰。我在注释里标记了比较重要的 7 个步骤,逐一分析。

looper.preparemainlooper()

初始化 looper。关于 handler 消息机制,可以阅读我的另一篇文章 深入理解 handler 消息机制 。最后会调用 looper.loop() 开启消息循环,开始处理消息。

createsystemcontext()

private void createsystemcontext() {
    // 创建 system_server 上下文信息
    activitythread activitythread = activitythread.systemmain();
    msystemcontext = activitythread.getsystemcontext();
    msystemcontext.settheme(default_system_theme);

    final context systemuicontext = activitythread.getsystemuicontext();
    // 设置主题,用于系统 dialog 等
    systemuicontext.settheme(default_system_theme);
}

创建系统上下文。首先调用 activitythread.systemmain() 方法获取 activitythread 对象,然后再获取上下文。

public static activitythread systemmain() {
    // 判断是否是大内存设备,在低内存设备上不启用硬件加速
    if (!activitymanager.ishighendgfx()) {
        threadedrenderer.disable(true);
    } else {
        threadedrenderer.enableforegroundtrimming();
    }
    activitythread thread = new activitythread();
    thread.attach(true, 0);
    return thread;
}

关于 activitythread.attach() 方法这里不做具体分析了,后面文章说到应用启动时再来详细解析。

创建完系统上下文,接下来就是启动各种系统服务了。源码中把服务大致分为了三类,再来回顾一下:

startbootstrapservices(); // 4. 启动系统引导服务
startcoreservices();      // 5. 启动系统核心服务
startotherservices();     // 6. 启动其他服务

逐一进行分析。

startbootstrapservices()

private void startbootstrapservices() {
    final string tag_system_config = "readingsystemconfig";
    systemserverinitthreadpool.get().submit(systemconfig::getinstance, tag_system_config);

    // 阻塞等待与 installd 建立 socket 通道
    installer installer = msystemservicemanager.startservice(installer.class);

    // 启动 deviceidentifierspolicyservice,在 activitymanagerservice 之前
    msystemservicemanager.startservice(deviceidentifierspolicyservice.class);

    // 启动服务 activitymanagerservice
    mactivitymanagerservice = msystemservicemanager.startservice(
            activitymanagerservice.lifecycle.class).getservice();
    mactivitymanagerservice.setsystemservicemanager(msystemservicemanager);
    mactivitymanagerservice.setinstaller(installer);

    // 启动服务 powermanagerservice
    mpowermanagerservice = msystemservicemanager.startservice(powermanagerservice.class);

    // now that the power manager has been started, let the activity manager
    // initialize power management features.
    mactivitymanagerservice.initpowermanagement();

    // 启动服务 recoverysystemservice
    msystemservicemanager.startservice(recoverysystemservice.class);

    // now that we have the bare essentials of the os up and running, take
    // note that we just booted, which might send out a rescue party if
    // we're stuck in a runtime restart loop.
    rescueparty.noteboot(msystemcontext);

    // 启动服务 lightsservice
    msystemservicemanager.startservice(lightsservice.class);

    // package manager isn't started yet; need to use sysprop not hardware feature
    if (systemproperties.getboolean("config.enable_sidekick_graphics", false)) {
        msystemservicemanager.startservice(wear_sidekick_service_class);
    }

    // 启动 displaymanagerservice,在 packagemanagerservice 之前
    mdisplaymanagerservice = msystemservicemanager.startservice(displaymanagerservice.class);

    // we need the default display before we can initialize the package manager.
    msystemservicemanager.startbootphase(systemservice.phase_wait_for_default_display);

    // 正在加密设备时只运行核心 app
    string cryptstate = systemproperties.get("vold.decrypt");
    if (encrypting_state.equals(cryptstate)) {
        slog.w(tag, "detected encryption in progress - only parsing core apps");
        monlycore = true;
    } else if (encrypted_state.equals(cryptstate)) {
        slog.w(tag, "device encrypted - only parsing core apps");
        monlycore = true;
    }

    // 启动服务 packagemanagerservice
    if (!mruntimerestart) {
        metricslogger.histogram(null, "boot_package_manager_init_start",
                (int) systemclock.elapsedrealtime());
    }
    mpackagemanagerservice = packagemanagerservice.main(msystemcontext, installer,
            mfactorytestmode != factorytest.factory_test_off, monlycore);
    mfirstboot = mpackagemanagerservice.isfirstboot();
    mpackagemanager = msystemcontext.getpackagemanager();
    if (!mruntimerestart && !isfirstbootorupgrade()) {
        metricslogger.histogram(null, "boot_package_manager_init_ready",
                (int) systemclock.elapsedrealtime());
    }
    if (!monlycore) {
        boolean disableotadexopt = systemproperties.getboolean("config.disable_otadexopt",
                false);
        if (!disableotadexopt) {
            tracebeginandslog("startotadexoptservice");
            try {
                otadexoptservice.main(msystemcontext, mpackagemanagerservice);
            } catch (throwable e) {
                reportwtf("starting otadexoptservice", e);
            } finally {
                traceend();
            }
        }
    }

    // 启动服务 usermanagerservice
    msystemservicemanager.startservice(usermanagerservice.lifecycle.class);

    // 初始化属性 cache 以缓存包资源
    attributecache.init(msystemcontext);

    // 设置 ams
    mactivitymanagerservice.setsystemprocess();

    // displaymanagerservice needs to setup android.display scheduling related policies
    // since setsystemprocess() would have overridden policies due to setprocessgroup
    mdisplaymanagerservice.setupschedulerpolicies();

    // 启动服务 overlaymanagerservice
    overlaymanagerservice overlaymanagerservice = new overlaymanagerservice(
            msystemcontext, installer);
    msystemservicemanager.startservice(overlaymanagerservice);

    if (systemproperties.getint("persist.sys.displayinset.top", 0) > 0) {
        // displaymanager needs the overlay immediately.
        overlaymanagerservice.updatesystemuicontext();
        localservices.getservice(displaymanagerinternal.class).onoverlaychanged();
    }

    // 在单独的线程中启动 sensorservice
    msensorservicestart = systemserverinitthreadpool.get().submit(() -> {
        timingstracelog tracelog = new timingstracelog(
                system_server_timing_async_tag, trace.trace_tag_system_server);
        startsensorservice();
    }, start_sensor_service);
}

startbootstrapservices() 方法中的都是系统启动过程中的关键服务,且相互依赖,主要下列服务 :

installer deviceidentifierspolicyservice activitymanagerservice powermanagerservice recoverysystemservice lightsservice startsidekickservice displaymanagerservice

systemservice.phase_wait_for_default_display (100)

packagemanagerservice usermanagerservice overlaymanagerservice sensorservice

一共启动了十二个核心服务。注意中间的 systemservice.phase_wait_for_default_display,它并不是代表什么系统服务,而是一个 int 值 100,类似的 int 值还有一些,定义在 systemservice 类中,它的作用是给服务启动过程划分阶段,每个阶段都有特定的含义,可以做不同的事情。这里先混个脸熟,等介绍完所有的服务,再回过头来总结一下有哪些阶段。

startcoreservices()

private void startcoreservices() {
    // 启动服务 batteryservice,需要 lightservice
    msystemservicemanager.startservice(batteryservice.class);

    // 启动服务 usagestatsservice,统计应用使用情况
    msystemservicemanager.startservice(usagestatsservice.class);
    mactivitymanagerservice.setusagestatsmanager(
            localservices.getservice(usagestatsmanagerinternal.class));

    // 检查是否存在可更新的 webview。存在就启动服务 webviewupdateservice
    if (mpackagemanager.hassystemfeature(packagemanager.feature_webview)) {
        mwebviewupdateservice = msystemservicemanager.startservice(webviewupdateservice.class);
    }

    // 启动服务 bindercallsstatsservice,跟踪 binder 调用的 cpu 时间消耗
    bindercallsstatsservice.start();
}

启动了四个服务,batteryservice usagestatsservice webviewupdateservicebindercallsstatsservice

startotherservices()

startotherservices() 源码有一千多行,就像一个杂货铺,启动了一系列的服务。下面尽量精简一下代码:

keyattestationapplicationidproviderservice/keychainsystemservice
schedulingpolicyservice/telecomloaderservice/telephonyregistry

mcontentresolver = context.getcontentresolver();

accountmanagerservice/contentservice

mactivitymanagerservice.installsystemproviders();
  
dropboxmanagerservice/vibratorservice/consumerirservice/alarmmanagerservice

final watchdog watchdog = watchdog.getinstance();
watchdog.init(context, mactivitymanagerservice);

inputmanagerservice/windowmanagerservice/vrmanagerservice/bluetoothservice
ipconnectivitymetrics/networkwatchlistservice/pinnerservice
inputmethodmanagerservice/accessibilitymanagerservice/storagemanagerservice
storagestatsservice/uimodemanagerservice/locksettingsservice
persistentdatablockservice/oemlockservice/deviceidlecontroller
devicepolicymanagerservice/statusbarmanagerservice/clipboardservice
networkmanagementservice/ipsecservice/textservicesmanagerservice
textclassificationmanagerservice/networkscoreservice/networkstatsservice
networkpolicymanagerservice/wifiscanningservice/rttservice
wifiaware/wifip2p/lowpan/ethernet/connectivityservice/nsdservice
systemupdatemanagerservice/updatelockservice/notificationmanagerservice
devicestoragemonitorservice/locationmanagerservice/countrydetectorservice
searchmanagerservice/wallpapermanagerservice/audioservice/broadcastradioservice
dockobserver/thermalobserver/wiredaccessorymanager/midimanager/usbservice
serialservice/hardwarepropertiesmanagerservice/twilightservice
colordisplayservice/jobschedulerservice/soundtriggerservice/trustmanagerservice
backupmanager/appwidgerservice/voicerecognitionmanager/gesturelauncherservice
sensornotificationservice/contexthubsystemservice/diskstatsservice
timezonerulesmanagerservice/networktimeupdateservice/commontimemanagementservice
certblacklister/emergencyaffordanceservice/dreammanagerservice/graphicsstatsservice
coverageservice/printmanager/companiondevicemanager/restrictionsmanagerservice
mediasessionservice/mediaupdateservice/hdmicontrolservice/tvinputmanagerservice
mediaresourcemonitorservice/tvremoteservice/mediarouterservice/fingerprintservice
backgrounddexoptservice/pruneinstantappsjobservice/shortcutservice
launcherappsservice/crossprofileappsservice/mediaprojectionmanagerservice
wearconfigservice/wearconnectivityservice/weartimeservice/wearleftyservice
wearglobalactionsservice/slicemanagerservice/cameraserviceproxy/iotsystemservice
mmsservicebroker/autofillservice

// it is now time to start up the app processes...
vibrator.systemready();
locksettings.systemready();

// 480
msystemservicemanager.startbootphase(systemservice.phase_lock_settings_ready); 
// 500
msystemservicemanager.startbootphase(systemservice.phase_system_services_ready); 

wm.systemready();
mpowermanagerservice.systemready(mactivitymanagerservice.getappopsservice());
mpackagemanagerservice.systemready();
mdisplaymanagerservice.systemready(safemode, monlycore);

// start device specific services
final string[] classes = msystemcontext.getresources().getstringarray(
        r.array.config_devicespecificsystemservices);
for (final string classname : classes) {
    try {
        msystemservicemanager.startservice(classname);
    } catch (throwable e) {
        reportwtf("starting " + classname, e);
    }
}

// 520
msystemservicemanager.startbootphase(systemservice.phase_device_specific_services_ready);

mactivitymanagerservice.systemready(() -> {
    // 550
    msystemservicemanager.startbootphase(systemservice.phase_activity_manager_ready);
    
    startsystemui(context, windowmanagerf);
    
    networkmanagementf.systemready();
    ipsecservicef.systemready();
    networkstatsf.systemready();
    connectivityf.systemready();
    
    watchdog.getinstance().start
    mpackagemanagerservice.waitforappdataprepared();

    // 600
    msystemservicemanager.startbootphase(systemservice.phase_third_party_apps_can_start);
    
    locationf.systemrunning();
    countrydetectorf.systemrunning();
    networktimeupdaterf.systemrunning();
    commontimemgmtservicef.systemrunning();
    inputmanagerf.systemrunning();
    telephonyregistryf.systemrunning();
    mediarouterf.systemrunning();
    mmsservicef.systemrunning();
    incident.systemrunning();
}

通过上面的代码可以看到启动了相当多的系统服务。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

最后调用的 mactivitymanagerservice.systemready() 方法。该方法中会调用 starthomeactivitylocked 来启动桌面 activity,这样桌面应用就启动了。

looper.loop()

至此,system_server 进程的主要工作就算完成了,进入 looper.loop() 状态,等待其他线程通过 handler 发送消息到主线程并处理。

systemserver 启动阶段分类

回过头再来看看前面提到的启动阶段分类,定义在 com.android.server.systemservice 类中:

/*
 * boot phases
 * 
 * 启动阶段
 */
public static final int phase_wait_for_default_display = 100; // maybe should be a dependency?

/**
 * after receiving this boot phase, services can obtain lock settings data.
 */
public static final int phase_lock_settings_ready = 480;

/**
 * after receiving this boot phase, services can safely call into core system services
 * such as the powermanager or packagemanager.
 * 
 * 在这个阶段之后,可以安全的调用系统核心服务,如 powermanager 和 packagemanager
 */
public static final int phase_system_services_ready = 500;

/**
 * after receiving this boot phase, services can safely call into device specific services.
 * 
 * 在这个阶段之后,可以安全调用设备特定的服务
 */
public static final int phase_device_specific_services_ready = 520;

/**
 * after receiving this boot phase, services can broadcast intents.
 * 
 * 在这个阶段之后,服务可以广播
 */
public static final int phase_activity_manager_ready = 550;

/**
 * after receiving this boot phase, services can start/bind to third party apps.
 * apps will be able to make binder calls into services at this point.
 * 
 * 在这个阶段之后,服务可以启动/绑定第三方应用
 * 应用此时可以进行 binder 调用
 */
public static final int phase_third_party_apps_can_start = 600;

/**
 * after receiving this boot phase, services can allow user interaction with the device.
 * this phase occurs when boot has completed and the home application has started.
 * system services may prefer to listen to this phase rather than registering a
 * broadcast receiver for action_boot_completed to reduce overall latency.
 * 
 * 在这个阶段之后,允许用户和设备交互。
 * 这个阶段发生在启动完成,home 应用已经开始。
 * 系统服务更倾向于监听这个阶段,而不是监听启动广播 action_boot_completed,以降低延迟
 */
public static final int phase_boot_completed = 1000;

system_server 启动过程中各个阶段的位置大致如下:

private void startbootstrapservices() {
    ...
    // 100
    msystemservicemanager.startbootphase(systemservice.phase_wait_for_default_display);
    ...
}

private void startotherservices() {
    ...
    // 480
    msystemservicemanager.startbootphase(systemservice.phase_lock_settings_ready);
    // 500
    msystemservicemanager.startbootphase(systemservice.phase_system_services_ready);

    ...
    // 520
    msystemservicemanager.startbootphase(systemservice.phase_device_specific_services_ready);

    mactivitymanagerservice.systemready(() -> {
        msystemservicemanager.startbootphase(
                    systemservice.phase_activity_manager_ready); // 550
                    
        ...
        msystemservicemanager.startbootphase(
                    systemservice.phase_third_party_apps_can_start); // 600
    }
}

最后的 systemservice.phase_boot_completed(1000) 在 ams 的 finishbooting() 方法中调用。另外注意 480500 两个阶段是连在一起的,中间没有发生任何事情。

那么,划分阶段的具体作用是什么呢?答案就在 startbootphase() 方法中:

public void startbootphase(final int phase) {
    if (phase <= mcurrentphase) {
        throw new illegalargumentexception("next phase must be larger than previous");
    }
    mcurrentphase = phase;

    try {
        final int servicelen = mservices.size();
        for (int i = 0; i < servicelen; i++) {
            final systemservice service = mservices.get(i);
            long time = systemclock.elapsedrealtime();
            try {
                // 回调系统服务的 onbootphase() 方法
                service.onbootphase(mcurrentphase);
            } catch (exception ex) {
                throw new runtimeexception("failed to boot service "
                        + service.getclass().getname()
                        + ": onbootphase threw an exception during phase "
                        + mcurrentphase, ex);
            }
            warniftoolong(systemclock.elapsedrealtime() - time, service, "onbootphase");
        }
    } finally {
        trace.traceend(trace.trace_tag_system_server);
    }
}

核心就在于 service.onbootphase(mcurrentphase);。所有系统服务都是继承于 systemservice 的,startbootphase() 方法会回调当前阶段已经加入 mservices 的所有系统服务的 onbootphase() 方法,在合适的阶段做一些合适的事情。以 ams 为例:

@override
public void onbootphase(int phase) {
    mservice.mbootphase = phase;
    if (phase == phase_system_services_ready) {
        mservice.mbatterystatsservice.systemservicesready();
        mservice.mservices.systemservicesready();
    }
}

systemserver 是如何启动服务的 ?

看完 systemserver 的源码,它最重要的工作就是创建和启动各种系统服务。那么服务一般是如何创建的呢?下面以 startbootstrapservices() 中创建的第一个服务 installer 为例来看一下:

installer installer = msystemservicemanager.startservice(installer.class);

进入 systemservicemanagerstartservice() 方法:

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

创建并启动一个系统服务。这个系统服务必须是 com.android.server.systemservice 的子类。根据参数传入的 class 对象反射创建其实例,再调用重载方法 startservice()

public void startservice(@nonnull final systemservice service) {
    // register it.
    mservices.add(service);
    // start it.
    long time = systemclock.elapsedrealtime();
    try {
        // 回调系统服务的 onstart() 方法
        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");
}

就两步。第一步,注册服务,mservices 是一个 arraylist<systemservice> 对象,用来保存已经创建的系统服务。第二步,回调服务的 onstart() 方法,还是以 installer 为例:

@override
public void onstart() {
    if (misolated) {
        minstalld = null;
    } else {
        connect();
    }
}

这样一个服务就启动完成了。这是一种比较普遍的启动方式,当然还有一些系统服务具有不一样的启动方式,这里就不一一分析了,后面有机会解析具体服务的时候再来分析。

总结

systemserver 的启动流程比较耿直,没有那么多弯弯绕,下面简单总结一下:

  1. 语言、时区、地区等设置
  2. 虚拟机内存设置
  3. 指纹信息,binder 调用设置
  4. looper.preparemainlooper() ,创建主线程 looper
  5. 初始化 native 服务,加载 libandroid_servers.so
  6. createsystemcontext(),初始化系统上下文
  7. 创建系统服务管理 systemservicemanager
  8. startbootstrapservices,启动系统引导服务
  9. startcoreservices,启动系统核心服务
  10. startotherservices,启动其他服务
  11. looper.loop(),开启消息循环

另外,在 startotherservices 的最后会调用 ams 的 onsystemready() 方法启动桌面 activity。

预告

还记得 zygote 进程的 runselectloop() 方法吗?zygote 在创建完 system_server 进程之后,就开始默默的等待客户端请求创建应用进程。下一篇,我们将从源码角度来捋一遍客户端是如何发送请求,zygote 是如何处理请求,应用进程是如何创建的,敬请期待!

文章首发微信公众号: 秉心说 , 专注 java 、 android 原创知识分享,leetcode 题解。

更多最新原创文章,扫码关注我吧!

Zygote家的大儿子 —— SystemServer