Activity的启动过程

语言: CN / TW / HK

theme: cyanosis


开启掘金成长之旅!这是我参与「掘金日新计划 · 12 月更文挑战」的第32天,点击查看活动详情

启动一个Activity有两个方法startActivity和startActivityForResult,前者最终会调用startActivityForResult因此直接对后者进行分析

1.Activity启动的发起

``` //Activity#startActivityForResult public void startActivityForResult(@RequiresPermission Intent intent, int requestCode, @Nullable Bundle options) { if (mParent == null) { options = transferSpringboardActivityOptions(options); Instrumentation.ActivityResult ar = mInstrumentation.execStartActivity( this, mMainThread.getApplicationThread(), mToken, this, intent, requestCode, options); if (ar != null) { mMainThread.sendActivityResult( mToken, mEmbeddedID, requestCode, ar.getResultCode(), ar.getResultData()); } if (requestCode >= 0) { // If this start is requesting a result, we can avoid making // the activity visible until the result is received. Setting // this code during onCreate(Bundle savedInstanceState) or onResume() will keep the // activity hidden during this time, to avoid flickering. // This can only be done when a result is requested because // that guarantees we will get information back when the // activity is finished, no matter what happens to it. mStartedActivity = true; }

    cancelInputsAndStartExitTransition(options);
    // TODO Consider clearing/flushing other event sources and events for child windows.
} else {
    if (options != null) {
        mParent.startActivityFromChild(this, intent, requestCode, options);
    } else {
        // Note we want to go through this method for compatibility with
        // existing applications that may have overridden it.
        mParent.startActivityFromChild(this, intent, requestCode);
    }
}

} ```

mParent == null的判断中有这么一行代码mMainThread.getApplicationThread(),其中的getApplication就是ApplicationThread它是ActivityThread的内部类,集成IApplication.Stub,也是个Binder对象,ActivityThreadApplicationThread在Activity的启动过程中发挥着重要的作用。

接着再看一下mInstrumentation.execStartActivity做了什么

//Instrumentation#execStartActivity @UnsupportedAppUsage public ActivityResult execStartActivity( Context who, IBinder contextThread, IBinder token, Activity target, Intent intent, int requestCode, Bundle options) { IApplicationThread whoThread = (IApplicationThread) contextThread; Uri referrer = target != null ? target.onProvideReferrer() : null; if (referrer != null) { intent.putExtra(Intent.EXTRA_REFERRER, referrer); } if (mActivityMonitors != null) { synchronized (mSync) { final int N = mActivityMonitors.size(); for (int i=0; i<N; i++) { final ActivityMonitor am = mActivityMonitors.get(i); ActivityResult result = null; if (am.ignoreMatchingSpecificIntents()) { result = am.onStartActivity(intent); } if (result != null) { am.mHits++; return result; } else if (am.match(who, null, intent)) { am.mHits++; if (am.isBlocking()) { return requestCode >= 0 ? am.getResult() : null; } break; } } } } try { intent.migrateExtraStreamToClipData(who); intent.prepareToLeaveProcess(who); int result = ActivityTaskManager.getService().startActivity(whoThread, who.getBasePackageName(), who.getAttributionTag(), intent, intent.resolveTypeIfNeeded(who.getContentResolver()), token, target != null ? target.mEmbeddedID : null, requestCode, 0, null, options); checkStartActivityResult(result, intent); } catch (RemoteException e) { throw new RuntimeException("Failure from system", e); } return null; }

由上面的代码可知启动Activity的真正实现是由ActivityTaskManager.getService().startActivity()完成的

``` //ActivityTaskManager#getService public static IActivityTaskManager getService() { return IActivityTaskManagerSingleton.get(); }

@UnsupportedAppUsage(trackingBug = 129726065) private static final Singleton IActivityTaskManagerSingleton = new Singleton() { @Override protected IActivityTaskManager create() { final IBinder b = ServiceManager.getService(Context.ACTIVITY_TASK_SERVICE); return IActivityTaskManager.Stub.asInterface(b); } }; ```

