Activity启动流程分析四 ActivtyB的生命周期执行和ActivityA的生命周期执行

事务处理器TransactionExecutor处理AMS跨进程传给App进程的事务ClientTransaction

之前分析到ActivityStackSupervisor,这个类中,AMS把希望ActivityB触发的起始生命周期和结束生命周期封装成ClientTransaction,通过Binder实现跨进程通信把ClientTransaction传递给了App进程。在ActivityThread的ApplicationThread里面通过sendMessage从子线程切换到主线程。

 final ClientTransaction transaction = (ClientTransaction) msg.obj;
                   //TransactionExecutor
                    mTransactionExecutor.execute(transaction);
                    if (isSystem()) {
                        // Client transactions inside system process are recycled on the client side
                        // instead of ClientLifecycleManager to avoid being cleared before this
                        // message is handled.
                        transaction.recycle();
                    }

通过代码可以看到在App端,ClientTransaction交给TransactionExecutor这个事务处理器处理

    public void execute(ClientTransaction transaction) {
        ......
        //这里执行的callback就是AMS添加到ClientTransaction里面,希望App执行的起始生命周期
        executeCallbacks(transaction);
        //AMS添加到ClientTransaction里面,希望App执行的最终的生命周期
        executeLifecycleState(transaction);
        ......
    }

事务处理器TransactionExecutor处理AMS添加到ClientTransaction里面,希望App执行的起始生命周期

AMS在ClientTransaction里面添加了一个起始生命周期和结束生命周期,那么对应的在我们App进程里面的TransactionExecutor事务处理器里面,也是分两步进行。先处理AMS要求的起始生命周期LaunchActivityItem和结束生命周期ResumeActivityItem。

public void executeCallbacks(ClientTransaction transaction) {
         ......
         //遍历 callbacks数组,AMS只添加了一个LaunchActivityItem
        for (int i = 0; i < size; ++i) {
            //从 callbacks数组中取出item
            final ClientTransactionItem item = callbacks.get(i);
            if (DEBUG_RESOLVER) Slog.d(TAG, tId(transaction) + "Resolving callback: " + item);
            final int postExecutionState = item.getPostExecutionState();
            final int closestPreExecutionState = mHelper.getClosestPreExecutionState(r,
                    item.getPostExecutionState());
            if (closestPreExecutionState != UNDEFINED) {
                cycleToPath(r, closestPreExecutionState, transaction);
            }

            //调用 launchActivityItem 的execute方法
            item.execute(mTransactionHandler, token, mPendingActions);
            item.postExecute(mTransactionHandler, token, mPendingActions);
            ......
        }
    }

可以看到executeCallbacks就是在执行LaunchActivityItem的execute方法

@Override
    public void execute(ClientTransactionHandler client, IBinder token,
            PendingTransactionActions pendingActions) {
        Trace.traceBegin(TRACE_TAG_ACTIVITY_MANAGER, "activityStart");
        ActivityClientRecord r = new ActivityClientRecord(token, mIntent, mIdent, mInfo,
                mOverrideConfig, mCompatInfo, mReferrer, mVoiceInteractor, mState, mPersistentState,
                mPendingResults, mPendingNewIntents, mIsForward,
                mProfilerInfo, client, mAssistToken, mFixedRotationAdjustments);
        client.handleLaunchActivity(r, pendingActions, null /* customIntent */);
        Trace.traceEnd(TRACE_TAG_ACTIVITY_MANAGER);
    }

ActivityClientRecord是什么

可以看到一来就创建了一个ActivityClientRecord ,这个ActivityClientRecord 是什么?
ActivityClientRecord 是在ActivityThread里面专门创建的一个类,个人觉得可以把它理解为在App进程中的,当Activity还没启动时候的Activity对象。ActivityClientRecord 是apk进程中一个Activity的代表,这个对象的activity成员引用真正的Activity组件。

