Lifecycle作用:让所有定义组件都有生命周期
使用Lifecycle的继承LifecycleOwner
BaseActivity代码
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mLifecycleRegistry =new LifecycleRegistry(this);
mLifecycleRegistry.setCurrentState(Lifecycle.State.CREATED);
}
@Override
protected void onStart() {
super.onStart();
mLifecycleRegistry.setCurrentState(Lifecycle.State.START);
}
@Override
protected void onResume() {
super.onResume();
mLifecycleRegistry.setCurrentState(Lifecycle.State.RESUMED);
}
---------------------------------------------------------------
使用的组件中添加下面代码
private LifecycleOwner mLifecycleOwner;
public void setLifecycleOwner(LifecycleOwner lifecycleOwner) {
mLifecycleOwner = lifecycleOwner;
mLifecycleOwner.getLifecycle().addObserver(new LifecycleEventObserver() {
@Override
public void onStateChanged(LifecycleOwner source, final Lifecycle.Event event) {
if (event == Lifecycle.Event.ON_CREATE) {
onCreate();
}else if (event == Lifecycle.Event.ON_START) {
onStart();
}else if (event == Lifecycle.Event.ON_RESUME) {
onResume();
}
//其它生命周期自己补全
}
});
}
public void onCreate() {
Log.e(TAG, "onCreate:");
}
public void onStart() {
Log.e(TAG, "onStart:");
}
public void onResume() {
Log.e(TAG, "onResume:");
}
-----------------------------------------