ActivityTaskManager的主要工作就是管理Activity它接替了ActivityManager的一些工作。

看到Binder就可以明白了这里是获取一个跨进程服务,获取的是ActivityTaskManagerService(ATMS),它继承自IActivityTaskManager.Stub,是个Binder对象并且通过单例提供服务。

ATMS就是管理Activity及其容器(任务、堆栈、显示等)的系统服务,运行在系统服务进程(system_server)。

execStartActivity方法中还有一个方法调用checkStartActivityResult

``` //Instrumentation#checkStartActivityResult @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 115609023) public static void checkStartActivityResult(int res, Object intent) { if (!ActivityManager.isStartResultFatalError(res)) { return; }

switch (res) {
    case ActivityManager.START_INTENT_NOT_RESOLVED:
    case ActivityManager.START_CLASS_NOT_FOUND:
        if (intent instanceof Intent && ((Intent)intent).getComponent() != null)
            throw new ActivityNotFoundException(
            "Unable to find explicit activity class "
            + ((Intent)intent).getComponent().toShortString()
            + "; have you declared this activity in your AndroidManifest.xml?");
        throw new ActivityNotFoundException(
            "No Activity found to handle " + intent);
    case ActivityManager.START_PERMISSION_DENIED:
        throw new SecurityException("Not allowed to start activity "
                                    + intent);
    case ActivityManager.START_FORWARD_AND_REQUEST_CONFLICT:
        throw new AndroidRuntimeException(
            "FORWARD_RESULT_FLAG used while also requesting a result");
    case ActivityManager.START_NOT_ACTIVITY:
        throw new IllegalArgumentException(
            "PendingIntent is not an activity");
    case ActivityManager.START_NOT_VOICE_COMPATIBLE:
        throw new SecurityException(
            "Starting under voice control not allowed for: " + intent);
    case ActivityManager.START_VOICE_NOT_ACTIVE_SESSION:
        throw new IllegalStateException(
            "Session calling startVoiceActivity does not match active session");
    case ActivityManager.START_VOICE_HIDDEN_SESSION:
        throw new IllegalStateException(
            "Cannot start voice activity on a hidden session");
    case ActivityManager.START_ASSISTANT_NOT_ACTIVE_SESSION:
        throw new IllegalStateException(
            "Session calling startAssistantActivity does not match active session");
    case ActivityManager.START_ASSISTANT_HIDDEN_SESSION:
        throw new IllegalStateException(
            "Cannot start assistant activity on a hidden session");
    case ActivityManager.START_CANCELED:
        throw new AndroidRuntimeException("Activity could not be started for "
                                          + intent);
    default:
        throw new AndroidRuntimeException("Unknown error code "
                                          + res + " when starting " + intent);
}

} ```

checkStartActivityResult的代码中可以知道它的作用就是检查启动Activity的结果,无法正确启动时就抛出一个异常。

2.Activity的管理-ATMS

到这里Activity的启动流程就通过跨进程转移到了ATMS中,接着分析ATMS中的startActivity方法