构造完ActivityClientRecord ,把它传递给ActivityThread的handleLaunchActivity方法,开始执行launch动作。在handleLaunchActivity中执行performLaunchActivity,在performLaunchActivity中通过反射创建出activity对象,makeApplication做个保险,执行activity的attach方法,创建PhoneWindow,绑定DecorView,再执行activity的onCreate方法,把activity对象赋值给ActivityClientRecord里面的activity变量,最后把ActivityClientRecord的生命周期状态变量mLifecycleState设置为ON_CREATE。

 /**  Core implementation of activity launch. */
    private Activity performLaunchActivity(ActivityClientRecord r, Intent customIntent) {
        ......
        Activity activity = null;
        try {
            java.lang.ClassLoader cl = appContext.getClassLoader();
            //创建一个activity
            activity = mInstrumentation.newActivity(
                    cl, component.getClassName(), r.intent);
            StrictMode.incrementExpectedActivityCount(activity.getClass());
            r.intent.setExtrasClassLoader(cl);
            r.intent.prepareToEnterProcess();
            if (r.state != null) {
                r.state.setClassLoader(cl);
            }
        } 

        try {
            //LoadedApk 构建 makeApplication,因为创建Application和启动Activity是使用Binder异步通信,所以可能先启动Activity后创建出                       
            //application。这边做个保险,如果启动activity的时候,application还没创建成功就再创建一次
            Application app = r.packageInfo.makeApplication(false, mInstrumentation);
            ......
				//会在这个方法中创建Activity的PhoneWindow,并绑定对应的WindowManager。
                activity.attach(appContext, this, getInstrumentation(), r.token,
                        r.ident, app, r.intent, r.activityInfo, title, r.parent,
                        r.embeddedID, r.lastNonConfigurationInstances, config,
                        r.referrer, r.voiceInteractor, window, r.configCallback,
                        r.assistToken);
                ......
                // 设置 mLifecycleState 为 ON_CREATE,执行onCreate方法
                if (r.isPersistable()) {
                    mInstrumentation.callActivityOnCreate(activity, r.state, r.persistentState);
                } else {
                    mInstrumentation.callActivityOnCreate(activity, r.state);
                }
                //把创建的activity对象赋值给ActivityClientRecord里面的activity 变量
                r.activity = activity;
                mLastReportedWindowingMode.put(activity.getActivityToken(),
                        config.windowConfiguration.getWindowingMode());
            }
            // 设置 mLifecycleState 为 ON_CREATE
            r.setState(ON_CREATE);
            ......
        return activity;
    }

事务处理器TransactionExecutor通过对AMS传递给APP起始生命周期和结束生命周期的计算,执行onStart生命周期

接下来执行executeLifecycleState方法,executeLifecycleState首先执行了cycleToPath方法,这个方法中会执行onStart生命周期。然后才是执行ResumeActivityItem 的 execute

 private void executeLifecycleState(ClientTransaction transaction) {
        // 获取ActivityLifecycleItem,这里获取的是我们之前添加的ResumeActivityItem
        final ActivityLifecycleItem lifecycleItem = transaction.getLifecycleStateRequest();
        ......
        // ResumeActivityItem的 getTargetState 是 ON_RESUME
        cycleToPath(r, lifecycleItem.getTargetState(), true /* excludeLastState */, transaction);

        // Execute the final transition with proper parameters.
        // 执行 ResumeActivityItem 的 execute
        lifecycleItem.execute(mTransactionHandler, token, mPendingActions);
        lifecycleItem.postExecute(mTransactionHandler, token, mPendingActions);
    }

cycleToPath方法里面接受到一个结束的生命周期标识,ResumeActivityItem的 生命周期标识是ON_RESUME(3),在getLifecyclePath去比较当前存储在ActivityClientRecord里面的生命周期标识的值,我们结束的生命周期标识是ON_RESUME(3),存储在ActivityClientRecord的生命周期标识是ON_CREATE(1),会把生命周期ON_START(2)添加到一个数组里面,最后执行performLifecycleSequence根据属组里面的值去执行相关生命周期。

private void cycleToPath(ActivityClientRecord r, int finish, boolean excludeLastState,
            ClientTransaction transaction) {
        final int start = r.getLifecycleState();//这里的start是ON_CREATE  ON_CREATE = 1;
       // 这里的 start 是 ON_CREATE,finish 是 ON_RESUME  ON_RESUME = 3;
       // mHelper是 TransactionExecutorHelper 类的对象,
       //调用 getLifecyclePath 返回的 path 包含 ON_START 和 ON_RESUME
       // 这里是 Activity 执行 onStart 函数的关键所在  
        final IntArray path = mHelper.getLifecyclePath(start, finish, excludeLastState);
         // 执行path中的相关的生命周期函数
        performLifecycleSequence(r, path, transaction);
    }
    @VisibleForTesting
    public IntArray getLifecyclePath(int start, int finish, boolean excludeLastState) {
       ......
        if (finish >= start) {//走到此分支  3>=1
            if (start == ON_START && finish == ON_STOP) {
                // A case when we from start to stop state soon, we don't need to go
                // through the resumed, paused state.
                mLifecycleSequence.add(ON_STOP);
            } else {
                // just go there
                for (int i = start + 1; i <= finish; i++) {
                    //把 ON_START 和 ON_RESUME 添加到 mLifecycleSequence 中
                    mLifecycleSequence.add(i);
                }
            }
        } 
        ......

        // Remove last transition in case we want to perform it with some specific params.
        // 因为 excludeLastState 为 true,所以删除掉 ON_RESUME 状态
        if (excludeLastState && mLifecycleSequence.size() != 0) {
            mLifecycleSequence.remove(mLifecycleSequence.size() - 1);
        }

        return mLifecycleSequence;
    }

