Activity start process? Analysis of activity startup process based on api30

Time:2022-1-8

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 instrumentationexecStartActivityIn the method, there is such a sentence:

//Instrumentation class
    int result = ActivityTaskManager.getService().startActivity(...args);

Here, throughActivityTaskManager.getService()Get aIActivityTaskManagerObject. 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)startActivitymethod.

//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.executeMethod 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.
stayexecuteMethod is calledexecuteRequestMethod, which will process the request to start the activity and start a journey to start the activity (original code comments).
executeRequestMethod 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 frameTaskRecordYes. During the startup of an activity, the activity is represented by an activityrecord. Then, thestartActivityUncheckedMethod, and then the startactivityunchecked method will callstartActivityInnermethod.

staystartActivityInnerIn, the main thing is to handle the startup mode of activity, andActivityStackHandle 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 calledresumeFocusedStacksTopActivitiesmethod.

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,resumeFocusedStacksTopActivitiesThe 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.resumeTopActivityUncheckedLockedMethod 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, soresumeTopActivityUncheckedLockedThe activity to be started is restored. This method only makes some judgments, and finally calls.resumeTopActivityInnerLockedRealize specific functions.

stayresumeTopActivityInnerLockedIn 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, hereattachedToProcessFalse is returned. So let’s do it nextmStackSupervisor.startSpecificActivitymethod.

5. ActivityStackSupervisor

Mstacksupervisor isActivityStackSupervisorThe 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 activitystacksupervisorstartSpecificActivityMethod is called for an activity that has started a processrealStartActivityLockedMethod. 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 ATMsstartProcessAsyncMethod to start the process, which is another process).

realStartActivityLockedThe 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);

heremAtmServiceThe corresponding is activitytaskmanagerservice, namely ATMs; andgetLifecycleManagerThe corresponding class isClientLifecycleManager, through itsscheduleTransactionMethod to send the corresponding transaction to the app process.
hereobtainMethod 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. stayrealStartActivityLockedMethod, a transaction is established and submitted to lifecycle manager. The corresponding classes of livecyclemanager and transaction areClientLifecycleManagerandClientTransaction, 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 managerscheduleTransactionMethod and clienttransactionschedulemethod:

    // 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 calledmClientofscheduleTransactionmethod. This mclient is the end of the previous sectionobtainMethod.
That is, here, throughmClient.scheduleTransactionMethod, the system service process forwards the transaction to the app process.

3、 Go back to the app process

1. ApplicationThread / ActivityThread

As mentioned earliermClientThe corresponding class isActivityThread.ApplicationThread。 Activitythread can be understood as the main thread of an application (although it is not a thread)mainThe method is in this class and maintains the running state of the application through looperThis articleIt is analyzed in.

ApplicationThreadIs 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’sscheduleTransactionMethod actually calls the method with the same name as activitythread. The activitythread does not define this method itself, but inherits fromClientTransactionHandlerYes. 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);
    }

thereforescheduleTransactionMethod is actually an internal handler for activitythreadmHSent a value ofActivityThread.H.EXECUTE_TRANSACTIONAnd pass the transaction to the past.
The MH method is to hand over the transaction to themTransactionExecutorTo execute.

2. TransactionExecutor

mTransactionExecutorIt’s aTransactionExecutorThe object of type can be known by its name as a class specially used for transaction processing. Look at itexecutemethod:

    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 respectivelyexecutemethod; The other is to callcycleToPathMethod, which is used for the transition of the life cycle.
The callback and lifecycle state here are in the activitystacksupervisorrealStartActivityLockedThe processes created correspond toLaunchActivityItemandResumeActivityItem
Look at these two classesexecutemethod:

// 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 hereclientParameters andmTransactionHandlerIt is passed in when the transactionexecutor object is created. In fact, it corresponds to the application processActivityThreadObject.
In other words, in the end, the activitythread is called separatelyhandleLaunchActivityhandleStartActivityandhandleResumeActivitymethod.

3. ActivityThread

handleLaunchActivityThe core of is callingperformLaunchActivitymethod. Performlunchactivity generally does these things in turn:

  • Create an activity instance through reflectionInstrumentation.newActivityMethod implementation;
  • Through activity Attach method to instantiate the window object;
  • Calling activityonCreateCallback;

stayhandleStartActivityMethod, the corresponding activity is called mainly through instrumentationonStartAnd onrestoreinstancestate callback, and set the state toON_START

Similar to handlelaunchactivity,handleResumeActivityIs calledperformResumeActivitymethod. They generally do the following in turn:

  • If necessary, call the onnewintent and onactivityresult callbacks of the activity to be resumed;
  • Calling activityperformResumeMethod is calledonResumeCallback;

4、 Illustration

Click to view the original image

Activity start process? Analysis of activity startup process based on api30

Activity starts the process png

Recommended Today

The whole tutorial of docker installation and use, installation / complete command / dockerfile image production / docker container arrangement and one click installation of nginx + redis + MySQL / visualizer portal (version 2022)

官网: https://docs.docker.com/ 官网: https://www.docker.com/ docker 镜像市场: https://hub.docker.com/ 一、docker 说明 1.1、docker 核心 1、Docker 是一个开源的应用容器引擎,基于 Go 语言 并遵从 Apache2.0 协议开源,Docker 是一个 CS 架构软件。 2、Docker 是一个虚拟化轻量级linux服务器,可以解决我们在开发环境中运行配置问题 3.、Docker的主要目标是‘build ,ship and run any app,anywhere’,一次封装,到处运行 4、容器是完全使用沙箱机制,相互之间不会有任何接口(类似 iPhone 的 app),更重要的是容器性能开销极低。 1.2、docker 版本问题 .Docker 从 17.03 版本之后分为 CE(Community Edition: 社区版) 和 EE(Enterprise Edition: 企业版),我们用社区版就可以了。 1.3、docker 架构( 3大核心) · 1、Images 镜像 (等于软件) · 2、Registry […]