``` //ActivityTaskManagerService#startActivity @Override public final int startActivity(IApplicationThread caller, String callingPackage, Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode, int startFlags, ProfilerInfo profilerInfo, Bundle bOptions) { return startActivityAsUser(caller, callingPackage, intent, resolvedType, resultTo, resultWho, requestCode, startFlags, profilerInfo, bOptions, UserHandle.getCallingUserId()); }

//ActivityTaskManagerService#startActivityAsUser @Override public int startActivityAsUser(IApplicationThread caller, String callingPackage, Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode, int startFlags, ProfilerInfo profilerInfo, Bundle bOptions, int userId) { return startActivityAsUser(caller, callingPackage, intent, resolvedType, resultTo, resultWho, requestCode, startFlags, profilerInfo, bOptions, userId, true /validateIncomingUser/); }

//ActivityTaskManagerService#startActivityAsUser int startActivityAsUser(IApplicationThread caller, String callingPackage, Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode, int startFlags, ProfilerInfo profilerInfo, Bundle bOptions, int userId, boolean validateIncomingUser) { enforceNotIsolatedCaller("startActivityAsUser");

userId = getActivityStartController().checkTargetUser(userId, validateIncomingUser,
                                                      Binder.getCallingPid(), Binder.getCallingUid(), "startActivityAsUser");

// TODO: Switch to user app stacks here.
return getActivityStartController().obtainStarter(intent, "startActivityAsUser")
    .setCaller(caller)
    .setCallingPackage(callingPackage)
    .setResolvedType(resolvedType)
    .setResultTo(resultTo)
    .setResultWho(resultWho)
    .setRequestCode(requestCode)
    .setStartFlags(startFlags)
    .setProfilerInfo(profilerInfo)
    .setActivityOptions(bOptions)
    .setMayWait(userId)
    .execute();

} ```

在ATMS中的startActivity方法中一层层的深入看到最终调用的是startActivityAsUser方法,这个方法中首先调用getActivityStartController.obtainStart获取到ActivityStarter实例,然后调用一系列方法(setCaller()、setUserId())等,最后通过execute()方法启动Activity

//ActivityStater#execute int execute() { try { // TODO(b/64750076): Look into passing request directly to these methods to allow // for transactional diffs and preprocessing. if (mRequest.mayWait) { return startActivityMayWait(mRequest.caller, mRequest.callingUid, mRequest.callingPackage, mRequest.realCallingPid, mRequest.realCallingUid, mRequest.intent, mRequest.resolvedType, mRequest.voiceSession, mRequest.voiceInteractor, mRequest.resultTo, mRequest.resultWho, mRequest.requestCode, mRequest.startFlags, mRequest.profilerInfo, mRequest.waitResult, mRequest.globalConfig, mRequest.activityOptions, mRequest.ignoreTargetSecurity, mRequest.userId, mRequest.inTask, mRequest.reason, mRequest.allowPendingRemoteAnimationRegistryLookup, mRequest.originatingPendingIntent, mRequest.allowBackgroundActivityStart); } else { return startActivity(mRequest.caller, mRequest.intent, mRequest.ephemeralIntent, mRequest.resolvedType, mRequest.activityInfo, mRequest.resolveInfo, mRequest.voiceSession, mRequest.voiceInteractor, mRequest.resultTo, mRequest.resultWho, mRequest.requestCode, mRequest.callingPid, mRequest.callingUid, mRequest.callingPackage, mRequest.realCallingPid, mRequest.realCallingUid, mRequest.startFlags, mRequest.activityOptions, mRequest.ignoreTargetSecurity, mRequest.componentSpecified, mRequest.outActivity, mRequest.inTask, mRequest.reason, mRequest.allowPendingRemoteAnimationRegistryLookup, mRequest.originatingPendingIntent, mRequest.allowBackgroundActivityStart); } } finally { onExecutionComplete(); } }

在execute中分了两种情况,但是无论哪种情况最终都会进入到startActivity中,这个startActivity中调用startActivityUnchecked

