Android init starts

Android Linux Zygote started

Android Java Zygote started

Android SystemServer startup

Continue the SystemServer startup analysis from the previous article.

The analysis was based on Android 10.0

run

The SystemServer run method is used to access SystemServer internal logic.

So let’s go straight to the run method

private void run() { try { traceBeginAndSlog("InitBeforeStartServices"); . . PrepareMainLooper (); // Create Looper looper.prepareMainLooper (); Looper.getMainLooper().setSlowLogThresholdMs( SLOW_DISPATCH_THRESHOLD_MS, SLOW_DELIVERY_THRESHOLD_MS); // Initialize native service system. loadLibrary(" android_Servers "); performPendingShutdown(); // createSystemContext createSystemContext(); // Create SystemServiceManager mSystemServiceManager = new SystemServiceManager(mSystemContext); mSystemServiceManager.setStartInfo(mRuntimeRestart, mRuntimeStartElapsedTime, mRuntimeStartUptime); / / added to the local LocalServices, so that subsequent access to the corresponding service object LocalServices. The addService (SystemServiceManager. Class, mSystemServiceManager); SystemServerInitThreadPool.get(); } finally { traceEnd(); // InitBeforeStartServices} // Start all 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(); } StrictMode.initVmDefaults(null); 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); }} // Start the loop and wait for the message looper.loop (); throw new RuntimeException("Main thread loop unexpectedly exited"); }Copy the code

The main things that SystemServer does in the run method are:

  1. Of the current threadLooper
  2. loadingnative servicesThe native libraryandroid_servers
  3. createSystemContextThrough theActivityThreadIn order to getSystemContext
  4. createSystemServiceManagerIs used to start the subsequent services
  5. Start services
  6. openLooperLoop, waiting for a message to arrive and execute

SystemContext

The SystemContext is created using ActivityThread

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

The resulting SystemContext is created by ContextImpl

public ContextImpl getSystemContext() { synchronized (this) { if (mSystemContext == null) { mSystemContext = ContextImpl.createSystemContext(this); } return mSystemContext; }}Copy the code

SystemServiceManager

It is the service manager for SystemServer and provides methods for starting services.

The main methods involved are

  1. startService: Creates the related service through reflection and invokes the corresponding serviceonStart()Method to start the service
  2. startBootPhase: Enable special startup nodes. Services execute different logic according to different startup nodes.

The nodes in the startup stage are as follows:

Public static final int PHASE_WAIT_FOR_DEFAULT_DISPLAY = 100; Public static final int PHASE_LOCK_SETTINGS_READY = 480; // This startup phase will invoke the core system services, such as PowerManager and PackageManager public static Final Int PHASE_SYSTEM_SERVICES_READY = 500; Public static final int PHASE_DEVICE_SPECIFIC_SERVICES_READY = 520; public static final int PHASE_DEVICE_SPECIFIC_SERVICES_READY = 520; Public static final int PHASE_ACTIVITY_MANAGER_READY = 550; public static final int PHASE_ACTIVITY_MANAGER_READY = 550; App public static final int PHASE_THIRD_PARTY_APPS_CAN_START = 600; Public static final int PHASE_BOOT_COMPLETED = 1000; public static final int PHASE_BOOT_COMPLETED = 1000;Copy the code

These startup phases are interspersed in various service startup sequences. The insertion of each startup node is accompanied by the service execution logic before the startup node.

So here the startup node is relative to the identity or dependency, that is, the subsequent startup phase depends on the characteristic processing logic of some of the previous services.

These startup node representations are distributed in these methods

traceBeginAndSlog("StartServices");
startBootstrapServices();
startCoreServices();
startOtherServices();
Copy the code

The node insertion time is

private void startBootstrapServices() { mSystemServiceManager.startBootPhase(SystemService.PHASE_WAIT_FOR_DEFAULT_DISPLAY); } private void startCoreServices() { ... } private void startOtherServices() { mSystemServiceManager.startBootPhase(SystemService.PHASE_LOCK_SETTINGS_READY); mSystemServiceManager.startBootPhase(SystemService.PHASE_SYSTEM_SERVICES_READY); mSystemServiceManager.startBootPhase(SystemService.PHASE_DEVICE_SPECIFIC_SERVICES_READY); mActivityManagerService.systemReady(() -> { mSystemServiceManager.startBootPhase( SystemService.PHASE_ACTIVITY_MANAGER_READY); mSystemServiceManager.startBootPhase( SystemService.PHASE_THIRD_PARTY_APPS_CAN_START); }}Copy the code

The processing logic for each phase of the response is in the onBootPhase() method of the corresponding service

public void onBootPhase(int phase) {
	...
}
Copy the code

Let’s take a look at what services are enabled in each phase.

startBootstrapServices

private void startBootstrapServices() { final String TAG_SYSTEM_CONFIG = "ReadingSystemConfig"; traceBeginAndSlog(TAG_SYSTEM_CONFIG); SystemServerInitThreadPool.get().submit(SystemConfig::getInstance, TAG_SYSTEM_CONFIG); traceEnd(); / / start the Installer Installer Installer. = mSystemServiceManager startService (Installer. Class); / / start DeviceIdentifiersPolicyService mSystemServiceManager. StartService (DeviceIdentifiersPolicyService. Class); / / start ActivityManagerService mActivityManagerService = mSystemServiceManager. StartService ( ActivityManagerService.Lifecycle.class).getService(); mActivityManagerService.setSystemServiceManager(mSystemServiceManager); mActivityManagerService.setInstaller(installer); / / start PowerManagerService mPowerManagerService = mSystemServiceManager. StartService (PowerManagerService. Class); / / initialize the PowerManager mActivityManagerService. InitPowerManagement (); / / start RecoverySystemService mSystemServiceManager. StartService (RecoverySystemService. Class); RescueParty.noteBoot(mSystemContext); / / start LightsService mSystemServiceManager. StartService (LightsService. Class); / / start SidekickService if (SystemProperties getBoolean (" config. Enable_sidekick_graphics ", false)) { mSystemServiceManager.startService(WEAR_SIDEKICK_SERVICE_CLASS); } / / start DisplayManagerService mDisplayManagerService = mSystemServiceManager. StartService (DisplayManagerService. Class); / / insert the startup phase node, perform the corresponding node logic mSystemServiceManager. StartBootPhase (SystemService. PHASE_WAIT_FOR_DEFAULT_DISPLAY); . . }Copy the code

Before starting the insertion of the startup node, also known as BootPhase 0, the services started are:

Installer
DeviceIdentifiersPolicyService
UriGrantsManagerService
ActivityManagerService
PowerManagerService
RecoverySystemService
LightsService
DisplayManagerService
Copy the code

Since the PackageManager startup requires DisplayManagerService information, set the BootPhase 100, Execute the onBootPhase method in DisplayManagerService to handle the logic of BootPhase 100

public void onBootPhase(int phase) { if (phase == PHASE_WAIT_FOR_DEFAULT_DISPLAY) { synchronized (mSyncRoot) { long timeout = SystemClock.uptimeMillis() + mInjector.getDefaultDisplayDelayTimeout(); while (mLogicalDisplays.get(Display.DEFAULT_DISPLAY) == null || mVirtualDisplayAdapter == null) { long delay = timeout -  SystemClock.uptimeMillis(); if (delay <= 0) { throw new RuntimeException("Timeout waiting for default display " + "to be initialized. DefaultDisplay=" + mLogicalDisplays.get(Display.DEFAULT_DISPLAY) + ", mVirtualDisplayAdapter=" + mVirtualDisplayAdapter); } if (DEBUG) { Slog.d(TAG, "waitForDefaultDisplay: waiting, timeout=" + delay); } try { mSyncRoot.wait(delay); } catch (InterruptedException ex) { } } } } }Copy the code

Start the PackageManagerService and other services.

BootPhase 100 through BootPhase 480 will start a large number of services.

This includes initialized services, core services, and other services. StartBootstrapServices, startCoreServices, and startOtherServices respectively.

private void startBootstrapServices() { ... . // BootPhase 100 // Start PackageManagerService 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 UserManagerService, create/data/user/directory mSystemServiceManager. StartService (UserManagerService. LifeCycle. Class); / / set the AMS mActivityManagerService setSystemProcess (); / / start OverlayManagerService mSystemServiceManager. StartService (new OverlayManagerService (mSystemContext, installer)); / / start SensorPrivacyService, sensor mSystemServiceManager. StartService (new SensorPrivacyService (mSystemContext)); . }Copy the code

In the BootPhase 100 phase, startBootstrapServices starts the following services

PackageManagerService
UserManagerService
OverlayManagerService
SensorPrivacyService
Copy the code

Then enter startCoreServices

startCoreServices

Private void startCoreServices() {// Start BatterService. Need LightService mSystemServiceManager. StartService (BatteryService. Class); / / start UsageStatsService, statistical application usage mSystemServiceManager. StartService (UsageStatsService. Class); mActivityManagerService.setUsageStatsManager( LocalServices.getService(UsageStatsManagerInternal.class)); / / start WebViewUpdateService, Management WebView update the if (mPackageManager hasSystemFeature (PackageManager. FEATURE_WEBVIEW)) {mWebViewUpdateService = mSystemServiceManager.startService(WebViewUpdateService.class); } / / start CachedDeviceStateService, cache device status mSystemServiceManager. StartService (CachedDeviceStateService. Class); / / start BinderCallsStatsService, Record the time spent in the binder callback CPU mSystemServiceManager. StartService (BinderCallsStatsService. LifeCycle. Class); / / start LooperStatsService, Record using handler message time mSystemServiceManager. StartService (LooperStatsService. Lifecycle. Class); / / start RollbackManagerService, management apk rollback mSystemServiceManager. StartService (RollbackManagerService. Class); / / start BugreportManagerService, capture the bug report mSystemServiceManager. The startService (BugreportManagerService. Class); / / start GpuService, manage the GPU mSystemServiceManager. StartService (GpuService. Class); } // BootPhase 100 Startup service UsageStatsService WebViewUpdateService CachedDeviceStateService BinderCallsStatsService LooperStatsService RollbackManagerService BugreportManagerService GpuServiceCopy the code

These are the core services to launch; Continue to enter Star Tower Services

startOtherServices

private void startOtherServices() { final Context context = mSystemContext; / / get the Context try {ServiceManager. The addService (" sec_key_att_app_id_provider ", new KeyAttestationApplicationIdProviderService(context)); mSystemServiceManager.startService(KeyChainSystemService.class); ServiceManager.addService("scheduling_policy", new SchedulingPolicyService()); mSystemServiceManager.startService(TelecomLoaderService.class); telephonyRegistry = new TelephonyRegistry(context); ServiceManager.addService("telephony.registry", telephonyRegistry); mEntropyMixer = new EntropyMixer(context); mContentResolver = context.getContentResolver(); / / get ContentResolver mSystemServiceManager. StartService (ACCOUNT_SERVICE_CLASS); mSystemServiceManager.startService(CONTENT_SERVICE_CLASS); mActivityManagerService.installSystemProviders(); // Install the system Provider... mSystemServiceManager.startService(new AlarmManagerService(context)); // Alarm clock service... mActivityManagerService.setWindowManager(wm); // Set WindowManager... }... / / into safe mode if (safeMode) {mActivityManagerService. EnterSafeMode (); }... . // BootPhase 480 mSystemServiceManager.startBootPhase(SystemService.PHASE_LOCK_SETTINGS_READY); // BootPhase 500 mSystemServiceManager.startBootPhase(SystemService.PHASE_SYSTEM_SERVICES_READY); // BootPhase 520 mSystemServiceManager.startBootPhase(SystemService.PHASE_DEVICE_SPECIFIC_SERVICES_READY); try { wm.systemReady(); } catch (Throwable e) { reportWtf("making Window Manager Service ready", e); } if (safeMode) { mActivityManagerService.showSafeModeOverlay(); } / / update the Configuration to final Configuration config = wm.com puteNewConfiguration (DEFAULT_DISPLAY); DisplayMetrics metrics = new DisplayMetrics(); WindowManager w = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE); w.getDefaultDisplay().getMetrics(metrics); context.getResources().updateConfiguration(config, metrics); final Theme systemTheme = context.getTheme(); if (systemTheme.getChangingConfigurations() ! = 0) { systemTheme.rebase(); } try { mPowerManagerService.systemReady(mActivityManagerService.getAppOpsService()); } catch (Throwable e) { reportWtf("making Power Manager Service ready", e); } mSystemServiceManager.startService(PermissionPolicyService.class); mPackageManagerService.systemReady(); . mActivityManagerService.systemReady(() -> { // BootPhase 550 mSystemServiceManager.startBootPhase( SystemService.PHASE_ACTIVITY_MANAGER_READY); try { mActivityManagerService.startObservingNativeCrashes(); } catch (Throwable e) { reportWtf("observing native crashes", e); } traceBeginAndSlog("MakeConnectivityServiceReady"); try { if (connectivityF ! = null) { connectivityF.systemReady(); } } catch (Throwable e) { reportWtf("making Connectivity Service ready", e); }... // BootPhase 600 mSystemServiceManager.startBootPhase( SystemService.PHASE_THIRD_PARTY_APPS_CAN_START); try { if (locationF ! = null) { locationF.systemRunning(); } } catch (Throwable e) { reportWtf("Notifying Location Service running", e); } try { if (countryDetectorF ! = null) { countryDetectorF.systemRunning(); } } catch (Throwable e) { reportWtf("Notifying CountryDetectorService running", e); }... }, BOOT_TIMINGS_TRACE_LOG); }Copy the code

A large number of services are started in Startup Services, more than 80 in total, which I will not list here.

I’ve summed it up with the BootPhase here to see what services are started by each startup node and the operations of the corresponding services.

// BootPhase 100 KeyAttestationApplicationIdProviderService (startOtherServices) KeyChainSystemService SchedulingPolicyService TelecomLoaderService TelephonyRegistry EntropyMixer AccountManagerService ContentService ... AppBindingService BootPhase 480 BootPhase 500 PermissionPolicyService DeviceSpecificServices(containing a large number of Services) // Ready Power, Package and Diaplay service PowerManagerService. SystemReady PackageManagerService. SystemReady DisplayManagerService. SystemReady BootPhase 520 BootPhase 550 CarServiceHelperService startSystemUi / / ready Network, Ip, Connectivity service NetworkManagementService. SystemReady NetworkPolicyManagerService. SystemReady IpSecService.systemReady NetworkStatsService.systemReady ConnectivityService.systemReady NetworkPolicyService.systemReady BootPhase 600 NetworkStack // Operation Location, CountryDetection, Network, Input, Telephoney, Media, Mms, Incident services LocationService. SystemRunning CountryDetectionService.systemRunning NetworkTimeUpdateService.systemRunning InputManagerService.systemRunning TelephonyRegistry.systemRunning MediaRouterService.systemRunning MmsServiceBroker.systemRunning IncidentDaemon.systemRunningCopy the code

Finally, after the above series of service invocations, the finishBooting method of ActivityManagerService is called to perform the last BootPhase 1000.

final void finishBooting() { ... // BootPhase 1000 mSystemServiceManager.startBootPhase(SystemService.PHASE_BOOT_COMPLETED); . }Copy the code

At this point, the system service startup phase is complete, and the system_server process enters the looper.loop () state after starting, waiting for the Message in the Message queue MessageQueue, and then executing the corresponding Message.

BootPhase 0 to BootPhase 1000 is used to start different services. Different logic is implemented for the corresponding services according to different BootPhase. The subsequent Service startup logic and execution logic may depend on the previous Service, and the dependency management between them is established through BootPhase.

Wechat public number: Android supply station, focusing on Android advanced, algorithm and interview analysis, as well as irregular benefits

recommended

Android_startup: Provides a simpler and more efficient way to initialize components at application startup. Developers can use Android-startup to simplify the startup sequence and explicitly set the dependency between the initialization order and the components. Meanwhile, Android-startup supports synchronous and asynchronous wait, and ensures the initialization sequence of internal dependent components by means of directed acyclic topology sorting.

AwesomeGithub: Based on Github client, pure exercise project, support componentized development, support account password and authentication login. Kotlin language for development, the project architecture is based on Jetpack&DataBinding MVVM; Popular open source technologies such as Arouter, Retrofit, Coroutine, Glide, Dagger and Hilt are used in the project.

Flutter_github: a cross-platform Github client based on Flutter, corresponding to AwesomeGithub.

Android-api-analysis: A comprehensive analysis of Knowledge points related to Android with detailed Demo to help readers quickly grasp and understand the main points explained.

Daily_algorithm: advanced summary of algorithms, from shallow to deep, welcome to join us.