Jetpack组件之lifeCycle
2019-11-17 本文已影响0人
feifei_fly
一、声明周期的概念
1、Lifecycle 是一个抽象类,
它只有三个方法
- addObserver
- removeObserver
- getCurrentState
lifeCycle中 有Event和State的定义。
事件分为以下几种:
- ON_CREATE
- ON_START
- ON_RESUME
- ON_PAUSE
- ON_STOP
- ON_DESTROY
- ON_ANY
public abstract class Lifecycle {
//注册LifecycleObserver (比如Presenter)
public abstract void addObserver(@NonNull LifecycleObserver observer);
//移除LifecycleObserver
public abstract void removeObserver(@NonNull LifecycleObserver observer);
//获取当前状态
public abstract State getCurrentState();
public enum Event {
ON_CREATE,
ON_START,
ON_RESUME,
ON_PAUSE,
ON_STOP,
ON_DESTROY,
ON_ANY
}
public enum State {
DESTROYED,
INITIALIZED,
CREATED,
STARTED,
RESUMED;
public boolean isAtLeast(@NonNull State state) {
return compareTo(state) >= 0;
}
}
}
2、LifecycleOwner 声明周期的拥有者
LifecycleOwner 是一个接口,仅有一个方法getLifecycle()返回一个LiefCycle对象
public interface LifecycleOwner {
/**
* Returns the Lifecycle of the provider.
*
* @return The lifecycle of the provider.
*/
@NonNull
Lifecycle getLifecycle();
}
3、LifeCycleObserver
LifeCycleObserver 生命周期观察者,是一个interface,它不包含任何方法,它仅仅起一个标记的作用,标记某个类是一个LifeCycleOwner。
/**
* Marks a class as a LifecycleObserver. It does not have any methods, instead, relies on
* {@link OnLifecycleEvent} annotated methods.
* <p>
* @see Lifecycle Lifecycle - for samples and usage patterns.
*/
@SuppressWarnings("WeakerAccess")
public interface LifecycleObserver {
}
但是可以通过OnLifecycleEvent 注解来监听特定的生命周期
4、lifeCycleObsever通过监听LifeCycle,可以感知声明周期的状态
lifeCycle.addObserver(LifeCycleObserver)
二、lifeCycle的简单应用
1、Activity实现了LifeCycleOwner
public class FragmentActivity extends ComponentActivity implements
ActivityCompat.OnRequestPermissionsResultCallback,
ActivityCompat.RequestPermissionsRequestCodeValidator {
}
public class ComponentActivity extends androidx.core.app.ComponentActivity implements
LifecycleOwner,
ViewModelStoreOwner,
SavedStateRegistryOwner,
OnBackPressedDispatcherOwner {
private final LifecycleRegistry mLifecycleRegistry = new LifecycleRegistry(this);
@NonNull
@Override
public Lifecycle getLifecycle() {
return mLifecycleRegistry;
}
}
2、LifecycleRegistry
LifeCycle是一个抽象类,LifecycleRegistry 是LifeCycle的一个经典的实现类。Activity和Fragment中的LifeCycle的实现类都是LifecycleRegistry
LifecycleRegistry 中持有一个Map,保存所有添加到该lifeCycle的LifeCycleObserver,声明周期发生变化时,会向该map中的所有Observer同步。
public class LifecycleRegistry extends Lifecycle {
/**
* Custom list that keeps observers and can handle removals / additions during traversal.
*/
private FastSafeIterableMap<LifecycleObserver, ObserverWithState> mObserverMap =
new FastSafeIterableMap<>();
}
3、监听Activity中声明周期的实例
通过@OnLifecycleEvent(Lifecycle.Event.ON_ANY)指定fun onEvent()函数监听所有的生命周期事件
class TestLifeCycle :LifecycleObserver{
/**
* Lifecycle.Event.ON_ANY 监听所有的声明周期事件
*/
@OnLifecycleEvent(Lifecycle.Event.ON_ANY)
public fun onEvent(owner: LifecycleOwner, event: Lifecycle.Event) {
Log.d("feifei","onEvent ${event},LifecycleOwner:${owner}")
}
/**
* 指定监听 生命周期中的ON_CREATE事件
*/
@OnLifecycleEvent(Lifecycle.Event.ON_CREATE)
public fun onCreate(){
Log.d("feifei","TestLifeCycle onCreate ")
}
@OnLifecycleEvent(Lifecycle.Event.ON_START)
public fun onStart(){
Log.d("feifei","TestLifeCycle onStart ")
}
@OnLifecycleEvent(Lifecycle.Event.ON_RESUME)
public fun onResume(){
Log.d("feifei","TestLifeCycle onResume ")
}
@OnLifecycleEvent(Lifecycle.Event.ON_PAUSE)
public fun onPause(){
Log.d("feifei","TestLifeCycle onPause ")
}
@OnLifecycleEvent(Lifecycle.Event.ON_STOP)
public fun onStop(){
Log.d("feifei","TestLifeCycle onStop ")
}
@OnLifecycleEvent(Lifecycle.Event.ON_DESTROY)
public fun onDestory(){
Log.d("feifei","TestLifeCycle onDestory ")
}
}
class MainActivity : FragmentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
lifecycle.addObserver(TestLifeCycle())
Log.d("feifei","MainActivity onCreate")
}
override fun onStart() {
super.onStart()
Log.d("feifei","MainActivity onStart")
}
override fun onResume() {
super.onResume()
Log.d("feifei","MainActivity onResume")
}
override fun onPause() {
super.onPause()
Log.d("feifei","MainActivity onPause")
}
override fun onStop() {
super.onStop()
Log.d("feifei","MainActivity onStop")
}
override fun onDestroy() {
super.onDestroy()
Log.d("feifei","MainActivity onDestroy")
}
}
日志输出:
2019-11-17 21:51:46.067 30667-30667/com.example.testlifecycle D/feifei: MainActivity onCreate
2019-11-17 21:51:46.070 30667-30667/com.example.testlifecycle D/feifei: onEvent ON_CREATE,LifecycleOwner:com.example.testlifecycle.MainActivity@33b2075
2019-11-17 21:51:46.073 30667-30667/com.example.testlifecycle D/feifei: MainActivity onStart
2019-11-17 21:51:46.074 30667-30667/com.example.testlifecycle D/feifei: onEvent ON_START,LifecycleOwner:com.example.testlifecycle.MainActivity@33b2075
2019-11-17 21:51:46.081 30667-30667/com.example.testlifecycle D/feifei: MainActivity onResume
2019-11-17 21:51:46.083 30667-30667/com.example.testlifecycle D/feifei: onEvent ON_RESUME,LifecycleOwner:com.example.testlifecycle.MainActivity@33b2075
2019-11-17 21:52:04.287 30667-30667/com.example.testlifecycle D/feifei: onEvent ON_PAUSE,LifecycleOwner:com.example.testlifecycle.MainActivity@33b2075
2019-11-17 21:52:04.291 30667-30667/com.example.testlifecycle D/feifei: MainActivity onPause
2019-11-17 21:52:04.319 30667-30667/com.example.testlifecycle D/feifei: onEvent ON_STOP,LifecycleOwner:com.example.testlifecycle.MainActivity@33b2075
2019-11-17 21:52:04.340 30667-30667/com.example.testlifecycle D/feifei: MainActivity onStop
三、生命周期执行顺序
在FragmentActivity中
- onCreate()、onStart()、onResume() 正向声明周期
以onCreate()为例 会先之执行activity的onCreate()方法,再执行lifeCycle的onCreate() - onPause()、onStop()、onStop()、onDestory()等逆向生命周期
以onPause为例,会先执行lifeCycle的onPause(),再执行activity的onPause()方法
public class FragmentActivity implements xxx, LifecycleOwner {
//...
void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState); //1.先执行生命周期方法
//...省略代码
//2.生命周期事件分发
mFragmentLifecycleRegistry.handleLifecycleEvent(Lifecycle.Event.ON_CREATE);
}
void performStart() {
super.onStart();
//...
mFragmentLifecycleRegistry.handleLifecycleEvent(Lifecycle.Event.ON_START);
}
void performResume() {
super.onResume();
//...
mFragmentLifecycleRegistry.handleLifecycleEvent(Lifecycle.Event.ON_RESUME);
}
void performPause() {
//3.注意,调用顺序变了
mFragmentLifecycleRegistry.handleLifecycleEvent(Lifecycle.Event.ON_PAUSE);
//...
super.onPause();
}
void performStop() {
mFragmentLifecycleRegistry.handleLifecycleEvent(Lifecycle.Event.ON_STOP);
//...
super.onStop();
}
void performDestroy() {
mFragmentLifecycleRegistry.handleLifecycleEvent(Lifecycle.Event.ON_DESTROY);
//...
super.onDestroy();
}
}
为什么这样实现?
我想是因为通常声明周期的场景是
在actvity.onCreate()之后 执行一下初始化操作
在actvity.onDestory()之前,执行一些资源释放操作
而通过lifeCycle来向外传递生命周期到LifeCycleObserver 做资源的初始化和释放。
那么LifeObserver
- 在收到Lifecycle.Event.ON_CREATE,进行资源初始化时,需要保证activity已经创建(activity的onCreate()已经执行)
- 在收到Lifecycle.Event.ON_DESTROY,执行资源能释放时,activity尚未销毁(activity的onDestory尚未执行)