``` //ActivityStarter#startActivity private int startActivity(final ActivityRecord r, ActivityRecord sourceRecord, IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor, int startFlags, boolean doResume, ActivityOptions options, TaskRecord inTask, ActivityRecord[] outActivity, boolean restrictedBgActivity) { int result = START_CANCELED; final ActivityStack startedActivityStack; try { mService.mWindowManager.deferSurfaceLayout(); result = startActivityUnchecked(r, sourceRecord, voiceSession, voiceInteractor, startFlags, doResume, options, inTask, outActivity, restrictedBgActivity); } finally { final ActivityStack currentStack = r.getActivityStack(); startedActivityStack = currentStack != null ? currentStack : mTargetStack;

    if (ActivityManager.isStartResultSuccessful(result)) {
        if (startedActivityStack != null) {
            // If there is no state change (e.g. a resumed activity is reparented to
            // top of another display) to trigger a visibility/configuration checking,
            // we have to update the configuration for changing to different display.
            final ActivityRecord currentTop =
                startedActivityStack.topRunningActivityLocked();
            if (currentTop != null && currentTop.shouldUpdateConfigForDisplayChanged()) {
                mRootActivityContainer.ensureVisibilityAndConfig(
                    currentTop, currentTop.getDisplayId(),
                    true /* markFrozenIfConfigChanged */, false /* deferResume */);
            }
        }
    } else {
        // If we are not able to proceed, disassociate the activity from the task.
        // Leaving an activity in an incomplete state can lead to issues, such as
        // performing operations without a window container.
        final ActivityStack stack = mStartActivity.getActivityStack();
        if (stack != null) {
            stack.finishActivityLocked(mStartActivity, RESULT_CANCELED,
                                       null /* intentResultData */, "startActivity", true /* oomAdj */);
        }

        // Stack should also be detached from display and be removed if it's empty.
        if (startedActivityStack != null && startedActivityStack.isAttached()
            && startedActivityStack.numActivities() == 0
            && !startedActivityStack.isActivityTypeHome()) {
            startedActivityStack.remove();
        }
    }
    mService.mWindowManager.continueSurfaceLayout();
}

postStartActivityProcessing(r, result, startedActivityStack);

return result;

} ```

然后在startActivityUnChecked方法中调用mRootActivityContainer.resumeFocusedStacksTopActivities

,RootActivityContainer是Android10新增的类,分担了之前ActivityStackSupervisor的部分功能。

然后在resumeFocusedStacksTopActivites中进入了ActivityStack的resumeTopActivityUncheckedLocked方法中

``` //ActivityStack#resumeTopActivityUncheckedLocked //确保堆栈中最顶层的活动被恢复 @GuardedBy("mService") boolean resumeTopActivityUncheckedLocked(ActivityRecord prev, ActivityOptions options) { if (mInResumeTopActivity) { // Don't even start recursing. return false; }

boolean result = false;
try {
    // Protect against recursion.
    mInResumeTopActivity = true;
    result = resumeTopActivityInnerLocked(prev, options);

    // When resuming the top activity, it may be necessary to pause the top activity (for
    // example, returning to the lock screen. We suppress the normal pause logic in
    // {@link #resumeTopActivityUncheckedLocked}, since the top activity is resumed at the
    // end. We call the {@link ActivityStackSupervisor#checkReadyForSleepLocked} again here
    // to ensure any necessary pause logic occurs. In the case where the Activity will be
    // shown regardless of the lock screen, the call to
    // {@link ActivityStackSupervisor#checkReadyForSleepLocked} is skipped.
    final ActivityRecord next = topRunningActivityLocked(true /* focusableOnly */);
    if (next == null || !next.canTurnScreenOn()) {
        checkReadyForSleep();
    }
} finally {
    mInResumeTopActivity = false;
}

return result;

} ```

在reumeToActivityUncheckedLocked方法中又进入了resumeTopActivityInnerLocked方法

``` //ActivityStack#resumeTopActivityInnerLocked private boolean resumeTopActivityInnerLocked(ActivityRecord prev, ActivityOptions options) { ... boolean pausing = getDisplay().pauseBackStacks(userLeaving, next, false); if (mResumedActivity != null) { if (DEBUG_STATES) Slog.d(TAG_STATES, "resumeTopActivityLocked: Pausing " + mResumedActivity); // 暂停上一个Activity pausing |= startPausingLocked(userLeaving, false, next, false); } ... //这里next.attachedToProcess(),只有启动了的Activity才会返回true if (next.attachedToProcess()) { ...

            try {
                final ClientTransaction transaction =
                    ClientTransaction.obtain(next.app.getThread(), next.appToken);
                ...
                    //启动了的Activity就发送ResumeActivityItem事务给客户端了,后面会讲到
                    transaction.setLifecycleStateRequest(
                    ResumeActivityItem.obtain(next.app.getReportedProcState(),
                                              getDisplay().mDisplayContent.isNextTransitionForward()));
                mService.getLifecycleManager().scheduleTransaction(transaction);
                ....
                } catch (Exception e) {
                ....
                    mStackSupervisor.startSpecificActivityLocked(next, true, false);
                return true;
            }
        ....
        } else {
        ....
            if (SHOW_APP_STARTING_PREVIEW) {
                //这里就是 冷启动时 出现白屏 的原因了:取根activity的主题背景 展示StartingWindow
                next.showStartingWindow(null , false ,false);
            }
        // 继续当前Activity,普通activity的正常启动 关注这里即可
        mStackSupervisor.startSpecificActivityLocked(next, true, true);
    }
return true;

} ```

