SystemServer启动流程

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

时序图

SystemServer介绍

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

入口main函数

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

    private void run() {
        try {
            ......

            // Prepare the main looper thread (this thread).
            android.os.Process.setThreadPriority(
                android.os.Process.THREAD_PRIORITY_FOREGROUND);
            android.os.Process.setCanSelfBackground(false);
            //主线程looper就在当前线程运行
            Looper.prepareMainLooper();

            //加载android_servers.so库,该库包含的源码在frameworks/base/services/目录下
            System.loadLibrary("android_servers");

            //检测上次关机过程是否失败,该方法可能不会返回
            performPendingShutdown();

            //初始化系统上下文 
            createSystemContext();

            //创建系统服务管理
            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();
        } finally {
            traceEnd();  // InitBeforeStartServices
        }

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

createSystemContext

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

startBootstrapServices

private void startBootstrapServices() {
    //阻塞等待与installd建立socket通道
    Installer installer = mSystemServiceManager.startService(Installer.class);

    //启动服务ActivityManagerService
    mActivityManagerService = mSystemServiceManager.startService(
            ActivityManagerService.Lifecycle.class).getService();
    mActivityManagerService.setSystemServiceManager(mSystemServiceManager);
    mActivityManagerService.setInstaller(installer);

    //启动服务PowerManagerService
    mPowerManagerService = mSystemServiceManager.startService(PowerManagerService.class);

    ......

    //启动服务PackageManagerService
    mPackageManagerService = PackageManagerService.main(mSystemContext, installer,
            mFactoryTestMode != FactoryTest.FACTORY_TEST_OFF, mOnlyCore);
    mFirstBoot = mPackageManagerService.isFirstBoot();
    mPackageManager = mSystemContext.getPackageManager();

    //启动服务UserManagerService,新建目录/data/user/
    ServiceManager.addService(Context.USER_SERVICE, UserManagerService.getInstance());

    AttributeCache.init(mSystemContext);

    //设置AMS
    mActivityManagerService.setSystemProcess();

    //启动传感器服务
    startSensorService();
}
复制代码

该方法所创建的服务:

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

startCoreServices

private void startCoreServices() {
    //启动服务BatteryService,用于统计电池电量,需要LightService.
    mSystemServiceManager.startService(BatteryService.class);

    //启动服务UsageStatsService,用于统计应用使用情况
    mSystemServiceManager.startService(UsageStatsService.class);
    mActivityManagerService.setUsageStatsManager(
            LocalServices.getService(UsageStatsManagerInternal.class));

    mPackageManagerService.getUsageStatsIfNoPackageUsageInfo();

    //启动服务WebViewUpdateService
    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);

      // 执行一系列服务的systemReady方法
      networkScoreF.systemReady();
      networkManagementF.systemReady();
      networkStatsF.systemReady();

      ......

      //执行一系列服务的systemRunning方法
      wallpaper.systemRunning();
      inputMethodManager.systemRunning(statusBarF);
      location.systemRunning();

    }
});
复制代码

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

比如 TelephonyRegistry

try {
    if (telephonyRegistryF != null) telephonyRegistryF.systemRunning();
    } catch (Throwable e) {
        reportWtf("Notifying TelephonyRegistry running", e);
    }

    public void systemRunning() {
        // Watch for interesting updates
        final IntentFilter filter = new IntentFilter();
        filter.addAction(Intent.ACTION_USER_SWITCHED);
        filter.addAction(Intent.ACTION_USER_REMOVED);
        filter.addAction(TelephonyIntents.ACTION_DEFAULT_SUBSCRIPTION_CHANGED);
        log("systemRunning register for intents");
        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{

    public void systemReady(final Runnable goingCallback) {
        ...//更新操作
        mSystemReady = true; //系统处于ready状态
        removeProcessLocked(proc, true, false, "system update done");//杀掉所有非persistent进程
        mProcessesReady = true;  //进程处于ready状态

        goingCallback.run(); //这里有可能启动进程

        addAppLocked(info, false, null); //启动所有的persistent进程
        mBooting = true;  //正在启动中
        startHomeActivityLocked(mCurrentUserId, "systemReady"); //启动桌面
        mStackSupervisor.resumeTopActivitiesLocked(); //恢复栈顶的Activity
    }
}
复制代码

参考博客 Android系统启动-SystemServer

猜你喜欢

转载自juejin.im/post/5c4d3331e51d4550f31746f4