1.activity 或者fragment 实现LifecycleOwner 接口
2.在activity 或者fragment里面添加成员变量
LifecycleRegistry lifecycleRegistry =new LifecycleRegistry(this);
3.实现LifecycleOwner 的getLifecycle方法,里面返回 lifecycleRegistry ;
@Override public Lifecycle getLifecycle() { return lifecycleRegistry; }
4.定义一个类,实现LifecycleObserver接口。用于接收生命周期的回调和处理
public class MyLocationListenerObserver implements LifecycleObserver {
@OnLifecycleEvent(Lifecycle.Event.ON_RESUME)public void onResume() { Log.i(TAG, "MyLocationListenerObserver--->onResume"); }
@OnLifecycleEvent(Lifecycle.Event.ON_PAUSE) public void onPause() { Log.i(TAG, "MyLocationListenerObserver--->onPause"); }
@OnLifecycleEvent(Lifecycle.Event.ON_STOP) public void onStop() { Log.i(TAG, "MyLocationListenerObserver--->onStop"); }
}
5.在合适的地方添加观察者,一般在activity或者fragment的onCreate()
getLifecycle().addObserver(new MyLocationListenerObserver());