Lifecycle 是一个类,它持有关于组件(如 Activity 或 Fragment)生命周期状态的信息,并且允许其他对象观察此状态。
我们只需要2步:
1、Prestener继承LifecycleObserver接口
public interface IPresenter extends LifecycleObserver {
@OnLifecycleEvent(Lifecycle.Event.ON_CREATE)
void onCreate(@NotNull LifecycleOwner owner);
@OnLifecycleEvent(Lifecycle.Event.ON_DESTROY)
void onDestroy(@NotNull LifecycleOwner owner);
@OnLifecycleEvent(Lifecycle.Event.ON_ANY)
void onLifecycleChanged(@NotNull LifecycleOwner owner,
@NotNull Lifecycle.Event event);
}
Android官方架构组件:Lifecycle详解&原理分析
迪士尼彩乐园定制开发,需要请搜索【大神源码论坛】dsluntan.com 客服企娥3393756370 V信17061863513,
public class BasePresenter implements IPresenter {
private static final String TAG = "com.qingmei2.module.base.BasePresenter";
@Override
public void onLifecycleChanged(@NotNull LifecycleOwner owner, @NotNull Lifecycle.Event event) {
}
@Override
public void onCreate(@NotNull LifecycleOwner owner) {
Log.d("tag", "BasePresenter.onCreate" + this.getClass().toString());
}
@Override
public void onDestroy(@NotNull LifecycleOwner owner) {
Log.d("tag", "BasePresenter.onDestroy" + this.getClass().toString());
}
}
这里我直接将我想要观察到Presenter的生命周期事件都列了出来,然后封装到BasePresenter 中,这样每一个BasePresenter 的子类都能感知到Activity容器对应的生命周期事件,并在子类重写的方法中,对应相应行为。
2、在Activity/Fragment容器中添加Observer:
public class MainActivity extends AppCompatActivity {
private IPresenter mPresenter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.d("tag", "onCreate" + this.getClass().toString());
setContentView(R.layout.activity_main);
mPresenter = new MainPresenter(this);
getLifecycle().addObserver(mPresenter);//添加LifecycleObserver
}
@Override
protected void onDestroy() {
Log.d("tag", "onDestroy" + this.getClass().toString());
super.onDestroy();
}
}
如此,每当Activity发生了对应的生命周期改变,Presenter就会执行对应事件注解的方法:
除onCreate和onDestroy事件之外,Lifecycle一共提供了所有的生命周期事件,只要
通过注解进行声明,就能够使LifecycleObserver观察到对应的生命周期事件:
//以下为logcat日志
01-08 23:21:01.702 D/tag: onCreate class com.qingmei2.mvparchitecture.mvp.ui.MainActivity
01-08 23:21:01.778 D/tag: onCreate class com.qingmei2.mvparchitecture.mvp.presenter.MainPresenter
01-08 23:21:21.074 D/tag: onDestroy class com.qingmei2.mvparchitecture.mvp.presenter.MainPresenter
01-08 23:21:21.074 D/tag: onDestroy class com.qingmei2.mvparchitecture.mvp.ui.MainActivity
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
}