MVVM基础

698 阅读8分钟

一、基础介绍

1.1 主要构成

在这里插入图片描述

1.2 添加依赖

implementation 'androidx.appcompat:appcompat:1.2.0'

二、Lifecycle基础用法

通过在方法上添加lifecycle相关注解@OnLifecycleEvent(value = Lifecycle.Event.ON_START),在Activity执行对应生命周期函数后,会调用添加了该注解的方法。如下所示:

public class ThirdActivity extends AppCompatActivity {

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        // 关键方法,使用Lifecycle
        getLifecycle().addObserver(presenter);
    }
public class ThirdPresenter implements LifecycleObserver {

    private static String TAG = "ThirdPresenter";

    public ThirdPresenter(IThirdView thirdView) {
        this.thirdView = thirdView;
    }

	// 监听Lifecycle.Event
    @OnLifecycleEvent(value = Lifecycle.Event.ON_START)
    private void onStartTest(LifecycleOwner lifecycleOwner) {
        if (lifecycleOwner.getLifecycle().getCurrentState().isAtLeast(STARTED)) {
            Log.d(TAG, "OnLifecycleEvent: ON_START");
        }
    }

    @OnLifecycleEvent(value = Lifecycle.Event.ON_RESUME)
    private void onResumeTest() {
        Log.d(TAG, "OnLifecycleEvent: ON_RESUME");
    }
}

上面例子分别在onStartTest()和onResumeTest()上面添加了OnLifecycleEvent注解,则在Activty启动后,会分别调用对应方法,输出日志:

OnLifecycleEvent: ON_START
OnLifecycleEvent: ON_RESUME

三、LiveData基础用法

LiveData 是一种可观察的数据存储器类。与常规的可观察类不同,LiveData 具有生命周期感知能力,如果观察者(由 Observer 类表示)的生命周期处于 STARTED 或 RESUMED 状态,则 LiveData 会认为该观察者处于活跃状态。LiveData 只会将更新通知给活跃的观察者,非活跃观察者不会收到更改通知。

3.1 基础用法

示例如下:

public class ThirdActivity extends AppCompatActivity {

	private TextView textView;
    private MutableLiveData<String> liveData;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        textView = findViewById(R.id.text_view);
        initLiveData();
    }
    
    private void initLiveData() {
        liveData = new MutableLiveData<>();
        // 关键方法,使用LiveData
        liveData.observe(this, new Observer<String>() {
            @Override
            public void onChanged(String s) {
            	textView.setText(s);
            }
        });
        liveData.setValue("liveData...");
    }

3.2 LiveData更新数据

LiveData更新数据有两种方式:
(1)liveData.setValue("liveData...");
(2)liveData.postValue("liveData...");
两种方式都必须在主线程中执行,不同点是postValue是在主线程中通过postRunalbe执行: 所以,对于以下代码:

liveData.postValue("a");
liveData.setValue("b");
// "a"会覆盖"b";

分析postValue的源码如下:

public abstract class LiveData<T> {
	private final Runnable mPostValueRunnable = new Runnable() {
        public void run() {
            Object newValue;
            synchronized (mDataLock) {
                newValue = mPendingData;
                mPendingData = NOT_SET;
            }
            setValue((T) newValue);
        }
    };
	protected void postValue(T value) {
        boolean postTask;
        synchronized (mDataLock) {
            postTask = mPendingData == NOT_SET;
            mPendingData = value;
        }
        if (!postTask) {
            return;
        }
        ArchTaskExecutor.getInstance().postToMainThread(mPostValueRunnable);
    }

四、ViewModel基础用法

ViewModel 类旨在以注重生命周期的方式存储和管理界面相关的数据。ViewModel 类让数据可在发生屏幕旋转等配置更改后继续留存。
对于简单的数据,Activity 可以使用 onSaveInstanceState() 方法从 onCreate() 中的捆绑包恢复其数据,但此方法仅适合可以序列化再反序列化的少量数据,而不适合数量可能较大的数据,如用户列表或位图。 在这里插入图片描述 ViewModel的使用分为两步,首先需要自定义ViewModel并让ViewModel持有LiveData,然后即可在View中创建ViewModel。

4.1 自定义ViewModel

/**
 *  自定义ViewModel
 */
public class UserViewModel extends ViewModel {

