Android 面试总结 - ViewModel 是怎么保存和恢复?

·  阅读 2219
Android 面试总结 - ViewModel 是怎么保存和恢复?

结合上一篇文章 Android 面试总结 - ViewModel 我们知道:

在配置更改时会调用 Activity#onRetainNonConfigurationInstance() 来保存保存着 ViewModel 示例的对象 mViewModelStore,并在 Activity 重建后调用 getViewModelStore() ,其中会调用 ensureViewModelStore() 在它内部会调用 getLastNonConfigurationInstance() 方法获取是否有缓存的 ViewModelStore 对象,若有则返回,没有则创建新 ViewModelStore 实例。

这篇文章主要看看在配置更改后,怎么调用 Activity#onRetainNonConfigurationInstance()

通过断点调试方式知道在配置更改后会调用到 ActivityThread#handleRelaunchActivity 方法

为啥会调用 ActivityThread#handleRelaunchActivity 后面学到了再分析 (刚看了一遍,没看懂,看懂再说~啦啦啦)

    @Override
    public void handleRelaunchActivity(ActivityClientRecord tmp,
            PendingTransactionActions pendingActions) {
        ...
        handleRelaunchActivityInner(r, configChanges, tmp.pendingResults, tmp.pendingIntents,
                pendingActions, tmp.startsNotResumed, tmp.overrideConfig, "handleRelaunchActivity");
        ...
复制代码

handleRelaunchActivityInner

    private void handleRelaunchActivityInner(ActivityClientRecord r, int configChanges,
            List<ResultInfo> pendingResults, List<ReferrerIntent> pendingIntents,
            PendingTransactionActions pendingActions, boolean startsNotResumed,
            Configuration overrideConfig, String reason) {
        ...
        // 注意第三个参数为 true
        handleDestroyActivity(r.token, false, configChanges, true, reason);
        ...
        handleLaunchActivity(r, pendingActions, customIntent);

复制代码

内部调用了 handleDestroyActivity,并且第三个参数 getNonConfigInstance = true handleLaunchActivity 方法后面再说

    @Override
    public void handleDestroyActivity(IBinder token, boolean finishing, int configChanges,
            boolean getNonConfigInstance, String reason) {
        ActivityClientRecord r = performDestroyActivity(token, finishing,
                configChanges, getNonConfigInstance, reason);
        ....
复制代码

再看 performDestroyActivity 方法 它是 Activity 销毁调用的核心实现

    /** Core implementation of activity destroy call. */
    ActivityClientRecord performDestroyActivity(IBinder token, boolean finishing,
            int configChanges, boolean getNonConfigInstance, String reason) {
        ActivityClientRecord r = mActivities.get(token);
        if (r != null) {
            activityClass = r.activity.getClass();
            r.activity.mConfigChangeFlags |= configChanges;
            if (finishing) {
                r.activity.mFinished = true;
            }

            performPauseActivityIfNeeded(r, "destroy");

            if (!r.stopped) {
                callActivityOnStop(r, false /* saveState */, "destroy");
            }
            if (getNonConfigInstance) {
                try {
                	// 重点来了
                    r.lastNonConfigurationInstances
                            = r.activity.retainNonConfigurationInstances();
                } catch (Exception e) {
                    if (!mInstrumentation.onException(r.activity, e)) {
                        throw new RuntimeException(
                                "Unable to retain activity "
                                + r.intent.getComponent().toShortString()
                                + ": " + e.toString(), e);
                    }
                }
            }

复制代码

重点在 performDestroyActivity 中,r.lastNonConfigurationInstances = r.activity.retainNonConfigurationInstances(); 调用了 Activity 对象的 retainNonConfigurationInstances() 并将返回值赋值给了 ActivityClientRecord 类型的 r 对象的 lastNonConfigurationInstances 属性。

再看看 Activity#retainNonConfigurationInstances 做了啥:

    NonConfigurationInstances retainNonConfigurationInstances() {
    	// 重点
        Object activity = onRetainNonConfigurationInstance();
        HashMap<String, Object> children = onRetainNonConfigurationChildInstances();
        FragmentManagerNonConfig fragments = mFragments.retainNestedNonConfig();

        // We're already stopped but we've been asked to retain.
        // Our fragments are taken care of but we need to mark the loaders for retention.
        // In order to do this correctly we need to restart the loaders first before
        // handing them off to the next activity.
        mFragments.doLoaderStart();
        mFragments.doLoaderStop(true);
        ArrayMap<String, LoaderManager> loaders = mFragments.retainLoaderNonConfig();

        if (activity == null && children == null && fragments == null && loaders == null
                && mVoiceInteractor == null) {
            return null;
        }

        NonConfigurationInstances nci = new NonConfigurationInstances();
        nci.activity = activity;
        nci.children = children;
        nci.fragments = fragments;
        nci.loaders = loaders;
        if (mVoiceInteractor != null) {
            mVoiceInteractor.retainInstance();
            nci.voiceInteractor = mVoiceInteractor;
        }
        return nci;
    }
复制代码

retainNonConfigurationInstances 中调用了 onRetainNonConfigurationInstance() 。 到这儿,知道了 onRetainNonConfigurationInstance() 是怎么调用的了。

回头再看看 handleRelaunchActivityInner 中最后调用了 handleLaunchActivity熟悉Activity 启动流程的应该知道 handleLaunchActivity 是启动 Activity 的重要步骤

    private void handleRelaunchActivityInner(ActivityClientRecord r, int configChanges,
            List<ResultInfo> pendingResults, List<ReferrerIntent> pendingIntents,
            PendingTransactionActions pendingActions, boolean startsNotResumed,
            Configuration overrideConfig, String reason) {
        ...
        // 注意第三个参数为 true
        handleDestroyActivity(r.token, false, configChanges, true, reason);
        ...
        handleLaunchActivity(r, pendingActions, customIntent);
    }
复制代码

handleLaunchActivity

    @Override
    public Activity handleLaunchActivity(ActivityClientRecord r,
            PendingTransactionActions pendingActions, Intent customIntent) {
         final Activity a = performLaunchActivity(r, customIntent);
    }
复制代码

performLaunchActivity 启动 Activity 的核心实现

    /**  Core implementation of activity launch. */
    private Activity performLaunchActivity(ActivityClientRecord r, Intent customIntent) {
            Activity activity = null;
        try {
            java.lang.ClassLoader cl = appContext.getClassLoader();
            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);
            }
        }
        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);
复制代码

创建了 Activity 实例并调用了 activityattach 方法,注意 attach 方法有一个参数 传入了 r.lastNonConfigurationInstances ,有没有很熟悉,刚刚在 performDestroyActivity 中,r.lastNonConfigurationInstances = r.activity.retainNonConfigurationInstances(); 调用了 Activity 对象的 retainNonConfigurationInstances() 并将返回值赋值给了 ActivityClientRecord 类型的 r 对象的 lastNonConfigurationInstances 属性。 已经串起来了。

    @UnsupportedAppUsage
    final void attach(Context context, ActivityThread aThread,
            Instrumentation instr, IBinder token, int ident,
            Application application, Intent intent, ActivityInfo info,
            CharSequence title, Activity parent, String id,
            NonConfigurationInstances lastNonConfigurationInstances,
            Configuration config, String referrer, IVoiceInteractor voiceInteractor,
            Window window, ActivityConfigCallback activityConfigCallback, IBinder assistToken) {
        attachBaseContext(context);
        ...
        mLastNonConfigurationInstances = lastNonConfigurationInstances;
        ...
复制代码

attach 中把之前保存的 lastNonConfigurationInstances 对象又赋值进新的 Activity 实例的 mLastNonConfigurationInstances 对象中了。

再回顾一下 怎么获取 ViewModel

    val mainViewModel = ViewModelProvider(this).get(MainViewModel::class.java)

	// ViewModelProvider 的构造方法
    public ViewModelProvider(@NonNull ViewModelStoreOwner owner) {
        this(owner.getViewModelStore(), owner instanceof HasDefaultViewModelProviderFactory
                ? ((HasDefaultViewModelProviderFactory) owner).getDefaultViewModelProviderFactory()
                : NewInstanceFactory.getInstance());
    }
复制代码
	// 
    @NonNull
    @Override
    public ViewModelStore getViewModelStore() {
        if (getApplication() == null) {
            throw new IllegalStateException("Your activity is not yet attached to the "
                    + "Application instance. You can't request ViewModel before onCreate call.");
        }
        ensureViewModelStore();
        return mViewModelStore;
    }

    @SuppressWarnings("WeakerAccess") /* synthetic access */
    void ensureViewModelStore() {
        if (mViewModelStore == null) {
            NonConfigurationInstances nc =
                    (NonConfigurationInstances) getLastNonConfigurationInstance();
            if (nc != null) {
                // Restore the ViewModelStore from NonConfigurationInstances
                mViewModelStore = nc.viewModelStore;
            }
            if (mViewModelStore == null) {
                mViewModelStore = new ViewModelStore();
            }
        }
    }
复制代码

获取 ViewModelStore 时,调用了 ensureViewModelStore() 方法,ensureViewModelStore() 在它内部会调用 getLastNonConfigurationInstance() 获取是否有缓存的 ViewModelStore 对象,若有则返回,没有则创建新 ViewModelStore 实例。

getLastNonConfigurationInstance

    @Nullable
    public Object getLastNonConfigurationInstance() {
        return mLastNonConfigurationInstances != null
                ? mLastNonConfigurationInstances.activity : null;
    }
复制代码

getLastNonConfigurationInstance 内部返回的是刚刚 Activity#attach 赋值的 mLastNonConfigurationInstances 对象。

到此 ViewModel 怎么保存和恢复的 这个问题解决!

分类:
Android
标签: