其他分享
首页 > 其他分享> > 基于Android10.0 Activity启动流程

基于Android10.0 Activity启动流程

作者:互联网

基于Android10.0 Activity启动流程

前言

基于SDK 29也就是10.0的源码整理了一遍Activity的启动流程。在Launch上单击一个应用图标,一个新的应用究竟是如何启动的,新应用的Activity生命周期又是如何按着顺序一步步执行的,通过源码来看一下。由于涉及方法和类较多,会在最后补上一个时序图,可以代码结合时序图阅读。
整个流程分为几个阶段,这几个阶段在平时开发中都是非常熟悉的,现在就是要把这些阶段串联在一起,在这里先暂时不讨论其前后执行顺序:

  1. 当前app调用startActivity方法(这里指Launcher中单击一个应用图标,且该应用不在后台)
  2. 当前app执行Activity的onPause生命周期方法
  3. 启动新的App的进程
  4. 新app执行其Application的onCreate方法
  5. 新app执行Activity的onCreate生命周期方法
  6. 新app执行Activity的onResume生命周期方法

代码执行流程分析

这里分为5个阶段,现在就开始从执行startActivity开始,一步一步跟进代码。

startActivity阶段

这个阶段的起始是调用startActivity()方法启动一个Activity。调用startActivity()方法,首先会调用Activity.java中的startActivity()方法。

Activity.java
@Override
public void startActivity(Intent intent) {
    this.startActivity(intent, null);
}

继续调用startActivity()方法。

Activity.java
@Override
public void startActivity(Intent intent, @Nullable Bundle options) {
    if (options != null) {
        startActivityForResult(intent, -1, options);
    } else {
        // Note we want to go through this call for compatibility with
        // applications that may have overridden the method.
        startActivityForResult(intent, -1);
    }
}

两个分支都是调用的startActivityForResult()方法。

Activity.java
public void startActivityForResult(@RequiresPermission Intent intent, int requestCode) {
    startActivityForResult(intent, requestCode, null);
}

调用startActivityForResult()方法。

Activity.java
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);
		...
	} else {
	    ...
	}
}

可以看到在第六行调用了mInstrumentation类的execStartActivity()方法。

Instrumentation.java
@UnsupportedAppUsage
public ActivityResult execStartActivity(
        Context who, IBinder contextThread, IBinder token, Activity target,
        Intent intent, int requestCode, Bundle options) {
    IApplicationThread whoThread = (IApplicationThread) contextThread;
    ...
    try {
        intent.migrateExtraStreamToClipData();
        intent.prepareToLeaveProcess(who);
        int result = ActivityTaskManager.getService()
            .startActivity(whoThread, who.getBasePackageName(), 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;
}

在第10行调用了一个startActivity()方法。先看一下ActivityTaskManager.getService()得到的是什么。

ActivityTaskManager.java
/** @hide */
public static IActivityTaskManager getService() {
    return IActivityTaskManagerSingleton.get();
}
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);
            }
        };
        
Singleton.java
public abstract class Singleton<T> {

    @UnsupportedAppUsage
    public Singleton() {
    }

    @UnsupportedAppUsage
    private T mInstance;

    protected abstract T create();

    @UnsupportedAppUsage
    public final T get() {
        synchronized (this) {
            if (mInstance == null) {
                mInstance = create();
            }
            return mInstance;
        }
    }
}

我们把相关代码一起来看,涉及到ActivityTaskManager和Singleton两个类。究竟ActivityTaskManager.getService()得到的是什么。首先ActivityTaskManager的getService()方法的返回值是通过调用IActivityTaskManagerSingleton.get()得到的。看一下IActivityTaskManagerSingleton,它是Singleton类型,泛型传入了IActivityTaskManager。在Singleton的get()方法中,返回的mInstance是通过实现create()抽象方法得到的。在create方法中通过Stub.asInterface得到了一个IActivityTaskManager的实例,这是binder常见的用法。通过返回的IActivityTaskManager实例可以调用service端的方法,而ActivityTaskManager对应的service端为ActivityTaskManagerService,这是一个运行在系统进程的服务。回到Instrumentation的execStartActivity()方法,最终会调用ActivityTaskManagerService的startActivity()方法。

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

调用startActivityAsUser()方法。

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

调用startActivityAsUser()方法。

ActivityTaskManagerService.java
private int startActivityAsUser(IApplicationThread caller, String callingPackage,
        @Nullable String callingFeatureId, Intent intent, String resolvedType,
        IBinder resultTo, String resultWho, int requestCode, int startFlags,
        ProfilerInfo profilerInfo, Bundle bOptions, int userId, boolean validateIncomingUser) {
    ...

    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)
            .setCallingFeatureId(callingFeatureId)
            .setResolvedType(resolvedType)
            .setResultTo(resultTo)
            .setResultWho(resultWho)
            .setRequestCode(requestCode)
            .setStartFlags(startFlags)
            .setProfilerInfo(profilerInfo)
            .setActivityOptions(bOptions)
            .setMayWait(userId)
            .execute();

}

开始是做一些权限的检查,最后会调用ActivityStart类中的execute()方法。注意倒数第二个setMayWait()方法,会将mRequest.mayWait属性设为true。

ActivityStarter setMayWait(int userId) {
	mRequest.mayWait = true;
	mRequest.userId = userId;

	return this;
}

进到ActivityStarter类的execute()方法。

ActivityStarter.java
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.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);
		} else {
			…
		}
	} finally {
		onExecutionComplete();
	}
}

注意这里的mRequest.mayWait是已经被设为true的,所以执行if分支,调用startActivityMayWait()方法中。

ActivityStarter.java
private int startActivityMayWait(IApplicationThread caller, int callingUid,
		String callingPackage, Intent intent, String resolvedType,
		IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor,
		IBinder resultTo, String resultWho, int requestCode, int startFlags,
		ProfilerInfo profilerInfo, WaitResult outResult,
		Configuration globalConfig, SafeActivityOptions options, boolean ignoreTargetSecurity,
		int userId, TaskRecord inTask, String reason,
		boolean allowPendingRemoteAnimationRegistryLookup) {
	// Refuse possible leaked file descriptors
	if (intent != null && intent.hasFileDescriptors()) {
		throw new IllegalArgumentException("File descriptors passed in Intent");
	}
	…
	synchronized (mService) {
		final ActivityStack stack = mSupervisor.mFocusedStack;
		…
		final ActivityRecord[] outRecord = new ActivityRecord[1];
		int res = startActivity(caller, intent, ephemeralIntent, resolvedType, aInfo, rInfo,
				voiceSession, voiceInteractor, resultTo, resultWho, requestCode, callingPid,
				callingUid, callingPackage, realCallingPid, realCallingUid, startFlags, options,
				ignoreTargetSecurity, componentSpecified, outRecord, inTask, reason,
				allowPendingRemoteAnimationRegistryLookup);
		…
		mSupervisor.getActivityMetricsLogger().notifyActivityLaunched(res, outRecord[0]);
		return res;
	}
}

调用startActivity()方法。

ActivityStarter.java
private int startActivity(IApplicationThread caller, Intent intent, Intent ephemeralIntent,
		String resolvedType, ActivityInfo aInfo, ResolveInfo rInfo,
		IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor,
		IBinder resultTo, String resultWho, int requestCode, int callingPid, int callingUid,
		String callingPackage, int realCallingPid, int realCallingUid, int startFlags,
		SafeActivityOptions options, boolean ignoreTargetSecurity, boolean componentSpecified,
		ActivityRecord[] outActivity, TaskRecord inTask, String reason,
		boolean allowPendingRemoteAnimationRegistryLookup) {

	...
	mLastStartActivityTimeMs = System.currentTimeMillis();
	mLastStartActivityRecord[0] = null;

	mLastStartActivityResult = startActivity(caller, intent, ephemeralIntent, resolvedType,
			aInfo, rInfo, voiceSession, voiceInteractor, resultTo, resultWho, requestCode,
			callingPid, callingUid, callingPackage, realCallingPid, realCallingUid, startFlags,
			options, ignoreTargetSecurity, componentSpecified, mLastStartActivityRecord,
			inTask, allowPendingRemoteAnimationRegistryLookup);
	…
	return getExternalResult(mLastStartActivityResult);
}

继续调用startActivity()方法。

ActivityStarter.java
private int startActivity(IApplicationThread caller, Intent intent, Intent ephemeralIntent,
		String resolvedType, ActivityInfo aInfo, ResolveInfo rInfo,
		IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor,
		IBinder resultTo, String resultWho, int requestCode, int callingPid, int callingUid,
		String callingPackage, int realCallingPid, int realCallingUid, int startFlags,
		SafeActivityOptions options,
		boolean ignoreTargetSecurity, boolean componentSpecified, ActivityRecord[] outActivity,
		TaskRecord inTask, boolean allowPendingRemoteAnimationRegistryLookup) {

	...
	ActivityRecord r = new ActivityRecord(mService, callerApp, callingPid, callingUid,
			callingPackage, intent, resolvedType, aInfo, mService.getGlobalConfiguration(),
			resultRecord, resultWho, requestCode, componentSpecified, voiceSession != null,
			mSupervisor, checkedOptions, sourceRecord);

	...
	return startActivity(r, sourceRecord, voiceSession, voiceInteractor, startFlags,
			true /* doResume */, checkedOptions, inTask, outActivity);
}