	// ViewModel持有LiveData
    private MutableLiveData<String> usernameLiveData;

    public UserViewModel() {
        usernameLiveData = new MutableLiveData<>();
    }

    public MutableLiveData<String> getUsernameLiveData() {
        return usernameLiveData;
    }

    public void requestUsername() {
        // 异步获取user
    }
}

4.2 创建ViewModel

创建ViewModel的方法为ViewModelProviders.of(),示例如下:

public class MainActivity extends AppCompatActivity implements View.OnClickListener {

	private TextView textView;
    private UserViewModel userViewModel;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        textView = findViewById(R.id.text_view);
        // 关键方法,获取ViewModel
        userViewModel = ViewModelProviders.of(this).get(UserViewModel.class);
        // 获取ViewModel中的LiveData
        userViewModel.getUsernameLiveData().observe(this, new Observer<String>() {
            @Override
            public void onChanged(String s) {
            	textView.setText(s);
            }
        });
    }

    @Override
    public void onClick(View v) {
        if (v.getId() == R.id.fourth_button_view) {
            userViewModel.requestUsername();
        }
    }
}

五、Lifecycle源码分析

5.1 总结

(1)如何实现生命周期回调:添加了一个透明的ReportFragment;
(2)如何避免内存泄漏:LifecycleRegistry对lifecycleOwner是弱引用;
(3)如何发送生命周期事件:LifecycleRegistry内部维护着一个FastSafeIterableMap,当生命周期改变时,遍历map进行通知;

5.2 源码分析

public class ThirdActivity extends AppCompatActivity {

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        // 关键方法,使用Lifecycle
        getLifecycle().addObserver(presenter);
    }

对应lifecycle的使用方法getLifecycle().addObserver(),首先分析Activity.getLifecycle():

public class ComponentActivity extends androidx.core.app.ComponentActivity implements
        LifecycleOwner,
        ViewModelStoreOwner,
        SavedStateRegistryOwner,
        OnBackPressedDispatcherOwner {
    
	static final class NonConfigurationInstances {
        Object custom;
        ViewModelStore viewModelStore;
    }

    private final LifecycleRegistry mLifecycleRegistry = new LifecycleRegistry(this);
    // Lazily recreated from NonConfigurationInstances by getViewModelStore()
    private ViewModelStore mViewModelStore;
    
	public Lifecycle getLifecycle() {
        return mLifecycleRegistry;
    }

	@Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mSavedStateRegistryController.performRestore(savedInstanceState);
        // 关键代码,使用一个透明的ReportFragment分发生命周期
        ReportFragment.injectIfNeededIn(this);
        if (mContentLayoutId != 0) {
            setContentView(mContentLayoutId);
        }
    }
    protected void onResume() {
    	dispatchActivityResumed();
    }
    
    private void dispatchActivityResumed() {
        getApplication().dispatchActivityResumed(this);
        Object[] callbacks = collectActivityLifecycleCallbacks();
        if (callbacks != null) {
            for (int i = 0; i < callbacks.length; i++) {
                ((Application.ActivityLifecycleCallbacks) callbacks[i]).onActivityResumed(this);
            }
        }
    }
}

接下来分析ReportFragment:

public class ReportFragment extends Fragment {

    public static void injectIfNeededIn(Activity activity) {
        if (Build.VERSION.SDK_INT >= 29) {
            // On API 29+, we can register for the correct Lifecycle callbacks directly
            activity.registerActivityLifecycleCallbacks(
                    new LifecycleCallbacks());
        }
        // Prior to API 29 and to maintain compatibility with older versions of
        // ProcessLifecycleOwner (which may not be updated when lifecycle-runtime is updated and
        // need to support activities that don't extend from FragmentActivity from support lib),
        // use a framework fragment to get the correct timing of Lifecycle events
        android.app.FragmentManager manager = activity.getFragmentManager();
        if (manager.findFragmentByTag(REPORT_FRAGMENT_TAG) == null) {
            manager.beginTransaction().add(new ReportFragment(), REPORT_FRAGMENT_TAG).commit();
            manager.executePendingTransactions();
        }
    }

