上一篇文章分析了activity 的第一个生命周期 onPause 方法,也就是 resumeTopActivityInnerLocked 方法里面的第一部分,接下来继续分析剩下两部分
第二部分:根据任务栈判断是否直接调用 activity 的 onNewIntent 方法
回到 resumeTopActivityInnerLocked 方法中
private boolean resumeTopActivityInnerLocked(ActivityRecord prev, ActivityOptions options) {
//......
// 假如已经存在
if (next.app != null && next.app.thread != null) {
//.......
try {
//使用 ClientTransaction 调度生命周期
final ClientTransaction transaction = ClientTransaction.obtain(next.app.thread,
next.appToken);
//......
//判断 newIntents 的值是否存在,主要是判断是否需要调用 onNewIntent 方法
//这个值在哪里赋值呢,后面分析
if (next.newIntents != null) {
transaction.addCallback(NewIntentItem.obtain(next.newIntents,
false /* andPause */));
}
// 执行调度
mService.getLifecycleManager().scheduleTransaction(transaction);
//......
}
}
调用了 transaction.addCallback 方法,根据上一篇分析,当前 callback 有值所以调用 executeCallbacks 方法时
public void executeCallbacks(ClientTransaction transaction) {
//循环 callbacks
final int size = callbacks.size();
for (int i = 0; i < size; ++i) {
//执行 execute
item.execute(mTransactionHandler, token, mPendingActions);
item.postExecute(mTransactionHandler, token, mPendingActions);
}
}
根据前面,知道当前 item 是 NewIntentItem
public void execute(ClientTransactionHandler client, IBinder token,
PendingTransactionActions pendingActions) {
Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "activityNewIntent");
//根据前面文章的分析知道 client 为 ClientTransactionHandler 的子类 ActivityThread
client.handleNewIntent(token, mIntents, mPause);
Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
}
// ActivityThread 类中
public void handleNewIntent(IBinder token, List<ReferrerIntent> intents, boolean andPause) {
performNewIntents(token, intents, andPause);
}
void performNewIntents(IBinder token, List<ReferrerIntent> intents, boolean andPause) {
//判断是否已经调用了 paused 方法
final boolean resumed = !r.paused;
if (resumed) {
r.activity.mTemporaryPause = true;
//没有从新走一遍
mInstrumentation.callActivityOnPause(r.activity);
}
checkAndBlockForNetworkAccess();
//调用该方法
deliverNewIntents(r, intents);
}
private void deliverNewIntents(ActivityClientRecord r, List<ReferrerIntent> intents) {
final int N = intents.size();
for (int i=0; i<N; i++) {
ReferrerIntent intent = intents.get(i);
intent.setExtrasClassLoader(r.activity.getClassLoader());
intent.prepareToEnterProcess();
r.activity.mFragments.noteStateNotSaved();
//通过 mInstrumentation 调用 callActivityOnNewIntent 方法
mInstrumentation.callActivityOnNewIntent(r.activity, intent);
}
}
public void callActivityOnNewIntent(Activity activity, Intent intent) {
//调用activity 的 performNewIntent
activity.performNewIntent(intent);
}
//activity 类中
final void performNewIntent(Intent intent) {
mCanEnterPictureInPicture = true;
//调用 onNewIntent 方法
onNewIntent(intent);
}
最终会走到 activity 中的 onNewIntent 方法。所以当设置 activity 的一些启动模式是,再次启动不会重走一遍生命周期,而会走到 onNewIntent 方法中。
还有一个问题 next.newIntents 是在那里赋值,怎么判断是否调用 onNewIntent 方法的呢?还记得前面分析的一个方法 startActivityUnchecked ,这个方法主要是用来判断启动的 activity 的启动模式
private int startActivityUnchecked(final ActivityRecord r, ActivityRecord sourceRecord,
IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor,
int startFlags, boolean doResume, ActivityOptions options, TaskRecord inTask,
ActivityRecord[] outActivity) {
//......
//判断当前的启动模式是否为 SINGLE_INSTANCE 或则 LAUNCH_SINGLE_TASK
//这两种分别对应 singleTask 和 singleInstance
if ((mLaunchFlags & FLAG_ACTIVITY_CLEAR_TOP) != 0
|| isDocumentLaunchesIntoExisting(mLaunchFlags)
|| isLaunchModeOneOf(LAUNCH_SINGLE_INSTANCE, LAUNCH_SINGLE_TASK)) {
final TaskRecord task = reusedActivity.getTask();
//......
if (top != null) {
if (top.frontOfTask) {
// Activity aliases may mean we use different intents for the top activity,
// so make sure the task now has the identity of the new intent.
top.getTask().setIntent(mStartActivity);
}
//调用该方法给 newIntents 赋值
deliverNewIntent(top);
}
}
//......
final ActivityStack topStack = mSupervisor.mFocusedStack;
final ActivityRecord topFocused = topStack.getTopActivity();
final ActivityRecord top = topStack.topRunningNonDelayedActivityLocked(mNotTop);
//判断当前启动模式是否为 singleTop 并且要启动的 activity 位于栈顶
final boolean dontStart = top != null && mStartActivity.resultTo == null
&& top.realActivity.equals(mStartActivity.realActivity)
&& top.userId == mStartActivity.userId
&& top.app != null && top.app.thread != null
&& ((mLaunchFlags & FLAG_ACTIVITY_SINGLE_TOP) != 0
|| isLaunchModeOneOf(LAUNCH_SINGLE_TOP, LAUNCH_SINGLE_TASK));
if (dontStart) {
// For paranoia, make sure we have correctly resumed the top activity.
topStack.mLastPausedActivity = null;
if (mDoResume) {
mSupervisor.resumeFocusedStackTopActivityLocked();
}
ActivityOptions.abort(mOptions);
if ((mStartFlags & START_FLAG_ONLY_IF_NEEDED) != 0) {
// We don't need to start a new activity, and the client said not to do
// anything if that is the case, so this is it!
return START_RETURN_INTENT_TO_CALLER;
}
//调用该方法
deliverNewIntent(top);
}
//........
int result = START_SUCCESS;
//如果是NEW_TASK
if (mStartActivity.resultTo == null && mInTask == null && !mAddingToTask
&& (mLaunchFlags & FLAG_ACTIVITY_NEW_TASK) != 0) {
newTask = true;
//新建task
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 (result != START_SUCCESS) {
return result;
}
//.....
}
private void deliverNewIntent(ActivityRecord activity) {
//....
activity.deliverNewIntentLocked(mCallingUid, mStartActivity.intent,
mStartActivity.launchedFromPackage);
mIntentDelivered = true;
}
final void deliverNewIntentLocked(int callingUid, Intent intent, String referrer) {
//......
//判断状态是否为 resumed 或 paused 是就直接执行 onNewIntent 方法
if ((mState == RESUMED || mState == PAUSED
|| isTopActivityWhileSleeping) && app != null && app.thread != null) {
try {
ArrayList<ReferrerIntent> ar = new ArrayList<>(1);
ar.add(rintent);
//使用 LifecycleManager 调度生命周期
service.getLifecycleManager().scheduleTransaction(app.thread, appToken,
NewIntentItem.obtain(ar, mState == PAUSED));
unsent = false;
} catch (RemoteException e) {
Slog.w(TAG, "Exception thrown sending new intent to " + this, e);
} catch (NullPointerException e) {
Slog.w(TAG, "Exception thrown sending new intent to " + this, e);
}
}
if (unsent) {
//给前面说的 newIntents 赋值,再后面判断是否调用 onNewIntent 方法
addNewIntentLocked(rintent);
}
}
private void addNewIntentLocked(ReferrerIntent intent) {
if (newIntents == null) {
newIntents = new ArrayList<>();
}
//add 进去
newIntents.add(intent);
}
从上面可以知道,通过判断 activity 的启动模式来判断是否调用 deliverNewIntent 方法,从而调用 onNewIntent
第三部分:启动一个新的 activity
继续回到 resumeTopActivityInnerLocked 方法中
private boolean resumeTopActivityInnerLocked(ActivityRecord prev, ActivityOptions options) {
//.......
//判断是否存在,前面已经分析了,现在分析不存在的部分
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);
}
}
void startSpecificActivityLocked(ActivityRecord r,
boolean andResume, boolean checkConfig) {
//判断该 app 的进程和线程是否存在
if (app != null && app.thread != null) {
try {
//.....
//假如存在,直接调用该方法
//这个方法后面在来分析,先看进程
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.
}
//当前启动的 activity 没有对应的进程
mService.startProcessLocked(r.processName, r.info.applicationInfo, true, 0,
"activity", r.intent.getComponent(), false, false, true);
}
这里判断当前需要启动的 activity 进程和线程是否存在,先看不存在的情况
final ProcessRecord startProcessLocked(String processName,
ApplicationInfo info, boolean knownToBeDead, int intentFlags,
String hostingType, ComponentName hostingName, boolean allowWhileBooting,
boolean isolated, boolean keepIfLarge) {
return startProcessLocked(processName, info, knownToBeDead, intentFlags, hostingType,
hostingName, allowWhileBooting, isolated, 0 /* isolatedUid */, keepIfLarge,
null /* ABI override */, null /* entryPoint */, null /* entryPointArgs */,
null /* crashHandler */);
}
final ProcessRecord startProcessLocked(String processName, ApplicationInfo info,
boolean knownToBeDead, int intentFlags, String hostingType, ComponentName hostingName,
boolean allowWhileBooting, boolean isolated, int isolatedUid, boolean keepIfLarge,
String abiOverride, String entryPoint, String[] entryPointArgs, Runnable crashHandler) {
//.....
final boolean success = startProcessLocked(app, hostingType, hostingNameStr, abiOverride);
//...
return success ? app : null;
}
private final boolean startProcessLocked(ProcessRecord app,
String hostingType, String hostingNameStr, String abiOverride) {
return startProcessLocked(app, hostingType, hostingNameStr,
false /* disableHiddenApiChecks */, abiOverride);
}
private final boolean startProcessLocked(ProcessRecord app, String hostingType,
String hostingNameStr, boolean disableHiddenApiChecks, String abiOverride) {
//.....
//需要开启的线程名称
final String entryPoint = "android.app.ActivityThread";
return startProcessLocked(hostingType, hostingNameStr, entryPoint, app, uid, gids,
runtimeFlags, mountExternal, seInfo, requiredAbi, instructionSet, invokeWith,
startTime);
}
private boolean startProcessLocked(String hostingType, String hostingNameStr, String entryPoint,
ProcessRecord app, int uid, int[] gids, int runtimeFlags, int mountExternal,
String seInfo, String requiredAbi, String instructionSet, String invokeWith,
long startTime) {
//....
final ProcessStartResult startResult = startProcess(app.hostingType, entryPoint,
}
private ProcessStartResult startProcess(String hostingType, String entryPoint,
ProcessRecord app, int uid, int[] gids, int runtimeFlags, int mountExternal,
String seInfo, String requiredAbi, String instructionSet, String invokeWith,
long startTime) {
startResult = Process.start(entryPoint,
app.processName, uid, uid, gids, runtimeFlags, mountExternal,
app.info.targetSdkVersion, seInfo, requiredAbi, instructionSet,
app.info.dataDir, invokeWith,
new String[] {PROC_START_SEQ_IDENT + app.startSeq});
}
public static final ProcessStartResult start(final String processClass,
final String niceName,
int uid, int gid, int[] gids,
int runtimeFlags, int mountExternal,
int targetSdkVersion,
String seInfo,
String abi,
String instructionSet,
String appDataDir,
String invokeWith,
String[] zygoteArgs) {
return zygoteProcess.start(processClass, niceName, uid, gid, gids,
runtimeFlags, mountExternal, targetSdkVersion, seInfo,
abi, instructionSet, appDataDir, invokeWith, zygoteArgs);
}
public final Process.ProcessStartResult start(final String processClass,
final String niceName,
int uid, int gid, int[] gids,
int runtimeFlags, int mountExternal,
int targetSdkVersion,
String seInfo,
String abi,
String instructionSet,
String appDataDir,
String invokeWith,
String[] zygoteArgs) {
try {
return startViaZygote(processClass, niceName, uid, gid, gids,
runtimeFlags, mountExternal, targetSdkVersion, seInfo,
abi, instructionSet, appDataDir, invokeWith, false /* startChildZygote */,
zygoteArgs);
} catch (ZygoteStartFailedEx ex) {
Log.e(LOG_TAG,
"Starting VM process through Zygote failed");
throw new RuntimeException(
"Starting VM process through Zygote failed", ex);
}
}
private Process.ProcessStartResult startViaZygote(final String processClass,
final String niceName,
final int uid, final int gid,
final int[] gids,
int runtimeFlags, int mountExternal,
int targetSdkVersion,
String seInfo,
String abi,
String instructionSet,
String appDataDir,
String invokeWith,
boolean startChildZygote,
String[] extraArgs)
throws ZygoteStartFailedEx {
synchronized(mLock) {
return zygoteSendArgsAndGetResult(openZygoteSocketIfNeeded(abi), argsForZygote);
}
}
这一大段代码主要是:通过 zygote fork 出一个进程再创建出一个 android.app.ActivityThread 线程,调用该线程的 main 方法,接下来看 ActivityThread 的 main 方法
public static void main(String[] args) {
//创建该线程的 looper 对象
Looper.prepareMainLooper();
ActivityThread thread = new ActivityThread();
//调用 attach
thread.attach(false, startSeq);
//循环
Looper.loop();
throw new RuntimeException("Main thread loop unexpectedly exited");
}
private void attach(boolean system, long startSeq) {
sCurrentActivityThread = this;
mSystemThread = system;
//根据 main 方法中的值,当前 system 值为 false
if (!system) {
android.ddm.DdmHandleAppName.setAppName("<pre-initialized>",
UserHandle.myUserId());
RuntimeInit.setApplicationObject(mAppThread.asBinder());
//获取当前的 ActivityManagerService
final IActivityManager mgr = ActivityManager.getService();
try {
//注意 mAppThread 是 ApplicationThread 对象
//主要作用是作为一个 service 端接收 ActivityManagerService 的消息
mgr.attachApplication(mAppThread, startSeq);
} catch (RemoteException ex) {
throw ex.rethrowFromSystemServer();
}
}
}
public final void attachApplication(IApplicationThread thread, long startSeq) {
synchronized (this) {
//获取对应 ID
int callingPid = Binder.getCallingPid();
final int callingUid = Binder.getCallingUid();
final long origId = Binder.clearCallingIdentity();
//绑定 Application
attachApplicationLocked(thread, callingPid, callingUid, startSeq);
Binder.restoreCallingIdentity(origId);
}
}
private final boolean attachApplicationLocked(IApplicationThread thread,
int pid, int callingUid, long startSeq) {
//......
//创建 ContextImpl 对象
//创建 mInstrumentation 实例
//创建 Application 调用对应的 onCreate 方法
//这里就不展开了
thread.bindApplication(processName, appInfo, providers,
app.instr.mClass,
profilerInfo, app.instr.mArguments,
app.instr.mWatcher,
app.instr.mUiAutomationConnection, testMode,
mBinderTransactionTrackingEnabled, enableTrackAllocation,
isRestrictedBackupMode || !normalMode, app.persistent,
new Configuration(getGlobalConfiguration()), app.compat,
getCommonServicesLocked(app.isolated),
mCoreSettingsObserver.getCoreSettingsLocked(),
buildSerial, isAutofillCompatEnabled);
//.....
if (normalMode) {
try {
//启动对应 activity
if (mStackSupervisor.attachApplicationLocked(app)) {
didSomething = true;
}
} catch (Exception e) {
Slog.wtf(TAG, "Exception thrown launching activities in " + app, e);
badApp = true;
}
}
//....
}
boolean attachApplicationLocked(ProcessRecord app) throws RemoteException {
final String processName = app.processName;
boolean didSomething = false;
//调用 realStartActivityLocked 方法
if (realStartActivityLocked(activity, app,
top == activity /* andResume */, true /* checkConfig */)) {
didSomething = true;
}
return didSomething;
}
最后走了一圈,又回到了 realStartActivityLocked 方法,所以启动 activity 不管进程有没有存在,最终都会走到realStartActivityLocked 方法中
final boolean realStartActivityLocked(ActivityRecord r, ProcessRecord app,
boolean andResume, boolean checkConfig) throws RemoteException {
//.....
//使用 ClientTransaction 管理生命周期
final ClientTransaction clientTransaction = ClientTransaction.obtain(app.thread,
r.appToken);
//将 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, app.repProcState, r.icicle,
r.persistentState, results, newIntents, mService.isNextTransitionForward(),
profilerInfo));
// 根据前面,可以知道 andResume 值为true
final ActivityLifecycleItem lifecycleItem;
if (andResume) {
lifecycleItem = ResumeActivityItem.obtain(mService.isNextTransitionForward());
} else {
lifecycleItem = PauseActivityItem.obtain();
}
//设置状态
clientTransaction.setLifecycleStateRequest(lifecycleItem);
// 调度
mService.getLifecycleManager().scheduleTransaction(clientTransaction);
//....
}
根据前面的分析,知道分别会调用 LaunchActivityItem.execute 方法和 ResumeActivityItem.execute 方法,先来看第一个
// LaunchActivityItem 类中 execute 方法
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);
//调用 handleLaunchActivity 方法
//通过之前的分析可以知道 client 为 ActivityThread
client.handleLaunchActivity(r, pendingActions, null /* customIntent */);
Trace.traceEnd(TRACE_TAG_ACTIVITY_MANAGER);
}
// ActivityThread 中
public Activity handleLaunchActivity(ActivityClientRecord r,
PendingTransactionActions pendingActions, Intent customIntent) {
//.....
final Activity a = performLaunchActivity(r, customIntent);
//....
return a;
}
//该方法通过反射创建对应的activity实例
//调用该 activity 的onCreate 方法
private Activity performLaunchActivity(ActivityClientRecord r, Intent customIntent) {
ActivityInfo aInfo = r.activityInfo;
//获取包名
ComponentName component = r.intent.getComponent();
//创建 ContextImpl 实例
//这里可以知道 activity 中的 context 的实例为 ContextImpl
ContextImpl appContext = createBaseContextForActivity(r);
Activity activity = null;
try {
//获取 ClassLoader
java.lang.ClassLoader cl = appContext.getClassLoader();
//反射生成 activity 对象
activity = mInstrumentation.newActivity(
cl, component.getClassName(), r.intent);
StrictMode.incrementExpectedActivityCount(activity.getClass());
r.intent.setExtrasClassLoader(cl);
r.intent.prepareToEnterProcess();
if (r.state != null) {
r.state.setClassLoader(cl);
}
} catch (Exception e) {
if (!mInstrumentation.onException(activity, e)) {
throw new RuntimeException(
"Unable to instantiate activity " + component
+ ": " + e.toString(), e);
}
}
try {
//....
//初始化参数
//关联该 activity 和 context
//创建 PhoneWindow
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);
//调用activity 的 onCreate 方法
if (r.isPersistable()) {
mInstrumentation.callActivityOnCreate(activity, r.state, r.persistentState);
} else {
mInstrumentation.callActivityOnCreate(activity, r.state);
}
//将状态置为 ON_CREATE
r.setState(ON_CREATE);
} 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;
}
public void callActivityOnCreate(Activity activity, Bundle icicle,
PersistableBundle persistentState) {
prePerformCreate(activity);
activity.performCreate(icicle, persistentState);
postPerformCreate(activity);
}
final void performCreate(Bundle icicle, PersistableBundle persistentState) {
//调用 onCreate 方法
if (persistentState != null) {
onCreate(icicle, persistentState);
} else {
onCreate(icicle);
}
//.....
}
到这里,activity 的创建和 onCreate 方法的调用就完成了,以此类推 ResumeActivityItem.execute 方法就是调用 activity 的 onResume 方法。那么问题来了,中间的 onStart 方法在什么时候调用呢?还记得下面这一句代码
final boolean realStartActivityLocked(ActivityRecord r, ProcessRecord app,
boolean andResume, boolean checkConfig) throws RemoteException {
//设置状态
clientTransaction.setLifecycleStateRequest(lifecycleItem);
}
//给状态赋值
public void setLifecycleStateRequest(ActivityLifecycleItem stateRequest) {
mLifecycleStateRequest = stateRequest;
}
上面的代码表示将 mLifecycleStateRequest 的值赋为 ResumeActivityItem,还记得之前的一段代码
private void executeLifecycleState(ClientTransaction transaction) {
//获取最终状态的 ActivityLifecycleItem
//通过上面的赋值可以知道 lifecycleItem 为 ResumeActivityItem
final ActivityLifecycleItem lifecycleItem = transaction.getLifecycleStateRequest();
// 循环到最终请求状态
//lifecycleItem.getTargetState() 值为 ON_RESUME
cycleToPath(r, lifecycleItem.getTargetState(), true /* excludeLastState */);
}
public void cycleToPath(ActivityClientRecord r, int finish) {
cycleToPath(r, finish, false /* excludeLastState */);
}
private void cycleToPath(ActivityClientRecord r, int finish,
boolean excludeLastState) {
//获取当前的状态
//执行完 onCreate 方法 所以状态为 ON_CREATE
final int start = r.getLifecycleState();
//获取需要执行状态列表
final IntArray path = mHelper.getLifecyclePath(start, finish, excludeLastState);
//执行
performLifecycleSequence(r, path);
}
上面这个方法主要做了三件事:
1.获取当前生命周期的状态,通过上面刚执行完 onCreate 方法可以知道为 ON_CREATE
2.构建中间需要执行的状态列表
3.执行需要执行的状态
来看第二件事
public IntArray getLifecyclePath(int start, int finish, boolean excludeLastState) {
//....
//通过分析知道 finish 为 ON_RESUME start 为 ON_CREATE
//这两个是一个枚举类,并且 ON_RESUME > ON_CREATE
//所以走这个循环
if (finish >= start) {
// 将中间状态增加进去,通过枚举类可以知道为ON_START
//所以当前 mLifecycleSequence 中存在的状态为 ON_START、 ON_RESUME
for (int i = start + 1; i <= finish; i++) {
mLifecycleSequence.add(i);
}
} else {
//....
}
return mLifecycleSequence;
}
第二件事就是将 ON_START 添加到 mLifecycleSequence 中,继续来看第三件事
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:
//执行 handleStartActivity 就是执行 onStart 方法
mTransactionHandler.handleStartActivity(r, mPendingActions);
break;
//通过分析,也会走这里
case ON_RESUME:
//调用 handleResumeActivity 就是执行 onResume 方法
mTransactionHandler.handleResumeActivity(r.token, false /* finalStateRequest */,
r.isForward, "LIFECYCLER_RESUME_ACTIVITY");
break;
//..
}
}
}
所以 onStart 方法会在 onResume 之前执行,一个问题,这里执行了一遍 onResume ,后面又调度执行了一遍 onResume,这就是 onResume 可能会执行多遍的原因?
到这里,activity 的启动就到此结束
网友评论