调用startActivity()方法。

ActivityStarter.java
private int startActivity(final ActivityRecord r, ActivityRecord sourceRecord,
		    IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor,
		    int startFlags, boolean doResume, ActivityOptions options, TaskRecord inTask,
		    ActivityRecord[] outActivity) {
    int result = START_CANCELED;
    try {
	mService.mWindowManager.deferSurfaceLayout();
	result = startActivityUnchecked(r, sourceRecord, voiceSession, voiceInteractor,
			startFlags, doResume, options, inTask, outActivity);
    } finally {
        ...
    }

    postStartActivityProcessing(r, result, mTargetStack);

    return result;
}

在try中调用了startActivityUnchecked()方法。

ActivityStarter.java
// Note: This method should only be called from {@link startActivity}.
private int startActivityUnchecked(final ActivityRecord r, ActivityRecord sourceRecord,
        IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor,
        int startFlags, boolean doResume, ActivityOptions options, TaskRecord inTask,
        ActivityRecord[] outActivity, boolean restrictedBgActivity) {

    ...

    // If the activity being launched is the same as the one currently at the top, then
    // we need to check if it should only be launched once.
    final ActivityStack topStack = mRootActivityContainer.getTopDisplayFocusedStack();
    final ActivityRecord topFocused = topStack.getTopActivity();
    final ActivityRecord top = topStack.topRunningNonDelayedActivityLocked(mNotTop);
    ...

    if (mDoResume) {
        final ActivityRecord topTaskActivity =
                mStartActivity.getTaskRecord().topRunningActivityLocked();
        if (!mTargetStack.isFocusable()
                || (topTaskActivity != null && topTaskActivity.mTaskOverlay
                && mStartActivity != topTaskActivity)) {
            ...
        } else {
            ...
            mRootActivityContainer.resumeFocusedStacksTopActivities(
                    mTargetStack, mStartActivity, mOptions);
        }
    } else if (mStartActivity != null) {
        mSupervisor.mRecentTasks.add(mStartActivity.getTaskRecord());
    }
    mRootActivityContainer.updateUserStack(mStartActivity.mUserId, mTargetStack);

    mSupervisor.handleNonResizableTaskIfNeeded(mStartActivity.getTaskRecord(),
            preferredWindowingMode, mPreferredDisplayId, mTargetStack);

    return START_SUCCESS;
}

调用RootActivityContainer.resumeFocusedStacksTopActivities()方法。

RootActivityContainer.java
boolean resumeFocusedStacksTopActivities(
        ActivityStack targetStack, ActivityRecord target, ActivityOptions targetOptions) {

    if (!mStackSupervisor.readyToResume()) {
        return false;
    }

    boolean result = false;
    if (targetStack != null && (targetStack.isTopStackOnDisplay()
            || getTopDisplayFocusedStack() == targetStack)) {
        result = targetStack.resumeTopActivityUncheckedLocked(target, targetOptions);
    }

    ...

    return result;
}

调用ActivityStack中的resumeTopActivityUncheckedLocked()方法。

ActivityStack.java
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);

        ...
    } finally {
        mInResumeTopActivity = false;
    }

    return result;
}

调用resumeTopActivityInnerLocked方法。

ActivityStack.java
private boolean resumeTopActivityInnerLocked(ActivityRecord prev, ActivityOptions options) {
    if (!mService.isBooting() && !mService.isBooted()) {
        // Not ready yet!
        return false;
    }

    // Find the next top-most activity to resume in this stack that is not finishing and is
    // focusable. If it is not focusable, we will fall into the case below to resume the
    // top activity in the next focusable task.

    ...

    boolean pausing = getDisplay().pauseBackStacks(userLeaving, next, false);

    ...

    // Launching this app's activity, make sure the app is no longer
    // considered stopped.
    try {
        AppGlobals.getPackageManager().setPackageStoppedState(
                next.packageName, false, next.mUserId); /* TODO: Verify if correct userid */
    } catch (RemoteException e1) {
    } catch (IllegalArgumentException e) {
        Slog.w(TAG, "Failed trying to unstop package "
                + next.packageName + ": " + e);
    }

    ...

    return true;
}

这个方法会执行getDisplay().pauseBackStacks()这步,用于暂停当前的Activity。getDisplay()会返回ActivityDisplay对象。

ActivityDisplay.java
ActivityDisplay getDisplay() {
    return mRootActivityContainer.getActivityDisplay(mDisplayId);
}

调用ActivityDisplay的pauseBackStacks()方法。

pause阶段

在启动一个Activity的时候,如果发现当前还有处于resume状态的Activity,会先走puase流程,暂停当前的Activity。

ActivityDisplay.java
boolean pauseBackStacks(boolean userLeaving, ActivityRecord resuming, boolean dontWait) {
    boolean someActivityPaused = false;
    for (int stackNdx = mStacks.size() - 1; stackNdx >= 0; --stackNdx) {
        final ActivityStack stack = mStacks.get(stackNdx);
        final ActivityRecord resumedActivity = stack.getResumedActivity();
        if (resumedActivity != null
                && (stack.getVisibility(resuming) != STACK_VISIBILITY_VISIBLE
                    || !stack.isFocusable())) {
            if (DEBUG_STATES) Slog.d(TAG_STATES, "pauseBackStacks: stack=" + stack +
                    " mResumedActivity=" + resumedActivity);
            someActivityPaused |= stack.startPausingLocked(userLeaving, false, resuming,
                    dontWait);
        }
    }
    return someActivityPaused;
}

调用ActivityStack的startPausingLocked方法。

ActivityStack.java
final ActivityTaskManagerService mService;
...
final boolean startPausingLocked(boolean userLeaving, boolean uiSleeping,
		ActivityRecord resuming, boolean pauseImmediately) {
	...
	ActivityRecord prev = mResumedActivity;

	...

	if (prev.attachedToProcess()) {
		if (DEBUG_PAUSE) Slog.v(TAG_PAUSE, "Enqueueing pending pause: " + prev);
		try {
			...

			mService.getLifecycleManager().scheduleTransaction(prev.app.getThread(),
					prev.appToken, PauseActivityItem.obtain(prev.finishing, userLeaving,
							prev.configChangeFlags, pauseImmediately));
		} catch (Exception e) {
			...
		}
	} else {
		mPausingActivity = null;
		mLastPausedActivity = null;
		mLastNoHistoryActivity = null;
	}

	...
}

主要关注scheduleTransaction()这个方法,后面还会遇到这个方法.先一步一步来看一下它,后面就一带而过了。mService是一个ActivityTaskManagerService对象,首先调用了ActivityTaskManagerService的getLifecycleManager()方法得到一个ClientLifecycleManager对象。

ActivityTaskManagerService.java
private final ClientLifecycleManager mLifecycleManager;
...
ClientLifecycleManager getLifecycleManager() {
    return mLifecycleManager;
}

调用ClientLifecycleManager的scheduleTransaction()方法。先看一下方法传入的参数,第一个参数通过调用prev.app.getThread()获得,会调用WindowProcessController的getThread()方法。

WindowProcessController.java
IApplicationThread getThread() {
    return mThread;
}

得到一个IApplicationThread对象。其实这里使用了AIDL,这个IApplicationThread是系统进程与应用进程通信的桥梁,当系统进程向应用进程请求时,会通过这个对象进行调用。最终会调用到应用进程中ApplicationThread对应的方法。ApplicationThread是ActivityThread的内部类,继承了IApplicationThread.Stub。

private class ApplicationThread extends IApplicationThread.Stub {
    ...
}

接着看第三个参数PauseActivityItem.obtain。

PauseActivityItem.java
public static PauseActivityItem obtain() {
    PauseActivityItem instance = ObjectPool.obtain(PauseActivityItem.class);
    if (instance == null) {
        instance = new PauseActivityItem();
    }
    instance.mFinished = false;
    instance.mUserLeaving = false;
    instance.mConfigChanges = 0;
    instance.mDontReport = true;

    return instance;
}

创建了一个PauseActivityItem实例。回到上面,接着看scheduleTransaction()方法。

ClientLifecycleManager.java
void scheduleTransaction(@NonNull IApplicationThread client, @NonNull IBinder activityToken,
        @NonNull ActivityLifecycleItem stateRequest) throws RemoteException {
    final ClientTransaction clientTransaction = transactionWithState(client, activityToken,
            stateRequest);
    scheduleTransaction(clientTransaction);
}

在这个方法中首先会通过外部传入的三个参数调用transactionWithState()方法创建一个ClientTransaction对象,先看一下这个ClientTransaction对象是如何创建的。

ClientLifecycleManager.java
private static ClientTransaction transactionWithState(@NonNull IApplicationThread client,
        @NonNull IBinder activityToken, @NonNull ActivityLifecycleItem stateRequest) {
    final ClientTransaction clientTransaction = ClientTransaction.obtain(client, activityToken);
    clientTransaction.setLifecycleStateRequest(stateRequest);
    return clientTransaction;
}

首先调用ClientTransaction.obtain()方法创建ClientTransaction实例。