    // 分发生命周期事件
    static void dispatch(@NonNull Activity activity, @NonNull Lifecycle.Event event) {
    	// 生命周期分发最终调用了LifecycleRegistry.handleLifecycleEvent()
        if (activity instanceof LifecycleRegistryOwner) {
            ((LifecycleRegistryOwner) activity).getLifecycle().handleLifecycleEvent(event);
            return;
        }

        if (activity instanceof LifecycleOwner) {
            Lifecycle lifecycle = ((LifecycleOwner) activity).getLifecycle();
            if (lifecycle instanceof LifecycleRegistry) {
                ((LifecycleRegistry) lifecycle).handleLifecycleEvent(event);
            }
        }
    }
    
    private void dispatchCreate(ActivityInitializationListener listener) {
        if (listener != null) {
            listener.onCreate();
        }
    }
    
    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        dispatchCreate(mProcessListener);
        dispatch(Lifecycle.Event.ON_CREATE);
    }
    
    // 生命周期回调
    static class LifecycleCallbacks implements Application.ActivityLifecycleCallbacks {
        @Override
        public void onActivityCreated(@NonNull Activity activity,
                @Nullable Bundle bundle) {
        }

        @Override
        public void onActivityPostCreated(@NonNull Activity activity,
                @Nullable Bundle savedInstanceState) {
            dispatch(activity, Lifecycle.Event.ON_CREATE);
        }
    }
}

然后分析LifecycleRegistry.handleLifecycleEvent()及LifecycleRegistry.addObserver():

public class LifecycleRegistry extends Lifecycle {
	// 所有添加的监听生命周期的observer
	private FastSafeIterableMap<LifecycleObserver, ObserverWithState> mObserverMap =
            new FastSafeIterableMap<>();
	// 弱引用避免内存泄漏
	private final WeakReference<LifecycleOwner> mLifecycleOwner;
	
	public LifecycleRegistry(@NonNull LifecycleOwner provider) {
        mLifecycleOwner = new WeakReference<>(provider);
        mState = INITIALIZED;
    }
    public void handleLifecycleEvent(@NonNull Lifecycle.Event event) {
        State next = getStateAfter(event);
        moveToState(next);
    }

    private void moveToState(State next) {
        if (mState == next) {
            return;
        }
        mState = next;
        if (mHandlingEvent || mAddingObserverCounter != 0) {
            mNewEventOccurred = true;
            // we will figure out what to do on upper level.
            return;
        }
        mHandlingEvent = true;
        sync();
        mHandlingEvent = false;
    }
    
	private void sync() {
        LifecycleOwner lifecycleOwner = mLifecycleOwner.get();
        if (lifecycleOwner == null) {
            throw new IllegalStateException("LifecycleOwner of this LifecycleRegistry is already"
                    + "garbage collected. It is too late to change lifecycle state.");
        }
        // 遍历map进行生命周期事件通知
        while (!isSynced()) {
            mNewEventOccurred = false;
            // no need to check eldest for nullability, because isSynced does it for us.
            if (mState.compareTo(mObserverMap.eldest().getValue().mState) < 0) {
                backwardPass(lifecycleOwner);
            }
            Entry<LifecycleObserver, ObserverWithState> newest = mObserverMap.newest();
            if (!mNewEventOccurred && newest != null
                    && mState.compareTo(newest.getValue().mState) > 0) {
                forwardPass(lifecycleOwner);
            }
        }
        mNewEventOccurred = false;
    }
	
	@Override
    public void addObserver(@NonNull LifecycleObserver observer) {
        State initialState = mState == DESTROYED ? DESTROYED : INITIALIZED;
        ObserverWithState statefulObserver = new ObserverWithState(observer, initialState);
        ObserverWithState previous = mObserverMap.putIfAbsent(observer, statefulObserver);

        if (previous != null) {
            return;
        }
        LifecycleOwner lifecycleOwner = mLifecycleOwner.get();
        if (lifecycleOwner == null) {
            // it is null we should be destroyed. Fallback quickly
            return;
        }

        boolean isReentrance = mAddingObserverCounter != 0 || mHandlingEvent;
        State targetState = calculateTargetState(observer);
        mAddingObserverCounter++;
        while ((statefulObserver.mState.compareTo(targetState) < 0
                && mObserverMap.contains(observer))) {
            pushParentState(statefulObserver.mState);
            statefulObserver.dispatchEvent(lifecycleOwner, upEvent(statefulObserver.mState));
            popParentState();
            // mState / subling may have been changed recalculate
            targetState = calculateTargetState(observer);
        }

        if (!isReentrance) {
            // we do sync only on the top level.
            sync();
        }
        mAddingObserverCounter--;
    }
}