这里先暂停上一个Actiivty然后在执行创建Activity的工作,最终进入了ActivityStackSupervisor.startSpecificActivityLocked方法。这里有个点注意下,启动activity前调用了next.showStartingWindow方法来展示一个window,这就是 冷启动时 出现白屏 的原因了。

``` //ActivityStackSupervisor#startSpecificActivityLocked void startSpecificActivityLocked(ActivityRecord r, boolean andResume, boolean checkConfig) { // Is this activity's application already running? final WindowProcessController wpc = mService.getProcessController(r.processName, r.info.applicationInfo.uid);

boolean knownToBeDead = false;
if (wpc != null && wpc.hasThread()) {
    try {
        realStartActivityLocked(r, wpc, andResume, checkConfig);
        return;
    } catch (RemoteException e) {
        Slog.w(TAG, "Exception when starting activity "
               + r.intent.getComponent().flattenToShortString(), e);
    }
    knownToBeDead = true;
}

...

    try {
        if (Trace.isTagEnabled(TRACE_TAG_ACTIVITY_MANAGER)) {
            Trace.traceBegin(TRACE_TAG_ACTIVITY_MANAGER, "dispatchingStartProcess:"
                             + r.processName);
        }
        // 上面的wpc != null && wpc.hasThread()不满足的话,说明没有进程,就会取创建进程
        final Message msg = PooledLambda.obtainMessage(
            ActivityManagerInternal::startProcess, mService.mAmInternal, r.processName,
            r.info.applicationInfo, knownToBeDead, "activity", r.intent.getComponent());
        mService.mH.sendMessage(msg);
    } finally {
        Trace.traceEnd(TRACE_TAG_ACTIVITY_MANAGER);
    }

} ```

这里的判断条件if (wpc != null && wpc.hasThread())的意思是是否启动了应用程序,内部是通过IApplicationThread是否为空来判断的,这里只看应用已经被启动的情况,这里进入了realStartActivityLocked方法

``` //ActivityStackSupversion#realStartActivityLocked boolean realStartActivityLocked(ActivityRecord r, WindowProcessController proc, boolean andResume, boolean checkConfig) throws RemoteException {

...

    // Create activity launch transaction.
    final ClientTransaction clientTransaction = ClientTransaction.obtain(
    proc.getThread(), r.appToken);

final DisplayContent dc = r.getDisplay().mDisplayContent;
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);

...

    return true;

} ```

这个方法中获取了ClientTransaction,它是一个容器,包含了等待客户端处理的事务,客户端接收后取出并执行。

然后使用clientTransaction.addCallback添加了LaunchActivityItem实例

//都是用来发送到客户端的 private List<ClientTransactionItem> mActivityCallbacks; public void addCallback(ClientTransactionItem activityCallback) { if (mActivityCallbacks == null) { mActivityCallbacks = new ArrayList<>(); } mActivityCallbacks.add(activityCallback); }

LauncherActivityItem又是什么

