乐趣区

Android Frameworks 190310期 —— onSaveInstanceState到底做了些什么?

Android Frameworks 是最近我刚创建的一个文集,这篇文章也是 Android Frameworks 这个文集的第一篇文章(发现自己好久没写简书了),主要目的是想跟大家从源码的角度分享,或者更多的是交流一下 Android Frameworks 里的一些关键的机制,对于描述的内容有异议的可以留言,大家一起交流和学习。今天的内容是从源码角度了解 Activity 中的 onSaveInstanceState 和 onRestoreInstanceState:
1. onSaveInstanceState 到底做了些什么?
protected void onSaveInstanceState(Bundle outState) {
// 存储窗口视图状态
outState.putBundle(WINDOW_HIERARCHY_TAG, mWindow.saveHierarchyState());

outState.putInt(LAST_AUTOFILL_ID, mLastAutofillId);
// 存储 Fragment 状态
Parcelable p = mFragments.saveAllState();
if (p != null) {
outState.putParcelable(FRAGMENTS_TAG, p);
}
if (mAutoFillResetNeeded) {
outState.putBoolean(AUTOFILL_RESET_NEEDED, true);
// 存储 Android 自动填充的状态,非重点
getAutofillManager().onSaveInstanceState(outState);
}
// 调用 ActivityLifeCallbacks 的 onSaveInstanceState 方法进行状态存储
getApplication().dispatchActivitySaveInstanceState(this, outState);
}

从源码上看,不难发现 onSaveInstanceState 主要做了以下三个内容:

存储窗口视图状态
存储 Fragment 状态
调用 ActivityLifeCallbacks 的 onSaveInstanceState 方法进行状态存储

通过调用 PhoneWindow 的 saveHierarchyState 方法实际上是调用 mContentParent 的 saveHierarchyState 方法:
@Override
public Bundle saveHierarchyState() {
Bundle outState = new Bundle();
if (mContentParent == null) {
return outState;
}

SparseArray<Parcelable> states = new SparseArray<Parcelable>();
mContentParent.saveHierarchyState(states);
outState.putSparseParcelableArray(VIEWS_TAG, states);
….
return outState;
}
其中 mContentParent 是 Activity 的主视图,本质是一个 View 对象,在 Activity#setContentView() 方法里进行初始化操作,接下来回到 View 的 saveHierarchyState 方法:
public void saveHierarchyState(SparseArray<Parcelable> container) {
dispatchSaveInstanceState(container);
}

protected void dispatchSaveInstanceState(SparseArray<Parcelable> container) {
if (mID != NO_ID && (mViewFlags & SAVE_DISABLED_MASK) == 0) {
mPrivateFlags &= ~PFLAG_SAVE_STATE_CALLED;
Parcelable state = onSaveInstanceState();
if ((mPrivateFlags & PFLAG_SAVE_STATE_CALLED) == 0) {
throw new IllegalStateException(
“Derived class did not call super.onSaveInstanceState()”);
}
if (state != null) {
// 以当前 View 的 ID 为 key 值存储起来
container.put(mID, state);
}
}
}
在 View 的 dispatchSaveInstanceState 方法里,会将 View#onSaveInstanceState() 方法返回的 Parcelable 对象以当前 View 的 ID 为 key 值存储起来,并返回,这也意味着如果当前 View 没有设置 ID,那么将无法进行 View 的 onSaveInstanceState 操作:
android:id=”@+id/tv_save_state”
View 的 onSaveInstanceState 方法默认返回空状态 BaseSavedState.EMPTY_STATE,可交由子 View 重写,如 TextView#onSaveInstanceState():
@Override
public Parcelable onSaveInstanceState() {
Parcelable superState = super.onSaveInstanceState();
// Save state if we are forced to
final boolean freezesText = getFreezesText();
boolean hasSelection = false;
int start = -1;
int end = -1;
if (mText != null) {
start = getSelectionStart();
end = getSelectionEnd();
if (start >= 0 || end >= 0) {
// Or save state if there is a selection
hasSelection = true;
}
}
if (freezesText || hasSelection) {
SavedState ss = new SavedState(superState);
if (freezesText) {
if (mText instanceof Spanned) {
final Spannable sp = new SpannableStringBuilder(mText);
if (mEditor != null) {
removeMisspelledSpans(sp);
sp.removeSpan(mEditor.mSuggestionRangeSpan);
}
ss.text = sp;
} else {
ss.text = mText.toString();
}
}
if (hasSelection) {
// XXX Should also save the current scroll position!
ss.selStart = start;
ss.selEnd = end;
}
if (isFocused() && start >= 0 && end >= 0) {
ss.frozenWithFocus = true;
}
ss.error = getError();
if (mEditor != null) {
ss.editorState = mEditor.saveInstanceState();
}
return ss;
}
return superState;
}

