Zygote and SystemServer are based on Android28, Android10 source code

Click launch’s logo flow

Let’s start with the conclusion and follow it down to the code

  1. Launcher is an application that calls startActivity() with binder to initiate startActivity requests to AMS across processes
  2. When AMS receives this request, it checks to see if the process exists. If it does not, AMS sends a request to Zygote through the Socket to create the process
  3. After the process is created, use reflection to create an ActivityThread and execute the main() method of the ActivityThread. The main() method sends AMS a request for attachApplication(ApplicationThread), which is a binder mechanism. So that AMS can call the method of this app
  4. AMS call ApplicationThread bindApplication command, when ApplicationThread after receiving this command, Send a sendMessage(H.bin_application, data) to H (Handler);
  5. H receives the message and processes it, creating ContextImle, Instrumentation, and Application. Instrumentation then calls the onCreate method of Application,
  6. ActivityThread handleBindApplication, walk on the AMS attachApplicationLocked method, it is really open up the Activity
  7. AMS will send an EXECUTE_TRANSACTION to each ActivityThread, which used to have a message for each call. After 8.0, AMS will call handleLaunchActivity. The next step is to initialize the Activity and walk through the Activity lifecycle

We’ll talk about Instrumentation

Click the Launcher

Launcher is also an application, a system application. When you start up, the PMS will record all the information about the installation, and then you can use this to know what applications are installed and the information about the application.

// Launcher click the logo
Launcher.startActivity()

// Then execute the familiar code, startActivity
Activity.startActivity()

Activity.startActivityForResult()

// Go to Instrumentation, this class is a hook, equivalent to the management of activities, are through this class, this time will
// The IApplicationThread is the argument that allows AMS to communicate to the App. Specifically, the IApplicationThread is the page Launcher.
Instrumentation.execStartActivity()

// IActivityManager is the AMS proxy in our app, which is equivalent to calling the AMS startActivity method
// It also returns an int, whether it succeeded. Exceptions such as whether they are registered in the manifest file are determined by the return value
ActivityManager.getService().startActivity() 
IActivityManager.startActivity()
Copy the code

Let’s go to the AMS startActivity method

/ / call the ActivityTaskManagerService method in AMS
ActivityManagerService.startActivity()

/ / ActivityTaskManagerService android10 after class, this class is to manage the Activity in the future
ActivityTaskManagerService.startActivity()

ActivityTaskManagerService.startActivityAsUser()
/ / ActivityTaskManagerService method. Activitystarter.execute () is called
// Note that mrequest. mayWait is set to true
int startActivityAsUser(IApplicationThread caller, String callingPackage,
        Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
        int startFlags, ProfilerInfo profilerInfo, Bundle bOptions, int userId,
        boolean validateIncomingUser) {
    enforceNotIsolatedCaller("startActivityAsUser");

    userId = getActivityStartController().checkTargetUser(userId, validateIncomingUser,
            Binder.getCallingPid(), Binder.getCallingUid(), "startActivityAsUser");
    return getActivityStartController().obtainStarter(intent, "startActivityAsUser")
            .setCaller(caller)
            .setCallingPackage(callingPackage)
            .setResolvedType(resolvedType)
            .setResultTo(resultTo)
            .setResultWho(resultWho)
            .setRequestCode(requestCode)
            .setStartFlags(startFlags)
            .setProfilerInfo(profilerInfo)
            .setActivityOptions(bOptions)
            // Note that mrequest. mayWait is set to true
            .setMayWait(userId)
            .execute();

    }
    

ActivityStarter.execute()
// Continue calling the method in ActivityStarter, where an ActivityRecord object is created to record the Activity
// At the same time
ActivityStarter.startActivityMayWait()
ActivityStarter.startActivity()
// Handle the startup mode and rollback and TaskRecord situations
ActivityStarter.startActivityUnchecked()
// Create ActivityStack for ActivityRecord
ActivityStarter.setTaskFromReuseOrCreateNewTask()

