Android技术周报是最近我刚创建的一个文集,这篇文章也是Android技术周报这个文集的第一篇文章(发现自己好久没写文章了),主要目的是记录和分享一些工作中遇到的问题,并对其进行深入研究,对于描述的内容有异议的可以留言,大家一起交流和学习。今天的内容是从源码角度了解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,今天的内容就到这里,下篇文章见 ~