六、LiveData源码分析

6.1 总结

(1)如何实现可感知生命周期:调用了owner.getLifecycle().addObserver(wrapper);将liveData的封装wrapper添加到生命周期observer里;
(2)如何避免内存泄漏:在接收到destroy生命周期事件,调用removeObserver移除引用;
(3)如何数据更新原理:LiveData内部维护了一个SafeIterableMap,在数据发生变化时,遍历该map进行通知;

6.2 源码分析

对于LiveData的用法:

public class ThirdActivity extends AppCompatActivity {

	private TextView textView;
    private MutableLiveData<String> liveData;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        textView = findViewById(R.id.text_view);
        initLiveData();
    }
    
    private void initLiveData() {
        liveData = new MutableLiveData<>();
        // 关键方法,使用LiveData
        liveData.observe(this, new Observer<String>() {
            @Override
            public void onChanged(String s) {
            	textView.setText(s);
            }
        });
        liveData.setValue("onCreate...");
    }

首先从LiveData.observe()开始分析:

public abstract class LiveData<T> {

	private SafeIterableMap<Observer<? super T>, ObserverWrapper> mObservers = new SafeIterableMap<>();
            
	@MainThread
    public void observe(@NonNull LifecycleOwner owner, @NonNull Observer<? super T> observer) {
        assertMainThread("observe");
        if (owner.getLifecycle().getCurrentState() == DESTROYED) {
            // ignore
            return;
        }
        // 关键代码,将observer和lifecycleOwner绑定在一起,put到mObservers中
        LifecycleBoundObserver wrapper = new LifecycleBoundObserver(owner, observer);
        ObserverWrapper existing = mObservers.putIfAbsent(observer, wrapper);
        if (existing != null && !existing.isAttachedTo(owner)) {
            throw new IllegalArgumentException("Cannot add the same observer"
                    + " with different lifecycles");
        }
        if (existing != null) {
            return;
        }
        // 关键代码,可见LiveData可感知生命周期的原理就是通过Lifecycle实现的
        owner.getLifecycle().addObserver(wrapper);
    }
    
    @MainThread
    protected void setValue(T value) {
        assertMainThread("setValue");
        mVersion++;
        mData = value;
        dispatchingValue(null);
    }
    
    void dispatchingValue(@Nullable ObserverWrapper initiator) {
        if (mDispatchingValue) {
            mDispatchInvalidated = true;
            return;
        }
        mDispatchingValue = true;
        do {
            mDispatchInvalidated = false;
            if (initiator != null) {
                considerNotify(initiator);
                initiator = null;
            } else {
            	// 关键代码,遍历map将新的value发送给observer
                for (Iterator<Map.Entry<Observer<? super T>, ObserverWrapper>> iterator =
                        mObservers.iteratorWithAdditions(); iterator.hasNext(); ) {
                    considerNotify(iterator.next().getValue());
                    if (mDispatchInvalidated) {
                        break;
                    }
                }
            }
        } while (mDispatchInvalidated);
        mDispatchingValue = false;
    }
    
    private void considerNotify(ObserverWrapper observer) {
        if (!observer.mActive) {
            return;
        }
        if (!observer.shouldBeActive()) {
            observer.activeStateChanged(false);
            return;
        }
        if (observer.mLastVersion >= mVersion) {
            return;
        }
        observer.mLastVersion = mVersion;
        // 最后调用了Observer的onChanged()
        observer.mObserver.onChanged((T) mData);
    }
    
    // ObserverWrapper内
    // 实现了LifecycleEventObserver所以可感知生命周期
    class LifecycleBoundObserver extends ObserverWrapper implements LifecycleEventObserver {
        @NonNull
        final LifecycleOwner mOwner;

        LifecycleBoundObserver(@NonNull LifecycleOwner owner, Observer<? super T> observer) {
            super(observer);
            mOwner = owner;
        }

        @Override
        boolean shouldBeActive() {
            return mOwner.getLifecycle().getCurrentState().isAtLeast(STARTED);
        }

        @Override
        public void onStateChanged(@NonNull LifecycleOwner source, @NonNull Lifecycle.Event event) {
            if (mOwner.getLifecycle().getCurrentState() == DESTROYED) {
            	// 关键代码,DESTROYED时移除避免了内存泄漏
                removeObserver(mObserver);
                return;
            }
            activeStateChanged(shouldBeActive());
        }
    }
}

七、ViewModel源码分析

7.1 总结

7.1.1 Activity销毁重建恢复数据

如何实现屏幕旋转等配置改变导致activity销毁时ViewModel仍存在:

  1. 在DESTROY生命周期事件时判断如果是配置改变导致重建则不调用ViewModelStore().clear();
  2. 在Activity销毁时,performDestroyActivity()会调用retainNonConfigurationInstances()保存需要恢复的数据;
  3. Activity在调用retainNonConfigurationInstances()时,会先把ViewModel保存在ActivityClientRecord.NonConfigurationInstances中,然后在重建时调用performLaunchActivity(ActivityClientRecord r, Intent customIntent)时即可重新拿到ActivityClientRecord,实现了Activity重建时ViewModel不销毁;

7.1.2 onSaveInstance()区别

扩展一下,retainNonConfigurationInstances()onSaveInstance()都是用来销毁重建时保存状态的,二者区别在于:

onSaveInstanceretainNonConfigurationInstances
恢复方法与getLastNonConfigurationInstance()配合使用与onRestoreInstanceState()配合使用
保存的数据类型onSaveInstanceState(Bundle outState)
只支持Bundle类型
Object类型,可保存任何数据
保存的位置ActivityManagerService.ActivityRecord
进程被销毁重建时仍存在
ActivityClientRecord
进程被销毁后不存在
保存的进程ActivityManagerService.ActivityRecord位于ASM进程ActivityClientRecord位于APP进程

7.2 源码分析

对于ViewModel的用法:

public class MainActivity extends AppCompatActivity {
    private UserViewModel userViewModel;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        // 关键方法,获取ViewModel
        userViewModel = ViewModelProviders.of(this).get(UserViewModel.class);
        }
        
}

首先介绍下ComponentActivity内ViewModelStore保存了和该Activity关联的所有ViewModel:

public class ComponentActivity extends androidx.core.app.ComponentActivity implements
        LifecycleOwner,
        ViewModelStoreOwner,
        SavedStateRegistryOwner,
        OnBackPressedDispatcherOwner {
	// ViewModelStore
	private ViewModelStore mViewModelStore;
	
	public ComponentActivity() {
        Lifecycle lifecycle = getLifecycle();
        if (Build.VERSION.SDK_INT >= 19) {
            getLifecycle().addObserver(new LifecycleEventObserver() {
                @Override
                public void onStateChanged(@NonNull LifecycleOwner source,
                        @NonNull Lifecycle.Event event) {
                    if (event == Lifecycle.Event.ON_STOP) {
                        Window window = getWindow();
                        final View decor = window != null ? window.peekDecorView() : null;
                        if (decor != null) {
                            decor.cancelPendingInputEvents();
                        }
                    }
                }
            });
        }
        getLifecycle().addObserver(new LifecycleEventObserver() {
            @Override
            public void onStateChanged(@NonNull LifecycleOwner source, @NonNull Lifecycle.Event event) {
                if (event == Lifecycle.Event.ON_DESTROY) {
                	// 关键代码:旋转屏幕等配置改变导致的重建,不清空ViewModel
                    if (!isChangingConfigurations()) {
                        getViewModelStore().clear();
                    }
                }
            }
        });

        if (19 <= SDK_INT && SDK_INT <= 23) {
            getLifecycle().addObserver(new ImmLeaksCleaner(this));
        }
    }
    
    public ViewModelStore getViewModelStore() {
        if (mViewModelStore == null) {
            NonConfigurationInstances nc =
                    (NonConfigurationInstances) getLastNonConfigurationInstance();
            if (nc != null) {
                // 关键代码:Restore the ViewModelStore from NonConfigurationInstances
                mViewModelStore = nc.viewModelStore;
            }
            if (mViewModelStore == null) {
                mViewModelStore = new ViewModelStore();
            }
        }
        return mViewModelStore;
    }
    
    /**
    * 当配置改变导致销毁重建时会调用该方法保存和配置无关的数据,可见ComponentActivity保存了ViewModel;
    **/ 
    public final Object onRetainNonConfigurationInstance() {
        Object custom = onRetainCustomNonConfigurationInstance();

        ViewModelStore viewModelStore = mViewModelStore;
        if (viewModelStore == null) {
            // No one called getViewModelStore(), so see if there was an existing
            // ViewModelStore from our last NonConfigurationInstance
            NonConfigurationInstances nc =
                    (NonConfigurationInstances) getLastNonConfigurationInstance();
            if (nc != null) {
                viewModelStore = nc.viewModelStore;
            }
        }

        if (viewModelStore == null && custom == null) {
            return null;
        }

        NonConfigurationInstances nci = new NonConfigurationInstances();
        nci.custom = custom;
        nci.viewModelStore = viewModelStore;
        return nci;
    }
}

