天天看点

Android系统启动流程完整分析(五)

(1)SystemServer启动

SystemServer的进程名实际上叫做“system_server”,通常简称为SS。

是系统中的服务驻留在其中,常见的比如WindowManagerServer(WmS)、ActivityManagerSystemService(AmS)、 PackageManagerServer(PmS)等,这些系统服务都是以一个线程的方式存在于SystemServer进程中。

//frameworks/base/services/java/com/android/server/SystemServer.java
	/**
	* The main entry point from zygote.
	*/
	public static void main(String[] args) {
		new SystemServer().run();
	}

	public SystemServer() {
        // Check for factory test mode.
        mFactoryTestMode = FactoryTest.getMode();
        // Remember if it's runtime restart(when sys.boot_completed is already set) or reboot
        mRuntimeRestart = "1".equals(SystemProperties.get("sys.boot_completed"));

        mRuntimeStartElapsedTime = SystemClock.elapsedRealtime();
        mRuntimeStartUptime = SystemClock.uptimeMillis();
    }
           

SystemServer是一个Java类,从main函数入口分析,主要调用run方法

//frameworks/base/services/java/com/android/server/SystemServer.java

private void run() {
    try {
        traceBeginAndSlog("InitBeforeStartServices");
        if (System.currentTimeMillis() < EARLIEST_SUPPORTED_TIME) {
            Slog.w(TAG, "System clock is before 1970; setting to 1970.");
            SystemClock.setCurrentTimeMillis(EARLIEST_SUPPORTED_TIME);
        }

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

        // 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();

        // The system server has to run all of the time, so it needs to be
        // as efficient as possible with its memory usage.
        VMRuntime.getRuntime().setTargetHeapUtilization(0.8f);

        // Some devices rely on runtime fingerprint generation, so make sure
        // we've defined it before booting further.
        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);

        // Ensure binder calls into the system always run at foreground priority.
        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);
        Looper.prepareMainLooper();

        // Initialize native services.
        System.loadLibrary("android_servers");

        // Check whether we failed to shut down last time we tried.
        // This call may not return.
        performPendingShutdown();

        // Initialize the system context.
        createSystemContext();

        // Create the system service manager.
        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
    }

    // Start services.
    try {
        traceBeginAndSlog("StartServices");
        startBootstrapServices();
        startCoreServices();
        startOtherServices();
        SystemServerInitThreadPool.shutdown();
    } catch (Throwable ex) {
        Slog.e("System", "******************************************");
        Slog.e("System", "************ Failure starting system services", ex);
        throw ex;
    } finally {
        traceEnd();
    }

    // For debug builds, log event loop stalls to dropbox for analysis.
    if (StrictMode.conditionallyEnableDebugLogging()) {
        Slog.i(TAG, "Enabled StrictMode for system server main thread.");
    }
    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);
        }
    }

    // Loop forever.
    Looper.loop();
    throw new RuntimeException("Main thread loop unexpectedly exited");
}
           

以上run方法的主要工作如下:

  • 调整时间,如果系统时间比1970还要早,调整到1970年
  • 设置语言
  • 调整虚拟机堆内存大小和内存利用率
  • 初始化Looper为mainLooper
  • 装载库libandroid_server.so
  • 初始化系统Context
  • 创建SystemServiceManager负责系统Service启动
  • 启动各种服务
  • 调用Looper.loop(),进入处理消息的循环

这里简单介绍几个功能:

(1)初始化系统Context,可用于后续创建SystemServiceManager等

private void createSystemContext() {
	ActivityThread activityThread = ActivityThread.systemMain();
	mSystemContext = activityThread.getSystemContext();
	mSystemContext.setTheme(DEFAULT_SYSTEM_THEME);

	final Context systemUiContext = activityThread.getSystemUiContext();
	systemUiContext.setTheme(DEFAULT_SYSTEM_THEME);
    }
           

(2)创建SystemServiceManager实例

// Create the system service manager.
	mSystemServiceManager = new SystemServiceManager(mSystemContext);
	mSystemServiceManager.setStartInfo(mRuntimeRestart,
	mRuntimeStartElapsedTime, mRuntimeStartUptime);
	LocalServices.addService(SystemServiceManager.class, mSystemServiceManager);
           

可用于后面通过SystemServiceManager.start方法启动各种服务。

(3)创建和启动服务有两种方式

//(1)通过SystemServiceManager.start
	mSystemServiceManager.startService(AlarmManagerService.class);
	mSystemServiceManager.startService(DisplayManagerService.class);
	mSystemServiceManager.startService(
    					ActivityManagerService.Lifecycle.class).getService();

//(2)通过ServiceManager.addService
	ServiceManager.addService("telephony.registry", telephonyRegistry);
	ServiceManager.addService(Context.SYSTEM_UPDATE_SERVICE,
                        new SystemUpdateManagerService(context));
    ServiceManager.addService(Context.MEDIA_ROUTER_SERVICE, mediaRouter);
           

(4)启动系统各种核心服务

