开启成长之旅!这是我参加「日新计划 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<IActivityTaskManager> IActivityTaskManagerSingleton =
    new Singleton<IActivityTaskManager>() {
    @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<ResultInfo> pendingResults,
                                        List<ReferrerIntent> 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<ClientTransactionItem> 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办法之后)