SystemUI启动流程

首先我们来看一个时序图:
SystemUI启动流程_第1张图片

SystemServer前面的部分不再多说,有兴趣的朋友可以参考这篇博客《Android系统启动流程》

SystemServer 名为系统服务进程,负责启动 Android 系统的关键服务。SystemServer进程其实也是由Zygote进程fork出来的,并且执行其main方法,那么这里我们以android23的源码为例,看一下SystemServer的main方法的执行逻辑:SystemServer.main():

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

/**
     * The main entry point from zygote.
     */
    public static void main(String[] args) {
        new SystemServer().run();
    }

可以看到main()中生成了SystemServer对象并执行了run方法。
SystemServer.run():

private void run() {
		//***1. 时间判断
		
        // If a device's clock is before 1970 (before 0), a lot of
        // APIs crash dealing with negative numbers, notably
        // java.io.File#setLastModified, so instead we fake it and
        // hope that time from cell towers or NTP fixes it shortly.
        if (System.currentTimeMillis() < EARLIEST_SUPPORTED_TIME) {
            Slog.w(TAG, "System clock is before 1970; setting to 1970.");
            SystemClock.setCurrentTimeMillis(EARLIEST_SUPPORTED_TIME);
        }

       ....
}

首先判断系统当前时间,若当前时间小于1970年1月1日,则一些初始化操作可能会处所,所以当系统的当前时间小于1970年1月1日的时候,设置系统当前时间为该时间点。

private void run() {
		/***1. 时间判断 ***/
		...
		/***2. 设置系统的语言环境 ***/
		// Enable the sampling profiler.
        if (SamplingProfilerIntegration.isEnabled()) {
            SamplingProfilerIntegration.start();
            mProfilerSnapshotTimer = new Timer();
            mProfilerSnapshotTimer.schedule(new TimerTask() {
                @Override
                public void run() {
                    SamplingProfilerIntegration.writeSnapshot("system_server", null);
                }
            }, SNAPSHOT_INTERVAL, SNAPSHOT_INTERVAL);
        }
        ...
}

下面的主要是设置虚拟机运行内存,加载运行库,设置SystemServer的异步消息,具体的异步消息机制可参见《 android源码解析之(二)–>异步消息机制》

private void run() {
		/***1. 时间判断 ***/
		...
		/***2. 设置系统的语言环境 ***/

		/***3. 设置运行内存等 ***/
		 // 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);

        // Ensure binder calls into the system always run at foreground priority.
        BinderInternal.disableBackgroundScheduling(true);

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

        ///M:Add for low storage feature,to delete the reserver file.@{
        try {
            Runtime.getRuntime().exec("rm -r /data/piggybank");
        } catch (IOException e) {
            Slog.e(TAG, "system server init delete piggybank fail" + e);
        }
        ///@}

        // Check whether we failed to shut down last time we tried.
        // This call may not return.
        performPendingShutdown();
	 
		 /***4.创建Context ***/
		// Initialize the system context.
        createSystemContext();
		
		/***5.new 了一个SystemServiceManager ***/
        // Create the system service manager.
        mSystemServiceManager = new SystemServiceManager(mSystemContext);
        
        /***6.把创建的SystemServiceManager加入到LocalServices ***/
        LocalServices.addService(SystemServiceManager.class, mSystemServiceManager);
		 ...
 }
private void createSystemContext() {
        ActivityThread activityThread = ActivityThread.systemMain();
        mSystemContext = activityThread.getSystemContext();
        mSystemContext.setTheme(android.R.style.Theme_DeviceDefault_Light_DarkActionBar);
    }

可以看到在SystemServer进程中也存在着Context对象,并且是通过ActivityThread.systemMain方法创建context的,这一部分的逻辑以后会通过介绍Activity的启动流程来介绍,这里就不在扩展,这里我们只知道在SystemServer进程中也需要创建Context对象。

然后将SystemServiceManager对象保存SystemServer进程中的一个数据结构中。

继续分析:

private void run() {
		/***1. 时间判断 ***/
		...
		/***2. 设置系统的语言环境 ***/

		/***3. 设置运行内存等 ***/
		
		/***4.创建Context ***/
		
		/***5.new 了一个SystemServiceManager ***/
		
		/***6.把创建的SystemServiceManager加入到LocalServices ***/

		/***7.启动服务 ***/
		// Start services.
        try {
            startBootstrapServices();
            startCoreServices();
            startOtherServices();
        } catch (Throwable ex) {
            Slog.e("System", "******************************************");
            Slog.e("System", "************ Failure starting system services", ex);
            /// M: RecoveryManagerService  @{
            if (mRecoveryManagerService != null && ex instanceof RuntimeException) {
                mRecoveryManagerService.handleException((RuntimeException)ex, true);
            }
            /// @}
        }

里面主要涉及了是三个方法:
startBootstrapServices() 主要用于启动系统Boot级服务
startCoreServices() 主要用于启动系统核心的服务
startOtherServices() 主要用于启动一些非紧要或者是非需要及时启动的服务

下面我们重点介绍这三个启动服务的方法,包括启动那些系统服务已经如何启动系统服务等。

private void startBootstrapServices() {
        /*** 1. 获取installer ***/
        Installer installer = mSystemServiceManager.startService(Installer.class);

		/*** 2. 获取并配置 mActivityManagerService ***/
		
		/*** 这段代码主要是用于启动ActivityManagerService服务,并为其设置SystemServiceManager和Installer。ActivityManagerService是系统中一个非常重要的服务,Activity,service,Broadcast,contentProvider都需要通过其与系统交互。 ***/
		/*** Lifecycle可以看到其实ActivityManagerService的一个静态内部类,在其构造方法中会创建一个ActivityManagerService,通过刚刚对Installer服务的分析我们知道,SystemServiceManager的startService方法会调用服务的onStart()方法,而在Lifecycle类的定义中我们看到其onStart()方法直接调用了mService.start()方法,mService是Lifecycle类中对ActivityManagerService的引用***/
		
        // Activity manager runs the show.
        // Activity manager runs the show.
        mActivityManagerService = mSystemServiceManager.startService(
                ActivityManagerService.Lifecycle.class).getService();
        mActivityManagerService.setSystemServiceManager(mSystemServiceManager);
        mActivityManagerService.setInstaller(installer);
		
		/*** 3. 获取并配置 mPowerManagerService ***/

        // Power manager needs to be started early because other services need it.
        // Native daemons may be watching for it to be registered so it must be ready
        // to handle incoming binder calls immediately (including being able to verify
        // the permissions for those calls).
        mPowerManagerService = mSystemServiceManager.startService(PowerManagerService.class);

        // Now that the power manager has been started, let the activity manager
        // initialize power management features.
        mActivityManagerService.initPowerManagement();
        
		/*** 4. 获取并配置 mDisplayManagerService 主要是手机显示方面的服务***/
		
		// Display manager is needed to provide display metrics before package manager
        // starts up.
        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);

        // Only run "core" apps if we're encrypting the device.
        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;
        }

        /// M: RecoveryManagerService  @{
        boolean disabled = "0".equals(SystemProperties.get("ro.mtk_antibricking_level"));
        if (!disabled) {
            try {
                Slog.i(TAG, "Recovery Manager");
                mRecoveryManagerService = new RecoveryManagerService(mSystemContext);
                if (mRecoveryManagerService != null) {
                    ServiceManager.addService(Context.RECOVERY_SERVICE, mRecoveryManagerService.asBinder());
                    mRecoveryManagerService.startBootMonitor();
                }
            } catch (Throwable e) {
                reportWtf("Failure starting Recovery Manager", e);
            }
        }
        /// @}

		/*** 5. 开启PackageManagerService包管理服务  ***/
		
		/***该服务也是android系统中一个比较重要的服务,包括多apk文件的安装,解析,删除,卸载等等操作。***/
		/***PackageManagerService服务的启动方式与其他服务的启动方式有一些区别,直接调用了PackageManagerService的静态main方法,在静态方法里面也是直接使用new的方式创建了一个PackageManagerService对象,并在其构造方法中初始化相关变量。***/
		/*** 最后调用了ServiceManager.addService方法,主要是通过Binder机制与JNI层交互,这里不再扩展 ***/
        // Start the package manager.
        Slog.i(TAG, "Package Manager");
        mPackageManagerService = PackageManagerService.main(mSystemContext, installer,
        mFactoryTestMode != FactoryTest.FACTORY_TEST_OFF, mOnlyCore);
        mFirstBoot = mPackageManagerService.isFirstBoot();
        mPackageManager = mSystemContext.getPackageManager();
		
		/*** 6.然后启动UserManagerService和SensorService,至此startBootstrapServices方法执行完成。 ***/
        Slog.i(TAG, "User Service");
        ServiceManager.addService(Context.USER_SERVICE, UserManagerService.getInstance());

        // Initialize attribute cache used to cache resources from packages.
        AttributeCache.init(mSystemContext);

        // Set up the Application instance for the system process and get started.
        mActivityManagerService.setSystemProcess();
 }