traceBeginAndSlog("StartBatteryService");
    // Tracks the battery level.  Requires LightService.
    mSystemServiceManager.startService(BatteryService.class);
    traceEnd();

	traceBeginAndSlog("StartActivityManager");
	mActivityManagerService = mSystemServiceManager.startService(
				ActivityManagerService.Lifecycle.class).getService();
    mActivityManagerService.setSystemServiceManager(mSystemServiceManager);
	mActivityManagerService.setInstaller(installer);
	traceEnd();

	traceBeginAndSlog("StartPackageManagerService");
	mPackageManagerService = PackageManagerService.main(mSystemContext, installer,
	mFactoryTestMode != FactoryTest.FACTORY_TEST_OFF, mOnlyCore);
	mFirstBoot = mPackageManagerService.isFirstBoot();
	mPackageManager = mSystemContext.getPackageManager();
	traceEnd();

	traceBeginAndSlog("StartDisplayManager");
	mDisplayManagerService = mSystemServiceManager.startService(DisplayManagerService.class);
	traceEnd();
           
Android系统启动流程完整分析(五)

(2)AMS.systemReady

systemReady是在SystemServer.startOtherServices的最后被调用,主要的动作是标记和等待各个服务启动完成如等待PMS启动结束,紧接着启动SystemUI和启动Launcher。

//frameworks/base/services/core/java/com/android/server/am/ActivityManagerService.java

public void systemReady(final Runnable goingCallback, TimingsTraceLog traceLog) {

	//startSystemUi
	traceBeginAndSlog("StartSystemUI");
	try {
		startSystemUi(context, windowManagerF);
	} catch (Throwable e) {
		reportWtf("starting System UI", e);
	}
	traceEnd();

	//startHomeActivity
	traceLog.traceBegin("PhaseActivityManagerReady");
	startHomeActivityLocked(currentUserId, "systemReady");
	...
}
           

startSystemUi(SystemUI启动)

SystemUI是在AMS.systemReady时启动,主要是通过Intent启动包名为com.android.systemui组件名为SystemUIService的服务,然后通过调用WindowManager.onSystemUiStarted方法调用KeyguardService启动锁屏服务。SystemUI启动成功后表示系统的通知栏和导航栏已经初始化成功,接下来就是启动Launcher。

static final void startSystemUi(Context context, WindowManagerService windowManager) {
        Intent intent = new Intent();
        intent.setComponent(new ComponentName("com.android.systemui",
                    "com.android.systemui.SystemUIService"));
        intent.addFlags(Intent.FLAG_DEBUG_TRIAGED_MISSING);
        //Slog.d(TAG, "Starting service: " + intent);
        context.startServiceAsUser(intent, UserHandle.SYSTEM);
        windowManager.onSystemUiStarted();
    }
           

startHomeActivity(Launcher启动)

Launcher的启动是在AMS的最后,通过startHomeActivityLocked来启动Launcher的Activity并将其置于Activity栈顶,然后通过resumeFocusedStackTopActivityLocked将栈顶的Activity显示到界面上,launcher的启动就已经完成了。

Intent getHomeIntent() {
        Intent intent = new Intent(mTopAction, mTopData != null ? Uri.parse(mTopData) : null);
        intent.setComponent(mTopComponent);
        intent.addFlags(Intent.FLAG_DEBUG_TRIAGED_MISSING);
        if (mFactoryTest != FactoryTest.FACTORY_TEST_LOW_LEVEL) {
            intent.addCategory(Intent.CATEGORY_HOME);
        }
        return intent;
    }

boolean startHomeActivityLocked(int userId, String reason) {
        if (mFactoryTest == FactoryTest.FACTORY_TEST_LOW_LEVEL
                && mTopAction == null) {
            // We are running in factory test mode, but unable to find
            // the factory test app, so just sit around displaying the
            // error message and don't try to start anything.
            return false;
        }
        
        //获得HomeActivity的Intent
        Intent intent = getHomeIntent();
        ActivityInfo aInfo = resolveActivityInfo(intent, STOCK_PM_FLAGS, userId);
        if (aInfo != null) {
            intent.setComponent(new ComponentName(aInfo.applicationInfo.packageName, aInfo.name));
            // Don't do this if the home app is currently being
            // instrumented.
            aInfo = new ActivityInfo(aInfo);
            aInfo.applicationInfo = getAppInfoForUser(aInfo.applicationInfo, userId);
            ProcessRecord app = getProcessRecordLocked(aInfo.processName,
                    aInfo.applicationInfo.uid, true);
            if (app == null || app.instr == null) {
                intent.setFlags(intent.getFlags() | FLAG_ACTIVITY_NEW_TASK);
                final int resolvedUserId = UserHandle.getUserId(aInfo.applicationInfo.uid);
                // For ANR debugging to verify if the user activity is the one that actually
                // launched.
                final String myReason = reason + ":" + userId + ":" + resolvedUserId;
                
               	//用于启动HomeActivity
                mActivityStartController.startHomeActivity(intent, aInfo, myReason);
            }
        } else {
            Slog.wtf(TAG, "No home screen found for " + intent, new Throwable());
        }
        return true;
    }
           
Android系统启动流程完整分析(五)

接下来我们画一个简单的UML图来表示Android开机全过程。

Android系统启动流程完整分析(五)

具体后续的开机动画(bootanimation)如何启动和退出的,我们将在后面的博文中在进行详细分析。

继续阅读