First, the overall process

Init process > Zygote process > SystemServer process >Launcher start

  • Init: the root process of Linux. Android is based on Linux, so it can be counted as the first process of the entire Android operating system.
  • Zygote: the root process of the Android system. It can fork the SystemServer process and various application processes.
  • SystemService process: mainly in this process to start the system services, such as ActivityManagerService, PackageManagerService, WindowManagerService and so on;
  • Launcher: as a system desktop application, it displays a list of applications. Users can start an application by clicking the icon of the application

Init process

1. Startup timing:

After the Linux kernel completes the system Settings, it looks for the init.rc file in the system file and starts the init process.

2. Main functions:
  • Create and mount file directories
  • Initialize and start the properties service
  • Parse the init.rc configuration file and start the Zygote process

Zygote process

1. Call the main method in ZygoteInit in the Java layer via JNI
#ZygoteInit
public static void main(String argv[]) {
    ......
    try {
        ......

        if(startSystemServer) {// Start the SystemService process startSystemServer(abiList, socketName, zygoteServer); } (1) zygoteServer. RunSelectLoop (abiList); zygoteServer.closeServerSocket(); } catch (Zygote.MethodAndArgsCallercaller) {
        caller.run();
    } catch (Throwable ex) {
        Log.e(TAG, "System zygote died with exception", ex); zygoteServer.closeServerSocket(); throw ex; }}Copy the code

(1) Create a Socket and use the runSelectLoop function to wait for ActivityManagerService to request a new application process.

Question: When is ActivityManagerService created? When is ActivityManagerService requested?

2. Main functions:
  • Create a Java virtual machine and register JNI methods for the virtual machine
  • Enter Zygote’s Java framework layer by calling ZygoteInit’s main function from JNI.
  • Initialize Zygote classes, resource files, OpenGL, class libraries, etc.
  • Create a Server Socket
  • Fork The SystemServer process
  • The registerZygoteSocket function creates the server Socket and the runSelectLoop function waits for ActivityManagerService’s request to create a new application process.

The SystemServer process

Start a Binder thread pool
#ZygoteInitprivate static void handleSystemServerProcess( ZygoteConnection.Arguments parsedArgs) throws Zygote.MethodAndArgsCaller {... ClassLoader cl = null;if(systemServerClasspath ! = null) {/ / create a PathClassLoader cl = createPathClassLoader (systemServerClasspath, parsedArgs. TargetSdkVersion); Thread.currentThread().setContextClassLoader(cl); } / / call zygoteInit method zygoteInit. ZygoteInit (parsedArgs. TargetSdkVersion, parsedArgs remainingArgs, cl); } /* should never reach here */ } public static final void zygoteInit(int targetSdkVersion, String[] argv, ClassLoader classLoader) throws Zygote.MethodAndArgsCaller {if (RuntimeInit.DEBUG) {
        Slog.d(RuntimeInit.TAG, "RuntimeInit: Starting application from zygote");
    }

    Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "ZygoteInit"); RuntimeInit.redirectLogStreams(); RuntimeInit.commonInit(); / / start Binder thread pool ZygoteInit. NativeZygoteInit (); / / call the main method of SystemService RuntimeInit. ApplicationInit (targetSdkVersion, argv, this); }#app_main.cpp