// Omit the code call
// Set the current resume Activity to onPause()
Activity.startPausingLocked()
    mService.getLifecycleManager().scheduleTransaction(prev.app.getThread(),
                        prev.appToken, PauseActivityItem.obtain(prev.finishing, userLeaving,
                                prev.configChangeFlags, pauseImmediately));

// This class is used to set the Activity lifecycle. The parameter passed here is PauseActivityItem
ClientLifecycleManager.scheduleTransaction()

ClientTransaction.schedule()

// execute to the method in ApplicationThread
IApplicationThread.scheduleTransaction

// The scheduleTransaction of ActivityThread is finally called
ApplicationThread.scheduleTransaction()
ActivityThread.this.scheduleTransaction(transaction);
	 sendMessage(ActivityThread.H.EXECUTE_TRANSACTION, transaction);
     
// The pause is executed when H (Handler receives the message)
TransactionExecutor.execute(transaction)
PostExecute () of PauseActivityItem is executed after onPause of the Activity.
TransactionExecutor.executeCallbacks()



// ClientTransactionHandler ON_PAUSE when TransactionExecutor (ClientTransactionHandler ClientTransactionHandler) is created
// ActivityThread inherits ClientTransactionHandler
// When TransactionExecutor is created
// Member variables of ActivityThread
private final TransactionExecutor mTransactionExecutor = new TransactionExecutor(this);

// Then go to the handlePauseActivity method of ActivityThread
ActivityThread.handlePauseActivity()

/ / in this asked whether to save the current state Namely callActivityOnSaveInstanceState
ActivityThread.performPauseActivity(r, finished, reason, pendingActions);
ActivityThread.performPauseActivityIfNeeded();

// Call the Activity lifecycle with Instrumentation
Instrumentation.callActivityOnPause
Activity.performPause()
Activity.onPause();

// When the process is complete, go to the PauseActivityItem abovePauseActivityItem.postExecute() ActivityTaskManager.getService().activityPaused(token); ActivityTaskManagerService.. activityPaused()ActivityTask is then called
ActivityStack.activityPausedLocked()
ActivityStack.completePauseLocked()

RootActivityContainer.resumeFocusedStacksTopActivities()
ActivityStack.resumeTopActivityUncheckedLocked()
ActivityStack.resumeTopActivityInnerLocked()

// This method determines if there is no process yet, and sends Handler to create a Message for the process
ActivityStackSupervisor.startSpecificActivityLocked()

// AMS creates the process
ActivityManagerService.startProcessLocked()
ProcessList.startProcessLocked()
// Check whether the system process is a user process
ProcessList.startProcess()
Process.start()

ZygoteProcess.start()
ZygoteProcess.startViaZygote()
ZygoteProcess.zygoteSendArgsAndGetResult()

// This method sends a socket notifying Zygote to create a process
// zygoteWriter.write(msgStr);
// zygoteWriter.flush();
ZygoteProcess.attemptZygoteSendArgsAndGetResult()

// When the process is created, the ActivityThread class is reflected through the main method of the ActivityThread
ActivityThread.main()


// Call Attach from main(), create Instrumentation and ContextImpl inside, create Application
ActivityThread.attach(false, startSeq);
// Also enable the attachApplication command to be sent to ActivityManagerService to transfer ApplicationThread
// we can have AMS call our method
ActivityManagerService.attachApplication(mAppThread,startSeq)
// In this method bindApplication of ApplicationThread is called
ActivityManagerService.attachApplicationLocked()

// sendMessage(h.bin_application, data);
ApplicationThread.bindApplication()

// In this
ActivityThread.handleBindApplication()
// Execute Application's onCreate method
Instrumentation.callApplicationOnCreate(app)

// After the creation process is complete, continue with the code inside
ActivityManagerService.attachApplicationLocked()

ActivityTaskManagerInternal.attachApplication()
ActivityTaskManagerService.attachApplication()
RootActivityContainer.attachApplication(wpc)

