Android官方架构组件Lifecycle
2019-06-26 本文已影响5人
MengkZhang
Lifecycle 是一个类,它持有关于组件(如 Activity 或 Fragment)生命周期状态的信息,并且允许其他对象观察此状态。
使用:
1、Prestener继承LifecycleObserver接口
public interface IPresenter extends LifecycleObserver {
@OnLifecycleEvent(Lifecycle.Event.ON_CREATE)
void onCreate(@NonNull LifecycleOwner owner);
@OnLifecycleEvent(Lifecycle.Event.ON_DESTROY)
void onDestroy(@NonNull LifecycleOwner owner);
@OnLifecycleEvent(Lifecycle.Event.ON_ANY)
void onLifecycleChanged(@NonNull LifecycleOwner owner, @NonNull Lifecycle.Event event);
}
public class BasePresenter implements IPresenter {
private static final String TAG = "BasePresenter";
@Override
public void onCreate(@NonNull LifecycleOwner owner) {
Log.d("tag", "BasePresenter.onCreate" + this.getClass().toString());
}
@Override
public void onDestroy(@NonNull LifecycleOwner owner) {
Log.d("tag", "BasePresenter.onDestroy" + this.getClass().toString());
}
@Override
public void onLifecycleChanged(@NonNull LifecycleOwner owner, @NonNull Lifecycle.Event event) {
}
}
public class MainPresenter extends BasePresenter {
}
将想要观察到Presenter的生命周期事件都列了出来,然后封装到BasePresenter 中,这样每一个BasePresenter 的子类都能感知到Activity容器对应的生命周期事件,并在子类重写的方法中,对应相应行为。
2、在Activity/Fragment容器中添加Observer
public class MainActivity extends AppCompatActivity {
MainPresenter mainPresenter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Log.d("tag", "onCreate" + this.getClass().toString());
mainPresenter = new MainPresenter();
getLifecycle().addObserver(mainPresenter);
}
@Override
protected void onDestroy() {
Log.d("tag", "onDestroy" + this.getClass().toString());
super.onDestroy();
}
}
结果:
tag: onCreateclass com.example.administrator.myapplication.MainActivity
tag: BasePresenter.onCreateclass com.example.administrator.myapplication.MainPresenter
tag: BasePresenter.onDestroyclass com.example.administrator.myapplication.MainPresenter
tag: onDestroyclass com.example.administrator.myapplication.MainActivity