基本概念
LifeCycle的原理
Jetpack为我们提供了两个接口:LifecycleOwner(被观察者)和LifecycleObserver(观察者)。即通过观察者模式,实现对页面生命周期的监听。
- LifeCycleOwner
public interface LifecycleOwner {
/**
* Returns the Lifecycle of the provider.
*
* @return The lifecycle of the provider.
*/
@NonNull
Lifecycle getLifecycle();
}
在新版本SDK包中,Activity/Fragment已经默认实现了LifecycleOwner接口。以Activity为例,Activity的基类 - ComponentActivity,实现了LifeCycleOwner接口:
public class ComponentActivity extends androidx.core.app.ComponentActivity implements
LifecycleOwner,
ViewModelStoreOwner,
SavedStateRegistryOwner,
OnBackPressedDispatcherOwner {
......
@NonNull
@Override
public Lifecycle getLifecycle() {
return mLifecycleRegistry;
}
}
----------------------Fragment----------------------
public class Fragment implements ComponentCallbacks, OnCreateContextMenuListener, LifecycleOwner,
ViewModelStoreOwner, SavedStateRegistryOwner{
......
}
而mLifecycleRegistry的类型是LifecycleRegistry,LifecycleRegistry是LifeCycle抽象类的子类,如下图所示: