Activity启动流程(基于Android 9.0)

最近基于SDK 28也就是9.0的源码跟了一边Activity的启动流程,发现每个版本都有点修改,边看边顺便做了个记录巩固一下,以后有时间会继续补充及修改。

Activity.java
首先调用Activity.java中的startActivity()方法

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

继续往下看

@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()

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

继续往下

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类中的execStartActivity()方法。进到Instrumentation类中,找到execStartActivity()方法。

public ActivityResult execStartActivity(
	Context who, IBinder contextThread, IBinder token, String target,
	Intent intent, int requestCode, Bundle options) {
	...
	try {
		intent.migrateExtraStreamToClipData();
		intent.prepareToLeaveProcess(who);
		int result = ActivityManager.getService()
			.startActivity(whoThread, who.getBasePackageName(), intent,
					intent.resolveTypeIfNeeded(who.getContentResolver()),
					token, target, requestCode, 0, null, options);
		checkStartActivityResult(result, intent);
	} catch (RemoteException e) {
		throw new RuntimeException("Failure from system", e);
	}
	return null;
}

在第11行调用了ActivityManager.getService()的startActivity()。进到getService()中,发现返回的是一个IActivityManager类型。

public static IActivityManager getService() {
	return IActivityManagerSingleton.get();
}

进到IActivityManagerSingleton。

private static final Singleton<IActivityManager> IActivityManagerSingleton =
		new Singleton<IActivityManager>() {
	@Override
	protected IActivityManager create() {
		final IBinder b = ServiceManager.getService(Context.ACTIVITY_SERVICE);
		final IActivityManager am = IActivityManager.Stub.asInterface(b);
		return am;
	}
};

发现需要找到Singleton这个类,翻到ActivityManager类的最上面,看到这行话。
import android.util.Singleton;
直接在SDK的目录下找到这个类:Android\Sdk\sources\android-xx\android\util\Singleton.java

public abstract class Singleton<T> {
    private T mInstance;

    protected abstract T create();

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

这里泛型传入的是IActivityManager,回到上面IActivityManagerSingleton.get(),调用的是get()方法,其实返回就是mInstance,也是IActivityManager类型的。而且creat()方法中返回的am是通过
IActivityManager.Stub.asInterface()创建出来的,这不就是Binder吗。这就说明,以后通过getService()调用的方法其实都是在服务端执行的。
我们回到Instrumentation类中的execStartActivity方法。现在知道了,在第12行调用的这个startActivity()方法最终是会在服务端执行的。这个方法的实现其实是在ActivityManagerService类中的。果然发现这个类继承了IActivityManager。在ActivityManagerService中找到startActivity()。
//切换到AMS所在进程

public class ActivityManagerService extends IActivityManager.Stub
		implements Watchdog.Monitor, BatteryStatsImpl.BatteryCallback {
		...
		@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());
		}
		...
}

一直往下走,进到startActivityAsUser()。

public final 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("startActivity");

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

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

}

开始是做一些权限的检查,最后会调用ActivityStart类中的execute()方法。注意倒数第二个setMayWait(userId),发现只要调用了,mRequest.mayWait就会被设为true。

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

	return this;
}

