在 zygote 启动流程分析中,zygote 最后会调用 SystemServer 的 main 函数, 这篇就来介绍 SystemServer 的流程

时序图

SystemServer 介绍

SystemServer 有点 CPU 的感觉, 我们应用层用到的很多服务都是运行在该进程中的, 比如 WMS,AMS,PMS

入口 main 函数

    public static void main(String[] args) {
        new SystemServer().run();
    }
<span class="hljs-function"><span class="hljs-keyword">private</span> <span class="hljs-keyword">void</span> <span class="hljs-title">run</span><span class="hljs-params">()</span> </span>{
    <span class="hljs-keyword">try</span> {
        ......

        <span class="hljs-comment">// Prepare the main looper thread (this thread).</span>
        android.os.Process.setThreadPriority(
            android.os.Process.THREAD_PRIORITY_FOREGROUND);
        android.os.Process.setCanSelfBackground(<span class="hljs-keyword">false</span>);
        <span class="hljs-comment">//主线程looper就在当前线程运行</span>
        Looper.prepareMainLooper();

        <span class="hljs-comment">//加载android_servers.so库,该库包含的源码在frameworks/base/services/目录下</span>
        System.loadLibrary(<span class="hljs-string">"android_servers"</span>);

        <span class="hljs-comment">//检测上次关机过程是否失败,该方法可能不会返回</span>
        performPendingShutdown();

        <span class="hljs-comment">//初始化系统上下文 </span>
        createSystemContext();

        <span class="hljs-comment">//创建系统服务管理</span>
        mSystemServiceManager = <span class="hljs-keyword">new</span> SystemServiceManager(mSystemContext);
        mSystemServiceManager.setRuntimeRestarted(mRuntimeRestart);
        LocalServices.addService(SystemServiceManager.class, mSystemServiceManager);
        <span class="hljs-comment">// Prepare the thread pool for init tasks that can be parallelized</span>
        SystemServerInitThreadPool.get();
    } <span class="hljs-keyword">finally</span> {
        traceEnd();  <span class="hljs-comment">// InitBeforeStartServices</span>
    }

    <span class="hljs-comment">//启动各种系统服务</span>
    <span class="hljs-keyword">try</span> {
        traceBeginAndSlog(<span class="hljs-string">"StartServices"</span>);
        startBootstrapServices();
        startCoreServices();
        startOtherServices();
        SystemServerInitThreadPool.shutdown();
    } <span class="hljs-keyword">catch</span> (Throwable ex) {
        ......
    } <span class="hljs-keyword">finally</span> {
        traceEnd();
    }
    <span class="hljs-comment">// Loop forever. 一直处于循环状态</span>
    Looper.loop();
    <span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> RuntimeException(<span class="hljs-string">"Main thread loop unexpectedly exited"</span>);
}
复制代码

createSystemContext

该过程会创建对象有 ActivityThread,Instrumentation, ContextImpl,LoadedApk,Application

startBootstrapServices

private void startBootstrapServices() {
    // 阻塞等待与 installd 建立 socket 通道
    Installer installer = mSystemServiceManager.startService(Installer.class);
<span class="hljs-comment">//启动服务ActivityManagerService</span>
mActivityManagerService = mSystemServiceManager.startService(
        ActivityManagerService.Lifecycle.class).getService();
mActivityManagerService.setSystemServiceManager(mSystemServiceManager);
mActivityManagerService.setInstaller(installer);

<span class="hljs-comment">//启动服务PowerManagerService</span>
mPowerManagerService = mSystemServiceManager.startService(PowerManagerService.class);

......

<span class="hljs-comment">//启动服务PackageManagerService</span>
mPackageManagerService = PackageManagerService.main(mSystemContext, installer,
        mFactoryTestMode != FactoryTest.FACTORY_TEST_OFF, mOnlyCore);
mFirstBoot = mPackageManagerService.isFirstBoot();
mPackageManager = mSystemContext.getPackageManager();

<span class="hljs-comment">//启动服务UserManagerService,新建目录/data/user/</span>
ServiceManager.addService(Context.USER_SERVICE, UserManagerService.getInstance());

AttributeCache.init(mSystemContext);

<span class="hljs-comment">//设置AMS</span>
mActivityManagerService.setSystemProcess();

<span class="hljs-comment">//启动传感器服务</span>
startSensorService();

}

复制代码

该方法所创建的服务:

  • ActivityManagerService
  • PowerManagerService
  • LightsService
  • DisplayManagerService
  • PackageManagerService
  • UserManagerService
  • SensorService

startCoreServices

private void startCoreServices() {
    // 启动服务 BatteryService,用于统计电池电量,需要 LightService.
    mSystemServiceManager.startService(BatteryService.class);
<span class="hljs-comment">//启动服务UsageStatsService,用于统计应用使用情况</span>
mSystemServiceManager.startService(UsageStatsService.class);
mActivityManagerService.setUsageStatsManager(
        LocalServices.getService(UsageStatsManagerInternal.class));

mPackageManagerService.getUsageStatsIfNoPackageUsageInfo();

<span class="hljs-comment">//启动服务WebViewUpdateService</span>
mSystemServiceManager.startService(WebViewUpdateService.class);

}

复制代码

通过传入的类名进行实例化后添加到 mServices 中并调用自身的 onStart

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

该方法所创建的服务:

  • BatteryService
  • UsageStatsService
  • WebViewUpdateService

startOtherServices


// 和 SettingsProvider 关联
mActivityManagerService.installSystemProviders();
// 设置对象关联
mActivityManagerService.setWindowManager(wm);
......