ClientTransaction.java
public static ClientTransaction obtain(IApplicationThread client, IBinder activityToken) {
    ClientTransaction instance = ObjectPool.obtain(ClientTransaction.class);
    if (instance == null) {
        instance = new ClientTransaction();
    }
    instance.mClient = client;
    instance.mActivityToken = activityToken;

    return instance;
}

创建ClientTransaction实例并返回,并通过内部的mClient变量保存IApplicationThread对象,通过mActivityToken变量保存activityToken。回到上一步继续看transactionWithState()方法,接着调用了setLifecycleStateRequest方法。

ClientTransaction.java
public void setLifecycleStateRequest(ActivityLifecycleItem stateRequest) {
    mLifecycleStateRequest = stateRequest;
}

通过mLifecycleStateRequest属性保存了stateRequest对象,这个stateRequest就是前面创建的那个PauseActivityItem。到这里,我们得到了一个保存了IApplicationThread、activityToken、及PauseActivityItem的ClientTransaction对象,回到scheduleTransaction()方法,继续调用了一个参数的scheduleTransaction()方法,传入了这个刚刚创建的ClientTransaction对象。

ClientLifecycleManager.java
void scheduleTransaction(ClientTransaction transaction) throws RemoteException {
    final IApplicationThread client = transaction.getClient();
    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();
    }
}

调用了我们传入的ClientTransaction对象的schedule方法。

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

调用了mClient的scheduleTransaction方法,并传入了this,这个this就是这个经过我们填充的ClientTransaction对象本身。而mClient为传入的IApplicationThread对象,所以最终会在应用进程中调用ApplicationThread的scheduleTransaction方法。

ActivityThread.java::ApplicationThread
@Override
public void scheduleTransaction(ClientTransaction transaction) throws RemoteException {
    ActivityThread.this.scheduleTransaction(transaction);
}

调用scheduleTransaction()方法。ActivityThread继承自ClientTransactionHandler,实际调用的是ClientTransactionHandler的scheduleTransaction()方法,传入了创建好的transaction对象。

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

调用sendMessage方法,这里通过Handler发送了一个EXECUTE_TRANSACTION消息,会交给ActivityThread的H类来处理。

ActivityThread.java::H
private final TransactionExecutor mTransactionExecutor = new TransactionExecutor(this);
...
class H extends Handler {
	...
	public void handleMessage(Message msg) {
		...
		switch (msg.what) {
			...
			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;
			...
		}
		...
	}
}

在handleMessage()回调方法中执行EXECUTE_TRANSACTION对应的case。首先取出ClientTransaction对象,然后调用mTransactionExecutor的execute方法。mTransactionExecutor是一个TransactionExecutor对象。从类的命名也可以看出,TransactionExecutor这个类的作用是用来处理Transaction的。

TransactionExecutor.java
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);
    mPendingActions.clear();
    if (DEBUG_RESOLVER) Slog.d(TAG, tId(transaction) + "End resolving transaction");
}

会先调用executeCallbacks()方法。

TransactionExecutor.java
public void executeCallbacks(ClientTransaction transaction) {
	final List<ClientTransactionItem> callbacks = transaction.getCallbacks();
	if (callbacks == null || callbacks.isEmpty()) {
		// No callbacks to execute, return early.
		return;
	}
	...
}

调用ClientTransaction的getCallbacks()方法得到一个list。

ClientTransaction.java
private List<ClientTransactionItem> mActivityCallbacks;
...
List<ClientTransactionItem> getCallbacks() {
    return mActivityCallbacks;
}

我们前面在创建这个ClientTransaction对象的时候只赋值了其中的mClient、mActivityToken、mLifecycleStateRequest属性,并没有对mActivityCallbacks进行赋值,所以这里直接返回。回到execute()方法,接着调用executeLifecycleState()方法。

TransactionExecutor.java
private void executeLifecycleState(ClientTransaction transaction) {
    final ActivityLifecycleItem lifecycleItem = transaction.getLifecycleStateRequest();
if (lifecycleItem == null) {
    // No lifecycle request, return early.
    return;
}
	...

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

首先通过ClientTransaction的getLifecycleStateRequest()方法取出一个ActivityLifecycleItem对象,也就是在前面通过obtain()方法创建的PauseActivityItem对象。接着先调用了它的execute()方法,然后同步调用了postExecute()方法。先看execute()方法。

PauseActivityItem.java
public void execute(ClientTransactionHandler client, IBinder token,
        PendingTransactionActions pendingActions) {
    Trace.traceBegin(TRACE_TAG_ACTIVITY_MANAGER, "activityPause");
    client.handlePauseActivity(token, mFinished, mUserLeaving, mConfigChanges, pendingActions,
            "PAUSE_ACTIVITY_ITEM");
    Trace.traceEnd(TRACE_TAG_ACTIVITY_MANAGER);
}

调用了client的handlePauseActivity()方法。前面说了ActivityThread是继承了ClientTransactionHandler的,并且也有重写这个方法,所以执行了ActivityThread的handlePauseActivity()方法。

ActivityThread.java
public void handlePauseActivity(IBinder token, boolean finished, boolean userLeaving,
        int configChanges, PendingTransactionActions pendingActions, String reason) {
    ActivityClientRecord r = mActivities.get(token);
    if (r != null) {
        if (userLeaving) {
            performUserLeavingActivity(r);
        }

        r.activity.mConfigChangeFlags |= configChanges;
        performPauseActivity(r, finished, reason, pendingActions);

       ...
    }
}

调用了performPauseActivity()方法。

ActivityThread.java
private Bundle performPauseActivity(ActivityClientRecord r, boolean finished, String reason,
		PendingTransactionActions pendingActions) {
	...

	performPauseActivityIfNeeded(r, reason);

	// Notify any outstanding on paused listeners
	ArrayList<OnActivityPausedListener> listeners;
	synchronized (mOnPauseListeners) {
		listeners = mOnPauseListeners.remove(r.activity);
	}
	int size = (listeners != null ? listeners.size() : 0);
	for (int i = 0; i < size; i++) {
		listeners.get(i).onPaused(r.activity);
	}

	...

	return shouldSaveState ? r.state : null;
}

调用了performPauseActivityIfNeeded()方法。

ActivityThread.java
Instrumentation mInstrumentation;
...
private void performPauseActivityIfNeeded(ActivityClientRecord r, String reason) {
    ...

    try {
        r.activity.mCalled = false;
        mInstrumentation.callActivityOnPause(r.activity);
        ...
    } catch (SuperNotCalledException e) {
        throw e;
    } catch (Exception e) {
        ...
    }
    r.setState(ON_PAUSE);
}

调用了Instrumentation类的callActivityOnPause()方法。

Instrumentation.java
public void callActivityOnPause(Activity activity) {
    activity.performPause();
}

调用了Activity类的performPause方法。

final void performPause() {
	...
	onPause();
	...
	dispatchActivityPostPaused();
}

最后在这里调用了我们当前Activity的onPause方法。也就是执行了Activity生命周期的onPause方法。接下来就是新的Activity是如何启动的了。

新进程创建阶段

回到前面TransactionExecutor的executeLifecycleState()方法。在PauseActivityItem的execute()方法中执行了前一个Activity的onPause()方法,紧跟着会调用PauseActivityItem的postExecute()方法。

PauseActivityItem.java
public void postExecute(ClientTransactionHandler client, IBinder token,
        PendingTransactionActions pendingActions) {
    ...
    try {
        // TODO(lifecycler): Use interface callback instead of AMS.
        ActivityTaskManager.getService().activityPaused(token);
    } catch (RemoteException ex) {
        throw ex.rethrowFromSystemServer();
    }
}

调用ActivityTaskManager.getService()的activityPaused方法。这个方法在一开始startActivity的时候看过一次,它会得到一个IActivityTaskManager对象,通过它可以调用系统进程中对应的ActivityTaskManagerService的方法。

ActivityTaskManagerService.java
public final void activityPaused(IBinder token) {
    final long origId = Binder.clearCallingIdentity();
    synchronized (mGlobalLock) {
        ActivityStack stack = ActivityRecord.getStackLocked(token);
        if (stack != null) {
            stack.activityPausedLocked(token, false);
        }
    }
    Binder.restoreCallingIdentity(origId);
}

调用了ActivityStack的activityPausedLocked方法。

ActivityStack.java
final void activityPausedLocked(IBinder token, boolean timeout) {
	...

	if (r != null) {
		mHandler.removeMessages(PAUSE_TIMEOUT_MSG, r);
		if (mPausingActivity == r) {
			...
			try {
				completePauseLocked(true /* resumeNext */, null /* resumingActivity */);
			} finally {
				mService.mWindowManager.continueSurfaceLayout();
			}
			return;
		} else {
			...
		}
	}
	mRootActivityContainer.ensureActivitiesVisible(null, 0, !PRESERVE_WINDOWS);
}

调用completePauseLocked()方法。

ActivityStack.java
protected final RootActivityContainer mRootActivityContainer;
...
private void completePauseLocked(boolean resumeNext, ActivityRecord resuming) {
	ActivityRecord prev = mPausingActivity;

	...

	if (resumeNext) {
		final ActivityStack topStack = mRootActivityContainer.getTopDisplayFocusedStack();
		if (!topStack.shouldSleepOrShutDownActivities()) {
			mRootActivityContainer.resumeFocusedStacksTopActivities(topStack, prev, null);
		} else {
			...
		}
	}

	...
}

调用RootActivityContainer类的resumeFocusedStacksTopActivities()方法。发现这个方法在前面是看过的。

RootActivityContainer.java
boolean resumeFocusedStacksTopActivities(
		ActivityStack targetStack, ActivityRecord target, ActivityOptions targetOptions) {

	if (!mStackSupervisor.readyToResume()) {
		return false;
	}

	boolean result = false;
	if (targetStack != null && (targetStack.isTopStackOnDisplay()
			|| getTopDisplayFocusedStack() == targetStack)) {
		result = targetStack.resumeTopActivityUncheckedLocked(target, targetOptions);
	}

	...

	return result;
}

调用ActivityStack的resumeTopActivityUncheckedLocked()方法。

ActivityStack.java
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;
}

