观察者类,观察目标的生命周期
import android.arch.lifecycle.Lifecycle;
import android.arch.lifecycle.LifecycleObserver;
import android.arch.lifecycle.OnLifecycleEvent;
public class MyObserver implements LifecycleObserver {
private MyObserver() {
}
private static MyObserver m;
public static MyObserver instance() {
synchronized (MyObserver.class) {
if (null == m) {
synchronized (MyObserver.class) {
m = new MyObserver();
}
}
}
return m;
}
@OnLifecycleEvent( Lifecycle.Event.ON_CREATE )
public void ON_CREATE() {
System.out.println("MyObserver:ON_CREATE");
}
@OnLifecycleEvent( Lifecycle.Event.ON_START )
public void ON_START() {
System.out.println("MyObserver:ON_START");
}
@OnLifecycleEvent( Lifecycle.Event.ON_RESUME )
public void ON_RESUME() {
System.out.println("@@@@@@@@MyObserver:ON_RESUME");
}
@OnLifecycleEvent( Lifecycle.Event.ON_PAUSE )
public void ON_PAUSE() {
System.out.println("MyObserver:ON_PAUSE");
}
@OnLifecycleEvent( Lifecycle.Event.ON_STOP )
public void ON_STOP() {
System.out.println("MyObserver:ON_STOP");
}
@OnLifecycleEvent( Lifecycle.Event.ON_DESTROY )
public void ON_DESTROY() {
System.out.println("MyObserver:ON_DESTROY");
}
}
被观察的类,一般是activity或fragment
//实现 LifecycleOwner接口
//重写
LifecycleRegistry mLifecycleRegistry = new LifecycleRegistry(this);
@NonNull
@Override
public Lifecycle getLifecycle() {
return mLifecycleRegistry;
}
手动标记生命周期
@Override
public void onStart() {
super.onStart();
//标记状态
mLifecycleRegistry.markState(Lifecycle.State.STARTED);
}
@Override
protected void onResume() {
super.onResume();
//标记状态
mLifecycleRegistry.markState(Lifecycle.State.RESUMED);
}
@Override
protected void onDestroy() {
super.onDestroy();
//标记状态
mLifecycleRegistry.markState(Lifecycle.State.DESTROYED);
}
网友评论