// 准备好 window, power, package, display 服务
wm.systemReady();
mPowerManagerService.systemReady(…);
mPackageManagerService.systemReady();
mDisplayManagerService.systemReady(…);

mActivityManagerService.systemReady(new Runnable() {
public void run() {
……
}
});

复制代码

AMS.systemReady

在服务启动完毕后, 会调用各个服务的 systemReady

AMS 是最后一个启动的服务, 会调用 mActivityManagerService.systemReady

mActivityManagerService.systemReady(new Runnable() {
    public void run() {
        // 启动 WebView
      WebViewFactory.prepareWebViewInSystemServer();
      // 启动系统 UI
      startSystemUi(context);
  <span class="hljs-comment">// 执行一系列服务的systemReady方法</span>
  networkScoreF.systemReady();
  networkManagementF.systemReady();
  networkStatsF.systemReady();

  ......

  <span class="hljs-comment">//执行一系列服务的systemRunning方法</span>
  wallpaper.systemRunning();
  inputMethodManager.systemRunning(statusBarF);
  location.systemRunning();

}

});

复制代码

这个函数里进行了大量的 systemRunning 调用, 主要是注册广播等等

比如 TelephonyRegistry

try {
    if (telephonyRegistryF != null) telephonyRegistryF.systemRunning();
    } catch (Throwable e) {
        reportWtf("Notifying TelephonyRegistry running", e);
    }
<span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">systemRunning</span><span class="hljs-params">()</span> </span>{
    <span class="hljs-comment">// Watch for interesting updates</span>
    <span class="hljs-keyword">final</span> IntentFilter filter = <span class="hljs-keyword">new</span> IntentFilter();
    filter.addAction(Intent.ACTION_USER_SWITCHED);
    filter.addAction(Intent.ACTION_USER_REMOVED);
    filter.addAction(TelephonyIntents.ACTION_DEFAULT_SUBSCRIPTION_CHANGED);
    log(<span class="hljs-string">"systemRunning register for intents"</span>);
    mContext.registerReceiver(mBroadcastReceiver, filter);

}

复制代码

startSystemUi

static final void startSystemUi(Context context) {
    Intent intent = new Intent();
    intent.setComponent(new ComponentName("com.android.systemui",
                "com.android.systemui.SystemUIService"));
    context.startServiceAsUser(intent, UserHandle.OWNER);
}
复制代码

该函数的主要作用是启动服务 ”com.android.systemui.SystemUIService”

AMS 简单流程

这里需要介绍下 AMS 的流程, 因为后续的代码就是和 AMS 有关了

在前面 startBootstrapServices 的流程中有一段代码

ams.setSystemProcess()

在 startOtherServices 中有段代码

ams.installSystemProviders()

这些都是 AMS 的大致流程

  • 创建 AMS 对象
  • 调用 ams.setSystemProcess
  • 调用 ams.installSystemProviders
  • 调用 ams.systemReady

在 systemReady 的最后它会调用到 ams 中的 startHomeActivityLocked 函数, 他的主要作用就是启动桌面 Activity

boolean startHomeActivityLocked(int userId, String reason) {
    //home intent 有 CATEGORY_HOME
    Intent intent = getHomeIntent();
    ActivityInfo aInfo = resolveActivityInfo(intent, STOCK_PM_FLAGS, userId);
    if (aInfo != null) {
        intent.setComponent(new ComponentName(
                aInfo.applicationInfo.packageName, aInfo.name));
        aInfo = new ActivityInfo(aInfo);
        aInfo.applicationInfo = getAppInfoForUser(aInfo.applicationInfo, userId);
        ProcessRecord app = getProcessRecordLocked(aInfo.processName,
                aInfo.applicationInfo.uid, true);
        if (app == null || app.instrumentationClass == null) {
            intent.setFlags(intent.getFlags() | Intent.FLAG_ACTIVITY_NEW_TASK);
            // 启动桌面 Activity
            mStackSupervisor.startHomeActivity(intent, aInfo, reason);
        }
    }
    return true;
}
复制代码

systemReady 大致流程

public final class ActivityManagerService{
<span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">systemReady</span><span class="hljs-params">(<span class="hljs-keyword">final</span> Runnable goingCallback)</span> </span>{
    ...<span class="hljs-comment">//更新操作</span>
    mSystemReady = <span class="hljs-keyword">true</span>; <span class="hljs-comment">//系统处于ready状态</span>
    removeProcessLocked(proc, <span class="hljs-keyword">true</span>, <span class="hljs-keyword">false</span>, <span class="hljs-string">"system update done"</span>);<span class="hljs-comment">//杀掉所有非persistent进程</span>
    mProcessesReady = <span class="hljs-keyword">true</span>;  <span class="hljs-comment">//进程处于ready状态</span>

    goingCallback.run(); <span class="hljs-comment">//这里有可能启动进程</span>

    addAppLocked(info, <span class="hljs-keyword">false</span>, <span class="hljs-keyword">null</span>); <span class="hljs-comment">//启动所有的persistent进程</span>
    mBooting = <span class="hljs-keyword">true</span>;  <span class="hljs-comment">//正在启动中</span>
    startHomeActivityLocked(mCurrentUserId, <span class="hljs-string">"systemReady"</span>); <span class="hljs-comment">//启动桌面</span>
    mStackSupervisor.resumeTopActivitiesLocked(); <span class="hljs-comment">//恢复栈顶的Activity</span>
}

}

复制代码

参考博客 Android 系统启动 -SystemServer

  • Android

    开放手机联盟(一个由 30 多家科技公司和手机公司组成的团体)已开发出 Android,Android 是第一个完整、开放、免费的手机平台。

    293 引用
感谢    赞同    分享    收藏    关注    反对    举报    ...