调用resumeTopActivityInnerLocked()方法。前面就是在这个方法中开始了Activity的pause流程,但是现在会开始新Activity的创建流程。

ActivityStack.java
private boolean resumeTopActivityInnerLocked(ActivityRecord prev, ActivityOptions options) {
	...
    //前面就是在这个方法中判断需要先pause当前Activity的。
	boolean pausing = getDisplay().pauseBackStacks(userLeaving, next, false);
	
	if (anim) {
		next.applyOptionsLocked();
	} else {
		next.clearOptionsLocked();
	}
	
    mStackSupervisor.mNoAnimActivities.clear();

	if (next.attachedToProcess()) {
		...
	} else {
		...
		mStackSupervisor.startSpecificActivityLocked(next, true, true);
	}

	return true;
}

调用ActivityStackSupervisor的startSpecificActivityLocked()方法。

ActivityStackSupervisor.java
void startSpecificActivityLocked(ActivityRecord r, boolean andResume, boolean checkConfig) {
	...

	try {
		if (Trace.isTagEnabled(TRACE_TAG_ACTIVITY_MANAGER)) {
			Trace.traceBegin(TRACE_TAG_ACTIVITY_MANAGER, "dispatchingStartProcess:"
					+ r.processName);
		}
		// Post message to start process to avoid possible deadlock of calling into AMS with the
		// ATMS lock held.
		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);
	}
}

会在try中调用ActivityManagerService的startProcess()方法,从方法名可以看出,是启动一个新进程。

ActivityManagerService.java
public void startProcess(String processName, ApplicationInfo info,
        boolean knownToBeDead, String hostingType, ComponentName hostingName) {
    try {
        ...
        synchronized (ActivityManagerService.this) {
            startProcessLocked(processName, info, knownToBeDead, 0 /* intentFlags */,
                    new HostingRecord(hostingType, hostingName),
                    false /* allowWhileBooting */, false /* isolated */,
                    true /* keepIfLarge */);
        }
    } finally {
        Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
    }
}

调用startProcessLocked()方法。

ActivityManagerService.java
final ProcessRecord startProcessLocked(String processName,
        ApplicationInfo info, boolean knownToBeDead, int intentFlags,
        HostingRecord hostingRecord, boolean allowWhileBooting,
        boolean isolated, boolean keepIfLarge) {
    return mProcessList.startProcessLocked(processName, info, knownToBeDead, intentFlags,
            hostingRecord, allowWhileBooting, isolated, 0 /* isolatedUid */, keepIfLarge,
            null /* ABI override */, null /* entryPoint */, null /* entryPointArgs */,
            null /* crashHandler */);
}

调用ProcessList的startProcessLocked()方法。

ProcessList.java
final ProcessRecord startProcessLocked(String processName, ApplicationInfo info,
            boolean knownToBeDead, int intentFlags, HostingRecord hostingRecord,
            boolean allowWhileBooting, boolean isolated, int isolatedUid, boolean keepIfLarge,
            String abiOverride, String entryPoint, String[] entryPointArgs, Runnable crashHandler) {
	...

	checkSlow(startTime, "startProcess: stepping in to startProcess");
	final boolean success = startProcessLocked(app, hostingRecord, abiOverride);
	checkSlow(startTime, "startProcess: done starting proc!");
	return success ? app : null;
}

调用startProcessLocked()方法。

ProcessList.java
final boolean startProcessLocked(ProcessRecord app, HostingRecord hostingRecord,
        String abiOverride) {
    return startProcessLocked(app, hostingRecord,
            false /* disableHiddenApiChecks */, false /* mountExtStorageFull */, abiOverride);
}

调用startProcessLocked()方法。

ProcessList.java
boolean startProcessLocked(ProcessRecord app, HostingRecord hostingRecord,
		boolean disableHiddenApiChecks, boolean mountExtStorageFull,
		String abiOverride) {
	...

	try {
		...
		final String seInfo = app.info.seInfo
				+ (TextUtils.isEmpty(app.info.seInfoUser) ? "" : app.info.seInfoUser);
		// Start the process.  It will either succeed and return a result containing
		// the PID of the new process, or else throw a RuntimeException.
		final String entryPoint = "android.app.ActivityThread";

		return startProcessLocked(hostingRecord, entryPoint, app, uid, gids,
				runtimeFlags, mountExternal, seInfo, requiredAbi, instructionSet, invokeWith,
				startTime);
	} catch (RuntimeException e) {
		...
	}
}

在try中,创建了一个entryPoint字符串,并赋值为android.app.ActivityThread,先记着它,后面会用到这个字符串。然后调用了startProcessLocked()方法。

ProcessList.java
boolean startProcessLocked(HostingRecord hostingRecord,
		String entryPoint,
		ProcessRecord app, int uid, int[] gids, int runtimeFlags, int mountExternal,
		String seInfo, String requiredAbi, String instructionSet, String invokeWith,
		long startTime) {
	app.pendingStart = true;
	app.killedByAm = false;
	app.removed = false;
	app.killed = false;
	...

	if (mService.mConstants.FLAG_PROCESS_START_ASYNC) {
		if (DEBUG_PROCESSES) Slog.i(TAG_PROCESSES,
				"Posting procStart msg for " + app.toShortString());
		mService.mProcStartHandler.post(() -> {
			try {
				final Process.ProcessStartResult startResult = startProcess(app.hostingRecord,
						entryPoint, app, app.startUid, gids, runtimeFlags, mountExternal,
						app.seInfo, requiredAbi, instructionSet, invokeWith, app.startTime);
				synchronized (mService) {
					handleProcessStartedLocked(app, startResult, startSeq);
				}
			} catch (RuntimeException e) {
				...
			}
		});
		return true;
	} else {
		...
	}
}

调用startProcess()方法。

ProcessList.java
private Process.ProcessStartResult startProcess(HostingRecord hostingRecord, String entryPoint,
		ProcessRecord app, int uid, int[] gids, int runtimeFlags, int mountExternal,
		String seInfo, String requiredAbi, String instructionSet, String invokeWith,
		long startTime) {
	try {
		...
		final Process.ProcessStartResult startResult;
		if (hostingRecord.usesWebviewZygote()) {
			...
		} else if (hostingRecord.usesAppZygote()) {
			...
		} else {
			startResult = Process.start(entryPoint,
					app.processName, uid, uid, gids, runtimeFlags, mountExternal,
					app.info.targetSdkVersion, seInfo, requiredAbi, instructionSet,
					app.info.dataDir, invokeWith, app.info.packageName,
					new String[] {PROC_START_SEQ_IDENT + app.startSeq});
		}
		checkSlow(startTime, "startProcess: returned from zygote!");
		return startResult;
	} finally {
		Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
	}
}

调用Process类的start()方法。

Process.java
public static final ZygoteProcess ZYGOTE_PROCESS = new ZygoteProcess();
...
public static ProcessStartResult start(@NonNull final String processClass,
                                       @Nullable final String niceName,
                                       int uid, int gid, @Nullable int[] gids,
                                       int runtimeFlags,
                                       int mountExternal,
                                       int targetSdkVersion,
                                       @Nullable String seInfo,
                                       @NonNull String abi,
                                       @Nullable String instructionSet,
                                       @Nullable String appDataDir,
                                       @Nullable String invokeWith,
                                       @Nullable String packageName,
                                       @Nullable String[] zygoteArgs) {
    return ZYGOTE_PROCESS.start(processClass, niceName, uid, gid, gids,
                runtimeFlags, mountExternal, targetSdkVersion, seInfo,
                abi, instructionSet, appDataDir, invokeWith, packageName,
                /*useUsapPool=*/ true, zygoteArgs);
}

调用ZygoteProcess的start()方法。

ZygoteProcess.java
public final Process.ProcessStartResult start(@NonNull final String processClass,
                                              final String niceName,
                                              int uid, int gid, @Nullable int[] gids,
                                              int runtimeFlags, int mountExternal,
                                              int targetSdkVersion,
                                              @Nullable String seInfo,
                                              @NonNull String abi,
                                              @Nullable String instructionSet,
                                              @Nullable String appDataDir,
                                              @Nullable String invokeWith,
                                              @Nullable String packageName,
                                              boolean useUsapPool,
                                              @Nullable String[] zygoteArgs) {
    ...

    try {
        return startViaZygote(processClass, niceName, uid, gid, gids,
                runtimeFlags, mountExternal, targetSdkVersion, seInfo,
                abi, instructionSet, appDataDir, invokeWith, /*startChildZygote=*/ false,
                packageName, useUsapPool, zygoteArgs);
    } catch (ZygoteStartFailedEx ex) {
        ...
    }
}

