# Zygote startup Analysis for Android 10

Following on from the last article, let’s take a look at SystemServer from this article.

The system_server process hosts the core services of the entire framework, Such as creating ActivityManagerService, PowerManagerService, DisplayManagerService, PackageManagerService, WindowManagerService, LauncherApps Service and more than 80 core system services. These services exist in the system_server process in different threads.

SystemServer source code path for/frameworks/base/services/Java/com/android/server/SystemServer. Java, we from the main method of this class began to look at:

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

The main method creates an instance of SystemServer and calls the run method. The SystemServer constructor is just some simple variable initialization, so we continue reading directly from the run method.

private void run() { try { ... / / to the main thread lopper android. OS. Process. The setThreadPriority (android. OS. Process. THREAD_PRIORITY_FOREGROUND); android.os.Process.setCanSelfBackground(false); Looper.prepareMainLooper(); Looper.getMainLooper().setSlowLogThresholdMs( SLOW_DISPATCH_THRESHOLD_MS, SLOW_DELIVERY_THRESHOLD_MS); // Load the libandroid_servers.so library system. loadLibrary("android_servers"); // Check if the last shutdown failed. This call may not return performPendingShutdown(); // Initialize the system context createSystemContext(); // create a SystemServiceManager --SystemServiceManager mSystemServiceManager = new SystemServiceManager(mSystemContext); mSystemServiceManager.setStartInfo(mRuntimeRestart, mRuntimeStartElapsedTime, mRuntimeStartUptime); // add mSystemServiceManager to the local service, what is LocalServices, what does it do, / / will open an article to explain LocalServices alone later. The addService (SystemServiceManager. Class, mSystemServiceManager); / / thread pool for task can be parallelized init SystemServerInitThreadPool. The get (); } finally { traceEnd(); // InitBeforeStartServices} // Start a series of services here try {traceBeginAndSlog("StartServices"); // Start the boot service startBootstrapServices(); // Start the core service startCoreServices(); // startOtherServices startOtherServices(); / / stop init thread pool SystemServerInitThreadPool. Shutdown (); } catch (Throwable ex) { Slog.e("System", "******************************************"); Slog.e("System", "************ Failure starting system services", ex); throw ex; } finally { traceEnd(); }... // Execute looper.loop (); throw new RuntimeException("Main thread loop unexpectedly exited"); }Copy the code

Let’s focus on a few key approaches:

createSystemContext

Private void createSystemContext() {// Create context information for the System_server process ActivityThread ActivityThread = ActivityThread.systemMain(); mSystemContext = activityThread.getSystemContext(); // Set the theme msystemContext. setTheme(DEFAULT_SYSTEM_THEME); / / get systemui Context information, and set the theme final Context systemUiContext = activityThread. GetSystemUiContext (); systemUiContext.setTheme(DEFAULT_SYSTEM_THEME); }Copy the code

In the call ActivityThread. SystemMain method, this process will create objects have ActivityThread, Instrumentation, ContextImpl, LoadedApk, Application.

Why create an Application object? As far as the current source code is concerned, the Application object has no actual role in the SystemServer process, and I can only guess that this is preparation for future extensions or legacy code in android version iterations.

startBootstrapServices

In this method, the key services of the system, which are the cornerstone of the system, are started. Because they have complex dependencies, Google initializes them together.

Private void startBootstrapServices() {// Start the watchdog as early as possible, so that we can crash the System Server and restart it if the early boot gets locked. final Watchdog watchdog = Watchdog.getInstance(); watchdog.start(); // Start the Installer Service, which communicates with the Installd process through binder. Be responsible for the apk installation related Installer Installer = mSystemServiceManager. StartService (Installer. Class); / / device identifier strategy service mSystemServiceManager. StartService (DeviceIdentifiersPolicyService. Class); / / authorized management uri mSystemServiceManager. StartService (UriGrantsManagerService. Lifecycle. Class); / / start ActivityTaskManagerService and ActivityManagerService ActivityTaskManagerService ATM = mSystemServiceManager.startService( ActivityTaskManagerService.Lifecycle.class).getService(); mActivityManagerService = ActivityManagerService.Lifecycle.startService( mSystemServiceManager, atm); mActivityManagerService.setSystemServiceManager(mSystemServiceManager); mActivityManagerService.setInstaller(installer); mWindowManagerGlobalLock = atm.getGlobalLock(); // The power manager needs to start early because other services need it. mPowerManagerService = mSystemServiceManager.startService(PowerManagerService.class); / / start thermal relief services, the purpose is on the phone began to overheat heat effectively alleviate mSystemServiceManager. StartService (ThermalManagerService. Class); // Now that the power manager has been started, let the activity manager // initialize power management features. mActivityManagerService.initPowerManagement(); // Start the system recovery service, responsible for coordinating the recovery related functions on the device. mSystemServiceManager.startService(RecoverySystemService.class); // Up to this point, the required service has been loaded in rescueparty. noteBoot(mSystemContext); / / management LED and the screen backlight, we need it to show mSystemServiceManager startService (LightsService. Class); // Manage display devices // Before package Manager starts, You need to start display Manager to provide display metrics mDisplayManagerService = mSystemServiceManager.startService(DisplayManagerService.class); // Only DisplayManagerService does PHASE_WAIT_FOR_DEFAULT_DISPLAY before initializing the package manager, First of all need to get a default display device mSystemServiceManager. StartBootPhase (SystemService. PHASE_WAIT_FOR_DEFAULT_DISPLAY); // Start package Manager.if (! mRuntimeRestart) { MetricsLogger.histogram(null, "boot_package_manager_init_start", (int) SystemClock.elapsedRealtime()); } try { Watchdog.getInstance().pauseWatchingCurrentThread("packagemanagermain"); mPackageManagerService = PackageManagerService.main(mSystemContext, installer, mFactoryTestMode ! = FactoryTest.FACTORY_TEST_OFF, mOnlyCore); } finally { Watchdog.getInstance().resumeWatchingCurrentThread("packagemanagermain"); } mFirstBoot = mPackageManagerService.isFirstBoot(); mPackageManager = mSystemContext.getPackageManager(); / / start UserManager Service mSystemServiceManager. StartService (UserManagerService. LifeCycle. Class); / / set up the application for the system process instance and start mActivityManagerService. SetSystemProcess (); // Use the ActivityManager instance to complete the watchdog setting and listen to restart watchdog.init(mSystemContext, mActivityManagerService); // DisplayManagerService needs to setup android.display scheduling related policies // since setSystemProcess() would have overridden policies due to setProcessGroup mDisplayManagerService.setupSchedulerPolicies(); / / is responsible for dynamic resource overlay mSystemServiceManager. StartService (new OverlayManagerService (mSystemContext, installer)); mSystemServiceManager.startService(new SensorPrivacyService(mSystemContext)); if (SystemProperties.getInt("persist.sys.displayinset.top", 0) > 0) { // DisplayManager needs the overlay immediately. mActivityManagerService.updateSystemUiContext(); LocalServices.getService(DisplayManagerInternal.class).onOverlayChanged(); } // The sensor service needs access to the package manager service, app OPS service, and permission service, so we start it after them. // Start sensor service in a separate thread. You should check completion before using it. mSensorServiceStart = SystemServerInitThreadPool.get().submit(() -> { TimingsTraceLog traceLog = new TimingsTraceLog( SYSTEM_SERVER_TIMING_ASYNC_TAG, Trace.TRACE_TAG_SYSTEM_SERVER); traceLog.traceBegin(START_SENSOR_SERVICE); startSensorService(); traceLog.traceEnd(); }, START_SENSOR_SERVICE); }Copy the code

To sum up, there are 15 boot services:

The service name describe
Installer Responsible for apK installation related work
DeviceIdentifiersPolicyService Device Id policy service
UriGrantsManagerService Uri Authorization Management
ActivityTaskManagerService Manage activities and their containers (Task, Stacks, displays,…) System services of
ActivityManagerService Manage Activity startup, scheduling, etc
PowerManagerService Responsible for coordinating power management functions on the equipment
ThermalManagerService Heat mitigation service
RecoverySystemService Coordinate recovery related functions on equipment
LightsService Manage LED and screen backlight
DisplayManagerService Managing display devices
PackageManagerService Mainly responsible for APK and JAR package management
UserManagerService Manage system services for users
OverlayManagerService Responsible for dynamic resource overlay work, please search Android RRO technology for details
SensorPrivacyService It has something to do with sensors
SensorPrivacySere Sensor service

startCoreServices

Private void startCoreServices() {// Track battery status and charge. Need LightService mSystemServiceManager. StartService (BatteryService. Class); / / tracking application using state mSystemServiceManager startService (UsageStatsService. Class); mActivityManagerService.setUsageStatsManager( LocalServices.getService(UsageStatsManagerInternal.class)); // Track whether updatable WebViews are ready and monitor the update installation. if (mPackageManager.hasSystemFeature(PackageManager.FEATURE_WEBVIEW)) { traceBeginAndSlog("StartWebViewUpdateService"); mWebViewUpdateService = mSystemServiceManager.startService(WebViewUpdateService.class); traceEnd(); } // Track and cache device status. mSystemServiceManager.startService(CachedDeviceStateService.class); / / tracking in the Binder in the call of CPU time spent mSystemServiceManager. StartService (BinderCallsStatsService. LifeCycle. Class); // Tracks the time it takes to process messages in handlers. mSystemServiceManager.startService(LooperStatsService.Lifecycle.class); / / management apk rollback mSystemServiceManager. StartService (RollbackManagerService. Class); / / for capturing bugreport, adb bugreport command. This service call is mSystemServiceManager startService (BugreportManagerService. Class); / / management of Gpu and Gpu driver service mSystemServiceManager startService (GpuService. Class); }Copy the code

To sum up, there are 9 core services:

The service name describe
BatteryService Track battery charge status and charge level
UsageStatsManagerInternal Track application usage status
WebViewUpdateService Track whether the updatable WebView is in a ready state and monitor the update installation.
CachedDeviceStateService Track and cache device status
BinderCallsStatsService Track CPU time spent in Binder calls
LooperStatsService Tracks the time spent processing messages in handlers.
RollbackManagerService Manage APK rollback
BugreportManagerService Used to capture bugreport
GpuService Manage gpus and Gpu drivers

startOtherServices

This method is responsible for starting the rest of the service, there are more than 70 in total, due to space reasons, I will not list one by one here, post a picture found from the Internet for a simple understanding of the line:

AMS systemReady is called at the end of startOtherServices. AMS systemReady has this statement:

 mAtmInternal.startHomeOnAllDisplays(currentUserId, "systemReady");
Copy the code

This statement launches the Intent as follows:

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; }Copy the code

Notice that Intent.category_HOME is missing, which means startHomeOnAllDisplays ends up launching the Android launcher app.

So far, we have made a brief introduction to the whole startup process, from pressing the power button to finally presenting the page launcher. This concludes the Android 10 startup analysis series. We’ll cover some details about the startup process in the future. Thanks for watching! !