Lifecycle原理
lifecycle通过观察者模式加反射注解模式实习对生命周期的监听。其中实现了LifecycleOwner的为被观察者,实现了LifecycleObserver的微观察者,通过在被观察者中getLifecycle().addObserver(new TestPresenter());
实现绑定。
一 、LifecycleObserver被观察者
@OnLifecycleEvent(Lifecycle.Event.ON_CREATE)
public void onCreateX(LifecycleOwner owner) {
}
@OnLifecycleEvent(Lifecycle.Event.ON_START)
public void onStartX(LifecycleOwner owner) {
}
@OnLifecycleEvent(Lifecycle.Event.ON_RESUME)
public void onResumeX(LifecycleOwner owner) {
}
@OnLifecycleEvent(Lifecycle.Event.ON_PAUSE)
public void onPauseX(LifecycleOwner owner) {
}
@OnLifecycleEvent(Lifecycle.Event.ON_STOP)
public void onStopX(LifecycleOwner owner) {
}
@OnLifecycleEvent(Lifecycle.Event.ON_DESTROY)
public void onDestoryX(LifecycleOwner owner) {
}
@OnLifecycleEvent(Lifecycle.Event.ON_ANY)
public void onANYX(LifecycleOwner owner) {
}
在被观察者中创建对应生命周期的方法,并用OnLifecycleEvent注解,后面在add的时候会通过注解来获取方法。
二、getLifecycle().addObserver绑定流程
关键的方法是createInfo(Class klass, @Nullable Method[] declaredMethods)
在方法中通过反射获取observe的方法
Method[] methods = declaredMethods != null ? declaredMethods : getDeclaredMethods(klass);
然后通过过滤注解得到对应的TYPE和方法名,包装后放入集合中。
for (Method method : methods) {
OnLifecycleEvent annotation = method.getAnnotation(OnLifecycleEvent.class);
if (annotation == null) {
continue;
}
hasLifecycleMethods = true;
Class<?>[] params = method.getParameterTypes();
int callType = CALL_TYPE_NO_ARG;
if (params.length > 0) {
callType = CALL_TYPE_PROVIDER;
if (!params[0].isAssignableFrom(LifecycleOwner.class)) {
throw new IllegalArgumentException(
"invalid parameter type. Must be one and instanceof LifecycleOwner");
}
}
这里要注意下在注解参数为一个的时候是 int callType = CALL_TYPE_NO_ARG;后面会用到。
三、实现了LifecycleOwner的ComponentActivity调用观察者
getStateAfter这里有个状态机的概念
static State getStateAfter(Event event) {
switch (event) {
case ON_CREATE:
case ON_STOP:
return CREATED;
case ON_START:
case ON_PAUSE:
return STARTED;
case ON_RESUME:
return RESUMED;
case ON_DESTROY:
return DESTROYED;
case ON_ANY:
break;
}
throw new IllegalArgumentException("Unexpected event value " + event);
}