前言
面试中经常会被问到,让面试者简述一下Activity的启动流程,这个问题是考察面试者对源码的理解程度的,熟悉源码对于解决日常开发过程中遇到的很多问题都有帮助,下面我们就开始通过源码来分析Activity的启动流程。
Activity启动流程分为两类:
- 根Activity的启动流程:即第一次点击桌面上某个应用图标到该应用的第一个Activity显示出来的流程,这种情况下,刚开始这个应用的进程还不存在,所以会涉及到应用的进程的创建过程。
- 普通Activity的启动流程:这种情况下应用的进程已经存在了,相当于点击该应用的第一个Activity的某个按钮后,跳转到第二个Activity的流程。
根Activity的启动流程更加复杂,根Activity的启动流程包含了普通Activity的启动流程。下面我们就先通过源码来分析普通Activity的启动流程,源码基于Android R(11.0)。
应用调起ATMS
一般我们使用以下代码来启动SecondActivity:
java
Intent intent = new Intent(this, SecondActivity.class);
this.startActivity(intent);
用起来很方便,但是里面究竟做了什么?下面我们就来一探究竟。
所有的startActivity()方法最终都会调用startActivityForResult()方法,代码如下:
java
public class Activity{
public void startActivityForResult(@RequiresPermission Intent intent, int requestCode,
@Nullable Bundle options) {
if (mParent == null) {
...
Instrumentation.ActivityResult ar =
mInstrumentation.execStartActivity(
this, mMainThread.getApplicationThread(), mToken, this,
intent, requestCode, options);
...
} else {
...
}
}
}
mParent表示当前Activity的父Activity,一般情况下mParent为null,此时调用了mInstrumentation的execStartActivity()方法。execStartActivity()方法其中一个参数是mMainThread.getApplicationThread(),它的类型是ApplicationThread,ApplicationThread是ActivityThread的内部类,继承IApplicationThread.Stub,是个Binder对象,在Activity的启动流程中有重要作用。
Instrumentation是用来监控系统与应用之间的交互的,跟进去看看execStartActivity()方法,代码如下:
java
public class Instrumentation {
public ActivityResult execStartActivity(
Context who, IBinder contextThread, IBinder token, Activity target,
Intent intent, int requestCode, Bundle options) {
...
try {
...
//使用ActivityTaskManager.getService()来获取ATMS的代理对象
int result = ActivityTaskManager.getService().startActivity(whoThread,
who.getBasePackageName(), who.getAttributionTag(), intent,
intent.resolveTypeIfNeeded(who.getContentResolver()), token,
target != null ? target.mEmbeddedID : null, requestCode, 0, null, options);
checkStartActivityResult(result, intent);
} catch (RemoteException e) {
throw new RuntimeException("Failure from system", e);
}
return null;
}
}
execStartActivity()方法会调用ActivityTaskManager的getService()方法来获取ActivityTaskManagerService的代理对象,然后调用这个代理对象的startActivity()方法。
java
public class ActivityTaskManager {
public static IActivityTaskManager getService() {
return IActivityTaskManagerSingleton.get();
}
@UnsupportedAppUsage(trackingBug = 129726065)
private static final Singleton<IActivityTaskManager> IActivityTaskManagerSingleton =
new Singleton<IActivityTaskManager>() {
@Override
protected IActivityTaskManager create() {
final IBinder b = ServiceManager.getService(Context.ACTIVITY_TASK_SERVICE);
return IActivityTaskManager.Stub.asInterface(b);
}
};
}
这里是一个单例模式,通过 ServiceManager
的getService()
方法获得系统服务,然后通过 IActivityTaskManager.Stub.asInterface
将其转换为具体的代理端对象,通过这个代理端对象我们就可以发起RPC调用了。
接下来发起远程调用 startActivity
,该远程调用在 aidl 文件中,定义如下:
java
// frameworks/base/core/java/android/app/IActivityTaskManager.aidl
int startActivity(in IApplicationThread caller, in String callingPackage,
in String callingFeatureId, in Intent intent, in String resolvedType,
in IBinder resultTo, in String resultWho, int requestCode,
int flags, in ProfilerInfo profilerInfo, in Bundle options);
ActivityTaskManagerService(ATMS)继承自IActivityTaskManager.Stub,ATMS是在Android10中新增的,分担了之前ActivityManagerService(AMS)的一部分功能,是用于管理Activity及其容器(task, stacks, displays,...)的系统服务,运行在SystemServer进程之中,与当前作为客户端的应用进程不在同一个进程。
ActivityTaskManager.getService().startActivity()有个返回值result,且调用了checkStartActivityResult(result, intent)对result进行检查:
java
public class Instrumentation {
public static void checkStartActivityResult(int res, Object intent) {
if (!ActivityManager.isStartResultFatalError(res)) {
return;
}
switch (res) {
case ActivityManager.START_INTENT_NOT_RESOLVED:
case ActivityManager.START_CLASS_NOT_FOUND:
if (intent instanceof Intent && ((Intent)intent).getComponent() != null)
throw new ActivityNotFoundException(
"Unable to find explicit activity class "
+ ((Intent)intent).getComponent().toShortString()
+ "; have you declared this activity in your AndroidManifest.xml?");
throw new ActivityNotFoundException(
"No Activity found to handle " + intent);
case ActivityManager.START_PERMISSION_DENIED:
throw new SecurityException("Not allowed to start activity "
+ intent);
...
default:
throw new AndroidRuntimeException("Unknown error code "
+ res + " when starting " + intent);
}
}
}
这是用来检查Activity启动的结果的,看到第一个case中就抛出了ActivityNotFoundException("have you declared this activity in your AndroidManifest.xml?"),如果Activity没有在Manifest中注册就会出现这个错误。
使用ATMS来管理Activity
通过上面的分析,启动流程跨进程进入到了ATMS中,调用了ATMS的startActivity()方法:
java
public class ActivityTaskManagerService extends IActivityTaskManager.Stub {
private ActivityStartController mActivityStartController;
@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());
}
@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*/);
}
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) {
assertPackageMatchesCallingUid(callingPackage);
enforceNotIsolatedCaller("startActivityAsUser");
userId = getActivityStartController().checkTargetUser(userId, validateIncomingUser,
Binder.getCallingPid(), Binder.getCallingUid(), "startActivityAsUser");
// TODO: Switch to user app stacks here.
return getActivityStartController().obtainStarter(intent, "startActivityAsUser")
.setCaller(caller)
.setCallingPackage(callingPackage)
.setCallingFeatureId(callingFeatureId)
.setResolvedType(resolvedType)
.setResultTo(resultTo)
.setResultWho(resultWho)
.setRequestCode(requestCode)
.setStartFlags(startFlags)
.setProfilerInfo(profilerInfo)
.setActivityOptions(bOptions)
.setUserId(userId)
.execute();
}
ActivityStartController getActivityStartController() {
return mActivityStartController;
}
}
startActivity()方法调用了startActivityAsUser()方法,最终通过getActivityStartController().obtainStarter(intent, "startActivityAsUser")来获取ActivityStarter实例:
java
public class ActivityStartController {
ActivityStarter obtainStarter(Intent intent, String reason) {
return mFactory.obtain().setIntent(intent).setReason(reason);
}
}
这里mFactory.obtain()是通过ActivityStarter的内部类DefaultFactory的obtain()方法来获取ActivityStarter实例的,其中mStarterPool是一个同步缓存池,先去同步缓存池中获取,没有获取到就new一个:
java
class ActivityStarter {
interface Factory {
void setController(ActivityStartController controller);
ActivityStarter obtain();
void recycle(ActivityStarter starter);
}
static class DefaultFactory implements Factory {
private final int MAX_STARTER_COUNT = 3;
private ActivityStartController mController;
private ActivityTaskManagerService mService;
private ActivityStackSupervisor mSupervisor;
private ActivityStartInterceptor mInterceptor;
private SynchronizedPool<ActivityStarter> mStarterPool =
new SynchronizedPool<>(MAX_STARTER_COUNT);
DefaultFactory(ActivityTaskManagerService service,
ActivityStackSupervisor supervisor, ActivityStartInterceptor interceptor) {
mService = service;
mSupervisor = supervisor;
mInterceptor = interceptor;
}
@Override
public void setController(ActivityStartController controller) {
mController = controller;
}
@Override
public ActivityStarter obtain() {
ActivityStarter starter = mStarterPool.acquire();
if (starter == null) {
starter = new ActivityStarter(mController, mService, mSupervisor, mInterceptor);
}
return starter;
}
@Override
public void recycle(ActivityStarter starter) {
starter.reset(true /* clearRequest*/);
mStarterPool.release(starter);
}
}
}
然后通过Builder模式(建造者模式)设置启动所需的各种参数给mRequest:
java
class ActivityStarter {
Request mRequest = new Request();
ActivityStarter setIntent(Intent intent) {
mRequest.intent = intent;
return this;
}
ActivityStarter setReason(String reason) {
mRequest.reason = reason;
return this;
}
ActivityStarter setCaller(IApplicationThread caller) {
mRequest.caller = caller;
return this;
}
ActivityStarter setCallingPackage(String callingPackage) {
mRequest.callingPackage = callingPackage;
return this;
}
ActivityStarter setCallingFeatureId(String callingFeatureId) {
mRequest.callingFeatureId = callingFeatureId;
return this;
}
...
}
最后调用ActivityStarter实例的execute()方法:
java
class ActivityStarter {
//根据mRequest里面的参数解析出必要的信息,执行Activity的启动流程的请求
int execute() {
try {
...
//Activity的启动流程的请求
res = executeRequest(mRequest);
...
} finally {
//启动Activity后的回调
onExecutionComplete();
}
}
//执行Activity的启动请求并开始Activity的启动流程,这里将开始执行几个初步的检查
private int executeRequest(Request request) {
...
//传入request中的参数
final IApplicationThread caller = request.caller;
Intent intent = request.intent;
NeededUriGrants intentGrants = request.intentGrants;
String resolvedType = request.resolvedType;
ActivityInfo aInfo = request.activityInfo;
ResolveInfo rInfo = request.resolveInfo;
final IVoiceInteractionSession voiceSession = request.voiceSession;
final IBinder resultTo = request.resultTo;
String resultWho = request.resultWho;
int requestCode = request.requestCode;
int callingPid = request.callingPid;
int callingUid = request.callingUid;
String callingPackage = request.callingPackage;
String callingFeatureId = request.callingFeatureId;
final int realCallingPid = request.realCallingPid;
final int realCallingUid = request.realCallingUid;
final int startFlags = request.startFlags;
final SafeActivityOptions options = request.activityOptions;
Task inTask = request.inTask;
...
ActivityRecord sourceRecord = null;
ActivityRecord resultRecord = null;
if (resultTo != null) {
//Launcher端的ActivityRecord
sourceRecord = mRootWindowContainer.isInAnyStack(resultTo);
if (DEBUG_RESULTS) {
Slog.v(TAG_RESULTS, "Will send result to " + resultTo + " " + sourceRecord);
}
if (sourceRecord != null) {
if (requestCode >= 0 && !sourceRecord.finishing) {
resultRecord = sourceRecord;
}
}
}
...
//进行一些初步的检查,如果检查出错了,返回错误码err
...
//权限检查
boolean abort = !mSupervisor.checkStartAnyActivityPermission(intent, aInfo, resultWho,
requestCode, callingPid, callingUid, callingPackage, callingFeatureId,
request.ignoreTargetSecurity, inTask != null, callerApp, resultRecord, resultStack);
...
//新建ActivityRecord
final ActivityRecord r = new ActivityRecord(mService, callerApp, callingPid, callingUid,
callingPackage, callingFeatureId, intent, resolvedType, aInfo,
mService.getGlobalConfiguration(), resultRecord, resultWho, requestCode,
request.componentSpecified, voiceSession != null, mSupervisor, checkedOptions,
sourceRecord);
mLastStartActivityRecord = r;
...
//接着调用startActivityUnchecked()
mLastStartActivityResult = startActivityUnchecked(r, sourceRecord, voiceSession,
request.voiceInteractor, startFlags, true /* doResume */, checkedOptions, inTask,
restrictedBgActivity, intentGrants);
...
return mLastStartActivityResult;
}
}
execute()方法又调用了executeRequest()方法,executeRequest()方法会把Request的参数传入,进行初步的检查和权限确认,然后在这里新建要启动的Activity对应的ActivityRecord,其包含了Activity的所有信息,然后继续调用startActivityUnchecked()方法:
java
class ActivityStarter {
private final ActivityTaskManagerService mService;
private final RootWindowContainer mRootWindowContainer;
ActivityStarter(ActivityStartController controller, ActivityTaskManagerService service,
ActivityStackSupervisor supervisor, ActivityStartInterceptor interceptor) {
...
mService = service;
mRootWindowContainer = service.mRootWindowContainer;
...
}
private int startActivityUnchecked(final ActivityRecord r, ActivityRecord sourceRecord,
IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor,
int startFlags, boolean doResume, ActivityOptions options, Task inTask,
boolean restrictedBgActivity, NeededUriGrants intentGrants) {
int result = START_CANCELED;
...
result = startActivityInner(r, sourceRecord, voiceSession, voiceInteractor,
startFlags, doResume, options, inTask, restrictedBgActivity, intentGrants);
...
return result;
}
int startActivityInner(final ActivityRecord r, ActivityRecord sourceRecord,
IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor,
int startFlags, boolean doResume, ActivityOptions options, Task inTask,
boolean restrictedBgActivity, NeededUriGrants intentGrants) {
//根据启动模式和Intent中的flag来计算mLaunchFlags
computeLaunchingTaskFlags();
...
//把mLaunchFlags传给mIntent
mIntent.setFlags(mLaunchFlags);
//获取可重用的task
final Task reusedTask = getReusableTask();
...
//如果reusedTask不为null,使用reusedTask;否则使用computeTargetTask()
final Task targetTask = reusedTask != null ? reusedTask : computeTargetTask();
//如果targetTask为null,newTask为true
final boolean newTask = targetTask == null;
//targetTask赋值给mTargetTask
mTargetTask = targetTask;
//计算启动参数,结果保存在mLaunchParams中
computeLaunchParams(r, sourceRecord, targetTask);
...
if (newTask) {
final Task taskToAffiliate = (mLaunchTaskBehind && mSourceRecord != null)
? mSourceRecord.getTask() : null;
//把目标ActivityRecord添加到新的Task
setNewTask(taskToAffiliate);
...
} else if (mAddingToTask) {
//把目标ActivityRecord添加到已有的targetTask
addOrReparentStartingActivity(targetTask, "adding to task");
}
if (!mAvoidMoveToFront && mDoResume) {
//移动新创建的Task到TaskDisplayArea的子节点的栈顶
mTargetStack.getStack().moveToFront("reuseOrNewTask", targetTask);
if (mOptions != null) {
if (mOptions.getTaskAlwaysOnTop()) {
mTargetStack.setAlwaysOnTop(true);
}
}
if (!mTargetStack.isTopStackInDisplayArea() && mService.mInternal.isDreaming()) {
// Launching underneath dream activity (fullscreen, always-on-top). Run the launch-
// -behind transition so the Activity gets created and starts in visible state.
mLaunchTaskBehind = true;
r.mLaunchTaskBehind = true;
}
}
//给目标Activity添加Uri权限
mService.mUgmInternal.grantUriPermissionUncheckedFromIntent(intentGrants, mStartActivity.getUriPermissionsLocked());
...
//调整目标Task相关参数,开启转场动画,为启动Activity做好准备
mTargetStack.startActivityLocked(mStartActivity, topStack.getTopNonFinishingActivity(), newTask, mKeepCurTransition, mOptions);
if (mDoResume) {
final ActivityRecord topTaskActivity =
mStartActivity.getTask().topRunningActivityLocked();
if (!mTargetStack.isTopActivityFocusable()
|| (topTaskActivity != null && topTaskActivity.isTaskOverlay()
&& mStartActivity != topTaskActivity)) {
//如果该activity无法获取到焦点,我们不能执行resume,但是启动它的时候
//还是要让它可见(这将会触发入场动画),RIP activities就是其中一个例子
mTargetStack.ensureActivitiesVisible(null /* starting */,
0 /* configChanges */, !PRESERVE_WINDOWS);
mTargetStack.getDisplay().mDisplayContent.executeAppTransition();
} else {
...
mRootWindowContainer.resumeFocusedStacksTopActivities(
mTargetStack, mStartActivity, mOptions);
}
}
mRootWindowContainer.updateUserStack(mStartActivity.mUserId, mTargetStack);
// Update the recent tasks list immediately when the activity starts
mSupervisor.mRecentTasks.add(mStartActivity.getTask());
mSupervisor.handleNonResizableTaskIfNeeded(mStartActivity.getTask(),
mPreferredWindowingMode, mPreferredTaskDisplayArea, mTargetStack);
return START_SUCCESS;
}
}
startActivityUnchecked()又调用了startActivityInner()方法,startActivityInner()中先根据launchMode和Intent中的flag计算目标Activity的启动模式,结果保存在mLaunchFlags中。如果targetTask为null,在第53行会新建一个Task对象,并将目标ActivityRecord插入。第62行移动新创建的Task到TaskDisplayArea的子节点的栈顶。
接下来分析RootWindowContainer的resumeFocusedStacksTopActivities()方法:
java
class RootWindowContainer extends WindowContainer<DisplayContent>
implements DisplayManager.DisplayListener {
boolean resumeFocusedStacksTopActivities(ActivityStack targetStack, ActivityRecord target, ActivityOptions targetOptions) {
...
for (int displayNdx = getChildCount() - 1; displayNdx >= 0; --displayNdx) {
boolean resumedOnDisplay = false;
...
if (!resumedOnDisplay) {
final ActivityStack focusedStack = display.getFocusedStack();
...
result |= focusedStack.resumeTopActivityUncheckedLocked(target, targetOptions);
...
}
}
return result;
}
}
RootWindowContainer是设备窗口容器(WindowContainer)的根容器,管理所有的窗口容器,设备上所有的窗口(Window)、显示(Display)都是由它来管理的。RootWindowContainer的resumeFocusedStacksTopActivities()方法转交给ActivityStack的resumeTopActivityUncheckedLocked()方法来继续启动流程:
java
class ActivityStack extends Task {
boolean resumeTopActivityUncheckedLocked(ActivityRecord prev, ActivityOptions options) {
if (mInResumeTopActivity) {
// Don't even start recursing.
return false;
}
boolean result = false;
try {
mInResumeTopActivity = true;
result = resumeTopActivityInnerLocked(prev, options);
final ActivityRecord next = topRunningActivity(true /* focusableOnly */);
if (next == null || !next.canTurnScreenOn()) {
checkReadyForSleep();
}
} finally {
mInResumeTopActivity = false;
}
return result;
}
private boolean resumeTopActivityInnerLocked(ActivityRecord prev, ActivityOptions options) {
...
//next就是当前要启动的Activity
ActivityRecord next = topRunningActivity(true /* focusableOnly */);
...
//暂定所有栈里面的Activity,不包括可见的栈
boolean pausing = taskDisplayArea.pauseBackStacks(userLeaving, next);
if (mResumedActivity != null) {
if (DEBUG_STATES) Slog.d(TAG_STATES,
"resumeTopActivityLocked: Pausing " + mResumedActivity);
//pause上一个Activity,上一个Activity处于resume状态
pausing |= startPausingLocked(userLeaving, false /* uiSleeping */, next);
}
...
//判断next是否已经启动了
if (next.attachedToProcess()) {
...
final ClientTransaction transaction =
ClientTransaction.obtain(next.app.getThread(), next.appToken);
...
//启动了的Activity就发送ResumeActivityItem事务给客户端,后面会讲到
transaction.setLifecycleStateRequest(
ResumeActivityItem.obtain(next.app.getReportedProcState(),
dc.isNextTransitionForward()));
mAtmService.getLifecycleManager().scheduleTransaction(transaction);
...
} else {
...
if (SHOW_APP_STARTING_PREVIEW) {
//这里就是冷启动出现白屏的原因,取根activity的主题背景展示StartingWindow
next.showStartingWindow(null /* prev */, false /* newTask */,
false /* taskSwich */);
}
//继续启动当前Activity
mStackSupervisor.startSpecificActivity(next, true, true);
}
return true;
}
}
从resumeTopActivityUncheckedLocked()方法继续跟进到resumeTopActivityInnerLocked()方法,resumeTopActivityInnerLocked()中先对上一个Activity执行了pause操作,然后判断当前要启动的Activity是否已经启动了,如果已经启动了,发送ResumeActivityItem事务给客户端,执行resume流程,如果没有启动,继续调用ActivityStackSupervisor的startSpecificActivity()方法。这里注意下,调用startSpecificActivity()方法前调用了next.showStartingWindow()方法来展示一个window,这就是冷启动时出现白屏的原因。我们继续来看ActivityStackSupervisor的startSpecificActivity()方法:
java
public class ActivityStackSupervisor{
void startSpecificActivity(ActivityRecord r, boolean andResume, boolean checkConfig) {
//该activity所在的应用已经在运行了吗?
final WindowProcessController wpc =
mService.getProcessController(r.processName, r.info.applicationInfo.uid);
boolean knownToBeDead = false;
//wpc.hasThread()通过判断IApplicationThread是否被赋值,如果已赋值,即应用已运行
//应用已运行,则是普通Activity的启动流程,走realStartActivityLocked()方法
if (wpc != null && wpc.hasThread()) {
try {
realStartActivityLocked(r, wpc, andResume, checkConfig);
return;
} catch (RemoteException e) {
Slog.w(TAG, "Exception when starting activity "
+ r.intent.getComponent().flattenToShortString(), e);
}
// If a dead object exception was thrown -- fall through to
// restart the application.
knownToBeDead = true;
}
r.notifyUnknownVisibilityLaunchedForKeyguardTransition();
final boolean isTop = andResume && r.isTopRunningActivity();
//否则需要ATMS的startProcessAsync()方法请求创建进程
mService.startProcessAsync(r, knownToBeDead, isTop, isTop ? "top-activity" : "activity");
}
}
startSpecificActivity()方法中通过wpc.hasThread()来判断activity所在的应用是否已经在运行,其内部是通过IApplicationThread是否已经被赋值来判断的,如果为true,走ActivityStackSupervisor的realStartActivityLocked()方法,即普通Activity的启动流程;否则需要调用ATMS的startProcessAsync()来创建应用进程。
本文分析的是普通Activity的启动流程,所以这里走ActivityStackSupervisor的realStartActivityLocked()方法:
java
public class ActivityStackSupervisor implements RecentTasks.Callbacks {
boolean realStartActivityLocked(ActivityRecord r, WindowProcessController proc,
boolean andResume, boolean checkConfig) throws RemoteException {
...
// 获取ClientTransaction实例
final ClientTransaction clientTransaction = ClientTransaction.obtain(
proc.getThread(), r.appToken);
final DisplayContent dc = r.getDisplay().mDisplayContent;
//给ClientTransaction实例添加LaunchActivityItem
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.getSavedState(), r.getPersistentSavedState(), results, newIntents,
dc.isNextTransitionForward(), proc.createProfilerInfoIfNeeded(),
r.assistToken, r.createFixedRotationAdjustmentsIfNeeded()));
//Set desired final state.
final ActivityLifecycleItem lifecycleItem;
//前面传入的参数andResume为true
if (andResume) {
lifecycleItem = ResumeActivityItem.obtain(dc.isNextTransitionForward());
} else {
lifecycleItem = PauseActivityItem.obtain();
}
//设置执行transaction后客户端的下一个生命周期状态
clientTransaction.setLifecycleStateRequest(lifecycleItem);
// Schedule transaction.
mService.getLifecycleManager().scheduleTransaction(clientTransaction);
...
return true;
}
}
该方法执行流程如下:
- 使用ClientTransaction.obtain(proc.getThread(), r.appToken)获取ClientTransaction实例,proc就是WindowProcessController,参数proc.getThread()是IApplicationThread类型,就是前面提到的ApplicationThread在系统进程的代理。
- 给ClientTransaction实例添加添加的LaunchActivityItem实例,LaunchActivityItem继承自ClientTransactionItem,ClientTransactionItem是一个抽象类。ClientTransaction是包含一系列的待客户端处理的事务的容器,客户端接收后取出事务并执行。
- 通过mService.getLifecycleManager()获取ClientLifecycleManager实例,调用其scheduleTransaction()方法。
先来看看ClientTransaction的addCallback()方法:
java
public class ClientTransaction implements Parcelable, ObjectPoolItem {
//都是用来发送到客户端的
private List<ClientTransactionItem> mActivityCallbacks;
//在mActivityCallbacks中添加ClientTransactionItem类型的消息
public void addCallback(ClientTransactionItem activityCallback) {
if (mActivityCallbacks == null) {
mActivityCallbacks = new ArrayList<>();
}
mActivityCallbacks.add(activityCallback);
}
}
addCallback()方法把ClientTransactionItem类型的消息添加到mActivityCallbacks中。
看下LaunchActivityItem实例怎么获取的:
java
public class LaunchActivityItem extends ClientTransactionItem {
/** Obtain an instance initialized with provided params. */
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, FixedRotationAdjustments fixedRotationAdjustments) {
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, fixedRotationAdjustments);
return instance;
}
}
obtain()方法里面new了一个LaunchActivityItem,然后把各种配置信息传给了它。从名字来看,它就是用来启动activity的。它是怎么发挥作用的呢?
前面的mService.getLifecycleManager()拿到的是ClientLifecycleManager,然后调用其scheduleTransaction()方法:
java
class ClientLifecycleManager {
//安排调度一个事务(启动、暂停等 Activity 事务),可能包含多个回调和一个生命周期请求
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()方法:
java
public class ClientTransaction implements Parcelable, ObjectPoolItem {
public void schedule() throws RemoteException {
mClient.scheduleTransaction(this);
}
}
mClient是IApplicationThread类型,它是ApplicationThread在系统进程的代理,所以真正执行的地方就是客户端的ApplicationThread中了。也就是说,Activity启动的操作又跨进程的还给了客户端。
线程切换及消息处理
接着上面的分析,我们找到ApplicationThread,ApplicationThread是ActivityThread的内部类:
java
public final class ActivityThread extends ClientTransactionHandler {
private class ApplicationThread extends IApplicationThread.Stub {
@Override
public void scheduleTransaction(ClientTransaction transaction) throws RemoteException {
ActivityThread.this.scheduleTransaction(transaction);
}
}
}
ApplicationThread的scheduleTransaction()方法又调用了ActivityThread的scheduleTransaction()方法,ActivityThread的scheduleTransaction()方法实际在其父类ClientTransactionHandler中
java
public abstract class ClientTransactionHandler {
void scheduleTransaction(ClientTransaction transaction) {
transaction.preExecute(this);
// 发送ActivityThread.H.EXECUTE_TRANSACTION消息
sendMessage(ActivityThread.H.EXECUTE_TRANSACTION, transaction);
}
}
使用sendMessage发送消息,参数是ActivityThread.H.EXECUTE_TRANSACTION和transaction,接着看ActivityThread的sendMessage()方法:
java
public final class ActivityThread extends ClientTransactionHandler {
final H mH = new H();
void sendMessage(int what, Object obj) {
sendMessage(what, obj, 0, 0, false);
}
private void sendMessage(int what, Object obj, int arg1, int arg2, boolean async) {
...
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(msg),mH是一个Handler对象,mH是在主线程创建的,所以通过mH.sendMessage(msg)把消息发送到了主线程。
那么前面ApplicationThread的scheduleTransaction()方法执行在哪个线程呢?根据IPC知识,服务器的Binder方法运行在Binder线程池中,也就是说系统进行跨进程调用ApplicationThread的scheduleTransaction()方法运行在Binder的线程池中,这样就把子线程中的消息通过Handler发送到了主线程。继续看ActivityThread.H的handleMessage()方法:
java
public final class ActivityThread extends ClientTransactionHandler {
class H extends Handler {
public static final int BIND_APPLICATION = 110;
@UnsupportedAppUsage
public static final int EXIT_APPLICATION = 111;
@UnsupportedAppUsage
public static final int RECEIVER = 113;
@UnsupportedAppUsage
public static final int CREATE_SERVICE = 114;
@UnsupportedAppUsage
public static final int SERVICE_ARGS = 115;
...
public static final int EXECUTE_TRANSACTION = 159;
public static final int RELAUNCH_ACTIVITY = 160;
...
public void handleMessage(Message msg) {
if (DEBUG_MESSAGES) Slog.v(TAG, ">>> handling: " + codeToString(msg.what));
switch (msg.what) {
case BIND_APPLICATION:
Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "bindApplication");
AppBindData data = (AppBindData)msg.obj;
handleBindApplication(data);
Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
break;
case EXIT_APPLICATION:
if (mInitialApplication != null) {
mInitialApplication.onTerminate();
}
Looper.myLooper().quit();
break;
case RECEIVER:
Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "broadcastReceiveComp");
handleReceiver((ReceiverData)msg.obj);
Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
break;
case CREATE_SERVICE:
Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, ("serviceCreate: " + String.valueOf(msg.obj)));
handleCreateService((CreateServiceData)msg.obj);
Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
break;
case BIND_SERVICE:
Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "serviceBind");
handleBindService((BindServiceData)msg.obj);
Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
break;
...
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();
}
break;
case RELAUNCH_ACTIVITY:
handleRelaunchActivityLocally((IBinder) msg.obj);
break;
...
}
Object obj = msg.obj;
if (obj instanceof SomeArgs) {
((SomeArgs) obj).recycle();
}
if (DEBUG_MESSAGES) Slog.v(TAG, "<<< done: " + codeToString(msg.what));
}
}
}
接下来H的handleMessage()方法中,代码第50行获取传递过来的ClientTransaction,然后执行TransactionExecutor的execute()方法:
java
public class TransactionExecutor {
public void execute(ClientTransaction transaction) {
...
final IBinder token = transaction.getActivityToken();
...
executeCallbacks(transaction);
executeLifecycleState(transaction);
...
}
}
继续跟进executeCallbacks()方法:
java
public class TransactionExecutor {
public TransactionExecutor(ClientTransactionHandler clientTransactionHandler) {
mTransactionHandler = clientTransactionHandler;
}
@VisibleForTesting
public void executeCallbacks(ClientTransaction transaction) {
final List<ClientTransactionItem> callbacks = transaction.getCallbacks();
if (callbacks == null || callbacks.isEmpty()) {
// No callbacks to execute, return early.
return;
}
if (DEBUG_RESOLVER) Slog.d(TAG, tId(transaction) + "Resolving callbacks in transaction");
final IBinder token = transaction.getActivityToken();
ActivityClientRecord r = mTransactionHandler.getActivityClient(token);
// In case when post-execution state of the last callback matches the final state requested
// for the activity in this transaction, we won't do the last transition here and do it when
// moving to final state instead (because it may contain additional parameters from server).
final ActivityLifecycleItem finalStateRequest = transaction.getLifecycleStateRequest();
final int finalState = finalStateRequest != null ? finalStateRequest.getTargetState()
: UNDEFINED;
// Index of the last callback that requests some post-execution state.
final int lastCallbackRequestingState = lastCallbackRequestingState(transaction);
final int size = callbacks.size();
for (int i = 0; i < size; ++i) {
final ClientTransactionItem item = callbacks.get(i);
...
item.execute(mTransactionHandler, token, mPendingActions);
item.postExecute(mTransactionHandler, token, mPendingActions);
...
}
}
}
在executeCallbacks()方法里遍历callbacks,调用ClientTransactionItem的execute方法,这里的ClientTransactionItem就是LaunchActivityItem,我们来看看它的execute()方法:
java
public class LaunchActivityItem extends ClientTransactionItem {
@Override
public void execute(ClientTransactionHandler client, IBinder token,
PendingTransactionActions pendingActions) {
Trace.traceBegin(TRACE_TAG_ACTIVITY_MANAGER, "activityStart");
ActivityClientRecord r = new ActivityClientRecord(token, mIntent, mIdent, mInfo,
mOverrideConfig, mCompatInfo, mReferrer, mVoiceInteractor, mState, mPersistentState,
mPendingResults, mPendingNewIntents, mIsForward,
mProfilerInfo, client, mAssistToken, mFixedRotationAdjustments);
client.handleLaunchActivity(r, pendingActions, null /* customIntent */);
Trace.traceEnd(TRACE_TAG_ACTIVITY_MANAGER);
}
}
里面调用了client.handleLaunchActivity()方法,client是ClientTransactionHandler的实例,是在TransactionExecutor的构造方法传入的,TransactionExecutor创建是在ActivityThread中:
java
public final class ActivityThread extends ClientTransactionHandler {
private final TransactionExecutor mTransactionExecutor = new TransactionExecutor(this);
}
所以这里的client实际上是ActivityThread,接下来执行ActivityThread的handleLaunchActivity()方法。
好了,这一步ApplicationThread通过给ActivityThead里面的Handler发消息,走到了主线程的ActivityThead的handleLaunchActivity()方法。
Activity初始化及生命周期处理
接着看ActivityThead的handleLaunchActivity()方法:
java
public final class ActivityThread extends ClientTransactionHandler {
@Override
public Activity handleLaunchActivity(ActivityClientRecord r,
PendingTransactionActions pendingActions, Intent customIntent) {
...
final Activity a = performLaunchActivity(r, customIntent);
...
return a;
}
}
继续跟进performLaunchActivity方法,这里就是activity 启动的核心实现了:
java
public final class ActivityThread extends ClientTransactionHandler {
private Activity performLaunchActivity(ActivityClientRecord r, Intent customIntent) {
//1、从ActivityClientRecord中获取待启动的Activity的组件信息
ActivityInfo aInfo = r.activityInfo;
if (r.packageInfo == null) {
r.packageInfo = getPackageInfo(aInfo.applicationInfo, r.compatInfo,
Context.CONTEXT_INCLUDE_CODE);
}
ComponentName component = r.intent.getComponent();
if (component == null) {
component = r.intent.resolveActivity(
mInitialApplication.getPackageManager());
r.intent.setComponent(component);
}
if (r.activityInfo.targetActivity != null) {
component = new ComponentName(r.activityInfo.packageName,
r.activityInfo.targetActivity);
}
//创建ContextImpl对象
ContextImpl appContext = createBaseContextForActivity(r);
Activity activity = null;
try {
java.lang.ClassLoader cl = appContext.getClassLoader();
//2、创建activity实例
activity = mInstrumentation.newActivity(
cl, component.getClassName(), r.intent);
StrictMode.incrementExpectedActivityCount(activity.getClass());
r.intent.setExtrasClassLoader(cl);
r.intent.prepareToEnterProcess();
if (r.state != null) {
r.state.setClassLoader(cl);
}
} catch (Exception e) {
if (!mInstrumentation.onException(activity, e)) {
throw new RuntimeException(
"Unable to instantiate activity " + component
+ ": " + e.toString(), e);
}
}
try {
//3、创建Application对象(如果没有的话)
Application app = r.packageInfo.makeApplication(false, mInstrumentation);
if (localLOGV) Slog.v(TAG, "Performing launch of " + r);
if (localLOGV) Slog.v(
TAG, r + ": app=" + app
+ ", appName=" + app.getPackageName()
+ ", pkg=" + r.packageInfo.getPackageName()
+ ", comp=" + r.intent.getComponent().toShortString()
+ ", dir=" + r.packageInfo.getAppDir());
if (activity != null) {
CharSequence title = r.activityInfo.loadLabel(appContext.getPackageManager());
Configuration config = new Configuration(mCompatConfiguration);
if (r.overrideConfig != null) {
config.updateFrom(r.overrideConfig);
}
if (DEBUG_CONFIGURATION) Slog.v(TAG, "Launching activity "
+ r.activityInfo.name + " with config " + config);
Window window = null;
if (r.mPendingRemoveWindow != null && r.mPreserveWindow) {
window = r.mPendingRemoveWindow;
r.mPendingRemoveWindow = null;
r.mPendingRemoveWindowManager = null;
}
// Activity resources must be initialized with the same loaders as the
// application context.
appContext.getResources().addLoaders(
app.getResources().getLoaders().toArray(new ResourcesLoader[0]));
appContext.setOuterContext(activity);
//4、attach方法为activity关联上下文环境
activity.attach(appContext, this, getInstrumentation(), r.token,
r.ident, app, r.intent, r.activityInfo, title, r.parent,
r.embeddedID, r.lastNonConfigurationInstances, config,
r.referrer, r.voiceInteractor, window, r.configCallback,
r.assistToken);
if (customIntent != null) {
activity.mIntent = customIntent;
}
r.lastNonConfigurationInstances = null;
checkAndBlockForNetworkAccess();
activity.mStartedActivity = false;
int theme = r.activityInfo.getThemeResource();
if (theme != 0) {
activity.setTheme(theme);
}
activity.mCalled = false;
//5、调用生命周期onCreate()方法
if (r.isPersistable()) {
mInstrumentation.callActivityOnCreate(activity, r.state, r.persistentState);
} else {
mInstrumentation.callActivityOnCreate(activity, r.state);
}
if (!activity.mCalled) {
throw new SuperNotCalledException(
"Activity " + r.intent.getComponent().toShortString() +
" did not call through to super.onCreate()");
}
r.activity = activity;
mLastReportedWindowingMode.put(activity.getActivityToken(),
config.windowConfiguration.getWindowingMode());
}
r.setState(ON_CREATE);
// updatePendingActivityConfiguration() reads from mActivities to update
// ActivityClientRecord which runs in a different thread. Protect modifications to
// mActivities to avoid race.
synchronized (mResourcesManager) {
mActivities.put(r.token, r);
}
} catch (SuperNotCalledException e) {
throw e;
} catch (Exception e) {
if (!mInstrumentation.onException(activity, e)) {
throw new RuntimeException(
"Unable to start activity " + component
+ ": " + e.toString(), e);
}
}
return activity;
}
}
performLaunchActivity主要完成以下事情:
- 从ActivityClientRecord中获取待启动的Activity的组件信息。
- 通过mInstrumentation.newActivity()方法使用类加载器创建activity实例。
- 通过LoadedApk的makeApplication()方法创建Application对象,内部也是通过mInstrumentation使用类加载器来创建的,创建后调用了instrumentation.callApplicationOnCreate()方法,也就是Application的onCreate()方法。
- 创建ContextImpl对象并通过activity.attach方法对重要数据初始化,关联了Context的具体实现ContextImpl,attach方法内部还完成了window创建,这样Window接收到外部事件后就能传递给Activity了。
- 调用Activity的onCreate()方法,是通过 mInstrumentation.callActivityOnCreate方法完成。
到这里Activity的onCreate()方法就执行完了,那么onStart()、onResume()呢?
回头看看TransactionExecutor的execute()方法,执行完executeCallbacks(transaction)之后会执行executeLifecycleState(transaction):
java
public class TransactionExecutor {
private void executeLifecycleState(ClientTransaction transaction) {
//获取执行transaction后,客户端应处于的生命周期状态
final ActivityLifecycleItem lifecycleItem = transaction.getLifecycleStateRequest();
if (lifecycleItem == null) {
// No lifecycle request, return early.
return;
}
final IBinder token = transaction.getActivityToken();
final ActivityClientRecord r = mTransactionHandler.getActivityClient(token);
...
if (r == null) {
// Ignore requests for non-existent client records for now.
return;
}
// Cycle to the state right before the final requested state.
cycleToPath(r, lifecycleItem.getTargetState(), true /* excludeLastState */, transaction);
// Execute the final transition with proper parameters.
lifecycleItem.execute(mTransactionHandler, token, mPendingActions);
lifecycleItem.postExecute(mTransactionHandler, token, mPendingActions);
}
}
在AcivityStackSupervisor的realStartActivityLocked()方法里面有执行transaction.setLifecycleStateRequest(),那么这里拿到的lifecycleItem就是ResumeActivityItem,接下来执行ResumeActivityItem的execute()方法:
java
public class ResumeActivityItem extends ActivityLifecycleItem {
@Override
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);
}
}
通过上面的分析,后面会执行ActivityThread的handleResumeActivity方法:
java
public final class ActivityThread extends ClientTransactionHandler {
@Override
public void handleResumeActivity(IBinder token, boolean finalStateRequest, boolean isForward,
String reason) {
...
//performResumeActivity()方法内部会走onStart、onResume
final ActivityClientRecord r = performResumeActivity(token, finalStateRequest, reason);
if (r == null) {
// We didn't actually resume the activity, so skipping any follow-up actions.
return;
}
...
if (r.window == null && !a.mFinished && willBeVisible) {
r.window = r.activity.getWindow();
View decor = r.window.getDecorView();
decor.setVisibility(View.INVISIBLE);
ViewManager wm = a.getWindowManager();
WindowManager.LayoutParams l = r.window.getAttributes();
a.mDecor = decor;
l.type = WindowManager.LayoutParams.TYPE_BASE_APPLICATION;
l.softInputMode |= forwardBit;
if (r.mPreserveWindow) {
a.mWindowAdded = true;
r.mPreserveWindow = false;
// Normally the ViewRoot sets up callbacks with the Activity
// in addView->ViewRootImpl#setView. If we are instead reusing
// the decor view we have to notify the view root that the
// callbacks may have changed.
ViewRootImpl impl = decor.getViewRootImpl();
if (impl != null) {
impl.notifyChildRebuilt();
}
}
if (a.mVisibleFromClient) {
if (!a.mWindowAdded) {
a.mWindowAdded = true;
//执行WindowManagerImpl的addView()方法,里面执行了绘制流程
wm.addView(decor, l);
} else {
// The activity will get a callback for this {@link LayoutParams} change
// earlier. However, at that time the decor will not be set (this is set
// in this method), so no action will be taken. This call ensures the
// callback occurs with the decor set.
a.onWindowAttributesChanged(l);
}
}
// If the window has already been added, but during resume
// we started another activity, then don't yet make the
// window visible.
} else if (!willBeVisible) {
if (localLOGV) Slog.v(TAG, "Launch " + r + " mStartedActivity set");
r.hideForNow = true;
}
// Get rid of anything left hanging around.
cleanUpPendingRemoveWindows(r, false /* force */);
// The window is now visible if it has been added, we are not
// simply finishing, and we are not starting another activity.
if (!r.activity.mFinished && willBeVisible && r.activity.mDecor != null && !r.hideForNow) {
if (r.newConfig != null) {
performConfigurationChangedForActivity(r, r.newConfig);
if (DEBUG_CONFIGURATION) {
Slog.v(TAG, "Resuming activity " + r.activityInfo.name + " with newConfig "
+ r.activity.mCurrentConfig);
}
r.newConfig = null;
}
if (localLOGV) Slog.v(TAG, "Resuming " + r + " with isForward=" + isForward);
ViewRootImpl impl = r.window.getDecorView().getViewRootImpl();
WindowManager.LayoutParams l = impl != null
? impl.mWindowAttributes : r.window.getAttributes();
if ((l.softInputMode
& WindowManager.LayoutParams.SOFT_INPUT_IS_FORWARD_NAVIGATION)
!= forwardBit) {
l.softInputMode = (l.softInputMode
& (~WindowManager.LayoutParams.SOFT_INPUT_IS_FORWARD_NAVIGATION))
| forwardBit;
if (r.activity.mVisibleFromClient) {
ViewManager wm = a.getWindowManager();
View decor = r.window.getDecorView();
wm.updateViewLayout(decor, l);
}
}
r.activity.mVisibleFromServer = true;
mNumVisibleActivities++;
if (r.activity.mVisibleFromClient) {
//里面设置了DecorView可见
r.activity.makeVisible();
}
}
r.nextIdle = mNewActivities;
mNewActivities = r;
if (localLOGV) Slog.v(TAG, "Scheduling idle handler for " + r);
Looper.myQueue().addIdleHandler(new Idler());
}
}
handleResumeActivity中主要做了这些事情:
- 调用performResumeActivity()方法,内部会调用onStart()、onResume()方法。
- 执行wm.addView(decor, l),里面执行了布局、测量与绘制三大流程,并把DecorView添加到窗口中。这就是为什么在OnResume()方法中无法获取到View的宽高的原因,因为在OnResume()方法中宽高还没有被赋值。
- 执行r.activity.makeVisible(),让DecorView可见。
来看看performResumeActivity()方法:
java
public final class ActivityThread extends ClientTransactionHandler {
public ActivityClientRecord performResumeActivity(IBinder token, boolean finalStateRequest,
String reason) {
final ActivityClientRecord r = mActivities.get(token);
...
r.activity.performResume(r.startsNotResumed, reason);
...
return r;
}
}
里面调用了Activity的performResume()方法:
java
public class Activity extends ContextThemeWrapper {
final void performResume(boolean followedByPause, String reason) {
dispatchActivityPreResumed();
//里面执行了Activity的onStart()方法
performRestart(true /* start */, reason);
...
//里面执行了Activity的onResume()方法
mInstrumentation.callActivityOnResume(this);
...
//里面执行了Fragment的onResume()方法
mFragments.dispatchResume();
mFragments.execPendingActions();
...
}
}
先执行了performRestart()方法,performRestart()方法里面执行了onStart()方法。然后执行了mInstrumentation.callActivityOnResume(this),里面执行了onResume()方法。到这里,启动Activity的生命周期方法就走完了。