performLifecycleSequence的path数组传递的是ON_START(2),所以会执行handleStartActivity方法。

private void performLifecycleSequence(ActivityClientRecord r, IntArray path,
            ClientTransaction transaction) {
        //通过mHelper调用getLifecyclePath返回的path 是 ON_START
        final int size = path.size();
        for (int i = 0, state; i < size; i++) {
            state = path.get(i);
            if (DEBUG_RESOLVER) {
                Slog.d(TAG, tId(transaction) + "Transitioning activity: "
                        + getShortActivityName(r.token, mTransactionHandler)
                        + " to state: " + getStateName(state));
            }
            switch (state) {
                case ON_CREATE:
                    mTransactionHandler.handleLaunchActivity(r, mPendingActions,
                            null /* customIntent */);
                    break;
                case ON_START:
                    mTransactionHandler.handleStartActivity(r.token, 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, 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);
            }
        }
    }

我们可以看到onStart生命周期并不是AMS去控制App进程去执行的,AMS只是给了App进程一个ClientTranstion事务,这个事务里面规定了Activity的开始生命周期和结束生命周期,分别是LaunchActivityItem和ResumeActivityItem。App进程接受到AMS传递过来的ClientTranstion事务后,会通知事务处理器TransactionExecutor去启动launch事件,onCreate事件。onStart事件是在launch事件和resume事件之间的,onStart事件是通过事务处理器TransactionExecutor的计算后执行。

事务处理器TransactionExecutor执行AMS传递的结束生命周期事件ResumeActivityItem

接下来执行ResumeActivityItem 的 execute方法,在这个方法里面会执行ActivityThread的handleResumeActivity方法。

至此ActivityB的启动过程中涉及到的生命周期全部执行完毕。

ActivityA的生命周期的onStop执行

在执行ActivityThread的handleResumeActivity方法时,先执行performResumeActivity调用activity的onResume生命周期,然后把DecorView添加到window上面,最后还执行了一行代码Looper.myQueue().addIdleHandler(new Idler());

private class Idler implements MessageQueue.IdleHandler {
        @Override
        public final boolean queueIdle() {
            ActivityClientRecord a = mNewActivities;
                ......
                //拿到AMS的本地代理
                IActivityTaskManager am = ActivityTaskManager.getService();
                ......
                //跨进程通信,执行AMS的activityIdle方法
                am.activityIdle(a.token, a.createdConfig, stopProfiling);
    }

MessageQueue.IdleHandler是当主线程没事做的时候,MessageQueue为空或者休眠时会执行。在这个方法里面会拿到AMS的本地代理,然后进行跨进程通信执行AMS的activityIdle方法

 @Override
    public final void activityIdle(IBinder token, Configuration config, boolean stopProfiling) {
                ......
                mStackSupervisor.activityIdleInternal(r, false /* fromTimeout */,
                        false /* processPausingActivities */, config);
                ......
               }

可以看到最后又跑到ActivityStackSupervisor类里面去了

private void processStoppingAndFinishingActivities(ActivityRecord launchedActivity,
            boolean processPausingActivities, String reason) {
        // Stop any activities that are scheduled to do so but have been waiting for the transition
        // animation to finish.
        //循环处理所有要执行onStop的activity
        ArrayList<ActivityRecord> readyToStopActivities = null;
        for (int i = mStoppingActivities.size() - 1; i >= 0; --i) {
            final ActivityRecord s = mStoppingActivities.get(i);
            ......
        }

        final int numReadyStops = readyToStopActivities == null ? 0 : readyToStopActivities.size();
        for (int i = 0; i < numReadyStops; i++) {
            final ActivityRecord r = readyToStopActivities.get(i);
            if (r.isInHistory()) {
                if (r.finishing) {
                    // TODO(b/137329632): Wait for idle of the right activity, not just any.
                    r.destroyIfPossible(reason);
                } else {
                    //执行onStop
                    r.stopIfPossible();
                }
            }
        }
        ......
    }

在ActivityStackSupervisor的processStoppingAndFinishingActivities方法里面循环处理了所有要准备执行onStop生命周期的activity,最后跑到ActivityRecord类里面执行stopIfPossible

    void stopIfPossible() {
           .......
            mAtmService.getLifecycleManager().scheduleTransaction(app.getThread(), appToken,
                    StopActivityItem.obtain(configChangeFlags));
            ......
    }

stopIfPossible方法里面也是把onStop方法封装成一个事务,通过ClientLifecycleManager对ClientTransaction进行封装管理,最后使用Binder跨进程通信,把ClientTransaction传递到ApplicationThread里面,通过sendMessage的方式切换到主线程里面。最后在事务管理器TransactionExector里面执行StopActivityItem的exec方法。

你可能感兴趣的:(FrameWork,zygote,java,开发语言,jvm,android)