LifeCycle
总体来说LifeCycle组件使用分为三个部分:
LifecycleRegistry LifeCycle子类
LifecycleOwner 被观察者
LifecycleObserver 观察者
先贴一下代码
LifecycleOwner
public class MainActivity extends AppCompatActivity implements LifecycleOwner {
private LifecycleRegistry mLifecycleRegistry;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
MyLifeCycle myLifeCycle = new MyLifeCycle();
mLifecycleRegistry = new LifecycleRegistry(this);
mLifecycleRegistry.markState(Lifecycle.State.CREATED);
mLifecycleRegistry.addObserver(myLifeCycle);
}
@Override
protected void onStart() {
super.onStart();
mLifecycleRegistry.markState(Lifecycle.State.STARTED);
}
@Override
protected void onPause() {
super.onPause();
}
}
看到以上代码主要分为几个步骤:
- 对接LifecycleOwner接口
- 实例化LifecycleRegistry, 这个LifecycleRegistry类其实是LifeCycle的子类
- 实例化观察者
- 将观察者注入LifecycleRegistry
- 添加生命周期标记
LifecycleObserver
public class MyLifeCycle implements LifecycleObserver {
@OnLifecycleEvent(Lifecycle.Event.ON_CREATE)
protected void myCreate(){
Log.d("test", "myCreate: 已启动");
}
@OnLifecycleEvent(Lifecycle.Event.ON_START)
protected void MyStart(){
Log.d("test", "myStart: 已开始");
}
}
看到以上代码主要分为几个步骤:
- 对接LifecycleObserver接口
- 根据标记的生命周期进行方法的实现即可
LifeCycle类源代码
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;
}
}
}
可以看到State和我们平时说的生命周期略有不同,我的理解是,不是所有生命周期都是直接观察的,比如说onPause,但是为什么不能添加onPause的状态标记却可以在观察者中实现方法呢,可能是因为当被观察者执行到下一个可直接观察状态时,其实之前的状态已经观察到了,就直接在所到之处执行了,但事实是有的会执行,有的不会执行,目前没找到明确的解释。