调用startViaZygote()方法。

ZygoteProcess.java
private Process.ProcessStartResult startViaZygote(@NonNull final String processClass,
												  @Nullable final String niceName,
												  final int uid, final int gid,
												  @Nullable final int[] gids,
												  int runtimeFlags, int mountExternal,
												  int targetSdkVersion,
												  @Nullable String seInfo,
												  @NonNull String abi,
												  @Nullable String instructionSet,
												  @Nullable String appDataDir,
												  @Nullable String invokeWith,
												  boolean startChildZygote,
												  @Nullable String packageName,
												  boolean useUsapPool,
												  @Nullable String[] extraArgs)
												  throws ZygoteStartFailedEx {
	ArrayList<String> argsForZygote = new ArrayList<>();

	// --runtime-args, --setuid=, --setgid=,
	// and --setgroups= must go first
	argsForZygote.add("--runtime-args");
	argsForZygote.add("--setuid=" + uid);
	argsForZygote.add("--setgid=" + gid);
	argsForZygote.add("--runtime-flags=" + runtimeFlags);
	if (mountExternal == Zygote.MOUNT_EXTERNAL_DEFAULT) {
		argsForZygote.add("--mount-external-default");
	} else if (mountExternal == Zygote.MOUNT_EXTERNAL_READ) {
		argsForZygote.add("--mount-external-read");
	} else if (mountExternal == Zygote.MOUNT_EXTERNAL_WRITE) {
		argsForZygote.add("--mount-external-write");
	} else if (mountExternal == Zygote.MOUNT_EXTERNAL_FULL) {
		argsForZygote.add("--mount-external-full");
	} else if (mountExternal == Zygote.MOUNT_EXTERNAL_INSTALLER) {
		argsForZygote.add("--mount-external-installer");
	} else if (mountExternal == Zygote.MOUNT_EXTERNAL_LEGACY) {
		argsForZygote.add("--mount-external-legacy");
	}

	argsForZygote.add("--target-sdk-version=" + targetSdkVersion);

	// --setgroups is a comma-separated list
	if (gids != null && gids.length > 0) {
		StringBuilder sb = new StringBuilder();
		sb.append("--setgroups=");

		int sz = gids.length;
		for (int i = 0; i < sz; i++) {
			if (i != 0) {
				sb.append(',');
			}
			sb.append(gids[i]);
		}

		argsForZygote.add(sb.toString());
	}

	if (niceName != null) {
		argsForZygote.add("--nice-name=" + niceName);
	}

	if (seInfo != null) {
		argsForZygote.add("--seinfo=" + seInfo);
	}

	if (instructionSet != null) {
		argsForZygote.add("--instruction-set=" + instructionSet);
	}

	...

	synchronized(mLock) {
		// The USAP pool can not be used if the application will not use the systems graphics
		// driver.  If that driver is requested use the Zygote application start path.
		return zygoteSendArgsAndGetResult(openZygoteSocketIfNeeded(abi),
										  useUsapPool,
										  argsForZygote);
	}
}

先创建了一个argsForZygote数组,填充一些启动进程需要的参数,最终调用了zygoteSendArgsAndGetResult()方法。其中将调用openZygoteSocketIfNeeded()方法返回的ZygoteState对象作为第一个参数,先看一下openZygoteSocketIfNeeded()方法。

ZygoteProcess.java
private ZygoteState openZygoteSocketIfNeeded(String abi) throws ZygoteStartFailedEx {
    try {
        attemptConnectionToPrimaryZygote();

        if (primaryZygoteState.matches(abi)) {
            return primaryZygoteState;
        }

        if (mZygoteSecondarySocketAddress != null) {
            // The primary zygote didn't match. Try the secondary.
            attemptConnectionToSecondaryZygote();

            if (secondaryZygoteState.matches(abi)) {
                return secondaryZygoteState;
            }
        }
    } catch (IOException ioe) {
        throw new ZygoteStartFailedEx("Error connecting to zygote", ioe);
    }

    throw new ZygoteStartFailedEx("Unsupported zygote ABI: " + abi);
}

调用attemptConnectionToPrimaryZygote()方法。

ZygoteProcess.java
private void attemptConnectionToPrimaryZygote() throws IOException {
    if (primaryZygoteState == null || primaryZygoteState.isClosed()) {
        //尝试与Zygote的socket连接,并将这个连接封装在了primaryZygoteState 中。
        primaryZygoteState =
                ZygoteState.connect(mZygoteSocketAddress, mUsapPoolSocketAddress);

        maybeSetApiBlacklistExemptions(primaryZygoteState, false);
        maybeSetHiddenApiAccessLogSampleRate(primaryZygoteState);
        maybeSetHiddenApiAccessStatslogSampleRate(primaryZygoteState);
    }
}

在这里我们尝试进程与Zygote进程的socket连接,并将这个连接封装在primaryZygoteState中,这个ZygoteState对象作为了openZygoteSocketIfNeeded()方法的返回值。接着调用zygoteSendArgsAndGetResult()方法。

ZygoteProcess.java
private Process.ProcessStartResult zygoteSendArgsAndGetResult(
        ZygoteState zygoteState, boolean useUsapPool, @NonNull ArrayList<String> args)
        throws ZygoteStartFailedEx {
    ...

    /*
     * See com.android.internal.os.ZygoteArguments.parseArgs()
     * Presently the wire format to the zygote process is:
     * a) a count of arguments (argc, in essence)
     * b) a number of newline-separated argument strings equal to count
     *
     * After the zygote process reads these it will write the pid of
     * the child or -1 on failure, followed by boolean to
     * indicate whether a wrapper process was used.
     */
    String msgStr = args.size() + "\n" + String.join("\n", args) + "\n";

    if (useUsapPool && mUsapPoolEnabled && canAttemptUsap(args)) {
        try {
            return attemptUsapSendArgsAndGetResult(zygoteState, msgStr);
        } catch (IOException ex) {
            ...
        }
    }

    return attemptZygoteSendArgsAndGetResult(zygoteState, msgStr);
}

将前面创建的包含启动进程参数的数组args转为一个String,然后调用attemptZygoteSendArgsAndGetResult()方法。

ZygoteProcess.java
private Process.ProcessStartResult attemptZygoteSendArgsAndGetResult(
		ZygoteState zygoteState, String msgStr) throws ZygoteStartFailedEx {
	try {
		final BufferedWriter zygoteWriter = zygoteState.mZygoteOutputWriter;
		final DataInputStream zygoteInputStream = zygoteState.mZygoteInputStream;

		zygoteWriter.write(msgStr);
		zygoteWriter.flush();

		// Always read the entire result from the input stream to avoid leaving
		// bytes in the stream for future process starts to accidentally stumble
		// upon.
		Process.ProcessStartResult result = new Process.ProcessStartResult();
		...

		return result;
	} catch (IOException ex) {
		...
	}
}

将前面封装过的数据通过socket传到Zygote进程。现在已经通知Zygote进程创建新的进程,接下来需要看一下Zygote进程是如何接收到消息,并创建新进程的。这里要先说一下Zygote进程启动的事。Zygote进程启动时,会调用ZygoteInit类中的main函数。

ZygoteInit.java
public static void main(String argv[]) {
              ZygoteServer zygoteServer = null;
	...
              zygoteServer = new ZygoteServer(isPrimaryZygote);
              ...
	Runnable caller;
	try {
		...

		// The select loop returns early in the child process after a fork and
		// loops forever in the zygote.
		caller = zygoteServer.runSelectLoop(abiList);
	} catch (Throwable ex) {
		...
	} finally {
		if (zygoteServer != null) {
			zygoteServer.closeServerSocket();
		}
	}

	// We're in the child process and have exited the select loop. Proceed to execute the
	// command.
	if (caller != null) {
		caller.run();
	}
}

在try中调用runSelectLoop()方法,返回了一个Runnable对象,如果该Runnable创建成功,会在后面通过run()方法执行这个runnable。看一下runSelectLoop()方法是如何创建一个Runnable的。

ZygoteServer.java
Runnable runSelectLoop(String abiList) {
        ArrayList<FileDescriptor> socketFDs = new ArrayList<FileDescriptor>();
	ArrayList<ZygoteConnection> peers = new ArrayList<ZygoteConnection>();

	socketFDs.add(mZygoteSocket.getFileDescriptor());
	peers.add(null);

	while (true) {
		...

		try {
			Os.poll(pollFDs, -1);
		} catch (ErrnoException ex) {
			throw new RuntimeException("poll failed", ex);
		}

		boolean usapPoolFDRead = false;

		while (--pollIndex >= 0) {
			...

			if (pollIndex == 0) {
				// Zygote server socket

				ZygoteConnection newPeer = acceptCommandPeer(abiList);
				peers.add(newPeer);
				socketFDs.add(newPeer.getFileDescriptor());

			} else if (pollIndex < usapPoolEventFDIndex) {
				// Session socket accepted from the Zygote server socket

				try {
					ZygoteConnection connection = peers.get(pollIndex);
					final Runnable command = connection.processOneCommand(this);

					// TODO (chriswailes): Is this extra check necessary?
					if (mIsForkChild) {
						// We're in the child. We should always have a command to run at this
						// stage if processOneCommand hasn't called "exec".
						if (command == null) {
							throw new IllegalStateException("command == null");
						}

						return command;
					} else {
						// We're in the server - we should never have any commands to run.
						if (command != null) {
							throw new IllegalStateException("command != null");
						}

						// We don't know whether the remote side of the socket was closed or
						// not until we attempt to read from it from processOneCommand. This
						// shows up as a regular POLLIN event in our regular processing loop.
						if (connection.isClosedByPeer()) {
							connection.closeSocket();
							peers.remove(pollIndex);
							socketFDs.remove(pollIndex);
						}
					}
				} catch (Exception e) {
					...
				} finally {
					// Reset the child flag, in the event that the child process is a child-
					// zygote. The flag will not be consulted this loop pass after the Runnable
					// is returned.
					mIsForkChild = false;
				}
			} else {
				...
			}
		}

		...
	}
}

