LifeCycle通过在FragmentActivity
中会添加ReportFragment用来监听Activity的生命周期 , 而在注册LifeCycleObserver
的时候 , 会通过反射将声明了LifecycleEvent
的Method找到 , 并且保存到CallbackInfo
的数据结构中.
当回调时 , 就会找到CallbackInfo
进行状态的回调.
FullLifecycleObserver
或者GenericLifecycleObserver
GeneratedAdapter
, 同时保证只有一个构造函数
GeneratedAdapter
对象保存 , 并且进行回调LifeCycleObserver
接口继承过深
AppCompatActivity
的基类ComponentActivity
中 , 会完成 :LifecycleRegistry
对象 , 用于管理回调以及生命周期ReportFragment.injectIfNeededIn
创建ReportFragment , 用于监听生命周期public class ComponentActivity extends Activity
implements LifecycleOwner, KeyEventDispatcher.Component {
...
private LifecycleRegistry mLifecycleRegistry = new LifecycleRegistry(this);
...
@Override
@SuppressWarnings("RestrictedApi")
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ReportFragment.injectIfNeededIn(this);
}
}
LifecycleObserver
的时候 :ObserverWithState
变量 , 其中就会通过反射获取注释标注的函数LifeCycleObserver
@Override
public void addObserver(@NonNull LifecycleObserver observer) {
State initialState = mState == DESTROYED ? DESTROYED : INITIALIZED;
// 创建ObserverWithState变量 , 其中就会通过反射获取注释标注的函数
ObserverWithState statefulObserver = new ObserverWithState(observer, initialState);
ObserverWithState previous = mObserverMap.putIfAbsent(observer, statefulObserver);
if (previous != null) {
return;
}
LifecycleOwner lifecycleOwner = mLifecycleOwner.get();
if (lifecycleOwner == null) {
// it is null we should be destroyed. Fallback quickly
return;
}
boolean isReentrance = mAddingObserverCounter != 0 || mHandlingEvent;
State targetState = calculateTargetState(observer);
mAddingObserverCounter++;
// 回调当前的状态给LifeCycleObserver
while ((statefulObserver.mState.compareTo(targetState) < 0
&& mObserverMap.contains(observer))) {
pushParentState(statefulObserver.mState);
statefulObserver.dispatchEvent(lifecycleOwner, upEvent(statefulObserver.mState));
popParentState();
// mState / subling may have been changed recalculate
targetState = calculateTargetState(observer);
}
if (!isReentrance) {
// we do sync only on the top level.
sync();
}
mAddingObserverCounter--;
}
ObserverWithState
创建的时候Lifecycling.getCallback(observer)
生成GenricLifecycleObserver对象LifecycleObserver
的class type以及构造函数生成对应的observerGeneratedAdapter
: 会回调callMethod
方法LifecycleObserver
: 会回调根据注释标注的方法static class ObserverWithState {
State mState;
GenericLifecycleObserver mLifecycleObserver;
ObserverWithState(LifecycleObserver observer, State initialState) {
mLifecycleObserver = Lifecycling.getCallback(observer);
mState = initialState;
}
void dispatchEvent(LifecycleOwner owner, Event event) {
State newState = getStateAfter(event);
mState = min(mState, newState);
mLifecycleObserver.onStateChanged(owner, event);
mState = newState;
}
}
@NonNull
static GenericLifecycleObserver getCallback(Object object) {
if (object instanceof FullLifecycleObserver) {
return new FullLifecycleObserverAdapter((FullLifecycleObserver) object);
}
if (object instanceof GenericLifecycleObserver) {
return (GenericLifecycleObserver) object;
}
final Class<?> klass = object.getClass();
int type = getObserverConstructorType(klass);
if (type == GENERATED_CALLBACK) {
// 判断Observer类是否为GeneratedAdapter子类
List<Constructor<? extends GeneratedAdapter>> constructors =
sClassToAdapters.get(klass);
if (constructors.size() == 1) {
GeneratedAdapter generatedAdapter = createGeneratedAdapter(
constructors.get(0), object);
// 如果是GeneratedAdapter子类 , 并且只有一个构造函数
return new SingleGeneratedAdapterObserver(generatedAdapter);
}
GeneratedAdapter[] adapters = new GeneratedAdapter[constructors.size()];
for (int i = 0; i < constructors.size(); i++) {
adapters[i] = createGeneratedAdapter(constructors.get(i), object);
}
// 生成多个GenerratedAdapter构造函数的对象 , 用于后面callMethod的回调
return new CompositeGeneratedAdaptersObserver(adapters);
}
// 如果只是lifecycleObserverd的话 , 就会走这里
return new ReflectiveGenericLifecycleObserver(object);
}
getObserverConstructorType
中 , 会调用resolveObserverCallbakType
, 用来解析Method private static int resolveObserverCallbackType(Class<?> klass) {
// anonymous class bug:35073837
if (klass.getCanonicalName() == null) {
return REFLECTIVE_CALLBACK;
}
Constructor<? extends GeneratedAdapter> constructor = generatedConstructor(klass);
// 判断是否为GeneratedAdapter的子类
if (constructor != null) {
sClassToAdapters.put(klass, Collections
.<Constructor<? extends GeneratedAdapter>>singletonList(constructor));
return GENERATED_CALLBACK;
}
// 判断是否有lifecycle的函数
boolean hasLifecycleMethods = ClassesInfoCache.sInstance.hasLifecycleMethods(klass);
if (hasLifecycleMethods) {
return REFLECTIVE_CALLBACK;
}
Class<?> superclass = klass.getSuperclass();
List<Constructor<? extends GeneratedAdapter>> adapterConstructors = null;
// 判断子类是不是LifecycleObserver的子类
if (isLifecycleParent(superclass)) {
if (getObserverConstructorType(superclass) == REFLECTIVE_CALLBACK) {
return REFLECTIVE_CALLBACK;
}
adapterConstructors = new ArrayList<>(sClassToAdapters.get(superclass));
}
// 判断子类是不是实现了LifecycleObserver的接口
for (Class<?> intrface : klass.getInterfaces()) {
if (!isLifecycleParent(intrface)) {
continue;
}
if (getObserverConstructorType(intrface) == REFLECTIVE_CALLBACK) {
return REFLECTIVE_CALLBACK;
}
if (adapterConstructors == null) {
adapterConstructors = new ArrayList<>();
}
adapterConstructors.addAll(sClassToAdapters.get(intrface));
}
if (adapterConstructors != null) {
sClassToAdapters.put(klass, adapterConstructors);
return GENERATED_CALLBACK;
}
return REFLECTIVE_CALLBACK;
}
LifecycleMethod
的时候 :MethodReference
引用 , 保存Methodboolean hasLifecycleMethods(Class klass) {
// 判断是否缓存中已经解析过该类
if (mHasLifecycleMethods.containsKey(klass)) {
return mHasLifecycleMethods.get(klass);
}
Method[] methods = getDeclaredMethods(klass);
// 遍历所有的Method
for (Method method : methods) {
// 反射得到Method的Annotation
OnLifecycleEvent annotation = method.getAnnotation(OnLifecycleEvent.class);
if (annotation != null) {
// 根据Annotation创建CallbackInfo
createInfo(klass, methods);
return true;
}
}
mHasLifecycleMethods.put(klass, false);
return false;
}
private CallbackInfo createInfo(Class klass, @Nullable Method[] declaredMethods) {
// 获取class的父类
Class superclass = klass.getSuperclass();
Map<MethodReference, Lifecycle.Event> handlerToEvent = new HashMap<>();
if (superclass != null) {
CallbackInfo superInfo = getInfo(superclass);
if (superInfo != null) {
handlerToEvent.putAll(superInfo.mHandlerToEvent);
}
}
Class[] interfaces = klass.getInterfaces();
for (Class intrfc : interfaces) {
for (Map.Entry<MethodReference, Lifecycle.Event> entry : getInfo(
intrfc).mHandlerToEvent.entrySet()) {
// 校验Handle的Method
verifyAndPutHandler(handlerToEvent, entry.getKey(), entry.getValue(), klass);
}
}
Method[] methods = declaredMethods != null ? declaredMethods : getDeclaredMethods(klass);
boolean hasLifecycleMethods = false;
for (Method method : methods) {
// 得到OnLifecycleEvent的Annotation
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");
}
}
// 得到Annotation的Event对象
Lifecycle.Event event = annotation.value();
if (params.length > 1) {
callType = CALL_TYPE_PROVIDER_WITH_EVENT;
if (!params[1].isAssignableFrom(Lifecycle.Event.class)) {
throw new IllegalArgumentException(
"invalid parameter type. second arg must be an event");
}
if (event != Lifecycle.Event.ON_ANY) {
throw new IllegalArgumentException(
"Second arg is supported only for ON_ANY value");
}
}
if (params.length > 2) {
throw new IllegalArgumentException("cannot have more than 2 params");
}
// 创建Method引用
MethodReference methodReference = new MethodReference(callType, method);
// 校验Method后 , 将MethodReference放到handler中
verifyAndPutHandler(handlerToEvent, methodReference, event, klass);
}
// 将CallbackInfo添加到mCallbackMap中
CallbackInfo info = new CallbackInfo(handlerToEvent);
mCallbackMap.put(klass, info);
mHasLifecycleMethods.put(klass, hasLifecycleMethods);
// 返回解析后的callbackInfo
return info;
}