继续进到ActivityStart.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()方法中。

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");
	}
	mSupervisor.getActivityMetricsLogger().notifyActivityLaunching();
	boolean componentSpecified = intent.getComponent() != null;

	final int realCallingPid = Binder.getCallingPid();
	final int realCallingUid = Binder.getCallingUid();

	int callingPid;
	if (callingUid >= 0) {
		callingPid = -1;
	} else if (caller == null) {
		callingPid = realCallingPid;
		callingUid = realCallingUid;
	} else {
		callingPid = callingUid = -1;
	}
	...
	synchronized (mService) {
		final ActivityStack stack = mSupervisor.mFocusedStack;
		stack.mConfigWillChange = globalConfig != null
				&& mService.getGlobalConfiguration().diff(globalConfig) != 0;
		if (DEBUG_CONFIGURATION) Slog.v(TAG_CONFIGURATION,
				"Starting activity when config will change = " + stack.mConfigWillChange);

		final long origId = Binder.clearCallingIdentity();
		...
		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()方法。

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

	if (TextUtils.isEmpty(reason)) {
		throw new IllegalArgumentException("Need to specify a reason.");
	}
	mLastStartReason = reason;
	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()方法。

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) {
	int err = ActivityManager.START_SUCCESS;
	// Pull the optional Ephemeral Installer-only bundle out of the options early.
	final Bundle verificationBundle
			= options != null ? options.popAppVerificationBundle() : null;
	...
	ActivityRecord r = new ActivityRecord(mService, callerApp, callingPid, callingUid,
			callingPackage, intent, resolvedType, aInfo, mService.getGlobalConfiguration(),
			resultRecord, resultWho, requestCode, componentSpecified, voiceSession != null,
			mSupervisor, checkedOptions, sourceRecord);
	if (outActivity != null) {
		outActivity[0] = r;
	}

	if (r.appTimeTracker == null && sourceRecord != null) {
		// If the caller didn't specify an explicit time tracker, we want to continue
		// tracking under any it has.
		r.appTimeTracker = sourceRecord.appTimeTracker;
	}
	...
	return startActivity(r, sourceRecord, voiceSession, voiceInteractor, startFlags,
			true /* doResume */, checkedOptions, inTask, outActivity);
}

中间省略了无数代码,发现最后还是调用的startActivity()方法。

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()方法。

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

	setInitialState(r, options, inTask, doResume, startFlags, sourceRecord, voiceSession,
			voiceInteractor);

	computeLaunchingTaskFlags();

	computeSourceStack();

	mIntent.setFlags(mLaunchFlags);

	ActivityRecord reusedActivity = getReusableIntentActivity();
	...
	// Should this be considered a new task?
	int result = START_SUCCESS;
	if (mStartActivity.resultTo == null && mInTask == null && !mAddingToTask
			&& (mLaunchFlags & FLAG_ACTIVITY_NEW_TASK) != 0) {
		newTask = true;
		result = setTaskFromReuseOrCreateNewTask(taskToAffiliate, topStack);
	} else if (mSourceRecord != null) {
		result = setTaskFromSourceRecord();
	} else if (mInTask != null) {
		result = setTaskFromInTask();
	} else {
		// This not being started from an existing activity, and not part of a new task...
		// just put it in the top task, though these days this case should never happen.
		setTaskToCurrentTopOrCreateNewTask();
	}
	...
	if (mDoResume) {
		final ActivityRecord topTaskActivity =
				mStartActivity.getTask().topRunningActivityLocked();
		if (!mTargetStack.isFocusable()
				|| (topTaskActivity != null && topTaskActivity.mTaskOverlay
				&& mStartActivity != topTaskActivity)) {
				...
		} else {
			// If the target stack was not previously focusable (previous top running activity
			// on that stack was not visible) then any prior calls to move the stack to the
			// will not update the focused stack.  If starting the new activity now allows the
			// task stack to be focusable, then ensure that we now update the focused stack
			// accordingly.
			if (mTargetStack.isFocusable() && !mSupervisor.isFocusedStack(mTargetStack)) {
				mTargetStack.moveToFront("startActivityUnchecked");
			}
			mSupervisor.resumeFocusedStackTopActivityLocked(mTargetStack, mStartActivity,
					mOptions);
		}
	} else if (mStartActivity != null) {
		mSupervisor.mRecentTasks.add(mStartActivity.getTask());
	}
	mSupervisor.updateUserStackLocked(mStartActivity.userId, mTargetStack);

	mSupervisor.handleNonResizableTaskIfNeeded(mStartActivity.getTask(), preferredWindowingMode,
			preferredLaunchDisplayId, mTargetStack);

	return START_SUCCESS;
}

进到resumeFocusedStackTopActivityLocked()方法中