首先分析ViewModelProviders.of(this)如下:

public class ViewModelProviders {
	private final Factory mFactory;
    private final ViewModelStore mViewModelStore;
    
    public ViewModelProvider(@NonNull ViewModelStore store, @NonNull Factory factory) {
        mFactory = factory;
        mViewModelStore = store;
    }
    
	public static ViewModelProvider of(@NonNull FragmentActivity activity) {
		// factory为null,则会创建一个默认的factory
        return of(activity, null);
    }
    
    public static ViewModelProvider of(@NonNull FragmentActivity activity,
            @Nullable Factory factory) {
        Application application = checkApplication(activity);
        if (factory == null) {
            factory = ViewModelProvider.AndroidViewModelFactory.getInstance(application);
        }
        return new ViewModelProvider(activity.getViewModelStore(), factory);
    }
    
    // ViewModelProviders.of().get()方法k-v的key是唯一字符串标识,value是ViewModel,将k-v添加到Activity的ViewModelStore中
    public <T extends ViewModel> T get(@NonNull Class<T> modelClass) {
        String canonicalName = modelClass.getCanonicalName();
        if (canonicalName == null) {
            throw new IllegalArgumentException("Local and anonymous classes can not be ViewModels");
        }
        return get(DEFAULT_KEY + ":" + canonicalName, modelClass);
    }
    
    public <T extends ViewModel> T get(@NonNull String key, @NonNull Class<T> modelClass) {
        ViewModel viewModel = mViewModelStore.get(key);

        if (modelClass.isInstance(viewModel)) {
            if (mFactory instanceof OnRequeryFactory) {
                ((OnRequeryFactory) mFactory).onRequery(viewModel);
            }
            return (T) viewModel;
        } else {
            //noinspection StatementWithEmptyBody
            if (viewModel != null) {
                // TODO: log a warning.
            }
        }
        if (mFactory instanceof KeyedFactory) {
            viewModel = ((KeyedFactory) (mFactory)).create(key, modelClass);
        } else {
            viewModel = (mFactory).create(modelClass);
        }
        mViewModelStore.put(key, viewModel);
        return (T) viewModel;
    }

八、销毁重建Activity

上面分析出了ViewModel是保存在ActivityClientRecord.NonConfigurationInstances实现了配置改变重建Activity 时不被销毁,这里继续分析NonConfigurationInstances在Activity销毁重建时是如何保存下来的,代码在ActivityThread中:

public final class ActivityThread extends ClientTransactionHandler {