接下来进入 Fragment 状态的保存方法,mFragments.saveAllState(),mFragments 是一个 FragmentController 对象,主要用于提供 FragmentManager 对象,维护 Fragments 的生命周期,这里不做过多介绍,所以最终是调用 FragmentManager#saveAllState() 方法,该方法最终会返回一个 FragmentManagerState 对象:
Parcelable saveAllState() {

// 第一步:收集所有处于 active 状态的 Fragment
int N = mActive.size();
FragmentState[] active = new FragmentState[N];
boolean haveFragments = false;
for (int i=0; i<N; i++) {
Fragment f = mActive.valueAt(i);
if (f != null) {

FragmentState fs = new FragmentState(f);
active[i] = fs;
if (f.mState > Fragment.INITIALIZING && fs.mSavedFragmentState == null) {
fs.mSavedFragmentState = saveFragmentBasicState(f);

} else {
fs.mSavedFragmentState = f.mSavedFragmentState;
}
}
}

// 第二步:收集已经添加的 Fragments 的 Index
int[] added = null;
BackStackState[] backStack = null;
N = mAdded.size();
if (N > 0) {
added = new int[N];
for (int i=0; i<N; i++) {
added[i] = mAdded.get(i).mIndex;

}
}

// 第三步:保存回退栈的内容,FragmentManager 中的 BackStack 主要是用来存储 FragmentTransaction,具体可见下篇文章的讲解
if (mBackStack != null) {
N = mBackStack.size();
if (N > 0) {
backStack = new BackStackState[N];
for (int i=0; i<N; i++) {
backStack[i] = new BackStackState(this, mBackStack.get(i));
if (DEBUG) Log.v(TAG, “saveAllState: adding back stack #” + i
+ “: ” + mBackStack.get(i));
}
}
}

FragmentManagerState fms = new FragmentManagerState();
fms.mActive = active;
fms.mAdded = added;
fms.mBackStack = backStack;
fms.mNextFragmentIndex = mNextFragmentIndex;
if (mPrimaryNav != null) {
fms.mPrimaryNavActiveIndex = mPrimaryNav.mIndex;
}
saveNonConfig();
return fms;
}
对于第一步的方法最终会调用 FragmentManager#saveFragmentBasicState() 方法,此方法主要有以下任务:
Bundle saveFragmentBasicState(Fragment f) {
Bundle result = null;

// 调用 Fragment#onSaveInstanceState() 方法(可由子类重写)
f.performSaveInstanceState(mStateBundle);
dispatchOnFragmentSaveInstanceState(f, mStateBundle, false);

// 保存 View 的视图状态,跟上面内容介绍一致
if (f.mView != null) {
saveFragmentViewState(f);
}
// mSavedViewState 为已保存的视图状态
if (f.mSavedViewState != null) {
if (result == null) {
result = new Bundle();
}
result.putSparseParcelableArray(
FragmentManagerImpl.VIEW_STATE_TAG, f.mSavedViewState);
}
// 记录 Fragment 的显示属性
if (!f.mUserVisibleHint) {
if (result == null) {
result = new Bundle();
}
// Only add this if it’s not the default value
result.putBoolean(FragmentManagerImpl.USER_VISIBLE_HINT_TAG, f.mUserVisibleHint);
}
return result;
}
Fragment 的 performSaveInstanceState 除了保存自身状态还会保存子 Fragment 的状态,实现如下:
void performSaveInstanceState(Bundle outState) {
onSaveInstanceState(outState);
if (mChildFragmentManager != null) {
Parcelable p = mChildFragmentManager.saveAllState();
if (p != null) {
outState.putParcelable(Activity.FRAGMENTS_TAG, p);
}
}
}
最后,看一下 Activity#onSaveInstanceState 的最后一步:
getApplication().dispatchActivitySaveInstanceState(this, outState);

实际上是遍历已注册的 ActivityLifecycleCallback,并调用其 onActivitySaveInstanceState() 方法:
void dispatchActivitySaveInstanceState(Activity activity, Bundle outState) {
Object[] callbacks = collectActivityLifecycleCallbacks();
if (callbacks != null) {
for (int i=0; i<callbacks.length; i++) {
((ActivityLifecycleCallbacks)callbacks[i]).onActivitySaveInstanceState(activity,
outState);
}
}
}

至此,Activity#onSaveInstanceState 的工作已经做完了,总结起来,其时序图如下:
讲解过程省略了不少代码,需要做详细了解的可以进一步查看源码,关于 onRestoreInstanceState 的方法实现,主要是以上方法的一个逆过程,这里不再做过多的叙述,接下来内容主要讲 onSaveInstanceState 与 onRestoreInstanceState 的调用时机。
2. onSaveInstanceState 与 onRestoreInstanceState 调用时机
关于 onSaveInstanceState 调用时机的追踪,我们先来简单看一下一个 Activity 的启动过程:
Activity 的启动过程与 Binder 进程间通信机制息息相关,对于 Binder 进程间通信机制以及 Activity 的启动过程,我们在后期的文章里会仔细说明,这里就不在做过多说明。Activity 的启动过程主要的步骤可以概括如下:

MainActivity 向 ActivityManagerService 发送一个启动 SecondActivity 的进程间通信请求;
ActivityManagerService 保存 SecondActivity 的相关信息,并向 MainActivity 发送一个进入中止状态(pause)的进程间通信请求;
MainActivity 进入中止状态后,向 ActivityManagerService 发送一个已进入中止状态的进程间通信请求;
ActivityManagerService 发现 SecondActivity 所在进程不存在,则会发起启动新进程的请求;
当新进程启动完毕后,会向 SecondActivity 发送一个启动完成的进程间通信请求;
ActivityManagerService 将保存的 SecondActivity 信息发送给新创建的进程,以便其将 SecondActivity 启动起来

我们主要看第三步,Activity 接收 ActivityManagerService 的进程间通信请求最终都会由该 Activity 所在的进程对象 ActivityThread 里的 Handler 对象去处理:
// ActivityThread.java
private class H extends Handler {
public void handleMessage(Message msg) {
if (DEBUG_MESSAGES) Slog.v(TAG, “>>> handling: ” + codeToString(msg.what));
switch (msg.what) {

case PAUSE_ACTIVITY: {
// 通知 Activity 进入中止状态
Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, “activityPause”);
SomeArgs args = (SomeArgs) msg.obj;
handlePauseActivity((IBinder) args.arg1, false,
(args.argi1 & USER_LEAVING) != 0, args.argi2,
(args.argi1 & DONT_REPORT) != 0, args.argi3);
Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
} break;

}
}
核心方法为 handlePauseActivity:
private void handlePauseActivity(IBinder token, boolean finished,
boolean userLeaving, int configChanges, boolean dontReport, int seq) {
ActivityClientRecord r = mActivities.get(token);
if (DEBUG_ORDER) Slog.d(TAG, “handlePauseActivity ” + r + “, seq: ” + seq);
if (!checkAndUpdateLifecycleSeq(seq, r, “pauseActivity”)) {
return;
}
if (r != null) {

r.activity.mConfigChangeFlags |= configChanges;
performPauseActivity(token, finished, r.isPreHoneycomb(), “handlePauseActivity”);

}
}
接着在往下看 performPauseActivity:

final Bundle performPauseActivity(IBinder token, boolean finished,
boolean saveState, String reason) {
ActivityClientRecord r = mActivities.get(token);
return r != null ? performPauseActivity(r, finished, saveState, reason) : null;
}

final Bundle performPauseActivity(ActivityClientRecord r, boolean finished,
boolean saveState, String reason) {

if (finished) {
r.activity.mFinished = true;
}

// Next have the activity save its current state and managed dialogs…
if (!r.activity.mFinished && saveState) {
callCallActivityOnSaveInstanceState(r);
}

}
这时候关键方法已经显而易见了:
private void callCallActivityOnSaveInstanceState(ActivityClientRecord r) {
r.state = new Bundle();
r.state.setAllowFds(false);
if (r.isPersistable()) {
r.persistentState = new PersistableBundle();
mInstrumentation.callActivityOnSaveInstanceState(r.activity, r.state,
r.persistentState);
} else {
mInstrumentation.callActivityOnSaveInstanceState(r.activity, r.state);
}
}

public void callActivityOnSaveInstanceState(Activity activity, Bundle outState,
PersistableBundle outPersistentState) {
activity.performSaveInstanceState(outState, outPersistentState);
}

final void performSaveInstanceState(Bundle outState, PersistableBundle outPersistentState) {
// 这就是我们希望看到的方法
onSaveInstanceState(outState, outPersistentState);
saveManagedDialogs(outState);
storeHasCurrentPermissionRequest(outState);
if (DEBUG_LIFECYCLE) Slog.v(TAG, “onSaveInstanceState ” + this + “: ” + outState +
“, ” + outPersistentState);
}

总结起来,onSaveInstanceState 会在以下情况下被调用:

当用户按下 home 键;
长按 home 键切换应用程序;
按下电源键;
启动一个新的 Activity;
屏幕方向切换;
电话打入等情况发生

而 onRestoreInstanceState 只有在 activity 确实是被系统回收,重新创建 activity 的情况下才会被调用,所以主要分为以下两种情况:
a. activity 没有被销毁:
onPause -> onSaveInstanceState -> onStop -> onRestart -> onStart -> onResume
b. activity 被销毁:
onPause -> onSaveInstanceState -> onStop -> onDestroy -> onCreate -> onStart -> onRestoreInstanceState -> onResume
OK,今天的内容就到这里,下篇文章见 ~

退出移动版