boolean resumeFocusedStackTopActivityLocked(
		ActivityStack targetStack, ActivityRecord target, ActivityOptions targetOptions) {

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

	if (targetStack != null && isFocusedStack(targetStack)) {
		return targetStack.resumeTopActivityUncheckedLocked(target, targetOptions);
	}

	final ActivityRecord r = mFocusedStack.topRunningActivityLocked();
	if (r == null || !r.isState(RESUMED)) {
		mFocusedStack.resumeTopActivityUncheckedLocked(null, null);
	} else if (r.isState(RESUMED)) {
		// Kick off any lingering app transitions form the MoveTaskToFront operation.
		mFocusedStack.executeAppTransition(targetOptions);
	}

	return false;
}

调用resumeTopActivityUncheckedLocked()方法。

@GuardedBy("mService")
boolean resumeTopActivityUncheckedLocked(ActivityRecord prev, ActivityOptions options) {
	if (mStackSupervisor.inResumeTopActivity) {
		// Don't even start recursing.
		return false;
	}

	boolean result = false;
	try {
		// Protect against recursion.
		mStackSupervisor.inResumeTopActivity = true;
		result = resumeTopActivityInnerLocked(prev, options);
		...
	} finally {
		mStackSupervisor.inResumeTopActivity = false;
	}

	return result;
}

调用resumeTopActivityInnerLocked()。

@GuardedBy("mService")
private boolean resumeTopActivityInnerLocked(ActivityRecord prev, ActivityOptions options) {
	...
	//启动新Activity前,先暂停当前Activity
	boolean pausing = mStackSupervisor.pauseBackStacks(userLeaving, next, false);
	if (mResumedActivity != null) {
		if (DEBUG_STATES) Slog.d(TAG_STATES,
				"resumeTopActivityLocked: Pausing " + mResumedActivity);
		pausing |= startPausingLocked(userLeaving, false, next, false);
	}
	if (pausing && !resumeWhilePausing) {
		...
		return true;
	} else if (mResumedActivity == next && next.isState(RESUMED)
		...
		return true;
	}
	...
	mStackSupervisor.mNoAnimActivities.clear();

	ActivityStack lastStack = mStackSupervisor.getLastStack();
	if (next.app != null && next.app.thread != null) {
		...
	} else {
		// Whoops, need to restart this activity!
		if (!next.hasBeenLaunched) {
			next.hasBeenLaunched = true;
		} else {
			if (SHOW_APP_STARTING_PREVIEW) {
				next.showStartingWindow(null /* prev */, false /* newTask */,
						false /* taskSwich */);
			}
			if (DEBUG_SWITCH) Slog.v(TAG_SWITCH, "Restarting: " + next);
		}
		if (DEBUG_STATES) Slog.d(TAG_STATES, "resumeTopActivityLocked: Restarting " + next);
		mStackSupervisor.startSpecificActivityLocked(next, true, true);
	}

	if (DEBUG_STACK) mStackSupervisor.validateTopActivitiesLocked();
	return true;
}

执行ActivityStackSupervisor类中的startSpecificActivityLocked()方法。

void startSpecificActivityLocked(ActivityRecord r,
		boolean andResume, boolean checkConfig) {
	// Is this activity's application already running?
	//获取要调用Activity的进程,包括UID、进程名、UI主线程等
	ProcessRecord app = mService.getProcessRecordLocked(r.processName,
			r.info.applicationInfo.uid, true);

	getLaunchTimeTracker().setLaunchTime(r);

	if (app != null && app.thread != null) {
		try {
			if ((r.info.flags&ActivityInfo.FLAG_MULTIPROCESS) == 0
					|| !"android".equals(r.info.packageName)) {
				// Don't add this if it is a platform component that is marked
				// to run in multiple processes, because this is actually
				// part of the framework so doesn't make sense to track as a
				// separate apk in the process.
				app.addPackage(r.info.packageName, r.info.applicationInfo.longVersionCode,
						mService.mProcessStats);
			}
			realStartActivityLocked(r, app, andResume, checkConfig);
			return;
		} catch (RemoteException e) {
			Slog.w(TAG, "Exception when starting activity "
					+ r.intent.getComponent().flattenToShortString(), e);
		}

		// If a dead object exception was thrown -- fall through to
		// restart the application.
	}
	//fork出新进程
	mService.startProcessLocked(r.processName, r.info.applicationInfo, true, 0,
			"activity", r.intent.getComponent(), false, false, true);
}

