Previous: API 29 version of the Activity start process analysis
This article will analyze the Activity startup process according to Api 30 (Android 11) source code.
I personally divide the Activity startup process into three stages: App in process (Binder) > System in process (Binder) > Back to App
The following in order to comb, mainly sort out the general context, not a large number of posted source code, only show the key code.
I. In the process of App
The first phase, which takes place in the user process, is simpler.
1. Activity
Activity. StartActivity (Intent) is typically used to start an Activity. Through a series of processing and passing, you end up with the startActivityForResult(Intent, Int, Bundle) method. Here, is called Instrumentation. ExecStartActivity (Context, IBinder IBinder, Activity, Intent, int, Bundle) method.
2. Instrumentation
In the Instrumentation execStartActivity method, there is such a sentence:
/ / Instrumentation class
intresult = ActivityTaskManager.getService().startActivity(... args);Copy the code
Here, through the ActivityTaskManager. GetService () to get a IActivityTaskManager object. By means of its acquisition:
/ / ActivityTaskManager class
public static IActivityTaskManager getService(a) {
return IActivityTaskManagerSingleton.get();
}
private static final Singleton<IActivityTaskManager> IActivityTaskManagerSingleton =
new Singleton<IActivityTaskManager>() {
@Override
protected IActivityTaskManager create(a) {
final IBinder b = ServiceManager.getService(Context.ACTIVITY_TASK_SERVICE);
returnIActivityTaskManager.Stub.asInterface(b); }};Copy the code
As you can see, this is a Binder object for invoking system services across processes.
Return to the Instrumentation code, this is across processes invoked the system service ActivityTaskManagerService startActivity (ATMS) method.
/ / Instrumentation class
intresult = ActivityTaskManager.getService().startActivity(... args);Copy the code
Second, the system process
1. ActivityTaskManagerService (ATMS)
ActivityTaskManagerService is the system service, the purpose is to manage the Activity and its container classes, such as Task/Stack/Display, etc. ATMS is a new version of the class that shares some of the responsibilities of AMS.
In ActivityTaskManagerService, will, in turn, call startActivity – > startActivityAsUser. In the startActivityAsUser method, you get an ActivityStarter object from the Starter pool, set some parameters, and then call the execute method to start the Activity.
public final int startActivity(... args) {
returnstartActivityAsUser(... args); }private int startActivityAsUser(... args) {
return getActivityStartController().obtainStarter(intent, "startActivityAsUser")
.setCaller(caller)
.setCallingPackage(callingPackage)
....
.execute();
}
Copy the code
2. ActivityStarter
As the name suggests, the ActivityStarter class is designed to start activities.
In the execute method, the executeRequest method is called, which processes the request to start the Activity and begins a journey to start the Activity (in the code comments).
The executeRequest method does a preliminary check and confirms permissions, and assembles an ActivityRecord for the Activity, which contains all information about the Activity and stores it in the Task stack frame TaskRecord. During the startup of an Activity, the Activity is represented by an ActivityRecord. The startActivityUnchecked method is then called, and the startActivityUnchecked method calls the startActivityInner method.
private int executeRequest(Request request) {...final ActivityRecord r = newActivityRecord(... args); mLastStartActivityResult = startActivityUnchecked(... args); }private int startActivityUnchecked(... args) {...try {
result = startActivityInner(r, sourceRecord, voiceSession, voiceInteractor,
startFlags, doResume, options, inTask, restrictedBgActivity, intentGrants);
} finally {}
return result;
}
Copy the code
One of the main things in startActivityInner is that it handles the mode in which the Activity starts and handles the Activity in the stack of tasks in ActivityStack. This includes, but is not limited to, adding the corresponding ActivityRecord to the TaskRecord and pushing the corresponding ActivityRecord to the top of the stack.
In the end, will be called RootWindowContainer resumeFocusedStacksTopActivities method.
3. RootWindowContainer
RootWindowContainer is the root of a WindowContainer. It manages all Windows containers and displays on the device.
As the name implies, resumeFocusedStacksTopActivities will restore corresponding task Activity with the top of the stack. This method will check some visibility related attributes, and then passed on to ActivityStack. ResumeTopActivityUncheckedLocked method to continue the process.
4. ActivityStack
An ActivityStack contains several TaskRecords, each of which contains several ActivityRecords, each of which corresponds to an Activity. In this case, a TaskRecord acts as a “task stack” in startup mode. Depending on the startup mode, different actions are performed on the TaskRecord when the Activity is started.
Because before has corresponding Activity ActivityRecord added to the stack, so resumeTopActivityUncheckedLocked recovery is to start the Activity. This method just do some judgment, finally call resumeTopActivityInnerLocked to achieve specific functions.
In resumeTopActivityInnerLocked method, made a series of judgment, make sure to start the Activity of visibility, due to the Activity of switching animation, etc.
if (next.attachedToProcess()) {
...
} else{... mStackSupervisor.startSpecificActivity(next,true.true);
}
Copy the code
AttachedToProcess returns false for an Activity that has not yet been started, since the corresponding Activity has not been added to the application. So the next execution mStackSupervisor startSpecificActivity method.
5. ActivityStackSupervisor
MStackSupervisor is an ActivityStackSupervisor. It manages ActivityStack. According to the comment, this class will be removed soon, although the comment has lasted for many versions.
In the startSpecificActivity method of ActivityStackSupervisor, realStartActivityLocked is called for activities that have already started the process, The name indicates that this is actually starting the Activity (if the corresponding Activity process has not already started, it is started using the startProcessAsync method of the ATMS, which is a different process).
The core code for the realStartActivityLocked process is as follows:
finalClientTransaction clientTransaction = ClientTransaction.obtain(proc.getThread(), r.appToken); clientTransaction.addCallback(LaunchActivityItem.obtain(...) ); clientTransaction.setLifecycleStateRequest(ResumeActivityItem.obtain(...) ); mService.getLifecycleManager().scheduleTransaction(clientTransaction);Copy the code
Here, the corresponding is ActivityTaskManagerService mAtmService, namely generally; The corresponding class of getLifecycleManager is ClientLifecycleManager, which sends the corresponding transaction to the App process through its scheduleTransaction method. In this case, proc.getThread(), passed in by the obtain method, is the Binder object that contacts the Activity process to start, which then communicates across the system service process and App process.
5. ClientLifecycleManager and Transaction
In development, transaction is generally translated as “transaction” and refers to an upcoming or ongoing task. In the realStartActivityLocked method, a transaction is established and submitted to LifecycleManager. The corresponding classes of LivecycleManager and Transaction are ClientLifecycleManager and ClientTransaction, respectively, which are used to manage the life cycle of the App process.
Take a look at ClientLifecycleManager’s scheduleTransaction method and ClientTransaction’s Schedule method:
// ClientLifecycleManager.scheduleTransaction
void scheduleTransaction(ClientTransaction transaction) throws RemoteException {
transaction.schedule();
}
// ClientTransaction.schedule
public void schedule(a) throws RemoteException {
mClient.scheduleTransaction(this);
}
Copy the code
As you can see, the scheduleTransaction method of ClientTransaction member mClient is finally called. This mClient is the Binder passed in from the obtain method at the end of the previous section. . That is to say, here, through mClient scheduleTransaction method, system service process forward transactions to the App.
Go back to the App process
1. ApplicationThread / ActivityThread
Front said to the corresponding class is ActivityThread mClient ApplicationThread. ActivityThread can be thought of as the main thread of an application (although it is not a thread), the main method of the application is in this class, and Looper is used to maintain the running state of the application, as analyzed in this article.
ApplicationThread is an internal class of ActivityThread, derived from iApplicationThread. Stub, which is a Binder class used for cross-process communication between current application processes and system processes. The scheduleTransaction method of the ApplicationThread actually calls the ActivityThread method of the same name. ActivityThread does not define this method itself, but inherits it from ClientTransactionHandler. Take a look at this method:
// ClientTransactionHandler
void scheduleTransaction(ClientTransaction transaction) {
transaction.preExecute(this);
sendMessage(ActivityThread.H.EXECUTE_TRANSACTION, transaction);
}
// ActivityThread
private void sendMessage(int what, Object obj) {
Message msg = Message.obtain();
msg.what = what;
msg.obj = obj;
mH.sendMessage(msg);
}
Copy the code
The scheduleTransaction method sends an activityThread.h.execute_TRANSACTION message to the internal ActivityThread HandlermH and passes the transaction. What mH does is hand this transaction over to the mTransactionExecutor to execute.
2. TransactionExecutor
MTransactionExecutor mTransactionExecutor is an object of type TransactionExecutor, which by its name is a class dedicated to handling transactions. Take a look at its execute method:
public void execute(ClientTransaction transaction) {... executeCallbacks(transaction); executeLifecycleState(transaction); mPendingActions.clear(); }public void executeCallbacks(ClientTransaction transaction) {
finalList<ClientTransactionItem> callbacks = transaction.getCallbacks(); .final int size = callbacks.size();
for (int i = 0; i < size; ++i) {
finalClientTransactionItem item = callbacks.get(i); item.execute(mTransactionHandler, token, mPendingActions); }}private void executeLifecycleState(ClientTransaction transaction) {
finalActivityLifecycleItem lifecycleItem = transaction.getLifecycleStateRequest(); . cycleToPath(r, lifecycleItem.getTargetState(),true, transaction);
lifecycleItem.execute(mTransactionHandler, token, mPendingActions);
}
Copy the code
The logic is simple: the transaction Callback and LifecycleState execute methods are called, respectively. The other is to call the cycleToPath method, which is used for lifecycle transitions. Callback and LifecycleState are created in the realStartActivityLocked process of ActivityStackSupervisor, The LaunchActivityItem and ResumeActivityItem correspond respectively. Take a look at the execute methods of these two classes:
// LaunchActivityItem
public void execute(... args) { client.handleLaunchActivity(... args); }// ResumeActivityItem
public void execute(... args) { client.handleResumeActivity(... args); }// cycleToPath
private void cycleToPath(... args) {... performLifecycleSequence(r, path, transaction); }private void performLifecycleSequence(... args) {...// 这里的state是ON_START
switch (state) {
...
caseON_START: mTransactionHandler.handleStartActivity(r.token, mPendingActions); }}Copy the code
The client parameters and mTransactionHandler are passed in when the TransactionExecutor object is created, which are actually ActivityThread objects for the application process. That is, you end up calling the ActivityThread’s handleLaunchActivity, handleStartActivity, and handleResumeActivity methods, respectively.
3. ActivityThread
At the heart of the handleLaunchActivity is the call to the performLaunchActivity method. PerformLaunchActivity does these things in general order:
- Create an instance of the Activity through reflection, which is done by
Instrumentation.newActivity
Method implementation; - Instantiate the Window object with the activity. attach method.
- Call the Activity’s onCreate callback;
In the handleStartActivity method, mainly through Instrumentation calls the corresponding Activity onStart and onRestoreInstanceState callbacks, and set the state to ON_START;
Like handleLaunchActivity, handleResumeActivity calls the performResumeActivity method. It does in general order:
- If necessary, call the onNewIntent and onActivityResult callback of the Activity to Resume.
- Call the Activity of
performResume
Method, which is calledonResumeThe callback.
Iv. Flow chart
Click to see the original image
The nuggets image seems to be compressed, if you can’t see the larger image, click here