``` public static LaunchActivityItem obtain(Intent intent, int ident, ActivityInfo info, Configuration curConfig, Configuration overrideConfig, CompatibilityInfo compatInfo, String referrer, IVoiceInteractor voiceInteractor, int procState, Bundle state, PersistableBundle persistentState, List pendingResults, List pendingNewIntents, boolean isForward, ProfilerInfo profilerInfo, IBinder assistToken) { LaunchActivityItem instance = ObjectPool.obtain(LaunchActivityItem.class); if (instance == null) { instance = new LaunchActivityItem(); } setValues(instance, intent, ident, info, curConfig, overrideConfig, compatInfo, referrer, voiceInteractor, procState, state, persistentState, pendingResults, pendingNewIntents, isForward, profilerInfo, assistToken);

return instance;

} ```

将LauncherActivityItem的实例添加到setValues中配置了各种参数。从名字可以知道它就是用来启动Activity的,它又是怎么发挥作用的呢?再回头去看realStartActivityLocked,调用了

mService.getLifecycleManager().scheduleTransaction(clientTransaction);里面的service就是ATMS,getLifecycleManager获取的是ClientLifecycleManager实例,scheduleTransaction方法如下:

``` void scheduleTransaction(ClientTransaction transaction) throws RemoteException { final IApplicationThread client = transaction.getClient(); transaction.schedule(); if (!(client instanceof Binder)) { transaction.recycle(); } }

public void schedule() throws RemoteException { mClient.scheduleTransaction(this); } ```

调用的就是IApplicationThread的scheduleTransaction方法,因为IApplicationThread是ApplicationThread在系统进程中的代理所以真正执行的地方就是ApplicationThread,也就是说Activity的启动操作又跨进程还给了客户端。

总结一下,启动Activity的操作从客户端跨进程转移到了ATMS中,然后ATMS通过ActivityStrater、ActivityStack、ActivityStackSupervisor对Activity任务、Activity栈,Activity管理后又用跨进程方式把正在启动的过程转移表到了客户端。

3.切换线程及消息处理

经过上面的分析进入了Application的scheduleTransaction,然后在Application的scheduleTransaction中可以看到又进入了ActivityThread的scheduleTransaction,ActvityThread的scheduleTransaction是在其父类CientTransactionHandler中

``` //ActivityThread#ApplicationThread#scheduleTransaction @Override public void scheduleTransaction(ClientTransaction transaction) throws RemoteException { ActivityThread.this.scheduleTransaction(transaction); }

//ClientTransactionHandler void scheduleTransaction(ClientTransaction transaction) { transaction.preExecute(this); sendMessage(ActivityThread.H.EXECUTE_TRANSACTION, transaction); } ```

sendMessage最终调用如下

private void sendMessage(int what, Object obj, int arg1, int arg2, int seq) { if (DEBUG_MESSAGES) Slog.v( TAG, "SCHEDULE " + mH.codeToString(what) + " arg1=" + arg1 + " arg2=" + arg2 + "seq= " + seq); Message msg = Message.obtain(); msg.what = what; SomeArgs args = SomeArgs.obtain(); args.arg1 = obj; args.argi1 = arg1; args.argi2 = arg2; args.argi3 = seq; msg.obj = args; mH.sendMessage(msg); }

上面代码中sendMessage最终收益通过mH发送了一个消息,这个mH继承自Handler,是Handler的一个子类,它利用sendMessage将消息发送到了主线程

class H extends Handler { ... }

那么mH又是从哪个线程发送的呢?

这就要从ApplicationThread的sceduleTransaction方法中看起,因为sendMessage是通过它调用的,已知ApplicationThread是通过跨进程调用的因此可以得出结论ApplicationThread的scheduleTransaction的调用是在Binder线程池中。

到这里,消息就在主线程处理了,那么又是怎么处理Activity启动的呢?回到ActivityThread的方法scheduleTransaction的实现中,也就是它的父类ClientTransactionHandler,在sendMessage方法中传递了一个what参数ActivityThread.H.EXECUTE_TRANSACTION,这块就是启动Activiy处理的地方,看一下它的实现

class H extends Handler { public void handleMessage(Message msg) { 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; } }