	/**
	* 销毁Activity时调用
	*/
	ActivityClientRecord performDestroyActivity(IBinder token, boolean finishing,
            int configChanges, boolean getNonConfigInstance, String reason) {
        // 获得Activity的ActivityClientRecord
        ActivityClientRecord r = mActivities.get(token);
        Class<? extends Activity> activityClass = null;
        if (localLOGV) Slog.v(TAG, "Performing finish of " + r);
        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 {
                    // 这里在销毁的时候判断了是否是配置改变导致销毁重建,是则调用retainNonConfigurationInstances保存需要保存的数据
                    // 把retainNonConfigurationInstances()返回的数据保存到了ActivityClientRecord的lastNonConfigurationInstances里
                    r.lastNonConfigurationInstances = r.activity.retainNonConfigurationInstances();
                } catch (Exception e) {

                }
            }
            try {
                r.activity.mCalled = false;
                mInstrumentation.callActivityOnDestroy(r.activity);
                if (r.window != null) {
                    r.window.closeAllPanels();
                }
            } catch (Exception e) {
            }
            r.setState(ON_DESTROY);
        }
        schedulePurgeIdler();
        synchronized (mResourcesManager) {
            mActivities.remove(token);
        }
        StrictMode.decrementExpectedActivityCount(activityClass);
        return r;
    }
    
    /**
    * 启动Activity时调用
    */
    private Activity performLaunchActivity(ActivityClientRecord r, Intent customIntent) {
        ActivityInfo aInfo = r.activityInfo;
        if (r.packageInfo == null) {
            r.packageInfo = getPackageInfo(aInfo.applicationInfo, r.compatInfo,
                    Context.CONTEXT_INCLUDE_CODE);
        }

        ComponentName component = r.intent.getComponent();
        if (component == null) {
            component = r.intent.resolveActivity(
                mInitialApplication.getPackageManager());
            r.intent.setComponent(component);
        }

        if (r.activityInfo.targetActivity != null) {
            component = new ComponentName(r.activityInfo.packageName,
                    r.activityInfo.targetActivity);
        }

        ContextImpl appContext = createBaseContextForActivity(r);
        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) {
        }

        try {
            Application app = r.packageInfo.makeApplication(false, mInstrumentation);
            if (activity != null) {
                CharSequence title = r.activityInfo.loadLabel(appContext.getPackageManager());
                Configuration config = new Configuration(mCompatConfiguration);
                if (r.overrideConfig != null) {
                    config.updateFrom(r.overrideConfig);
                }
                if (DEBUG_CONFIGURATION) Slog.v(TAG, "Launching activity "
                        + r.activityInfo.name + " with config " + config);
                Window window = null;
                if (r.mPendingRemoveWindow != null && r.mPreserveWindow) {
                    window = r.mPendingRemoveWindow;
                    r.mPendingRemoveWindow = null;
                    r.mPendingRemoveWindowManager = null;
                }

                // Activity resources must be initialized with the same loaders as the
                // application context.
                appContext.getResources().addLoaders(
                        app.getResources().getLoaders().toArray(new ResourcesLoader[0]));

                appContext.setOuterContext(activity);
                // 这里将上次销毁重建时的NonConfigurationInstances重新赋给了新的Activity
                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);

                if (customIntent != null) {
                    activity.mIntent = customIntent;
                }
                r.lastNonConfigurationInstances = null;
                checkAndBlockForNetworkAccess();
                activity.mStartedActivity = false;
                int theme = r.activityInfo.getThemeResource();
                if (theme != 0) {
                    activity.setTheme(theme);
                }

                activity.mCalled = false;
                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;
                mLastReportedWindowingMode.put(activity.getActivityToken(),
                        config.windowConfiguration.getWindowingMode());
            }
            r.setState(ON_CREATE);

            // updatePendingActivityConfiguration() reads from mActivities to update
            // ActivityClientRecord which runs in a different thread. Protect modifications to
            // mActivities to avoid race.
            synchronized (mResourcesManager) {
                mActivities.put(r.token, r);
            }
        } catch (Exception e) {

        }

        return activity;
    }
}

The End

欢迎关注我,一起解锁更多技能:BC的主页~~💐💐💐 个人信息汇总.png

MVVM架构官方文档:developer.android.com/jetpack/gui…
lifecycle官方文档:developer.android.com/topic/libra…
LiveData官方文档:developer.android.com/topic/libra…
ViewModel官方文档:developer.android.com/topic/libra…
MVVM+kotlin协程:developer.android.com/topic/libra…
MVP与MVVM:proandroiddev.com/architectur…