来自google的一段介绍
生命周期感知组件执行操作以响应另一个组件(例如活动和片段)的生命周期状态的更改。这些组件可帮助您生成更易于组织且通常更轻量级的代码,这些代码更易于维护。
一种常见的模式是在活动和片段的生命周期方法中实现依赖组件的操作。但是,这种模式导致代码组织不良以及错误的增加。通过使用生命周期感知组件,您可以将依赖组件的代码移出生命周期方法并移入组件本身。
这个组件我们主要使用的就是一下这些类:
LifecycleOwner,LifecycleRegistry,LifecycleObserver,Lifecycle,Lifecycle.Event,Lifecycle.State.
1.LifecycleOwner简单的说就是拥有状态变化的类,它是一个接口,里面只有一个方法
/**
* Returns the Lifecycle of the provider.
*
* @return The lifecycle of the provider.
*/
@NonNull
Lifecycle getLifecycle();
当一个具有生命状态变化的类需要让其他类感知自己的生命状态变化时,就要继承LifecycleOwner.
例如我们的Activity其实就已经实现了该类,追本溯源
@RestrictTo({Scope.LIBRARY_GROUP})
public class SupportActivity extends Activity implements LifecycleOwner, Component {
private SimpleArrayMap<Class<? extends SupportActivity.ExtraData>, SupportActivity.ExtraData> mExtraDataMap = new SimpleArrayMap();
private LifecycleRegistry mLifecycleRegistry = new LifecycleRegistry(this);
public SupportActivity() {
}
@RestrictTo({Scope.LIBRARY_GROUP})
public void putExtraData(SupportActivity.ExtraData extraData) {
this.mExtraDataMap.put(extraData.getClass(), extraData);
}
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ReportFragment.injectIfNeededIn(this);
}
@CallSuper
protected void onSaveInstanceState(Bundle outState) {
this.mLifecycleRegistry.markState(State.CREATED);
super.onSaveInstanceState(outState);
}
@RestrictTo({Scope.LIBRARY_GROUP})
public <T extends SupportActivity.ExtraData> T getExtraData(Class<T> extraDataClass) {
return (SupportActivity.ExtraData)this.mExtraDataMap.get(extraDataClass);
}
public Lifecycle getLifecycle() {
return this.mLifecycleRegistry;
}
@RestrictTo({Scope.LIBRARY_GROUP})
public boolean superDispatchKeyEvent(KeyEvent event) {
return super.dispatchKeyEvent(event);
}
public boolean dispatchKeyShortcutEvent(KeyEvent event) {
View decor = this.getWindow().getDecorView();
return decor != null && KeyEventDispatcher.dispatchBeforeHierarchy(decor, event) ? true : super.dispatchKeyShortcutEvent(event);
}
public boolean dispatchKeyEvent(KeyEvent event) {
View decor = this.getWindow().getDecorView();
return decor != null && KeyEventDispatcher.dispatchBeforeHierarchy(decor, event) ? true : KeyEventDispatcher.dispatchKeyEvent(this, decor, this, event);
}
@RestrictTo({Scope.LIBRARY_GROUP})
public static class ExtraData {
public ExtraData() {
}
}
}
从上面我们也能发现,当一个类要想成为一个lifecycleOwner时,要在类中创建一个LifecycleRegistry对象,用于对当前的类的生命周期状态做修改和发送给其观察者。
2.LifecycleRegistry是什么?
LifecycleRegistry继承了Lifecycle。
那就先了解下Lifecycle
官方对于Lifecycle的解释:一个类,它包含有关组件生命周期状态的信息(如活动或片段),并允许其他对象观察此状态。
看下源码
public abstract class Lifecycle {
/**
* Adds a LifecycleObserver that will be notified when the LifecycleOwner changes
* state.
* <p>
* The given observer will be brought to the current state of the LifecycleOwner.
* For example, if the LifecycleOwner is in {@link State#STARTED} state, the given observer
* will receive {@link Event#ON_CREATE}, {@link Event#ON_START} events.
*
* @param observer The observer to notify.
*/
@MainThread
public abstract void addObserver(@NonNull LifecycleObserver observer);
/**
* Removes the given observer from the observers list.
* <p>
* If this method is called while a state change is being dispatched,
* <ul>
* <li>If the given observer has not yet received that event, it will not receive it.
* <li>If the given observer has more than 1 method that observes the currently dispatched
* event and at least one of them received the event, all of them will receive the event and
* the removal will happen afterwards.
* </ul>
*
* @param observer The observer to be removed.
*/
@MainThread
public abstract void removeObserver(@NonNull LifecycleObserver observer);
/**
* Returns the current state of the Lifecycle.
*
* @return The current state of the Lifecycle.
*/
@MainThread
@NonNull
public abstract State getCurrentState();
@SuppressWarnings("WeakerAccess")
public enum Event {
/**
* Constant for onCreate event of the {@link LifecycleOwner}.
*/
ON_CREATE,
/**
* Constant for onStart event of the {@link LifecycleOwner}.
*/
ON_START,
/**
* Constant for onResume event of the {@link LifecycleOwner}.
*/
ON_RESUME,
/**
* Constant for onPause event of the {@link LifecycleOwner}.
*/
ON_PAUSE,
/**
* Constant for onStop event of the {@link LifecycleOwner}.
*/
ON_STOP,
/**
* Constant for onDestroy event of the {@link LifecycleOwner}.
*/
ON_DESTROY,
/**
* An {@link Event Event} constant that can be used to match all events.
*/
ON_ANY
}
/**
* Lifecycle states. You can consider the states as the nodes in a graph and
* {@link Event}s as the edges between these nodes.
*/
@SuppressWarnings("WeakerAccess")
public enum State {
/**
* Destroyed state for a LifecycleOwner. After this event, this Lifecycle will not dispatch
* any more events. For instance, for an {@link android.app.Activity}, this state is reached
* <b>right before</b> Activity's {@link android.app.Activity#onDestroy() onDestroy} call.
*/
DESTROYED,
/**
* Initialized state for a LifecycleOwner. For an {@link android.app.Activity}, this is
* the state when it is constructed but has not received
* {@link android.app.Activity#onCreate(android.os.Bundle) onCreate} yet.
*/
INITIALIZED,
/**
* Created state for a LifecycleOwner. For an {@link android.app.Activity}, this state
* is reached in two cases:
* <ul>
* <li>after {@link android.app.Activity#onCreate(android.os.Bundle) onCreate} call;
* <li><b>right before</b> {@link android.app.Activity#onStop() onStop} call.
* </ul>
*/
CREATED,
/**
* Started state for a LifecycleOwner. For an {@link android.app.Activity}, this state
* is reached in two cases:
* <ul>
* <li>after {@link android.app.Activity#onStart() onStart} call;
* <li><b>right before</b> {@link android.app.Activity#onPause() onPause} call.
* </ul>
*/
STARTED,
/**
* Resumed state for a LifecycleOwner. For an {@link android.app.Activity}, this state
* is reached after {@link android.app.Activity#onResume() onResume} is called.
*/
RESUMED;
/**
* Compares if this State is greater or equal to the given {@code state}.
*
* @param state State to compare with
* @return true if this State is greater or equal to the given {@code state}
*/
public boolean isAtLeast(@NonNull State state) {
return compareTo(state) >= 0;
}
}
}
Lifecycle的代码还是挺简洁的就是,一个添加观察者和一个移除观察者方法,同时还有两个枚举(状态,事件)
由此可见,Lifecycle主要就是编辑下当前类的生命周期状态和通知其观察者的生命周期状态变化的事件。
回过来再看一下LifecycleRegistry的代码(这里就不贴出了),发现包含一些设置类状态和通知观察者状态变化的方法。
3.LifecycleObserver
@SuppressWarnings("WeakerAccess")
public interface LifecycleObserver {
}
一脸懵逼,怎么就一个光杆司令。。。好吧,那其实一个类要想成为一个观察者那就非常简单了,直接实现这个接口,然后如果要监听某一个生命周期状态变化时只需要在方法上加一个事件注解。
class MyObserver:LifecycleObserver{
@OnLifecycleEvent(Lifecycle.Event.ON_CREATE)
fun onCreate(){
Log.d("1--","MyObserver-------onCreate")
}
@OnLifecycleEvent(Lifecycle.Event.ON_RESUME)
fun onResume(){
Log.d("1--","MyObserver-------onResume")
}
@OnLifecycleEvent(Lifecycle.Event.ON_DESTROY)
fun onDestory(){
Log.d("1--","MyObserver-------onDestory")
}
}
然后在生命周期拥有者类中添加这个观察者,就能实时接受到生命周期的变化
最后来一段完整的使用代码,仅供参考
/**
* ================================================
* @author:黄佃华
* @date:2018/10/16 13:54.
* @description:
* ================================================
*/
class MyOwner:LifecycleOwner {
var lifecycleRegistry:LifecycleRegistry
var myObserver:MyObserver
init {
lifecycleRegistry = LifecycleRegistry(this)
myObserver = MyObserver()
lifecycle.addObserver(myObserver)
}
override fun getLifecycle(): Lifecycle {
return lifecycleRegistry
}
fun onCreate(){
lifecycleRegistry.markState(Lifecycle.State.CREATED)
lifecycleRegistry.handleLifecycleEvent(Lifecycle.Event.ON_CREATE)
Log.d("1--","MyOwner-------onCreate")
}
fun onResume(){
lifecycleRegistry.markState(Lifecycle.State.CREATED)
lifecycleRegistry.handleLifecycleEvent(Lifecycle.Event.ON_RESUME)
Log.d("1--","MyOwner-------onResume")
}
fun onDestory(){
lifecycleRegistry.handleLifecycleEvent(Lifecycle.Event.ON_DESTROY)
lifecycleRegistry.markState(Lifecycle.State.DESTROYED)
lifecycle.removeObserver(myObserver)
Log.d("1--","MyOwner-------onDestory")
}
}
/**
* ================================================
* @author:黄佃华
* @date:2018/10/16 13:54.
* @description:
* ================================================
*/
class MyObserver:LifecycleObserver{
@OnLifecycleEvent(Lifecycle.Event.ON_CREATE)
fun onCreate(){
Log.d("1--","MyObserver-------onCreate")
}
@OnLifecycleEvent(Lifecycle.Event.ON_RESUME)
fun onResume(){
Log.d("1--","MyObserver-------onResume")
}
@OnLifecycleEvent(Lifecycle.Event.ON_DESTROY)
fun onDestory(){
Log.d("1--","MyObserver-------onDestory")
}
}