为什么要引进Lifecycle?
因为我们在Activity,fragment中使用某些成员变量时,需要保持与组件生命周期同步,就不免会增加多个onStop,onDestroy的回调方法,导致文件臃肿。
Lifecycle是什么
Lifecycle是Google官方提供的方便管理生命周期事件的方式,可以更方便的监听生命周期变化事件,它以注解的方式作用在方法上,当生命周期方法调用时,它也会被跟随调用。
Lifecycle是一个抽象类,它持有关于组件(如Activity 或 Fragment)生命周期状态的信息,并且允许其他对象观察此状态。
public abstract class Lifecycle {
AtomicReference<Object> mInternalScopeRef = new AtomicReference<>();
@MainThread
public abstract void addObserver(@NonNull LifecycleObserver observer);
@MainThread
public abstract void removeObserver(@NonNull LifecycleObserver observer);
@MainThread
@NonNull
public abstract State getCurrentState();
@SuppressWarnings("WeakerAccess")
public enum Event {
ON_CREATE,
ON_START,
ON_RESUME,
ON_PAUSE,
ON_STOP,
ON_DESTROY,
ON_ANY
}
@SuppressWarnings("WeakerAccess")
public enum State {
DESTROYED,
INITIALIZED,
CREATED,
STARTED,
RESUMED;
}
}
使用lifecycle监听Activity生命周期示例:
创建接口LifeCycleObserver继承LifecycleObserver接口:
public interface LifeCycleObserver extends LifecycleObserver {
@OnLifecycleEvent(Lifecycle.Event.ON_CREATE)
void onCreate( LifecycleOwner owner);
@OnLifecycleEvent(Lifecycle.Event.ON_RESUME)
void onResume(LifecycleOwner owner);
@OnLifecycleEvent(Lifecycle.Event.ON_STOP)
void onStop(LifecycleOwner owner);
@OnLifecycleEvent(Lifecycle.Event.ON_DESTROY)
void onDestroy( LifecycleOwner owner);
@OnLifecycleEvent(Lifecycle.Event.ON_ANY)
void onLifecycleChanged(LifecycleOwner owner,
Lifecycle.Event event);
}
实现接口监听到生命周期方法。
public class LifecycleObserverImp implements LifeCycleObserver {
@Override
public void onLifecycleChanged(LifecycleOwner owner, Lifecycle.Event event) {
}
@Override
public void onCreate(LifecycleOwner owner) {
Log.i("minfo", "onCreate");
}
@Override
public void onResume(LifecycleOwner owner) {
Log.i("minfo", "onResume");
}
@Override
public void onStop(LifecycleOwner owner) {
Log.i("minfo", "onStop");
}
@Override
public void onDestroy(LifecycleOwner owner) {
Log.i("minfo", "onDestroy");
}
}
通过getLifecycle()方法获取内部的Lifecycle对象,添加生命周期观察者。
getLifecycle().addObserver(new LifecycleObserverImp());
打印事件:
I/minfo: onCreate
I/minfo: onResume
I/minfo: onStop
I/minfo: onDestroy
示例分析:
LifecycleOwner(Lifecycle持有者):实现该接口的类持有生命周期(Lifecycle对象),该接口的生命周期(Lifecycle对象)的改变会被其注册的观察者LifecycleObserver观察到并触发其对应的事件。
LifecycleObserver( Lifecycle观察者):实现该接口的类,通过注解的方式,可以通过被LifecycleOwner类的addObserver(LifecycleObserver o)方法注册,被注册后,LifecycleObserver便可以观察到LifecycleOwner的生命周期事件。
State:当前生命周期所处状态
Event:当前生命周期改变对应的事件
LifecycleOwner实现:
@SuppressWarnings({"WeakerAccess", "unused"})
public interface LifecycleOwner {
@NonNull
Lifecycle getLifecycle();
}
组件中获取LifecycleOwner,LifecycleRegistry对象继承了Lifecycle。
public class ComponentActivity implements LifecycleOwner {
private final LifecycleRegistry mLifecycleRegistry = new LifecycleRegistry(this);
@Override
public Lifecycle getLifecycle() {
return mLifecycleRegistry;
}
当LifecycleRegistry 本身的生命周期改变后(可以想象,内部一定有一个成员变量State记录当前的生命周期),LifecycleRegistry 就会逐个通知每一个注册的LifecycleObserver ,并执行对应生命周期的方法。
网友评论