共计 24912 个字符,预计需要花费 63 分钟才能阅读完成。
前言
最近在阅读 Android 源码时,发现最新的 Android9.0 源码中 startActivity 启动 Activity 的流程相比于低版本的 Android 源码来说改动较大,且本人在网上也没有找到基于 Android9.0 的相关源码分析文章。故写下此文,记录下源码追踪流程,方便以后自己复查,同时也分享给有需要的读者。
Activity->startActivity
@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->startActivityForResult
public void startActivityForResult(@RequiresPermission Intent intent, int requestCode,
@Nullable Bundle options) {
// mParent 指的是 Activity 赋值是在内部 API 调用 setParent 方法
if (mParent == null) {options = transferSpringboardActivityOptions(options);
//Instrumentation 为工具类 ActivityResult 为其静态内部类 工具类调用执行开始 Activity 方法 execStartActity
//mMainThread 为 ActivityThread,getApplicationThread() 方法获取的是 ApplicationThread 实例
//ApplicationThread 是 ActivityThread 的内部类 该类继承 ApplicationThreadNative 抽象类,// 而 ApplicationThreadNative 继承 Binder 类并实现 IApplicationThread 接口
//IApplictionThread 继承了 IInterface 接口
//Binder 类继承 IBinder 接口,这就是为什么 execStartActivity 方法的第二个参数定义为 IBinder
Instrumentation.ActivityResult ar =
mInstrumentation.execStartActivity(this, mMainThread.getApplicationThread(), mToken, this,
intent, requestCode, options);
if (ar != null) {
// ar 不为空说明 Activity 启动成功
mMainThread.sendActivityResult(mToken, mEmbeddedID, requestCode, ar.getResultCode(),
ar.getResultData());
}
if (requestCode >= 0) {mStartedActivity = true;}
cancelInputsAndStartExitTransition(options);
} else {if (options != null) {mParent.startActivityFromChild(this, intent, requestCode, options);
} else {
// Note we want to go through this method for compatibility with
// existing applications that may have overridden it.
mParent.startActivityFromChild(this, intent, requestCode);
}
}
}
调用了 mInstrumentation.execStartActivity 方法
Instrumentation->execStartActivity
public ActivityResult execStartActivity(
Context who, IBinder contextThread, IBinder token, String target,
Intent intent, int requestCode, Bundle options) {IApplicationThread whoThread = (IApplicationThread) contextThread;
if (mActivityMonitors != null) {synchronized (mSync) {final int N = mActivityMonitors.size();
for (int i=0; i<N; i++) {
//ActivityMonitor 为 Activity 的监测器是 Instrumentation 的静态内部类,// 当一个 Activity 启动时将会被检测
final ActivityMonitor am = mActivityMonitors.get(i);
ActivityResult result = null;
if (am.ignoreMatchingSpecificIntents()) {result = am.onStartActivity(intent);
}
if (result != null) {
am.mHits++;
return result;
} else if (am.match(who, null, intent)) {
am.mHits++;
if (am.isBlocking()) {return requestCode >= 0 ? am.getResult() : null;
}
break;
}
}
}
}
try {intent.migrateExtraStreamToClipData();
intent.prepareToLeaveProcess(who);
// result 为启动 Activity 返回的状态码
// 这里通过 IPC 机制,调用了 ActivityManagerService 中的 startActivity 方法
int result = ActivityManager.getService()
.startActivity(whoThread, who.getBasePackageName(), intent,
intent.resolveTypeIfNeeded(who.getContentResolver()),
token, target, requestCode, 0, null, options);
// 检查 Activity 是否启动成功若未启动成功则抛出对应异常
checkStartActivityResult(result, intent);
} catch (RemoteException e) {throw new RuntimeException("Failure from system", e);
}
return null;
}
可以看到,这个方法最后是调用了 ActivityManager.getService().startActivity() 方法。
查看 ActivityManager 源码
ActivityManager->getService
public static IActivityManager getService() {return IActivityManagerSingleton.get();
}
private static final Singleton<IActivityManager> IActivityManagerSingleton =
new Singleton<IActivityManager>() {
@Override
protected IActivityManager create() {
// 通过 Binder 机制获取 ActivityManagerService
final IBinder b = ServiceManager.getService(Context.ACTIVITY_SERVICE);
final IActivityManager am = IActivityManager.Stub.asInterface(b);
return am;
}
};
这里是通过 Binder 的跨进程通信获取到了系统服务 ActivityManagerService,所以 ActivityManager.getService().startActivity() 是调用了 ActivityManagerService 中的 startActivity 方法。
ActivityManagerService->startActivity
@Override
public final int startActivity(IApplicationThread caller, String callingPackage,
Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
int startFlags, ProfilerInfo profilerInfo, Bundle bOptions) {
return startActivityAsUser(caller, callingPackage, intent, resolvedType, resultTo,
resultWho, requestCode, startFlags, profilerInfo, bOptions,
UserHandle.getCallingUserId());
}
@Override
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) {
return startActivityAsUser(caller, callingPackage, intent, resolvedType, resultTo,
resultWho, requestCode, startFlags, profilerInfo, bOptions, userId,
true /*validateIncomingUser*/);
}
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.
// 通过 mActivityStartController 获取 ActivityStarter,进行后续页面跳转
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();}
这里最后通过 mActivityStartController.obtainStarter 获取到了一个 ActivityStarter 对象,然后设置了一些属性,最后调用了 execute() 方法。所以流程走到 ActivityStarter 中的 execute() 方法。
ActivityStarter->execute
int execute() {
try {// TODO(b/64750076): Look into passing request directly to these methods to allow
// for transactional diffs and preprocessing.
// ActivityManagerService 中的 startActivityAsUser 方法中调用了 setMayWait 方法
// setMayWait 方法会将 mRequest.mayWait 置为 true,所以这里会走 startActivityMayWait 方法
// ActivityStarter setMayWait(int userId) {
// mRequest.mayWait = true;
// mRequest.userId = userId;
//
// return this;
// }
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 {
return startActivity(mRequest.caller, mRequest.intent, mRequest.ephemeralIntent,
mRequest.resolvedType, mRequest.activityInfo, mRequest.resolveInfo,
mRequest.voiceSession, mRequest.voiceInteractor, mRequest.resultTo,
mRequest.resultWho, mRequest.requestCode, mRequest.callingPid,
mRequest.callingUid, mRequest.callingPackage, mRequest.realCallingPid,
mRequest.realCallingUid, mRequest.startFlags, mRequest.activityOptions,
mRequest.ignoreTargetSecurity, mRequest.componentSpecified,
mRequest.outActivity, mRequest.inTask, mRequest.reason,
mRequest.allowPendingRemoteAnimationRegistryLookup);
}
} finally {onExecutionComplete();
}
}
查看 setMayWait 方法
ActivityStarter setMayWait(int userId) {
mRequest.mayWait = true;
mRequest.userId = userId;
return this;
}
ActivityManagerService 中的 startActivityAsUser 方法中调用了 setMayWait 方法。setMayWait 方法会将 mRequest.mayWait 置为 true,所以这里会走 startActivityMayWait 方法
ActivityStarter->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) {
... 略
// Collect information about the target of the Intent.
// 对 Intent 参数进行解析获取 Activity 的相关信息,并把数据保存在 aInfo 变量中
ActivityInfo aInfo = mSupervisor.resolveActivity(intent, rInfo, startFlags, profilerInfo);
synchronized (mService) {
... 略
final ActivityRecord[] outRecord = new ActivityRecord[1];
// 调用 ActivityStarter 的 startActivity 方法
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);
.... 略
// 通知跟踪器 Activity 正在启动
mSupervisor.getActivityMetricsLogger().notifyActivityLaunched(res, outRecord[0]);
return res;
}
}
调用 ActivityStarter 的 startActivity 方法
ActivityStarter->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) {
... 一些必要的判断...
// 检查是否有开启新 Activity 的权限
boolean abort = !mSupervisor.checkStartAnyActivityPermission(intent, aInfo, resultWho,
requestCode, callingPid, callingUid, callingPackage, ignoreTargetSecurity,
inTask != null, callerApp, resultRecord, resultStack);
abort |= !mService.mIntentFirewall.checkStartActivity(intent, callingUid,
callingPid, resolvedType, aInfo.applicationInfo);
...
// 如果我们开始的活动与当前恢复的活动的 UID 不同,检查是否允许应用程序切换。if (voiceSession == null && (stack.getResumedActivity() == null
|| stack.getResumedActivity().info.applicationInfo.uid != realCallingUid)) {
if (!mService.checkAppSwitchAllowedLocked(callingPid, callingUid,
realCallingPid, realCallingUid, "Activity start")) {
mController.addPendingActivityLaunch(new PendingActivityLaunch(r,
sourceRecord, startFlags, stack, callerApp));
ActivityOptions.abort(checkedOptions);
return ActivityManager.START_SWITCHES_CANCELED;
}
}
// 加载 PendingActivity
mController.doPendingActivityLaunches(false);
// 继续调用方法
return startActivity(r, sourceRecord, voiceSession, voiceInteractor, startFlags,
true /* doResume */, checkedOptions, inTask, outActivity);
}
继续调用同名方法 startActivity
ActivityStarter->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();
// 调用 startActivityUnchecked 方法,返回结果
result = startActivityUnchecked(r, sourceRecord, voiceSession, voiceInteractor,
startFlags, doResume, options, inTask, outActivity);
} finally {
// 如果我们无法继续,请解除活动与任务的关联。使活动处于不完整状态可能会导致问题,例如在没有窗口容器的情况下执行操作。final ActivityStack stack = mStartActivity.getStack();
if (!ActivityManager.isStartResultSuccessful(result) && stack != null) {
stack.finishActivityLocked(mStartActivity, RESULT_CANCELED,
null /* intentResultData */, "startActivity", true /* oomAdj */);
}
mService.mWindowManager.continueSurfaceLayout();}
postStartActivityProcessing(r, result, mTargetStack);
return result;
}
调用 startActivityUnchecked 方法
ActivityStarter->startActivityUnchecked
private int startActivityUnchecked(final ActivityRecord r, ActivityRecord sourceRecord,
IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor,
int startFlags, boolean doResume, ActivityOptions options, TaskRecord inTask,
ActivityRecord[] outActivity) {
// 初始化 ActivityStarter 全局变量
setInitialState(r, options, inTask, doResume, startFlags, sourceRecord, voiceSession,
voiceInteractor);
computeLaunchingTaskFlags();
computeSourceStack();
mIntent.setFlags(mLaunchFlags);
// 判断是否应将新 Activity 插入到现有任务栈中
// 如果不需要,则返回 null,如果需要,则返回该任务栈信息
ActivityRecord reusedActivity = getReusableIntentActivity();
......
// 使新 Activity 可见
if (mDoResume) {
final ActivityRecord topTaskActivity =
mStartActivity.getTask().topRunningActivityLocked();
if (!mTargetStack.isFocusable()
|| (topTaskActivity != null && topTaskActivity.mTaskOverlay
&& mStartActivity != topTaskActivity)) {mTargetStack.ensureActivitiesVisibleLocked(null, 0, !PRESERVE_WINDOWS);
mService.mWindowManager.executeAppTransition();} else {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;
}
这里需要关注的是 mSupervisor.resumeFocusedStackTopActivityLocked 方法
ActivityStackSupervisor->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 方法
ActivityStackSupervisor->resumeTopActivityUncheckedLocked
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);
// 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 {mStackSupervisor.inResumeTopActivity = false;}
return result;
}
这里调用了 resumeTopActivityInnerLocked 方法,resumeTopActivityInnerLocked 方法中会调用 startSpecificActivityLocked 方法,然后再调用 realStartActivityLocked 方法。Activity 的启动事务就是在 realStartActivityLocked 方法中启动的。
ActivityStackSupervisor->realStartActivityLocked
final boolean realStartActivityLocked(ActivityRecord r, ProcessRecord app,
boolean andResume, boolean checkConfig) throws RemoteException {
......
try {
......
// Create activity launch transaction.
// 创建 Activity 启动事务
// ClientTransaction.obtain 方法如下:// 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;
// }
// 这里传入的 app.thread 会赋值给 ClientTransaction 的成员变量 mClient,// 而 ClientTransaction 会调用 mClient.scheduleTransaction(this) 来执行事务
// 所以事务最终是调用 app.thread 的 scheduleTransaction 执行。// 而这个 app.thread 是 ActivityThread 的内部类 ApplicationThread。final ClientTransaction clientTransaction = ClientTransaction.obtain(app.thread,
r.appToken);
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, app.repProcState, r.icicle,
r.persistentState, results, newIntents, mService.isNextTransitionForward(),
profilerInfo));
// Set desired final state.
final ActivityLifecycleItem lifecycleItem;
if (andResume) {lifecycleItem = ResumeActivityItem.obtain(mService.isNextTransitionForward());
} else {lifecycleItem = PauseActivityItem.obtain();
}
clientTransaction.setLifecycleStateRequest(lifecycleItem);
// Schedule transaction.
// 执行 Activity 启动事务
mService.getLifecycleManager().scheduleTransaction(clientTransaction);
......
} catch (RemoteException e) {if (r.launchFailed) {
// 第二次启动失败的异常处理
return false;
}
// 第一次启动失败,重试
r.launchFailed = true;
app.activities.remove(r);
throw e;
}
} finally {endDeferResume();
}
......
return true;
}
方法中需要关注的部分已经用注释说明了,在 realStartActivityLocked 中最主要的工作就是创建了 Activity 的启动事务 ClientTransaction,并调用 ClientLifecycleManager 的 scheduleTransaction 方法启动它。接下来,看 ClientTransaction 事务中是怎么启动 Activity 的。
ClientLifecycleManager->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();}
}
调用 ClientTransaction 的 schedule 方法
public void schedule() throws RemoteException {mClient.scheduleTransaction(this);
}
这里调用了 mClient 的 scheduleTransaction 方法,那么这里的 mClient 是从哪来的呢。很容易想到,是在创建 ClientTransaction 事务对象的时候赋值的,也就是调用 obtain 方法时。
ClientTransaction->obtain
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;
}
我们回到 ActivityStackSupervisor 的 realStartActivityLocked 方法
ActivityStackSupervisor->realStartActivityLocked
final boolean realStartActivityLocked(ActivityRecord r, ProcessRecord app,
boolean andResume, boolean checkConfig) throws RemoteException {
......
try {
......
// Create activity launch transaction.
// 创建 Activity 启动事务
// ClientTransaction.obtain 方法如下:// 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;
// }
// 这里传入的 app.thread 会赋值给 ClientTransaction 的成员变量 mClient,// 而 ClientTransaction 会调用 mClient.scheduleTransaction(this) 来执行事务
// 所以事务最终是调用 app.thread 的 scheduleTransaction 执行。// 而这个 app.thread 是 ActivityThread 的内部类 ApplicationThread。final ClientTransaction clientTransaction = ClientTransaction.obtain(app.thread,
r.appToken);
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, app.repProcState, r.icicle,
r.persistentState, results, newIntents, mService.isNextTransitionForward(),
profilerInfo));
// Set desired final state.
final ActivityLifecycleItem lifecycleItem;
if (andResume) {lifecycleItem = ResumeActivityItem.obtain(mService.isNextTransitionForward());
} else {lifecycleItem = PauseActivityItem.obtain();
}
clientTransaction.setLifecycleStateRequest(lifecycleItem);
// Schedule transaction.
// 执行 Activity 启动事务
mService.getLifecycleManager().scheduleTransaction(clientTransaction);
......
} catch (RemoteException e) {if (r.launchFailed) {
// 第二次启动失败的异常处理
return false;
}
// 第一次启动失败,重试
r.launchFailed = true;
app.activities.remove(r);
throw e;
}
} finally {endDeferResume();
}
......
return true;
}
可以看到,赋值给 mClient 的是 app.thread,所以事务最终是调用的 app.thread 的 scheduleTransaction 方法来执行,而这个 app.thread 是 ActivityThread 的内部类 ApplicationThread。所以流程转到了 ActivityThread 的内部类 ApplicationThread 中。
ActivityThread->ApplicationThread->scheduleTransaction
@Override
public void scheduleTransaction(ClientTransaction transaction) throws RemoteException {ActivityThread.this.scheduleTransaction(transaction);
}
这里还是调用了 ActivityThread 的 scheduleTransaction 方法。但是在查看 ActivityThread 类就会发现 ActivityThread 类中并没有 scheduleTransaction 这个方法。因此自然会想到很可能是继承的父类中的方法。ActivityThread 继承的是 ClientTransactionHandler 类。到 ClientTransactionHandler 类中一查,果然发现了 scheduleTransaction 方法。所以这里最终调用的就是 ClientTransactionHandler 中的 scheduleTransaction 方法。
ClientTransactionHandler->scheduleTransaction
void scheduleTransaction(ClientTransaction transaction) {transaction.preExecute(this);
sendMessage(ActivityThread.H.EXECUTE_TRANSACTION, transaction);
}
这里调用了 sendMessage 方法,而 sendMessage 是一个抽象方法,所以这里调用的是 ActivityThread 类中的 sendMessage 实现。
ActivityThread->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);
}
这里就是生成了一个 Message 对象,并向 mH 这个 Handler 发送该消息。所以这里 mH 将会接受到一个 what 为 ActivityThread.H.EXECUTE_TRANSACTION 的消息。去查看 Handler 中对 EXECUTE_TRANSACTION 消息的处理。
ActivityThread->H->handleMessage
case EXECUTE_TRANSACTION:
final ClientTransaction transaction = (ClientTransaction) msg.obj;
// 调用 TransactionExecutor 的 execute 方法
mTransactionExecutor.execute(transaction);
if (isSystem()) {
// Client transactions inside system process are recycled on the client side
// instead of ClientLifecycleManager to avoid being cleared before this
// message is handled.
transaction.recycle();}
// TODO(lifecycler): Recycle locally scheduled transactions.
break;
这里调用了 TransactionExecutor 的 execute 方法
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 和 executeLifecycleState 两个方法,查看两个方法就会发现,这两个方法最后都会调用 cycleToPath 这个方法。
TransactionExecutor->cycleToPath
private void cycleToPath(ActivityClientRecord r, int finish,
boolean excludeLastState) {final int start = r.getLifecycleState();
log("Cycle from:" + start + "to:" + finish + "excludeLastState:" + excludeLastState);
final IntArray path = mHelper.getLifecyclePath(start, finish, excludeLastState);
performLifecycleSequence(r, path);
}
TransactionExecutor->performLifecycleSequence
private void performLifecycleSequence(ActivityClientRecord r, IntArray path) {final int size = path.size();
for (int i = 0, state; i < size; i++) {state = path.get(i);
log("Transitioning to state:" + state);
switch (state) {
case ON_CREATE:
mTransactionHandler.handleLaunchActivity(r, mPendingActions,
null /* customIntent */);
break;
case ON_START:
mTransactionHandler.handleStartActivity(r, mPendingActions);
break;
case ON_RESUME:
mTransactionHandler.handleResumeActivity(r.token, false /* finalStateRequest */,
r.isForward, "LIFECYCLER_RESUME_ACTIVITY");
break;
case ON_PAUSE:
mTransactionHandler.handlePauseActivity(r.token, false /* finished */,
false /* userLeaving */, 0 /* configChanges */, mPendingActions,
"LIFECYCLER_PAUSE_ACTIVITY");
break;
case ON_STOP:
mTransactionHandler.handleStopActivity(r.token, false /* show */,
0 /* configChanges */, mPendingActions, false /* finalStateRequest */,
"LIFECYCLER_STOP_ACTIVITY");
break;
case ON_DESTROY:
mTransactionHandler.handleDestroyActivity(r.token, false /* finishing */,
0 /* configChanges */, false /* getNonConfigInstance */,
"performLifecycleSequence. cycling to:" + path.get(size - 1));
break;
case ON_RESTART:
mTransactionHandler.performRestartActivity(r.token, false /* start */);
break;
default:
throw new IllegalArgumentException("Unexpected lifecycle state:" + state);
}
}
}
看到这里就豁然开朗了,Activity 的生命周期就是在这里进行一个相关方法的调用。
这里的成员变量 mTransactionHandler 是一个 ClientTransactionHandler 对象,在 ClientTransactionHandler 中这些方法都是抽象方法,这里执行的是 ClientTransactionHandler 的实现类 ActivityThread 中的 handleLaunchActivity 方法。
ActivityThread->handleLaunchActivity
public Activity handleLaunchActivity(ActivityClientRecord r,
PendingTransactionActions pendingActions, Intent customIntent) {
// If we are getting ready to gc after going to the background, well
// we are back active so skip it.
unscheduleGcIdler();
mSomeActivitiesChanged = true;
if (r.profilerInfo != null) {mProfiler.setProfiler(r.profilerInfo);
mProfiler.startProfiling();}
// Make sure we are running with the most recent config.
handleConfigurationChanged(null, null);
if (localLOGV) Slog.v(TAG, "Handling launch of" + r);
// Initialize before creating the activity
if (!ThreadedRenderer.sRendererDisabled) {GraphicsEnvironment.earlyInitEGL();
}
// 创建 WindowManagerServer
WindowManagerGlobal.initialize();
// 通过反射创建指定的 Activity,并回调 Activity 的 performCreate 方法执行 onCreate
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 {
// If there was an error, for any reason, tell the activity manager to stop us.
try {ActivityManager.getService()
.finishActivity(r.token, Activity.RESULT_CANCELED, null,
Activity.DONT_FINISH_TASK_WITH_ACTIVITY);
} catch (RemoteException ex) {throw ex.rethrowFromSystemServer();
}
}
return a;
}
到这,Activity 的启动流程也就走完了。
可以看到,一个 startActivity 方法在源码中的处理是多么的复杂。如果我们不去阅读源码的话,根本不会对 Activity 的启动有一个更深层的理解。所以作为开发,保持一个阅读源码的习惯是非常重要的。
希望本文能对各位读者有一点帮助,也欢迎指出文章中的错误,谢谢大家。