在一个死循环中不断监听socket连接,当socket连接已经建立并且监听到了消息的到来时,会调用ZygoteConnection的processOneCommand()方法来创建一个Runnable。

ZygoteConnection.java
Runnable processOneCommand(ZygoteServer zygoteServer) {
	String args[];
	ZygoteArguments parsedArgs = null;
	FileDescriptor[] descriptors;

	try {
                //读取socket传来的参数
		args = Zygote.readArgumentList(mSocketReader);

		// TODO (chriswailes): Remove this and add an assert.
		descriptors = mSocket.getAncillaryFileDescriptors();
	} catch (IOException ex) {
		throw new IllegalStateException("IOException on command socket", ex);
	}

	// readArgumentList returns null only when it has reached EOF with no available
	// data to read. This will only happen when the remote socket has disconnected.
	if (args == null) {
		isEof = true;
		return null;
	}

	int pid = -1;
	FileDescriptor childPipeFd = null;
	FileDescriptor serverPipeFd = null;
              //将读取的参数封装成ZygoteArguments对象
	parsedArgs = new ZygoteArguments(args);

	...
             //fork出子进程
	pid = Zygote.forkAndSpecialize(parsedArgs.mUid, parsedArgs.mGid, parsedArgs.mGids,
			parsedArgs.mRuntimeFlags, rlimits, parsedArgs.mMountExternal, parsedArgs.mSeInfo,
			parsedArgs.mNiceName, fdsToClose, fdsToIgnore, parsedArgs.mStartChildZygote,
			parsedArgs.mInstructionSet, parsedArgs.mAppDataDir, parsedArgs.mTargetSdkVersion);

	try {
		if (pid == 0) {
			// in child
			zygoteServer.setForkChild();

			zygoteServer.closeServerSocket();
			IoUtils.closeQuietly(serverPipeFd);
			serverPipeFd = null;

			return handleChildProc(parsedArgs, descriptors, childPipeFd,
					parsedArgs.mStartChildZygote);
		} else {
			...
		}
	} finally {
		IoUtils.closeQuietly(childPipeFd);
		IoUtils.closeQuietly(serverPipeFd);
	}
}

会先调用forkAndSpecialize()方法fork出新的进程,通过返回pid==0判断在fork出的子进程中执行接下来的方法。先看一下forkAndSpecialize()方法。

public static int forkAndSpecialize(int uid, int gid, int[] gids, int runtimeFlags,
        int[][] rlimits, int mountExternal, String seInfo, String niceName, int[] fdsToClose,
        int[] fdsToIgnore, boolean startChildZygote, String instructionSet, String appDataDir,
        int targetSdkVersion) {
    ZygoteHooks.preFork();
    // Resets nice priority for zygote process.
    resetNicePriority();
    //调用native方法创建进程
    int pid = nativeForkAndSpecialize(
            uid, gid, gids, runtimeFlags, rlimits, mountExternal, seInfo, niceName, fdsToClose,
            fdsToIgnore, startChildZygote, instructionSet, appDataDir);
    ...
    return pid;
}

nativeForkAndSpecialize()是一个native方法,用来fork出子进程。回到上面,看一下新的进程fork出来后在子进程中做了什么。看一下handleChildProc()方法。

ZygoteConnection.java
private Runnable handleChildProc(ZygoteArguments parsedArgs, FileDescriptor[] descriptors,
		FileDescriptor pipeFd, boolean isZygote) {
	/**
	 * By the time we get here, the native code has closed the two actual Zygote
	 * socket connections, and substituted /dev/null in their place.  The LocalSocket
	 * objects still need to be closed properly.
	 */

	...


	// End of the postFork event.
	Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
	if (parsedArgs.mInvokeWith != null) {
		...
	} else {
		if (!isZygote) {
			return ZygoteInit.zygoteInit(parsedArgs.mTargetSdkVersion,
					parsedArgs.mRemainingArgs, null /* classLoader */);
		} else {
			return ZygoteInit.childZygoteInit(parsedArgs.mTargetSdkVersion,
					parsedArgs.mRemainingArgs, null /* classLoader */);
		}
	}
}

调用ZygoteInit类的childZygoteInit()方法。

ZygoteInit.java
static final Runnable childZygoteInit(
        int targetSdkVersion, String[] argv, ClassLoader classLoader) {
    RuntimeInit.Arguments args = new RuntimeInit.Arguments(argv);
    return RuntimeInit.findStaticMain(args.startClass, args.startArgs, classLoader);
}

调用RuntimeInit类的findStaticMain()方法。

RuntimeInit.java
protected static Runnable findStaticMain(String className, String[] argv,
		ClassLoader classLoader) {
	Class<?> cl;

	try {
		cl = Class.forName(className, true, classLoader);
	} catch (ClassNotFoundException ex) {
		throw new RuntimeException(
				"Missing class when invoking static main " + className,
				ex);
	}

	Method m;
	try {
		m = cl.getMethod("main", new Class[] { String[].class });
	} catch (NoSuchMethodException ex) {
		throw new RuntimeException(
				"Missing static main on " + className, ex);
	} catch (SecurityException ex) {
		throw new RuntimeException(
				"Problem getting static main on " + className, ex);
	}

	...
	return new MethodAndArgsCaller(m, argv);
}

这里的className就是看到的在创建socket通信参数时,传入的"android.app.ActivityThread"。然后通过反射拿到ActivityThread类的main()方法,最后创建了一个类型为MethodAndArgsCaller的Runnable,这个Runnable会一直返回到一开始ZygoteInit的runSelectLoop()方法,作为返回结果赋值给caller。回到ZygoteInit的main函数中,在返回这个Runnable后,调用caller的run方法其实执行的就是MethodAndArgsCaller类中run()方法。

RuntimeInit.java::MethodAndArgsCaller
static class MethodAndArgsCaller implements Runnable {
    /** method to call */
    private final Method mMethod;

    /** argument array */
    private final String[] mArgs;
    //method是刚才传入的ActivityThread中的main。
    public MethodAndArgsCaller(Method method, String[] args) {
        mMethod = method;
        mArgs = args;
    }

    public void run() {
        try {
            //通过反射执行ActivityThread中的main方法。
            mMethod.invoke(null, new Object[] { mArgs });
        } catch (IllegalAccessException ex) {
            throw new RuntimeException(ex);
        } catch (InvocationTargetException ex) {
            ...
        }
    }
}

在run()函数中,通过反射执行了mMethod函数。而这个函数就是ActivityThread的main()函数。到这里,新的Activity所在的进程已经创建出来。
总结一下这一部分,在确认前Activity已经pause后,通过socket通信的方式一步步通知Zygote进程fork出新的要启动Activity所在的进程,在fork出这个新的进程后,通过反射执行了ActivityThread的main()函数,这是在这个新进程中执行的第一个方法。

onCreate阶段

接下来,通过ActivityThread类的main()函数开始了新的Activity的启动之旅。

ActivityThread.java
public static void main(String[] args) {
    ...
    
    Looper.prepareMainLooper();

    ...
    //创建ActivityThread,执行ActivityThread的attach方法
    ActivityThread thread = new ActivityThread();
    thread.attach(false, startSeq);

    if (sMainThreadHandler == null) {
        sMainThreadHandler = thread.getHandler();
    }

    if (false) {
        Looper.myLooper().setMessageLogging(new
                LogPrinter(Log.DEBUG, "ActivityThread"));
    }

    // End of event ActivityThreadMain.
    Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
    //创建主线程looper
    Looper.loop();

    throw new RuntimeException("Main thread loop unexpectedly exited");
}

ActivityThread的main函数主要做了几件事,一个是创建了这个进程的ActivityThread对象,并执行了attach()方法,一个是启动了主线程的looper,这就是为什么我们在一个应用的主线程中不需要自己启动looper也可以使用handler,因为这个主线程的looper在这个应用进程启动的时候系统已经帮我们启动了。

ActivityThread.java
private void attach(boolean system, long startSeq) {
	sCurrentActivityThread = this;
	mSystemThread = system;
	if (!system) {
		android.ddm.DdmHandleAppName.setAppName("<pre-initialized>",
												UserHandle.myUserId());
		RuntimeInit.setApplicationObject(mAppThread.asBinder());
		final IActivityManager mgr = ActivityManager.getService();
		try {
			mgr.attachApplication(mAppThread, startSeq);
		} catch (RemoteException ex) {
			throw ex.rethrowFromSystemServer();
		}
		...
	} else {
		...
	}

	...
}