/ / this method in startSpecificActivityLocked is watching process whether there is seen
Call the following method if the process exists, or start the Activity if the process does not exist
// When the process is created, the method comes back
ActivityStackSupervisor.realStartActivityLocked()
// Create ClientTransaction and set to LaunchActivityItem
// ClientLifecycleManager then executes the LaunchActivityItem
// The rest of the process is similar to the PauseItem.

Copy the code

Start the ActivityManagerService

Linux init process, parsing init.rc, start Zygote process, Zygote initialization, start SystemServer process, create a number of important Services in the Android system. This is where the ActivityManagerService is created in the code startBootstrapServices method in SystemServer, Really created in ActivityManagerService. Lifecycle inner classes, call the ActivityManagerService construction method, and the start () method is called, When ActivityManagerService has been started, notify or start some system service or application, such as


/ / android ActivityTaskManagerService introduced 10 class, used to manage the Activity to start the process
 ActivityTaskManagerService atm = mSystemServiceManager.startService(
           ActivityTaskManagerService.Lifecycle.class).getService();
   mActivityManagerService = ActivityManagerService.Lifecycle.startService(
           mSystemServiceManager, atm);
   mActivityManagerService.setSystemServiceManager(mSystemServiceManager);
   mActivityManagerService.setInstaller(installer);
Copy the code
public static final class Lifecycle extends SystemService { private final ActivityManagerService mService; private static ActivityTaskManagerService sAtm; public Lifecycle(Context context) { super(context); mService = new ActivityManagerService(context, sAtm); } public static ActivityManagerService startService( SystemServiceManager ssm, ActivityTaskManagerService atm) { sAtm = atm; return ssm.startService(ActivityManagerService.Lifecycle.class).getService(); } @Override public void onStart() { mService.start(); } @Override public void onBootPhase(int phase) { mService.mBootPhase = phase; if (phase == PHASE_SYSTEM_SERVICES_READY) { mService.mBatteryStatsService.systemServicesReady(); mService.mServices.systemServicesReady(); } else if (phase == PHASE_ACTIVITY_MANAGER_READY) { mService.startBroadcastObservers(); } else if (phase == PHASE_THIRD_PARTY_APPS_CAN_START) { mService.mPackageWatchdog.onPackagesReady(); } } @Override public void onCleanupUser(int userId) { mService.mBatteryStatsService.onCleanupUser(userId); } public ActivityManagerService getService() { return mService; }}Copy the code

Then let’s look at the constructor of ActivityManagerService