调用realStartActivityLocked()。

final boolean realStartActivityLocked(ActivityRecord r, ProcessRecord app,
		boolean andResume, boolean checkConfig) throws RemoteException {

	if (!allPausedActivitiesComplete()) {
		// While there are activities pausing we skipping starting any new activities until
		// pauses are complete. NOTE: that we also do this for activities that are starting in
		// the paused state because they will first be resumed then paused on the client side.
		if (DEBUG_SWITCH || DEBUG_PAUSE || DEBUG_STATES) Slog.v(TAG_PAUSE,
				"realStartActivityLocked: Skipping start of r=" + r
				+ " some activities pausing...");
		return false;
	}

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

	beginDeferResume();

	try {
		...
		try {
			...
			// Schedule transaction.
			mService.getLifecycleManager().scheduleTransaction(clientTransaction);
			...
		} catch (RemoteException e) {
			if (r.launchFailed) {
				// This is the second time we failed -- finish activity
				// and give up.
				Slog.e(TAG, "Second failure launching "
						+ r.intent.getComponent().flattenToShortString()
						+ ", giving up", e);
				mService.appDiedLocked(app);
				stack.requestFinishActivityLocked(r.appToken, Activity.RESULT_CANCELED, null,
						"2nd-crash", false);
				return false;
			}

			// This is the first time we failed -- restart process and
			// retry.
			r.launchFailed = true;
			app.activities.remove(r);
			throw e;
		}
	} finally {
		endDeferResume();
	}
	...
	return true;
}

调用scheduleTransaction()

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();
	}
}

发现调用了transaction.schedule(),这个transaction是一个ClientTransaction类型的,在Android Studio中找不到,继续去sdk中的源码目录中找。

public class ClientTransaction implements Parcelable, ObjectPoolItem {
	...
	private IApplicationThread mClient;
	...
	public void schedule() throws RemoteException {
           mClient.scheduleTransaction(this);
    }
	...
}

其中IApplicationThread作为AMS进程与应用进程交互的接口,IApplicationThread的实现类是ApplicationThread,ApplicationThread又是ActivityThread的一个内部类。

private class ApplicationThread extends IApplicationThread.Stub {
	...
	@Override
	public void scheduleTransaction(ClientTransaction transaction) throws RemoteException {
		ActivityThread.this.scheduleTransaction(transaction);
	}
}

所以mClient.scheduleTransaction(this)其实是调用了ApplicationThread中scheduleTransaction()方法。因为ActivityThread是继承了ClientTransactionHandler类的,所以ActivityThread.this.scheduleTransaction(transaction)的实现是在ClientTransactionHandler()类中。