virtual void onZygoteInit()
    {
        sp<ProcessState> proc = ProcessState::self();
        ALOGV("App process: starting thread pool.\n"); // Start Binder thread pool proc->startThreadPool(); / / 1}Copy the code

Problem: Binder thread pools

2. Start the system service

Call the run method in SystemServer’s main method

#SystemServer
private void run() {try {(1) mSystemServiceManager = new SystemServiceManager(mSystemContext); mSystemServiceManager.setRuntimeRestarted(mRuntimeRestart); LocalServices.addService(SystemServiceManager.class, mSystemServiceManager); // Prepare the thread poolfor init tasks that can be parallelized
        SystemServerInitThreadPool.get();
    } finally {
        traceEnd();  // InitBeforeStartServices
    }
    // Start services.
    try {
        traceBeginAndSlog("StartServices"); (2) startBootstrapServices (); (3) startCoreServices (); (4) startOtherServices (); SystemServerInitThreadPool.shutdown(); } catch (Throwable ex) { Slog.e("System"."* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *");
        Slog.e("System"."************ Failure starting system services", ex); throw ex; } finally { traceEnd(); }}Copy the code

(1) Create SystemServiceManager It creates, starts, and manages the life cycle of the system’s services (2) startBootstrapServices starts ActivityManagerService, PowerManagerService, and PackageManagerService with SystemServiceManager (3) startCoreServices Starts BatteryService, UsageStatsService and WebViewUpdateService (4) startOtherServices Starts CameraService, AlarmManagerService, and VrManagerService

Important services such as:

  • ActivityManagerService: Four components start, switch, etc
  • PackageManagerService: installs, resolves, and deletes apK
  • CameraService: camera-related services
  • AlarmManagerService: Specifies the scheduled management service
  • WindowManagerService: Window management service
  • NotificationManagerService: inform management services
  • InputManagerService: Enter the management service

System service startup:

# for example BatteryService
mSystemServiceManager.startService(BatteryService.class);

#SystemServiceManager   private final ArrayList<SystemService> mServices = new ArrayList<SystemService>(); Public void startService(@nonnull final SystemService service) {// add a SystemService to the mservice, A system service is registered. Mservices.add (service); // Start it. long time = System.currentTimeMillis(); Try {// Start Service service.onstart (); } catch (RuntimeException ex) { throw new RuntimeException("Failed to start service " + service.getClass().getName()
                + ": onStart threw an exception", ex);
    }
    warnIfTooLong(System.currentTimeMillis() - time, service, "onStart");
}
Copy the code

Obtaining system services:

  • Create system services and register them with ServerManager, which manages the services for Binder communication.
  • Registering with ServerManager assigns a Service name that other processes can then use to obtain Binder proxy objects to access services provided by the Service.
3. Main Functions:
  • Start a Binder thread pool for communicating with other processes.
  • Create SystemServiceManager and start various system services

Launcher

1. Startup process:

1. Start the Launcher with the systemReady function of ActivityManagerService

#SystemServer
private void startOtherServices() {... mActivityManagerService.systemReady(() -> { Slog.i(TAG,"Making services ready");
            traceBeginAndSlog("StartActivityManagerReadyPhase");
            mSystemServiceManager.startBootPhase(
                    SystemService.PHASE_ACTIVITY_MANAGER_READY);
}
Copy the code

SystemReady is called from ActivityManagerService in SystemServer

2. Call AMS

#ActivityManagerService
public void systemReady(final Runnable goingCallback, BootTimingsTraceLog traceLog) {
    traceLog.traceBegin("PhaseActivityManagerReady");
    synchronized(this) {
    ......
        mStackSupervisor.resumeFocusedStackTopActivityLocked();
        mUserController.sendUserSwitchBroadcastsLocked(-1, currentUserId);
        traceLog.traceEnd(); // ActivityManagerStartApps
        traceLog.traceEnd(); // PhaseActivityManagerReady
    }
}
Copy the code

Call the ActivityStackSupervisor resumeFocusedStackTopActivityLocked function — — > ActivityStack () is used to deal with the Activity stack resumeTopActivityUncheckedLocked – > the ActivityStack resumeTopActivityInnerLocked – > ActivityStackSupervisor resumehome packtask –> AMS startHomeActivityLocked–>

#AMSBoolean startHomeActivityLocked(int userId, String reason) {// Create an 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) { final String myReason = reason + ":" + userId + ":" + resolvedUserId; (1) mActivityStarter.startHomeActivityLocked(intent, aInfo, myReason); } } else { Slog.wtf(TAG, "No home screen found for " + intent, new Throwable()); } return true; }Copy the code

(1) the startHomeActivityLocked method of ActivityStarter is called

3. Proceed to ActivityStackSupervisor’s startHomeActivity method – > execute the subsequent startup logic for the Activity

2. Click the Item Launcher

The corresponding Activity Launcher displays a list of application ICONS, and saves the name of the application package and the name of the Activity class for each Item, so that when clicking on an application icon, we can launch our App according to the application package name and the name of the Activity to start.

#LauncherActivityprotected void onListItemClick(ListView l, View v, int position, long id) { Intent intent = intentForPosition(position);  startActivity(intent); }Copy the code

StartActivity is called to start the Activity