欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  移动技术

android里面的Activity体系结构(2)_Activity lifecycle实现原理说明

程序员文章站 2022-03-03 21:57:25
1.简介ClientLifecycleManager是管理Activity lifecycle的,在ActivityTaskManagerService里面提供getLifecycleManager来获取此对象,其中mLifecycleManager是在ActivityTaskManagerService的构造方法里面初始化的本文基于Android 10的源代码来分析说明 ClientLifecycleManager getLifecycleManager() { return...

1.简介

ClientLifecycleManager是管理Activity lifecycle的,在ActivityTaskManagerService里面提供getLifecycleManager来获取此对象,其中mLifecycleManager是在ActivityTaskManagerService的构造方法里面初始化的

本文基于Android 10的源代码来分析说明

    ClientLifecycleManager getLifecycleManager() {
        return mLifecycleManager;
    }

整体类图如下:
android里面的Activity体系结构(2)_Activity lifecycle实现原理说明
相关类功能说明:

  1. ClientTransctionItem对象,一个回调消息,client端可以调用执行,实现了BaseClientRequest接口,在接口里面定义了3个方法,preExecute/execute/poseExecute方法
  2. ActivityLifecycleItem继承自ClientTransctionItem,主要的子类有DestoryActivityItem、PauseActivityItem、StopActivityItem、ResumeActivityItem
  3. ClientTransaction
    是一个容器,持有一系列可以发送给client的消息,包括有callback列表和一个目标状态lifecycle
    /** A list of individual callbacks to a client. */
    @UnsupportedAppUsage
    private List<ClientTransactionItem> mActivityCallbacks;

    /**
     * Final lifecycle state in which the client activity should be after the transaction is
     * executed.
     */
    private ActivityLifecycleItem mLifecycleStateRequest;

    /** Target client. */
    private IApplicationThread mClient;

    /** Target client activity. Might be null if the entire transaction is targeting an app. */
    private IBinder mActivityToken;
  1. TransactionExecutor 管理变换的执行,

1.ClientTransactionHandler用来调用ActivityThread的实现方法
2.execute 方法里面会executeCallbacks和executeLifecycleState,
3.cycleToPath和performLifecycleSequence这2个方法用来辅助完成executeLifecycleState,其中cycleToPath把要转换的状态都加到一个IntArray数组里面,performLifecycleSequence依次来执行IntArray里面的方法,调用ActivityThread的实现方法

2.ClientLifecycleManager管理状态变化流程

从ClientTransaction的定义来看,变换主要有2种:mActivityCallbacks和mLifecycleStateRequest。

  • startPausingLocked方法里面,只涉及到addCallback
  • realStartActivityLocked里面涉及到mLifecycleStateRequest

以下以startPausingLocked和realStartActivityLocked的调用流程来说明

2.1 startPausingLocked

在startPausingLocked方法里面,只执行了callback方法

mService.getLifecycleManager().scheduleTransaction(prev.app.getThread(),
        prev.appToken, PauseActivityItem.obtain(prev.finishing, userLeaving,
               prev.configChangeFlags, pauseImmediately));

scheduleTransaction 传入的callcack对象是PauseActivityItem,通过obtain方法来获取,传入了ActivityThread和ActivityRecord.Token对象。

在ClientLifecycleManager类里面,定义了4个scheduleTransaction方法重载方法,最终都调用到如下方法,

    void scheduleTransaction(ClientTransaction transaction) throws RemoteException {
        final IApplicationThread client = transaction.getClient();
        transaction.schedule();
    }

继续调用ClientTransaction 的schedule方法,mClient是ActivityThread对象,ActivityThread未定义此方法,在其父类ClientTransactionHandler定义了此方法,通过handler机制,最终调用到了

   //ClientTransaction.java
    public void schedule() throws RemoteException {
        mClient.scheduleTransaction(this);
    }
    
    //ClientTransactionHandler.java
    void scheduleTransaction(ClientTransaction transaction) {
        transaction.preExecute(this); // 调用callback的preExecute方法
        sendMessage(ActivityThread.H.EXECUTE_TRANSACTION, transaction);
    }
    
    //ActivityThread.java
    case EXECUTE_TRANSACTION:
         final ClientTransaction transaction = (ClientTransaction) msg.obj;
         mTransactionExecutor.execute(transaction);

在前面有过介绍,TransactionExecutor 负责管理变换的执行,核心实现在这个里面

    public void execute(ClientTransaction transaction) {
        ...
        // 执行mActivityCallbacks里面的callcack
        executeCallbacks(transaction);
       // 执行mLifecycleStateRequest的变换,由于没有设置,此方法直接返回
        executeLifecycleState(transaction);
        mPendingActions.clear();
        if (DEBUG_RESOLVER) Slog.d(TAG, tId(transaction) + "End resolving transaction");
    }
    
    public void executeCallbacks(ClientTransaction transaction) {
        final List<ClientTransactionItem> callbacks = transaction.getCallbacks();
       
        for (int i = 0; i < size; ++i) {
            final ClientTransactionItem item = callbacks.get(i);
            // 执行callback的execute和postExecute方法
            item.execute(mTransactionHandler, token, mPendingActions);
            item.postExecute(mTransactionHandler, token, mPendingActions);
        }
    }

2.1 startPausingLocked

在realStartActivityLocked方法里面,同时添加了callback和目标lifecycle

                clientTransaction.addCallback(LaunchActivityItem.obtain(new Intent(r.intent),
                        System.identityHashCode(r), r.info,
                        // TODO: Have this take the merged configuration instead of separate global
                        // and override configs.
                        mergedConfiguration.getGlobalConfiguration(),
                        mergedConfiguration.getOverrideConfiguration(), r.compat,
                        r.launchedFromPackage, task.voiceInteractor, proc.getReportedProcState(),
                        r.icicle, r.persistentState, results, newIntents,
                        dc.isNextTransitionForward(), proc.createProfilerInfoIfNeeded(),
                                r.assistToken));

                // Set desired final state.
                final ActivityLifecycleItem lifecycleItem;
                if (andResume) { // 走的这个分支
                    lifecycleItem = ResumeActivityItem.obtain(dc.isNextTransitionForward());
                } else {
                    lifecycleItem = PauseActivityItem.obtain();
                }
                clientTransaction.setLifecycleStateRequest(lifecycleItem);

                // Schedule transaction.
                mService.getLifecycleManager().scheduleTransaction(clientTransaction);

前面的调用流程是一样的,LifecycleManager.scheduleTransaction ==> ClientTransaction.schedue ==> ClientTransactionHandler.scheduleTransaction ==> TransactionExecutor.execute

    public void execute(ClientTransaction transaction) {
        ...
        // 执行mActivityCallbacks里面的callcack
        executeCallbacks(transaction);
       // 执行mLifecycleStateRequest的变换
        executeLifecycleState(transaction);
        mPendingActions.clear();
        if (DEBUG_RESOLVER) Slog.d(TAG, tId(transaction) + "End resolving transaction");
    }
    
    public void executeCallbacks(ClientTransaction transaction) {
        final List<ClientTransactionItem> callbacks = transaction.getCallbacks();
       
        for (int i = 0; i < size; ++i) {
            final ClientTransactionItem item = callbacks.get(i);
            // 执行callback的execute和postExecute方法
            item.execute(mTransactionHandler, token, mPendingActions);
            item.postExecute(mTransactionHandler, token, mPendingActions);
        }
    }
    
    private void executeLifecycleState(ClientTransaction transaction) {
        // 获取 mLifecycleStateRequest
        final ActivityLifecycleItem lifecycleItem = transaction.getLifecycleStateRequest();
        //如果没有通过setLifecycleStateRequest设置,由直接返回
        if (lifecycleItem == null) { 
            // No lifecycle request, return early.
            return;
        }

        // Cycle to the state right before the final requested state.
        cycleToPath(r, lifecycleItem.getTargetState(), true /* excludeLastState */, transaction);

        // Execute the final transition with proper parameters.
        lifecycleItem.execute(mTransactionHandler, token, mPendingActions);
        lifecycleItem.postExecute(mTransactionHandler, token, mPendingActions);
    }
    
    private void cycleToPath(ActivityClientRecord r, int finish, boolean excludeLastState,
            ClientTransaction transaction) {
        final int start = r.getLifecycleState();
        // 通过mHelper来获取LifecyclePath,此方法会根据start和finish状态来构造一个状态数组
        //  1. start状态是ON_CREATE:由于LaunchActivityItem会调用handleLaunchActivity方法将状态设置为ON_CREATE
        // r.setState(ON_CREATE);
        // 2. finish状态是ON_RESUME:在ResumeActivityItem里面,getTargetState直接返回的ON_RESUME
        final IntArray path = mHelper.getLifecyclePath(start, finish, excludeLastState);
        performLifecycleSequence(r, path, transaction);
    }
    
    // 根据不同的状态,调用ActivityThread的对应方法
    private void performLifecycleSequence(ActivityClientRecord r, IntArray path,
            ClientTransaction transaction) {
        final int size = path.size();
        for (int i = 0, state; i < size; i++) {
            state = path.get(i);
            switch (state) {
                case ON_CREATE:
                    mTransactionHandler.handleLaunchActivity(r, mPendingActions,
                            null /* customIntent */);
                    break;
                case ON_START:
                    mTransactionHandler.handleStartActivity(r, mPendingActions);
                    break;
                case ON_RESUME:
                    mTransactionHandler.handleResumeActivity(r.token, false /* finalStateRequest */,
                            r.isForward, "LIFECYCLER_RESUME_ACTIVITY");
                    break;
                case ON_PAUSE:
                    mTransactionHandler.handlePauseActivity(r.token, false /* finished */,
                            false /* userLeaving */, 0 /* configChanges */, mPendingActions,
                            "LIFECYCLER_PAUSE_ACTIVITY");
                    break;
                case ON_STOP:
                    mTransactionHandler.handleStopActivity(r.token, false /* show */,
                            0 /* configChanges */, mPendingActions, false /* finalStateRequest */,
                            "LIFECYCLER_STOP_ACTIVITY");
                    break;
                case ON_DESTROY:
                    mTransactionHandler.handleDestroyActivity(r.token, false /* finishing */,
                            0 /* configChanges */, false /* getNonConfigInstance */,
                            "performLifecycleSequence. cycling to:" + path.get(size - 1));
                    break;
                case ON_RESTART:
                    mTransactionHandler.performRestartActivity(r.token, false /* start */);
                    break;
                default:
                    throw new IllegalArgumentException("Unexpected lifecycle state: " + state);
            }
        }
    }

重点说明一下 cycleToPath方法

  1. start状态是ON_CREATE:由于LaunchActivityItem会调用handleLaunchActivity方法将状态设置为ON_CREATE, r.setState(ON_CREATE);
  2. finish状态是ON_RESUME:在ResumeActivityItem里面,getTargetState直接返回的ON_RESUME
  3. 在TransactionExecutorHelper.getLifecyclePath方法里面,会依次加入ON_START和ON_RESUME

在execute方法里面

  1. executeCallbacks 方法
    会调用LaunchActivityItem的execute方法来handleLaunchActivity,最终会调用Activity.onCreate
  2. executeLifecycleState方法
    会依次调用handleStartActivity和handleResumeActivity,最终调用Activity.onStop和Acitivty.onResume

本文地址:https://blog.csdn.net/weixin_42695485/article/details/108741913