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

Posted 码农 小生

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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相关的核心笔记 ,面试题等一下资料,我免费分享给大家。如果需要直接点击链接领取点击这里免费领取


在这里插入图片描述

以上是关于Android 面试总结 - ViewModel 是怎么保存和恢复?的主要内容,如果未能解决你的问题,请参考以下文章

2020安卓开发面试总结

2020安卓开发面试总结

Android 面试题:为什么 Activity 都重建了 ViewModel 还存在?—— Jetpack 系列

Android面试题ViewModel源码分析,在什么情况下的「销毁重建」能够对数据进行无缝恢复?

2022年Android面试之Jetpack(AAC框架)篇

Android ViewModel 并不是直接写业务的讨论