Android应用程序(activity)启动过程(三)API28

文章基于API28本的activity启动过程,和26版本的启动过程改动不大,主要是在realStartActivityLocked方法之后,修改了activity的调用,读本文之前建议先了解之前版本activity的调用过程,文章将直接讲解主要不同之处。
Android应用程序(activity)启动过程(一)
Android应用程序(activity)启动过程(二)

对接启动过程(二) step 39或 step 50

  1. realStartActivityLocked()方法
                // 启动LaunchActivityItem
                clientTransaction.addCallback(LaunchActivityItem.obtain(new Intent(r.intent),
                        System.identityHashCode(r), r.info,   
                        mergedConfiguration.getGlobalConfiguration(),
                        mergedConfiguration.getOverrideConfiguration(), r.compat,
                        r.launchedFromPackage, task.voiceInteractor, app.repProcState, r.icicle,
                        r.persistentState, results, newIntents, mService.isNextTransitionForward(),
                        profilerInfo));
                final ActivityLifecycleItem lifecycleItem;
                if (andResume) {
                    // 启动 ResumeActivityItem  ActivityLifecycleItem
                    lifecycleItem = ResumeActivityItem.obtain(mService.isNextTransitionForward());
                } else {
                // 否则 启动 PauseActivityItem
                    lifecycleItem = PauseActivityItem.obtain();
                }
                // 利用 mLifecycleStateRequest 执行 resume方法
                clientTransaction.setLifecycleStateRequest(lifecycleItem);

                // Schedule transaction.启动事务
                mService.getLifecycleManager().scheduleTransaction(clientTransaction);

  1. scheduleTransaction()
// ClientLifecycleManager 类
void scheduleTransaction(ClientTransaction transaction) throws RemoteException {
        final IApplicationThread client = transaction.getClient();
        // 此处调用 transaction 的schedule()方法
        transaction.schedule();
        if (!(client instanceof Binder)) {
            // If client is not an instance of Binder - it's a remote call and at this point it is
            // safe to recycle the object. All objects used for local calls will be recycled after
            // the transaction is executed on client in ActivityThread.
            transaction.recycle();
        }
    }
  1. schedule() 方法中有个mClient 成员变量,private IApplicationThread mClient; 接口类型将用来回调ApplicationThread

// ClientTransaction

    public void schedule() throws RemoteException {
        mClient.scheduleTransaction(this);
    }
  1. scheduleTransaction(),方法调用了ActivityThread 的scheduleTransaction方法,这个方法是ActivityThread 父类 ClientTransactionHandler 定义的方法
// ActivityThread 内部类 ApplicationThread
 @Override
        public void scheduleTransaction(ClientTransaction transaction) throws RemoteException {
            ActivityThread.this.scheduleTransaction(transaction);
        }
  1. scheduleTransaction(),主要是发送了message到ActivityThread.H 的handler中,返回到ActivityThread
// ClientTransactionHandler  
    void scheduleTransaction(ClientTransaction transaction) {
        transaction.preExecute(this);
        sendMessage(ActivityThread.H.EXECUTE_TRANSACTION, transaction);
    }
  1. ActivityThread 中的H (handler)处理此消息,调用了mTransactionExecutor 的execute 方法,这个mTransactionExecutor 是个TransactionExecutor类。
case EXECUTE_TRANSACTION:
                    final ClientTransaction transaction = (ClientTransaction) msg.obj;
                    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();
                    }
                    // TODO(lifecycler): Recycle locally scheduled transactions.
                    break;
  1. TransactionExecutor 的execute方法,直接调用了executeCallbacks 之前将LaunchActivityItem添加到一个callback中,这里开始解析
    public void execute(ClientTransaction transaction) {
        final IBinder token = transaction.getActivityToken();
        log("Start resolving transaction for client: " + mTransactionHandler + ", token: " + token);

        executeCallbacks(transaction);

        executeLifecycleState(transaction);
        mPendingActions.clear();
        log("End resolving transaction");
    }
  1. TransactionExecutor 类 executeCallbacks()
 @VisibleForTesting
    public void executeCallbacks(ClientTransaction transaction) {
//        LaunchActivityItem 等将要执行的活动实现了
        final List callbacks = transaction.getCallbacks();
       
        final IBinder token = transaction.getActivityToken();
        ActivityClientRecord r = mTransactionHandler.getActivityClient(token);

        final ActivityLifecycleItem finalStateRequest = transaction.getLifecycleStateRequest();
        final int finalState = finalStateRequest != null ? finalStateRequest.getTargetState()
                : UNDEFINED;
        // Index of the last callback that requests some post-execution state.
        final int lastCallbackRequestingState = lastCallbackRequestingState(transaction);

        final int size = callbacks.size();
        for (int i = 0; i < size; ++i) {
            final ClientTransactionItem item = callbacks.get(i);
            log("Resolving callback: " + item);
            final int postExecutionState = item.getPostExecutionState();
            final int closestPreExecutionState = mHelper.getClosestPreExecutionState(r,
                    item.getPostExecutionState());
            if (closestPreExecutionState != UNDEFINED) {
                cycleToPath(r, closestPreExecutionState);
            }
			// 循环遍历执行item 也就是LaunchActivityItem  的execute方法
            item.execute(mTransactionHandler, token, mPendingActions);
            item.postExecute(mTransactionHandler, token, mPendingActions);
            if (r == null) {
                // Launch activity request will create an activity record.
                r = mTransactionHandler.getActivityClient(token);
            }

            if (postExecutionState != UNDEFINED && r != null) {
                // Skip the very last transition and perform it by explicit state request instead.
                final boolean shouldExcludeLastTransition =
                        i == lastCallbackRequestingState && finalState == postExecutionState;
                cycleToPath(r, postExecutionState, shouldExcludeLastTransition);
            }
        }
    }

  1. 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);
               // 最终回调了 ClientTransactionHandler 实现类 ActivityThread 的handleLaunchActivity方法,和之前版本的启动过程对接上了
        client.handleLaunchActivity(r, pendingActions, null /* customIntent */);
        Trace.traceEnd(TRACE_TAG_ACTIVITY_MANAGER);
    }
  1. 返回 step 7 解决完callback 后,开始 executeLifecycleState,继续处理后面的resume生命周期
    同理,直接进入ResumeActivityItem execute方法
private void executeLifecycleState(ClientTransaction transaction) {
        final ActivityLifecycleItem lifecycleItem = transaction.getLifecycleStateRequest();
        if (lifecycleItem == null) {
            // No lifecycle request, return early.
            return;
        }
        log("Resolving lifecycle state: " + lifecycleItem);

        final IBinder token = transaction.getActivityToken();
        final ActivityClientRecord r = mTransactionHandler.getActivityClient(token);

        if (r == null) {
            // Ignore requests for non-existent client records for now.
            return;
        }
        cycleToPath(r, lifecycleItem.getTargetState(), true /* excludeLastState */);

        // Execute the final transition with proper parameters.
        lifecycleItem.execute(mTransactionHandler, token, mPendingActions);
        lifecycleItem.postExecute(mTransactionHandler, token, mPendingActions);
    }
  1. ResumeActivityItem execute();看到 handleResumeActivity 又对接上之前的版本的方法
@Override
    public void execute(ClientTransactionHandler client, IBinder token,
            PendingTransactionActions pendingActions) {
        Trace.traceBegin(TRACE_TAG_ACTIVITY_MANAGER, "activityResume");
        client.handleResumeActivity(token, true /* finalStateRequest */, mIsForward,
                "RESUME_ACTIVITY");
        Trace.traceEnd(TRACE_TAG_ACTIVITY_MANAGER);
    }
  1. 中间经过 ActivityThread 类 performResumeActivity 进入到Activity performResume 方法 此方法会依次调用onStart和onResume方法

你可能感兴趣的:(Android,原理探索)