Previously:API 29 version activity startup process analysis
This article will analyze the startup process of activity according to the source code of API 30 (Android 11).
I personally divide the activity startup process into three stages:
App process – [through binder] – > system process – [through binder] – > return to app process
The following is sorted out in order, mainly sorting out the general context, not a large number of source codes, but only key codes.
1、 App in process
The first stage is carried out in the user process, which is relatively simple.
1. Activity
Generally through activity Startactivity (intent) to start the activity. Through a series of processing and transmission, it will eventually come tostartActivityForResult(Intent, Int, Bundle)
method. Here, theInstrumentation.execStartActivity(Context, IBinder, IBinder, Activity, Intent, int, Bundle)
method.
2. Instrumentation
In instrumentationexecStartActivity
In the method, there is such a sentence:
//Instrumentation class
int result = ActivityTaskManager.getService().startActivity(...args);
Here, throughActivityTaskManager.getService()
Get aIActivityTaskManager
Object. Through its acquisition method:
//Activitytaskmanager class
public static IActivityTaskManager getService() {
return IActivityTaskManagerSingleton.get();
}
private static final Singleton<IActivityTaskManager> IActivityTaskManagerSingleton =
new Singleton<IActivityTaskManager>() {
@Override
protected IActivityTaskManager create() {
final IBinder b = ServiceManager.getService(Context.ACTIVITY_TASK_SERVICE);
return IActivityTaskManager.Stub.asInterface(b);
}
};
As you can see, this is a binder object used to call system services across processes.
Returning to the code of instrumentation, here is a cross process call to the system service activity task manager service (ATMS)startActivity
method.
//Instrumentation class
int result = ActivityTaskManager.getService().startActivity(...args);
2、 System in progress
1. ActivityTaskManagerService(ATMS)
Activitytaskmanagerservice is a system service used to manage activities and their container classes, such as task / stack / display. ATMs is a class added in the new version to share some responsibilities of AMS.
In activitytaskmanagerservice, startactivity – > startactivityasuser will be called successively.
In the startActivityAsUser method, a ActivityStarter object is obtained through the Starter pool, and then some parameters are set.execute
Method to start the activity.
public final int startActivity(...args) {
return startActivityAsUser(...args);
}
private int startActivityAsUser(...args) {
return getActivityStartController().obtainStarter(intent, "startActivityAsUser")
.setCaller(caller)
.setCallingPackage(callingPackage)
....
.execute();
}
2. ActivityStarter
As the name suggests, the activitystarter class is used to start an activity.
stayexecute
Method is calledexecuteRequest
Method, which will process the request to start the activity and start a journey to start the activity (original code comments).
executeRequest
Method will perform a preliminary check and confirm the permission, and assemble the corresponding activity hereActivityRecord
, which contains all the information of the corresponding activity and is stored in the task stack frameTaskRecord
Yes. During the startup of an activity, the activity is represented by an activityrecord. Then, thestartActivityUnchecked
Method, and then the startactivityunchecked method will callstartActivityInner
method.
staystartActivityInner
In, the main thing is to handle the startup mode of activity, andActivityStack
Handle the related matters of the corresponding activity in the task stack, including but not limited to adding the corresponding activityrecord to the taskrecord and raising the corresponding activityrecord to the top of the stack.
Finally, the of rootwindowcontainer is calledresumeFocusedStacksTopActivities
method.
3. RootWindowContainer
Rootwindowcontainer is the root container of window container, which manages all window containers. It manages all windows and displays on the device.
seeing the name of a thing one thinks of its function,resumeFocusedStacksTopActivities
The activity at the top of the corresponding task stack will be restored. This method checks some visibility related properties and passes them on to the userActivityStack.resumeTopActivityUncheckedLocked
Method to continue the process.
4. ActivityStack
An activitystack contains several taskrecords, and each taskrecord contains several activityrecords. Each activityrecord corresponds to an activity. Here, taskrecord is equivalent to “task stack” in startup mode. According to different startup modes, different operations will be performed on taskrecord when starting activity.
Because the activityrecord of the corresponding activity has been added to the top of the stack before, soresumeTopActivityUncheckedLocked
The activity to be started is restored. This method only makes some judgments, and finally calls.resumeTopActivityInnerLocked
Realize specific functions.
stayresumeTopActivityInnerLocked
In the method, a series of judgments are made to ensure the visibility of the activity to be started, the switching animation of the scheduled activity, etc.
if (next.attachedToProcess()) {
...
} else {
...
mStackSupervisor.startSpecificActivity(next, true, true);
}
For activities that have not been started, since the corresponding activity has not been added to the application, hereattachedToProcess
False is returned. So let’s do it nextmStackSupervisor.startSpecificActivity
method.
5. ActivityStackSupervisor
Mstacksupervisor isActivityStackSupervisor
The main function of an object of type is to manage the activitystack. According to the comment, this class will be removed in the near future, although this comment has lasted for many versions.
In the of activitystacksupervisorstartSpecificActivity
Method is called for an activity that has started a processrealStartActivityLocked
Method. You can see from the name that this is the real start of the activity (if the process corresponding to the activity has not been started, it will pass ATMsstartProcessAsync
Method to start the process, which is another process).
realStartActivityLocked
The core code of the process is as follows:
final ClientTransaction clientTransaction = ClientTransaction.obtain(proc.getThread(), r.appToken);
clientTransaction.addCallback(LaunchActivityItem.obtain(...));
clientTransaction.setLifecycleStateRequest(ResumeActivityItem.obtain(...));
mService.getLifecycleManager().scheduleTransaction(clientTransaction);
heremAtmService
The corresponding is activitytaskmanagerservice, namely ATMs; andgetLifecycleManager
The corresponding class isClientLifecycleManager
, through itsscheduleTransaction
Method to send the corresponding transaction to the app process.
hereobtain
Method passed inproc.getThread()
That is to contact the binder object of the activity process to be started, and then cross process communication will be conducted between the system service process and the app process.
5. Clientllifecycle manager and transaction
In development, transaction is generally translated into “transaction”, indicating a task to be or in progress. stayrealStartActivityLocked
Method, a transaction is established and submitted to lifecycle manager. The corresponding classes of livecyclemanager and transaction areClientLifecycleManager
andClientTransaction
, as the name suggests, it is used to manage the life cycle of the client, that is, the app process.
Take a look at the client lifecycle managerscheduleTransaction
Method and clienttransactionschedule
method:
// ClientLifecycleManager.scheduleTransaction
void scheduleTransaction(ClientTransaction transaction) throws RemoteException {
transaction.schedule();
}
// ClientTransaction.schedule
public void schedule() throws RemoteException {
mClient.scheduleTransaction(this);
}
As you can see, the clienttransaction member is finally calledmClient
ofscheduleTransaction
method. This mclient is the end of the previous sectionobtain
Method.
That is, here, throughmClient.scheduleTransaction
Method, the system service process forwards the transaction to the app process.
3、 Go back to the app process
1. ApplicationThread / ActivityThread
As mentioned earliermClient
The corresponding class isActivityThread.ApplicationThread
。 Activitythread can be understood as the main thread of an application (although it is not a thread)main
The method is in this class and maintains the running state of the application through looperThis articleIt is analyzed in.
ApplicationThread
Is an internal class of activitythread, inherited fromIApplicationThread.Stub
, a binder class, is used for cross process communication between the current application process and the system process.
And applicationthread’sscheduleTransaction
Method actually calls the method with the same name as activitythread. The activitythread does not define this method itself, but inherits fromClientTransactionHandler
Yes. 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);
}
thereforescheduleTransaction
Method is actually an internal handler for activitythreadmH
Sent a value ofActivityThread.H.EXECUTE_TRANSACTION
And pass the transaction to the past.
The MH method is to hand over the transaction to themTransactionExecutor
To execute.
2. TransactionExecutor
mTransactionExecutor
It’s aTransactionExecutor
The object of type can be known by its name as a class specially used for transaction processing. Look at itexecute
method:
public void execute(ClientTransaction transaction) {
...
executeCallbacks(transaction);
executeLifecycleState(transaction);
mPendingActions.clear();
}
public void executeCallbacks(ClientTransaction transaction) {
final List<ClientTransactionItem> callbacks = transaction.getCallbacks();
...
final int size = callbacks.size();
for (int i = 0; i < size; ++i) {
final ClientTransactionItem item = callbacks.get(i);
item.execute(mTransactionHandler, token, mPendingActions);
}
}
private void executeLifecycleState(ClientTransaction transaction) {
final ActivityLifecycleItem lifecycleItem = transaction.getLifecycleStateRequest();
...
cycleToPath(r, lifecycleItem.getTargetState(), true, transaction);
lifecycleItem.execute(mTransactionHandler, token, mPendingActions);
}
The logic is very simple, that is, the transaction callback and lifecycle state are called respectivelyexecute
method; The other is to callcycleToPath
Method, which is used for the transition of the life cycle.
The callback and lifecycle state here are in the activitystacksupervisorrealStartActivityLocked
The processes created correspond toLaunchActivityItem
andResumeActivityItem
。
Look at these two classesexecute
method:
// 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) {
...
//The state here is on_ START
switch (state) {
...
case ON_START:
mTransactionHandler.handleStartActivity(r.token, mPendingActions);
}
}
And hereclient
Parameters andmTransactionHandler
It is passed in when the transactionexecutor object is created. In fact, it corresponds to the application processActivityThread
Object.
In other words, in the end, the activitythread is called separatelyhandleLaunchActivity
,handleStartActivity
andhandleResumeActivity
method.
3. ActivityThread
handleLaunchActivity
The core of is callingperformLaunchActivity
method. Performlunchactivity generally does these things in turn:
- Create an activity instance through reflection
Instrumentation.newActivity
Method implementation; - Through activity Attach method to instantiate the window object;
- Calling activityonCreateCallback;
stayhandleStartActivity
Method, the corresponding activity is called mainly through instrumentationonStartAnd onrestoreinstancestate callback, and set the state toON_START
;
Similar to handlelaunchactivity,handleResumeActivity
Is calledperformResumeActivity
method. They generally do the following in turn:
- If necessary, call the onnewintent and onactivityresult callbacks of the activity to be resumed;
- Calling activity
performResume
Method is calledonResumeCallback;
4、 Illustration
Click to view the original image