我们看到里面的服务都是通过SystemServiceManager启动的,调用startService方法,文件在frameworks/base/services/core/java/com/android/server/SystemServiceManager.java
SystemServiceManager的startService但是其实就是一句话,调用了所需要调用的Service中的onStart()方法,代码这里就不贴出来了;

然后查看startCoreServices方法:

/**
     * Starts some essential services that are not tangled up in the bootstrap process.
     */
    private void startCoreServices() {
        // Manages LEDs and display backlight.
        mSystemServiceManager.startService(LightsService.class);

        // Tracks the battery level.  Requires LightService.
        mSystemServiceManager.startService(BatteryService.class);

        // Tracks application usage stats.
        mSystemServiceManager.startService(UsageStatsService.class);
        mActivityManagerService.setUsageStatsManager(
                LocalServices.getService(UsageStatsManagerInternal.class));
        // Update after UsageStatsService is available, needed before performBootDexOpt.
        mPackageManagerService.getUsageStatsIfNoPackageUsageInfo();

        // Tracks whether the updatable WebView is in a ready state and watches for update installs.
        mSystemServiceManager.startService(WebViewUpdateService.class);
    }

可以看到这里启动了BatteryService(电池相关服务),UsageStatsService,WebViewUpdateService服务等。

最后看一下startOtherServices方法,主要用于启动系统中其他的服务,代码很多,这里就不贴代码了,启动的流程和ActivityManagerService的流程类似,会调用服务的构造方法与onStart方法初始化变量。

/*** 1.读配置 ***/
/*** 比如是否禁用SystemUI ****/
...
boolean disableSystemUI = SystemProperties.getBoolean("config.disable_systemui", false);
...

/***2.初始化各种服务****/
...
Slog.i(TAG, "Init Watchdog");
final Watchdog watchdog = Watchdog.getInstance();
watchdog.init(context, mActivityManagerService);

Slog.i(TAG, "Input Manager");
inputManager = new InputManagerService(context);
...

/***3.开启各种服务****/
mSystemServiceManager.startService(NotificationManagerService.class);
notification = INotificationManager.Stub.asInterface(
		  ServiceManager.getService(Context.NOTIFICATION_SERVICE));
networkPolicy.bindNotificationManager(notification);

mSystemServiceManager.startService(DeviceStorageMonitorService.class);

/***调用各种服务的systemReady方法***/
 mActivityManagerService.systemReady(new Runnable() {
            @Override
            public void run() {
                Slog.i(TAG, "Making services ready");
				...
				try {//SystemUIService就是在这里启动的  [email protected]
                    startSystemUi(context);
                } catch (Throwable e) {
                    reportWtf("starting System UI", e);
                }
				...
			}
}

,到了这里我们知道SystemUIService是通过组件的方式启动的,这个组件则是在编译的时候清单文件配置的方式配置到了系统中,这个SystemUIService的源码在

frameworks/base/packages/SystemUI/src/com/android/systemui/SystemUIService.java

我们继续分析;
SystemUIService的onCreate方法里面调用了Application的startServicesIfNeeded方法,就是在SystemUIService启动的时候把所有SystemUI应用里面相关服务都重新启动启动一遍;
这些服务包括:

 com.android.systemui.keyguard.KeyguardViewMediator.class,
 com.android.systemui.recent.Recents.class,
 com.android.systemui.volume.VolumeUI.class,
 com.android.systemui.statusbar.SystemBars.class,
 com.android.systemui.usb.StorageNotification.class,
 com.android.systemui.power.PowerUI.class,
 com.android.systemui.media.RingtonePlayer.class

嗯,下一节我们来分析SystemUI内部启动流程;

你可能感兴趣的:(系统定制)