通过ActivityManager.getService()拿到ActivityManagerService在客户端的IActivityManager对象,调用到服务端(系统进程)ActivityManagerService的attachApplication()方法。

ActivityManagerService.java
public final void attachApplication(IApplicationThread thread, long startSeq) {
    synchronized (this) {
        int callingPid = Binder.getCallingPid();
        final int callingUid = Binder.getCallingUid();
        final long origId = Binder.clearCallingIdentity();
        attachApplicationLocked(thread, callingPid, callingUid, startSeq);
        Binder.restoreCallingIdentity(origId);
    }
}

调用attachApplicationLocked方法。

ActivityManagerService.java
private final boolean attachApplicationLocked(IApplicationThread thread,
		int pid, int callingUid, long startSeq) {

	...
	final BackupRecord backupTarget = mBackupTargets.get(app.userId);
	try {
		...
		final ActiveInstrumentation instr2 = app.getActiveInstrumentation();
		if (app.isolatedEntryPoint != null) {
			// This is an isolated process which should just call an entry point instead of
			// being bound to an application.
			thread.runIsolatedEntryPoint(app.isolatedEntryPoint, app.isolatedEntryPointArgs);
		} else if (instr2 != null) {
			thread.bindApplication(processName, appInfo, providers,
					instr2.mClass,
					profilerInfo, instr2.mArguments,
					instr2.mWatcher,
					instr2.mUiAutomationConnection, testMode,
					mBinderTransactionTrackingEnabled, enableTrackAllocation,
					isRestrictedBackupMode || !normalMode, app.isPersistent(),
					new Configuration(app.getWindowProcessController().getConfiguration()),
					app.compat, getCommonServicesLocked(app.isolated),
					mCoreSettingsObserver.getCoreSettingsLocked(),
					buildSerial, autofillOptions, contentCaptureOptions);
		} else {
			thread.bindApplication(processName, appInfo, providers, null, profilerInfo,
					null, null, null, testMode,
					mBinderTransactionTrackingEnabled, enableTrackAllocation,
					isRestrictedBackupMode || !normalMode, app.isPersistent(),
					new Configuration(app.getWindowProcessController().getConfiguration()),
					app.compat, getCommonServicesLocked(app.isolated),
					mCoreSettingsObserver.getCoreSettingsLocked(),
					buildSerial, autofillOptions, contentCaptureOptions);
		}
		...
	} catch (Exception e) {
		...
	}

    ...

	// See if the top visible activity is waiting to run in this process...
	if (normalMode) {
		try {
			didSomething = mAtmInternal.attachApplication(app.getWindowProcessController());
		} catch (Exception e) {
			...
		}
	}

	...
	return true;
}

thread.bindApplication()方法中会创建应用的Application并调用Application的onCreate方法,这一部分先不看了,后面的流程图中会体现出来。mAtmInternal.attachApplication()方法会调用了到ActivityTaskManagerService的attachApplication(0方法。

ActivityTaskManagerService.java
public boolean attachApplication(WindowProcessController wpc) throws RemoteException {
    synchronized (mGlobalLockWithoutBoost) {
        return mRootActivityContainer.attachApplication(wpc);
    }
}

调用RootActivityContainer类的attachApplication()方法。

RootActivityContainer.java
boolean attachApplication(WindowProcessController app) throws RemoteException {
    final String processName = app.mName;
    boolean didSomething = false;
    for (int displayNdx = mActivityDisplays.size() - 1; displayNdx >= 0; --displayNdx) {
        final ActivityDisplay display = mActivityDisplays.get(displayNdx);
        final ActivityStack stack = display.getFocusedStack();
        if (stack != null) {
            stack.getAllRunningVisibleActivitiesLocked(mTmpActivityList);
            final ActivityRecord top = stack.topRunningActivityLocked();
            final int size = mTmpActivityList.size();
            for (int i = 0; i < size; i++) {
                final ActivityRecord activity = mTmpActivityList.get(i);
                if (activity.app == null && app.mUid == activity.info.applicationInfo.uid
                        && processName.equals(activity.processName)) {
                    try {
                        if (mStackSupervisor.realStartActivityLocked(activity, app,
                                top == activity /* andResume */, true /* checkConfig */)) {
                            didSomething = true;
                        }
                    } catch (RemoteException e) {
                        ...
                    }
                }
            }
        }
    }
    ...
    return didSomething;
}

在try中调用了ActivityStackSupervisor类的realStartActivityLocked()方法。

ActivityStackSupervisor.java
boolean realStartActivityLocked(ActivityRecord r, WindowProcessController proc,
		boolean andResume, boolean checkConfig) throws RemoteException {

	...

	final TaskRecord task = r.getTaskRecord();
	final ActivityStack stack = task.getStack();

	beginDeferResume();

	try {
		...

		try {
			...

			// 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);

			...

		} catch (RemoteException e) {
			...
		}
	} finally {
		endDeferResume();
	}

	...

	return true;
}

在这个方法中,会创建一个ClientTransaction对象,之前在阅读Activity的pause流程时,也有一个对象ClientTransaction,它会被传递到客户进程,这里就不再一步一步看了,忘记的同学可以回到上面pause流程去查看。同样通过obtain()方法创建出一个ClientTransaction实例,有一点与pause时不同的是,现在创建的这个ClientTransaction对象,调用了它的addCallback()方法,并传入了LaunchActivityItem.obtain()的返回值,先看一下LaunchActivityItem的obtain()方法。

LaunchActivityItem的obtain方法。
LaunchActivityItem.java
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;
}

创建了一个LaunchActivityItem实例,并对参数进行了一些赋值操作。回到上面看一下ClientTransaction的addCallback方法,传入的参数就是这个LaunchActivityItem实例。

ClientTransaction.java
private List<ClientTransactionItem> mActivityCallbacks;
...
public void addCallback(ClientTransactionItem activityCallback) {
    if (mActivityCallbacks == null) {
        mActivityCallbacks = new ArrayList<>();
    }
    mActivityCallbacks.add(activityCallback);
}

将这个LaunchActivityItem保存在了mActivityCallbacks数组中。回到realStartActivityLocked()方法。为ClientTransaction添加mActivityCallback后,也会调用setLifecycleStateRequest方法对ClientTransaction对象的mLifecycleStateRequest属性进行赋值,前面pause流程的时候就是通过的这个属性。这里会创建一个ResumeActivityItem对象添加到mLifecycleStateRequest中去。
我们再捋一下,和前面一样,这个ClientTransaction对象包含了与客户端通信的IApplicationThread、token,并且还包括了一个存有LaunchActivityItem对象的callback和一个存有ResumeActivityItem对象的mLifecycleStateRequest变量。接着继续执行了mService.getLifecycleManager().scheduleTransaction()方法,这里就不看了,也是和前面一样的流程,最终同样会在客户端调用到TransactionExecutor的execute()方法。

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

    final IBinder token = transaction.getActivityToken();
    ...
    //执行callback
    executeCallbacks(transaction);
    //执行lifecycleState
    executeLifecycleState(transaction);
    mPendingActions.clear();
    if (DEBUG_RESOLVER) Slog.d(TAG, tId(transaction) + "End resolving transaction");
}

可以回忆一下,在pause流程中,callback是空的,只有一个PauseActivityItem类型的lifecycleState。但是这一次,我们为callback赋值了。先看一下executeCallbacks()方法,onCreate流程就是从这个方法开始一步一步执行到的。

TransactionExecutor .java
public void executeCallbacks(ClientTransaction transaction) {
    //从服务端传来的transaction中取出callbacks数组,pause流程中这个列表是空,直接返回了。
    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();
    //遍历callbacks数组
    for (int i = 0; i < size; ++i) {
        //从callbacks数组中取出item。
        final ClientTransactionItem item = callbacks.get(i);
        ...
        //调用launchActivityItem的execute方法
        item.execute(mTransactionHandler, token, mPendingActions);
        item.postExecute(mTransactionHandler, token, mPendingActions);
        ...
    }
}

首先从系统进程传来的ClientTransaction中得到mActivityCallbacks列表。这个在前面addcallback的时候已经看了,里面保存了一个LaunchActivityItem。接着通过遍历取出这个LaunchActivityItem,接着调用了它的execute()方法,传入的第一个参数是持有的ActivityThread对象,第二个参数token是从系统进程传来的activityToken。

LaunchActivityItem.java
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);
}

调用了ActivityThread类的handleLaunchActivity()方法。

ActivityThread.java
public Activity handleLaunchActivity(ActivityClientRecord r,
		PendingTransactionActions pendingActions, Intent customIntent) {
	...

	final Activity a = performLaunchActivity(r, customIntent);

	if (a != null) {
		r.createdConfig = new Configuration(mConfiguration);
		reportSizeConfigurations(r);
		if (!r.activity.mFinished && pendingActions != null) {
			pendingActions.setOldState(r.state);
			pendingActions.setRestoreInstanceState(true);
			pendingActions.setCallOnPostCreate(true);
		}
	} else {
		...
	}

	return a;
}