从源码得知他进入了TransactionExecutor的execute方法,然后在executeCallbacks方法中遍历所有callback,然后调用了ClientTransactionItem的execute方法

``` //TransactionExecutor#execute public void execute(ClientTransaction transaction) { if (DEBUG_RESOLVER) Slog.d(TAG, tId(transaction) + "Start resolving transaction");

final IBinder token = transaction.getActivityToken();
 ...

executeCallbacks(transaction);

executeLifecycleState(transaction);
...

}

@VisibleForTesting public void executeCallbacks(ClientTransaction transaction) { final List callbacks = transaction.getCallbacks(); if (callbacks == null || callbacks.isEmpty()) { // No callbacks to execute, return early. return; } if (DEBUG_RESOLVER) Slog.d(TAG, tId(transaction) + "Resolving callbacks in transaction");

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

// In case when post-execution state of the last callback matches the final state requested
// for the activity in this transaction, we won't do the last transition here and do it when
// moving to final state instead (because it may contain additional parameters from server).
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();
//遍历所有callback
for (int i = 0; i < size; ++i) {
    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);
    }

    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, transaction);
    }
}

} ```

ClientTransactionItem有个子类LauncherActivityItem,在它的里面重写了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); client.handleLaunchActivity(r, pendingActions, null /* customIntent */); Trace.traceEnd(TRACE_TAG_ACTIVITY_MANAGER); }

代码中的client.handleLaunchActivity的client就是ClientTransactionHandler,是在TransactionExecutor构造方法传入的,而TransactionExecutor的构造是在ActivityThread中完成的

//ActivityThread private final TransactionExecutor mTransactionExecutor = new TransactionExecutor(this);

所以可以得出结论client的handleLaunchActivity就是ActivityThread的handleLauncherActivity方法。

总结:ApplicationThread把启动Activity的操作通过mH切换到了主线程,走到了ActivityThread的hanldeLaunchActivity方法中。

4.Activity的启动核心实现-初始化及生命周期

先看下ActivityThread中的handleLaunchActivity做了什么

``` public Activity handleLaunchActivity(ActivityClientRecord r, PendingTransactionActions pendingActions, Intent customIntent) {

...
final Activity a = performLaunchActivity(r, customIntent);
...

} ```