void scheduleTransaction(ClientTransaction transaction) {
	transaction.preExecute(this);
	sendMessage(ActivityThread.H.EXECUTE_TRANSACTION, transaction);
}
abstract void sendMessage(int what, Object obj);
ClientTransactionHandler类的sendMessage()是一个抽象函数,实现在ActivityThread类中。
```javascript
private void sendMessage(int what, Object obj, int arg1) {
	sendMessage(what, obj, arg1, 0, false);
}

继续调用sendMessage()

private void sendMessage(int what, Object obj, int arg1, int arg2, boolean async) {
	if (DEBUG_MESSAGES) Slog.v(
		TAG, "SCHEDULE " + what + " " + mH.codeToString(what)
		+ ": " + arg1 + " / " + obj);
	Message msg = Message.obtain();
	msg.what = what;
	msg.obj = obj;
	msg.arg1 = arg1;
	msg.arg2 = arg2;
	if (async) {
		msg.setAsynchronous(true);
	}
	mH.sendMessage(msg);
}

最后会调用mH的sendMessage()方法。

final H mH = new H();
class H extends Handler {
	...
	public void handleMessage(Message msg) {
		if (DEBUG_MESSAGES) Slog.v(TAG, ">>> handling: " + codeToString(msg.what));
		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;
			case RELAUNCH_ACTIVITY:
				handleRelaunchActivityLocally((IBinder) msg.obj);
				break;
		}
		...
	}
}

mH是H类型的,H类是ActivityThread的内部类。这就是一个Handle的过程,调用mH.sendMessage(msg),会在H类的handleMessage()方法中进行处理。回到前面的scheduleTransaction()方法,发现sendMessage中,传入的第一个参数也就是msg.what是ActivityThread.H.EXECUTE_TRANSACTION,所以在H的handleMessage()中,会执行EXECUTE_TRANSACTION这个case,在case中会接着会调用
mTransactionExecutor.execute(transaction)。其中mTransactionExecutor是TransactionExecutor类型的,进到TransactionExecutor类中,找到execute()方法。

public void execute(ClientTransaction transaction) {
	final IBinder token = transaction.getActivityToken();
	log("Start resolving transaction for client: " + mTransactionHandler + ", token: " + token);

	executeCallbacks(transaction);

	executeLifecycleState(transaction);
	mPendingActions.clear();
	log("End resolving transaction");
}

调用executeCallbacks()方法

@VisibleForTesting
public void executeCallbacks(ClientTransaction transaction) {
	final List<ClientTransactionItem> callbacks = transaction.getCallbacks();
	...
	final int size = callbacks.size();
	for (int i = 0; i < size; ++i) {
		final ClientTransactionItem item = callbacks.get(i);
		...
		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);
		}
		...
	}
}

调用了item.execute()方法,其实是执行了LaunchActivityItem中的execute()方法。进到LaunchActivityItem类中,找到execute()方法。

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

执行了ActivityThread类中的handleLaunchActivity()方法,回到ActivityThread类。

@Override
public Activity handleLaunchActivity(ActivityClientRecord r,
		PendingTransactionActions pendingActions, Intent customIntent) {
	...
	final Activity a = performLaunchActivity(r, customIntent);
	...
	return a;
}

调用performLaunchActivity()

/**  Core implementation of activity launch. */
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) {
			...
			//初始化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);

			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;
			if (r.isPersistable()) {
				mInstrumentation.callActivityOnCreate(activity, r.state, r.persistentState);
			} else {
				mInstrumentation.callActivityOnCreate(activity, r.state);
			}
			...
		}
		r.setState(ON_CREATE);

		mActivities.put(r.token, r);

	} catch (SuperNotCalledException e) {
		throw e;

	} catch (Exception e) {
		...
	}

	return activity;
}

首先创建和初始化Activity和Application做准备工作。最后会调用mInstrumentation.callActivityOnCreate()。也就是Instrumentation类中的callActivityOnCreate()方法。

public void callActivityOnCreate(Activity activity, Bundle icicle,
		PersistableBundle persistentState) {
	prePerformCreate(activity);
	activity.performCreate(icicle, persistentState);
	postPerformCreate(activity);
}
会调用Activity类中的performCreate()方法。
```javascript
final void performCreate(Bundle icicle, PersistableBundle persistentState) {
	mCanEnterPictureInPicture = true;
	restoreHasCurrentPermissionRequest(icicle);
	if (persistentState != null) {
		onCreate(icicle, persistentState);
	} else {
		onCreate(icicle);
	}
	writeEventLog(LOG_AM_ON_CREATE_CALLED, "performCreate");
	mActivityTransitionState.readState(icicle);

	mVisibleFromClient = !mWindow.getWindowStyle().getBoolean(
			com.android.internal.R.styleable.Window_windowNoDisplay, false);
	mFragments.dispatchActivityCreated();
	mActivityTransitionState.setEnterActivityOptions(this, getActivityOptions());
}

最终,终于调用到了新Activity的onCreate()方法。
以上就是从一个应用发出startActivity请求到新的应用调用onCreate()的大体流程。
如有什么错误或误导人的地方还请大家指出。

发布了10 篇原创文章 · 获赞 19 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/songkai0825/article/details/100717326