public ActivityManagerService(Context systemContext, ActivityTaskManagerService atm) {
   LockGuard.installLock(this, LockGuard.INDEX_ACTIVITY);
   mInjector = new Injector();
   // Create the context
   mContext = systemContext;
   mFactoryTest = FactoryTest.getMode();
   // Assign the current ActivityThread
   mSystemThread = ActivityThread.currentActivityThread();
   mUiContext = mSystemThread.getSystemUiContext();

   Slog.i(TAG, "Memory class: " + ActivityManager.staticGetMemoryClass());
   
   // Create a Handler thread to process Hander messages
   mHandlerThread = new ServiceThread(TAG,
           THREAD_PRIORITY_FOREGROUND, false /*allowIo*/);
   mHandlerThread.start();
   mHandler = new MainHandler(mHandlerThread.getLooper());
   mUiHandler = mInjector.getUiHandler(this);

   mProcStartHandlerThread = new ServiceThread(TAG + ":procStart",
           THREAD_PRIORITY_FOREGROUND, false /* allowIo */);
   mProcStartHandlerThread.start();
   mProcStartHandler = new Handler(mProcStartHandlerThread.getLooper());

 // Manage the constants of AMS, such as manufacturer, version, etc
   mConstants = new ActivityManagerConstants(mContext, this, mHandler);
   final ActiveUids activeUids = new ActiveUids(this.true /* postChangesToAtm */);
   mProcessList.init(this, activeUids);
   mLowMemDetector = new LowMemDetector(this);
   // About the kill process
   mOomAdjuster = new OomAdjuster(this, mProcessList, activeUids);

   // The following two broadcast queues should be compatible with the Android broadcast implementation
   final BroadcastConstants foreConstants = new BroadcastConstants(
           Settings.Global.BROADCAST_FG_CONSTANTS);
   foreConstants.TIMEOUT = BROADCAST_FG_TIMEOUT;

   final BroadcastConstants backConstants = new BroadcastConstants(
           Settings.Global.BROADCAST_BG_CONSTANTS);
   backConstants.TIMEOUT = BROADCAST_BG_TIMEOUT;

   final BroadcastConstants offloadConstants = new BroadcastConstants(
           Settings.Global.BROADCAST_OFFLOAD_CONSTANTS);
   offloadConstants.TIMEOUT = BROADCAST_BG_TIMEOUT;
   // by default, no "slow" policy in this queue
   offloadConstants.SLOW_TIME = Integer.MAX_VALUE;

   mEnableOffloadQueue = SystemProperties.getBoolean(
           "persist.device_config.activity_manager_native_boot.offload_queue_enabled".false);

   mFgBroadcastQueue = new BroadcastQueue(this, mHandler,
           "foreground", foreConstants, false);
   mBgBroadcastQueue = new BroadcastQueue(this, mHandler,
           "background", backConstants, true);
   mOffloadBroadcastQueue = new BroadcastQueue(this, mHandler,
           "offload", offloadConstants, true);
   mBroadcastQueues[0] = mFgBroadcastQueue;
   mBroadcastQueues[1] = mBgBroadcastQueue;
   mBroadcastQueues[2] = mOffloadBroadcastQueue;

   // Initialize the ActiveServices object for the management ServiceRecord
   mServices = new ActiveServices(this);
   // Initialize the ProviderMap object that manages ProviderMap
   mProviderMap = new ProviderMap(this);
   
   mPackageWatchdog = PackageWatchdog.getInstance(mUiContext);
   mAppErrors = new AppErrors(mUiContext, this, mPackageWatchdog);

   final File systemDir = SystemServiceManager.ensureSystemDir();

   // About the power service
   mBatteryStatsService = new BatteryStatsService(systemContext, systemDir,
           BackgroundThread.get().getHandler());
   mBatteryStatsService.getActiveStatistics().readLocked();
   mBatteryStatsService.scheduleWriteToDisk();
   mOnBattery = DEBUG_POWER ? true
           : mBatteryStatsService.getActiveStatistics().getIsOnBattery();
   mBatteryStatsService.getActiveStatistics().setCallback(this);
   mOomAdjProfiler.batteryPowerChanged(mOnBattery);

   mProcessStats = new ProcessStatsService(this.new File(systemDir, "procstats"));

   mAppOpsService = mInjector.getAppOpsService(new File(systemDir, "appops.xml"), mHandler);

   mUgmInternal = LocalServices.getService(UriGrantsManagerInternal.class);

   mUserController = new UserController(this);

   mPendingIntentController = new PendingIntentController(
           mHandlerThread.getLooper(), mUserController);

   if (SystemProperties.getInt("sys.use_fifo_ui".0) != 0) {
       mUseFifoUiScheduling = true;
   }

   mTrackingAssociations = "1".equals(SystemProperties.get("debug.track-associations"));
   mIntentFirewall = new IntentFirewall(new IntentFirewallInterface(), mHandler);

   mActivityTaskManager = atm;
   // Initializes ActivityTaskManager to manage activities
   mActivityTaskManager.initialize(mIntentFirewall, mPendingIntentController,
           DisplayThread.get().getLooper());
  / / to omit
}
Copy the code

Conclusion start

reference

ActivityMnagerService-AMS startup process for Android 10.0 What process does an APP go through from startup to home page display? Android 10.0 Activity startup