``` private Activity performLaunchActivity(ActivityClientRecord r, Intent customIntent) { //获取待启动Activity的组件信息 ActivityInfo aInfo = r.activityInfo; if (r.packageInfo == null) { r.packageInfo = getPackageInfo(aInfo.applicationInfo, r.compatInfo, Context.CONTEXT_INCLUDE_CODE); }

ComponentName component = r.intent.getComponent();
if (component == null) {
    component = r.intent.resolveActivity(
        mInitialApplication.getPackageManager());
    r.intent.setComponent(component);
}

if (r.activityInfo.targetActivity != null) {
    component = new ComponentName(r.activityInfo.packageName,
                                  r.activityInfo.targetActivity);
}

ContextImpl appContext = createBaseContextForActivity(r);
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);
    }
} catch (Exception e) {
    if (!mInstrumentation.onException(activity, e)) {
        throw new RuntimeException(
            "Unable to instantiate activity " + component
            + ": " + e.toString(), e);
    }
}

try {
    //获取Application实例,如果有责直接返回如果没有则创建
    Application app = r.packageInfo.makeApplication(false, mInstrumentation);

    if (localLOGV) Slog.v(TAG, "Performing launch of " + r);
    if (localLOGV) Slog.v(
        TAG, r + ": app=" + app
        + ", appName=" + app.getPackageName()
        + ", pkg=" + r.packageInfo.getPackageName()
        + ", comp=" + r.intent.getComponent().toShortString()
        + ", dir=" + r.packageInfo.getAppDir());

    if (activity != null) {
        CharSequence title = r.activityInfo.loadLabel(appContext.getPackageManager());
        Configuration config = new Configuration(mCompatConfiguration);
        if (r.overrideConfig != null) {
            config.updateFrom(r.overrideConfig);
        }
        if (DEBUG_CONFIGURATION) Slog.v(TAG, "Launching activity "
                                        + r.activityInfo.name + " with config " + config);
        Window window = null;
        if (r.mPendingRemoveWindow != null && r.mPreserveWindow) {
            window = r.mPendingRemoveWindow;
            r.mPendingRemoveWindow = null;
            r.mPendingRemoveWindowManager = null;
        }
        appContext.setOuterContext(activity);
        //通过attach方法关联Activity上下文环境
        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);

        if (customIntent != null) {
            activity.mIntent = customIntent;
        }
        r.lastNonConfigurationInstances = null;
        checkAndBlockForNetworkAccess();
        activity.mStartedActivity = false;
        int theme = r.activityInfo.getThemeResource();
        if (theme != 0) {
            activity.setTheme(theme);
        }

        activity.mCalled = false;
        //调用生命周期onCreate
        if (r.isPersistable()) {
            mInstrumentation.callActivityOnCreate(activity, r.state, r.persistentState);
        } else {
            mInstrumentation.callActivityOnCreate(activity, r.state);
        }
        if (!activity.mCalled) {
            throw new SuperNotCalledException(
                "Activity " + r.intent.getComponent().toShortString() +
                " did not call through to super.onCreate()");
        }
        r.activity = activity;
    }
    r.setState(ON_CREATE);

    // updatePendingActivityConfiguration() reads from mActivities to update
    // ActivityClientRecord which runs in a different thread. Protect modifications to
    // mActivities to avoid race.
    synchronized (mResourcesManager) {
        mActivities.put(r.token, r);
    }

} catch (SuperNotCalledException e) {
    throw e;

} catch (Exception e) {
    if (!mInstrumentation.onException(activity, e)) {
        throw new RuntimeException(
            "Unable to start activity " + component
            + ": " + e.toString(), e);
    }
}

return activity;

} ```

performLaunchActivity主要做了一下事情:

    • 通过ActivityClientRecord获取待启动Activity 的组件信息,例如主题,启动模式等
    • 通过mInstrumentation.newActivity创建Activity实例
    • 通过LoadedApk的makeApplication创建Application,内部也是通过mInstrumentation使用类加载器,创建后就调用了Instrumentation.callApplicationOnCreate方法,也就是Application的onCreate方法
    • 创建ContextImpl并通过activity.attach方法对重要数据进行初始化,关联了Context的具体实现ContextImpl,attach内部还完成了Window创建,这样Window接收到外部事件就可以传递给Activity了
    • 调用Activty的onCreate方法,是通过mInstrumentation.callActivityOnCreate完成的。

Activity的其他生命周期是如何被调用的

    • LaunchActivityItem 远程App端的onCreate生命周期事务
    • ResumeActivityItem 远程App端的onResume生命周期事务
    • PauseActivityItem 远程App端的onPause生命周期事务
    • StopActivityItem 远程App端的onStop生命周期事务
    • DestroyActivityItem 远程App端onDestroy生命周期事务

另外梳理过程中涉及的几个类:

    • ClientTransaction:客户端事务处理者
    • ClientLifecycleManager:客户端生命周期管理者
    • TransactionExecutor:远程通信事务执行者

那么我们再来看看ResumeActivityItem吧。

在ActivityStackSupervisor的realStartActivityLocked方法中调用了resumeActivityItem,再回到TransactionExecutor的execute方法中还有一个方法executeLifecyclestate,这个方法中祛除了ActivityLifecycleItem并调用了execute方法,这里实际上调用的就是ResumeActivityItem方法,最终走到ActivityThread的hanleResumeActivity方法,在handleResumeActivity方法中内部会走onStart、onResume。

handleResumeActivity主要做了以下事情:

    • 调用生命周期:通过performResumeActivity方法,内部调用生命周期onStart、onResume方法
    • 设置视图可见:通过activity.makeVisible方法,添加window、设置可见。(所以视图的真正可见是在onResume方法之后)