Activity生命周期调用顺序,接着上篇
源码分析:Activity声明周期调用顺序(一)
当进入一个Activity后,会执行attach()→onCreate()→onStart()→onRestoreInstanceState()→onPostCreate()→onResume()→onPostResume()等方法
public void handleMessage(Message msg) {
...
switch (msg.what) {
//启动Activity
case LAUNCH_ACTIVITY: {
final ActivityClientRecord r = (ActivityClientRecord) msg.obj;
r.packageInfo = getPackageInfoNoCheck(
r.activityInfo.applicationInfo, r.compatInfo);
//【注:1】处理启动的Activity
handleLaunchActivity(r, null, "LAUNCH_ACTIVITY");
} break;
...
//我们只看,要打开的activity的声明周期
private void handleLaunchActivity(ActivityClientRecord r, Intent customIntent, String reason) {
...
// Make sure we are running with the most recent config.
handleConfigurationChanged(null, null);
WindowManagerGlobal.initialize();
//【注:2】 这里执行了attach跟oncreate等
Activity a = performLaunchActivity(r, customIntent);
if (a != null) {
r.createdConfig = new Configuration(mConfiguration);
reportSizeConfigurations(r);
Bundle oldState = r.state;
//【注:3】 这里执行了onResume等
handleResumeActivity(r.token, false, r.isForward,
!r.activity.mFinished && !r.startsNotResumed, r.lastProcessedSeq, reason);
if (!r.activity.mFinished && r.startsNotResumed) {
performPauseActivityIfNeeded(r, reason);
if (r.isPreHoneycomb()) {
r.state = oldState;
}
}
} else {
try {
ActivityManager.getService()
.finishActivity(r.token, Activity.RESULT_CANCELED, null,
Activity.DONT_FINISH_TASK_WITH_ACTIVITY);
} catch (RemoteException ex) {
throw ex.rethrowFromSystemServer();
}
}
}
private Activity performLaunchActivity(ActivityClientRecord r, Intent customIntent) {
...
ContextImpl appContext = createBaseContextForActivity(r);
Activity activity = null;
java.lang.ClassLoader cl = appContext.getClassLoader();
//创建Activity
activity = mInstrumentation.newActivity(
cl, component.getClassName(), r.intent);
try {
if (activity != null) {
...
//执行activity的onAttach()方法
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.mCalled = false;
//执行activity的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;
r.stopped = true;
if (!r.activity.mFinished) {
//执行Activity的onStart()方法
activity.performStart();
r.stopped = false;
}
//执行Activity的onRestoreInstance()方法
if (!r.activity.mFinished) {
if (r.isPersistable()) {
if (r.state != null || r.persistentState != null) {
mInstrumentation.callActivityOnRestoreInstanceState(activity, r.state,
r.persistentState);
}
} else if (r.state != null) {
mInstrumentation.callActivityOnRestoreInstanceState(activity, r.state);
}
}
//执行Activity的onPostCreate()
if (!r.activity.mFinished) {
activity.mCalled = false;
if (r.isPersistable()) {
mInstrumentation.callActivityOnPostCreate(activity, r.state,
r.persistentState);
} else {
mInstrumentation.callActivityOnPostCreate(activity, r.state);
}
}
}
r.paused = true;
mActivities.put(r.token, r);
return activity;
}
这里面执行了Activity的onAttach(),onCreate(),onStart(),onRestoreInstance(),onPostCreate()方法
final void handleResumeActivity(IBinder token,
boolean clearHide, boolean isForward, boolean reallyResume, int seq, String reason) {
ActivityClientRecord r = mActivities.get(token);
if (!checkAndUpdateLifecycleSeq(seq, r, "resumeActivity")) {
return;
}
unscheduleGcIdler();
mSomeActivitiesChanged = true;
// 【注:4】执行onResume
r = performResumeActivity(token, clearHide, reason);
if (r != null) {
final Activity a = r.activity;
final int forwardBit = isForward ?
WindowManager.LayoutParams.SOFT_INPUT_IS_FORWARD_NAVIGATION : 0;
boolean willBeVisible = !a.mStartedActivity;
if (!willBeVisible) {
try {
willBeVisible = ActivityManager.getService().willActivityBeVisible(
a.getActivityToken());
} catch (RemoteException e) {
throw e.rethrowFromSystemServer();
}
}
//这里是处理Activity的View显示的,以后会分析
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;
ViewRootImpl impl = decor.getViewRootImpl();
if (impl != null) {
impl.notifyChildRebuilt();
}
}
if (a.mVisibleFromClient) {
if (!a.mWindowAdded) {
a.mWindowAdded = true;
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);
}
}
} 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;
}
WindowManager.LayoutParams l = 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) {
r.activity.makeVisible();
}
}
if (!r.onlyLocalRequest) {
r.nextIdle = mNewActivities;
mNewActivities = r;
if (localLOGV) Slog.v(
TAG, "Scheduling idle handler for " + r);
Looper.myQueue().addIdleHandler(new Idler());
}
r.onlyLocalRequest = false;
// Tell the activity manager we have resumed.
if (reallyResume) {
try {
ActivityManager.getService().activityResumed(token);
} catch (RemoteException ex) {
throw ex.rethrowFromSystemServer();
}
}
} else {
// 当Activity执行onResume时候出现异常,就直接关闭它
try {
ActivityManager.getService()
.finishActivity(token, Activity.RESULT_CANCELED, null,
Activity.DONT_FINISH_TASK_WITH_ACTIVITY);
} catch (RemoteException ex) {
throw ex.rethrowFromSystemServer();
}
}
}
这个放出除了调用了,接下来要【注:4】performResumeActivity()方法,还处理了Activity显示View的逻辑。这里,我们只看需要打开的Activity的声明周期调用。接下来,看【注:4】。
public final ActivityClientRecord performResumeActivity(IBinder token,
boolean clearHide, String reason) {
ActivityClientRecord r = mActivities.get(token);
if (r != null && !r.activity.mFinished) {
//...省略代码
//
r.activity.performResume();
//...省略代码
}
return r;
}
调用activity的performResume();
final void performResume() {
//1,执行performRestart
performRestart();
//...省略代码
mCalled = false;
// 2,通过Instrumentation调用onResume
mInstrumentation.callActivityOnResume(this);
//3,执行onPostResume()方法
onPostResume();
}
1,执行performRestart()方法都做了什么
final void performRestart() {
//...省略代码
//如果mStopped为true的话。会执行下面onRestart()方法
//后面我们早onStop()之后,mStopped会置为true
if (mStopped) {
mStopped = false;
mCalled = false;
//调用activity的onRestart()方法
mInstrumentation.callActivityOnRestart(this);
if (!mCalled) {
throw new SuperNotCalledException(
"Activity " + mComponent.toShortString() +
" did not call through to super.onRestart()");
}
//...省略代码
performStart();
}
}
这个方法,都是只有在,mStopped=true的情况下才会执行。
这里的mStopped其实在Activity的onStop()方法才会置为true,执行了onRestart(),
最后调用了performStart()这个方法
final void performStart() {
mActivityTransitionState.setEnterActivityOptions(this, getActivityOptions());
//调用了Instrumentation.callActivityOnStart(this);
mInstrumentation.callActivityOnStart(this);
//省略代码
这里执行了onStart()方法。
到这里,我们结合上面mStopped变量,就知道了performRestart()方法执行的流程。onStop()-onRestart()-onStart(),就是在跳转Activity,返回的时候,执行的。
最后,看下Instrumentation里面的方法。我们发现,其实Activity的声明周期都是通过Instrumentation类来实现的。
public class Instrumentation {
public void callActivityOnResume(Activity activity) {
activity.mResumed = true;
//这里看到,最终调用了onResume()
activity.onResume();
}
public void callActivityOnRestart(Activity activity) {
//调用onRestart
activity.onRestart();
}
public void callActivityOnStart(Activity activity) {
activity.onStart();
}
}
到这里就全部看完了。通过分析可以看到Activity的声明周期调用都是通过Instrumentation来调用的。
从ActivityThread.H的LAUNCH_ACTIVITY消息的执行流程图。