SystemServer啟動流程

zerozx發表於1970-01-01

在 zygote 啟動流程分析中,zygote最後會呼叫 SystemServer 的main函式,這篇就來介紹SystemServer的流程

時序圖

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

相關文章