调用了performLaunchActivity()方法。

ActivityThread.java
Instrumentation mInstrumentation;
...
private Activity performLaunchActivity(ActivityClientRecord r, Intent customIntent) {
	...

	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) {
		...
	}

	try {
	    //尝试创建Application,其实前面已经创建过了。
		Application app = r.packageInfo.makeApplication(false, mInstrumentation);

		...

		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);
			//会在这个方法中创建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);

			...
			int theme = r.activityInfo.getThemeResource();
			if (theme != 0) {
				activity.setTheme(theme);
			}

			activity.mCalled = false;
			//执行我们新Activity的OnCreate生命周期。
			if (r.isPersistable()) {
				mInstrumentation.callActivityOnCreate(activity, r.state, r.persistentState);
			} else {
				mInstrumentation.callActivityOnCreate(activity, r.state);
			}
			...
		}
		r.setState(ON_CREATE);

		...

	} catch (SuperNotCalledException e) {
		throw e;

	} catch (Exception e) {
		...
	}

	return activity;
}

这个方法做了很多事,主要分4个部分来看。
1、首先是Activity实例的创建,这里的Activity指的是我们要启动的新的XXXActivity。调用了Instrumentation类的newActivity()方法。

Instrumentation.java
public Activity newActivity(ClassLoader cl, String className,
        Intent intent)
        throws InstantiationException, IllegalAccessException,
        ClassNotFoundException {
    String pkg = intent != null && intent.getComponent() != null
            ? intent.getComponent().getPackageName() : null;
    return getFactory(pkg).instantiateActivity(cl, className, intent);
}

getFactory(pkg)返回的是AppComponentFactory类型的对象,调用了AppComponentFactory的instantiateActivity()方法。

AppComponentFactory.java
public @NonNull Activity instantiateActivity(@NonNull ClassLoader cl, @NonNull String className,
        @Nullable Intent intent)
        throws InstantiationException, IllegalAccessException, ClassNotFoundException {
    return (Activity) cl.loadClass(className).newInstance();
}

看到这里,通过反射调用了我们要启动Activity的构造方法,然后返回了我们Activity的实例。
2、接下来会尝试创建Application,r.packageInfo返回的是LoadedApk对象,调用了LoadedApk的makeApplication()方法。

LoadedApk.java
public Application makeApplication(boolean forceDefaultAppClass,
        Instrumentation instrumentation) {
    if (mApplication != null) {
        return mApplication;
    }

    ...

    return app;
}

这个方法很长,主要是创建应用的Application实例。但是因为之前在bindApplication时已经创建了Application,所以这里在一开始if的时候直接返回了。
3、回到performLaunchActivity()方法,接着调用了Activity类的attach()方法。

Activity.java
final void attach(Context context, ActivityThread aThread,
        Instrumentation instr, IBinder token, int ident,
        Application application, Intent intent, ActivityInfo info,
        CharSequence title, Activity parent, String id,
        NonConfigurationInstances lastNonConfigurationInstances,
        Configuration config, String referrer, IVoiceInteractor voiceInteractor,
        Window window, ActivityConfigCallback activityConfigCallback, IBinder assistToken) {
    attachBaseContext(context);

    mFragments.attachHost(null /*parent*/);
    //创建PhoneWindow
    mWindow = new PhoneWindow(this, window, activityConfigCallback);
    mWindow.setWindowControllerCallback(this);
    mWindow.setCallback(this);
    mWindow.setOnWindowDismissedCallback(this);
    mWindow.getLayoutInflater().setPrivateFactory(this);
    if (info.softInputMode != WindowManager.LayoutParams.SOFT_INPUT_STATE_UNSPECIFIED) {
        mWindow.setSoftInputMode(info.softInputMode);
    }
    if (info.uiOptions != 0) {
        mWindow.setUiOptions(info.uiOptions);
    }
    mUiThread = Thread.currentThread();

    ...
    //绑定window和windowManger
    mWindow.setWindowManager(
            (WindowManager)context.getSystemService(Context.WINDOW_SERVICE),
            mToken, mComponent.flattenToString(),
            (info.flags & ActivityInfo.FLAG_HARDWARE_ACCELERATED) != 0);
    if (mParent != null) {
        mWindow.setContainer(mParent.getWindow());
    }
    mWindowManager = mWindow.getWindowManager();
    ...
}

这个方法主要做的事情就是创建了应用的window,是一个PhoneWiondow,在Activity界面的创建和显示流程的时候还会看到这里。并且将当前线程设置成了主线程。我们在这个fork出来的新进程中还没有创建其他线程,这个Activity也是该App启动的第一个Activity,所以这个Activity就是在主线程中运行的。
4、回到performLaunchActivity方法,调用了Instrumentation的callActivityOnCreate()方法。

Instrumentation.java
public void callActivityOnCreate(Activity activity, Bundle icicle) {
    prePerformCreate(activity);
    activity.performCreate(icicle);
    postPerformCreate(activity);
}

调用了Activity类的performCreate()方法。

Activity.java
final void performCreate(Bundle icicle) {
    performCreate(icicle, null);
}

调用performCreate()方法。

final void performCreate(Bundle icicle, PersistableBundle persistentState) {
    dispatchActivityPreCreated(icicle);
    mCanEnterPictureInPicture = true;
    restoreHasCurrentPermissionRequest(icicle);
    if (persistentState != null) {diao
        onCreate(icicle, persistentState);
    } else {
        onCreate(icicle);
    }
    ...
}

在这个方法里调用了Activity的onCreate方法。这个Activity是我们前面通过反射实例化的新的Activity,所以这也就调用了新Activity的OnCreate方法。现在通过跟进TransactionExecutor的executeCallbacks方法已经执行了生命周期中的onCreate方法。
总结一下这一部分,从新进程执行的第一个方法:ActivityThread的main()出发,通过LaunchActivityItem的execute()方法一步一步完成了新Activity生命周期的onCreate阶段,并在这个过程中,完成了PhoneWindow的创建,主线程Handler的创建等几个重要的流程。接下来,onCreate后该到onResume阶段了。

onResume阶段

回到TransactionExecutor的execute()方法中,接着顺序执行了executeLifecycleState方法,这个流程和pause是一样的,最终会执行到ResumeActivityItem的execute()方法。

ResumeActivityItem.java
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);
}

与onPause、onCreate类似,实际调用了ActivityThread的handleResumeActivity()方法。

ActivityThread.java
public void handleResumeActivity(IBinder token, boolean finalStateRequest, boolean isForward,
		String reason) {
	// If we are getting ready to gc after going to the background, well
	// we are back active so skip it.
	unscheduleGcIdler();
	mSomeActivitiesChanged = true;

	// TODO Push resumeArgs into the activity for consideration
	final ActivityClientRecord r = performResumeActivity(token, finalStateRequest, reason);
	if (r == null) {
		// We didn't actually resume the activity, so skipping any follow-up actions.
		return;
	}
	...
}

方法一开始调用performResumeActivity方法,这也是我们本次要关注的方法,下面其余的部分主要是进行了界面的显示逻辑,这也是为什么生命周期在执行到oncreate是不会显示界面,只有onResume执行完才能看到界面的原因。

ActivityThread.java
public ActivityClientRecord performResumeActivity(IBinder token, boolean finalStateRequest,
		String reason) {
	...
	try {
		r.activity.onStateNotSaved();
		r.activity.mFragments.noteStateNotSaved();
		checkAndBlockForNetworkAccess();
		...
		r.activity.performResume(r.startsNotResumed, reason);

		r.state = null;
		r.persistentState = null;
		r.setState(ON_RESUME);

		reportTopResumedActivityChanged(r, r.isTopResumedActivity, "topWhenResuming");
	} catch (Exception e) {
		...		+ r.intent.getComponent().toShortString() + ": " + e.toString(), e);
		}
	}
	return r;
}

调用了Activity类的performResume()方法。

Activity.java
final void performResume(boolean followedByPause, String reason) {
	dispatchActivityPreResumed();
	performRestart(true /* start */, reason);

	mFragments.execPendingActions();

	mLastNonConfigurationInstances = null;

	...

	mCalled = false;
	// mResumed is set by the instrumentation
	mInstrumentation.callActivityOnResume(this);
	...
}

调用了Instrumentation类的callActivityOnResume()方法。

Instrumentation.java
public void callActivityOnResume(Activity activity) {
    activity.mResumed = true;
    activity.onResume();
    
    if (mActivityMonitors != null) {
        synchronized (mSync) {
            final int N = mActivityMonitors.size();
            for (int i=0; i<N; i++) {
                final ActivityMonitor am = mActivityMonitors.get(i);
                am.match(activity, activity, activity.getIntent());
            }
        }
    }
}

最终调用了我们新的Activity的onResume方法。
至此,在桌面单击一个应用图标,从Launcher应用Activity执行onPause,到新应用进程的创建,新应用Application的创建,新应用Activity顺序执行OnCreate、OnResume生命周期的流程就走了一遍了。

时序图

最后附上一个时序图,图有一点大
在这里插入图片描述
这个图有点大,建议用电脑来看。整个流程中如果有错误的话欢迎大家指正。

标签:...,Android10.0,java,String,int,流程,Activity,null,final
来源: https://blog.csdn.net/songkai0825/article/details/111415462