简单使用
class MyLifecycleObserver : LifecycleObserver {
private val TAG = LifecycleObserver::class.simpleName
@OnLifecycleEvent(Lifecycle.Event.ON_CREATE)
fun create() {
Log.e(TAG, "LifecycleObserver->onCreate")
}
@OnLifecycleEvent(Lifecycle.Event.ON_START)
fun start(){
Log.e(TAG, "LifecycleObserver->onStart")
}
@OnLifecycleEvent(Lifecycle.Event.ON_RESUME)
fun resume(){
Log.e(TAG, "LifecycleObserver->onResume")
}
@OnLifecycleEvent(Lifecycle.Event.ON_STOP)
fun stop(){
Log.e(TAG, "LifecycleObserver->onStop")
}
@OnLifecycleEvent(Lifecycle.Event.ON_DESTROY)
fun destory(){
Log.e(TAG, "LifecycleObserver->onDestory")
}
}
MainActivity中使用
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val observer = MyLifecycleObserver()
lifecycle.addObserver(observer)
}
}
源码分析
- getLifecycle
public Lifecycle getLifecycle() {
return mLifecycleRegistry;
}
实际返回的是LifecycleRegistry
- addObserver源码分析
public void addObserver(@NonNull LifecycleObserver observer) {
//判断当前状态是否等于DESTROYED,此时是INITIALIZED
State initialState = mState == DESTROYED ? DESTROYED : INITIALIZED;
//observer=自定义MyLifecycleObserver, initialState封装成新对象ObserverWithState
ObserverWithState statefulObserver = new ObserverWithState(observer, initialState);
//1 实际是MainActivity
LifecycleOwner lifecycleOwner = mLifecycleOwner.get();
if (lifecycleOwner == null) {
return;
}
//第一次是false
boolean isReentrance = mAddingObserverCounter != 0 || mHandlingEvent;
//代码省略
if (!isReentrance) {
//第一次实际进入到这里
sync();
}
mAddingObserverCounter--;
}
sync源码分析
private void sync() {
//返回的是MainActivity
LifecycleOwner lifecycleOwner = mLifecycleOwner.get();
while (!isSynced()) {
mNewEventOccurred = false;
// no need to check eldest for nullability, because isSynced does it for us.
if (mState.compareTo(mObserverMap.eldest().getValue().mState) < 0) {
backwardPass(lifecycleOwner);
}
Entry<LifecycleObserver, ObserverWithState> newest = mObserverMap.newest();
if (!mNewEventOccurred && newest != null
&& mState.compareTo(newest.getValue().mState) > 0) {
//进入到这里
forwardPass(lifecycleOwner);
}
}
mNewEventOccurred = false;
}
private void forwardPass(LifecycleOwner lifecycleOwner) {
Iterator<Entry<LifecycleObserver, ObserverWithState>> ascendingIterator =
mObserverMap.iteratorWithAdditions();
while (ascendingIterator.hasNext() && !mNewEventOccurred) {
Entry<LifecycleObserver, ObserverWithState> entry = ascendingIterator.next();
ObserverWithState observer = entry.getValue();
while ((observer.mState.compareTo(mState) < 0 && !mNewEventOccurred
&& mObserverMap.contains(entry.getKey()))) {
pushParentState(observer.mState);
//走这里
observer.dispatchEvent(lifecycleOwner, upEvent(observer.mState));
popParentState();
}
}
}
- observer是ObserverWithState对象,对owner和状态event进行封装
- upEvent(observer.mState)的源码
private static Event upEvent(State state) {
switch (state) {
case INITIALIZED:
case DESTROYED:
return ON_CREATE;
case CREATED:
return ON_START;
case STARTED:
return ON_RESUME;
case RESUMED:
throw new IllegalArgumentException();
}
throw new IllegalArgumentException("Unexpected state value " + state);
}
image.png
因为此时的mState是INITIALIZED所以upEvent(observer.mState)实际返回的是ON_CREATE,lifecleOwner就是MainActivity
- observer.dispatchEvent源码分析
static class ObserverWithState {
State mState;
LifecycleEventObserver mLifecycleObserver;
ObserverWithState(LifecycleObserver observer, State initialState) {
//observer=MainActivity
mLifecycleObserver = Lifecycling.lifecycleEventObserver(observer);
mState = initialState;
}
void dispatchEvent(LifecycleOwner owner, Event event) {
State newState = getStateAfter(event);
mState = min(mState, newState);
//owner=MainActivity event=ON_CREATE
mLifecycleObserver.onStateChanged(owner, event);
mState = newState;
}
}
实际最终会走到观察者的onStateChange
我们会发现mLifecycleObserver实际是个接口,所以我们需要知道mLifecycleObserver是什么
- Lifecycling.lifecycleEventObserver(observer)源码分析
static LifecycleEventObserver lifecycleEventObserver(Object object) {
//实际是MyLifecycleObserver的class
final Class<?> klass = object.getClass();
int type = getObserverConstructorType(klass);
//type实际是1
if (type == GENERATED_CALLBACK) {
//GENERATED_CALLBACK=2
return new CompositeGeneratedAdaptersObserver(adapters);
}
//所以会走到这里,这里留意,待会回到这里分析代码
return new ReflectiveGenericLifecycleObserver(object);
}
getObserverConstructorType(klass)源码分析
private static int getObserverConstructorType(Class<?> klass) {
//缓存
Integer callbackCache = sCallbackCache.get(klass);
if (callbackCache != null) {
return callbackCache;
}
//实际走的是这里
int type = resolveObserverCallbackType(klass);
sCallbackCache.put(klass, type);
return type;
}
private static int resolveObserverCallbackType(Class<?> klass) {
//代码省略
boolean hasLifecycleMethods = ClassesInfoCache.sInstance.hasLifecycleMethods(klass);
if (hasLifecycleMethods) {
//这里的值是1
return REFLECTIVE_CALLBACK;
}
//代码省略
return REFLECTIVE_CALLBACK;
}
boolean hasLifecycleMethods(Class<?> klass) {
Boolean hasLifecycleMethods = mHasLifecycleMethods.get(klass);
if (hasLifecycleMethods != null) {
return hasLifecycleMethods;
}
//解析MyLifecycleObserver所有的方法
Method[] methods = getDeclaredMethods(klass);
for (Method method : methods) {
//判断是否有注解
OnLifecycleEvent annotation = method.getAnnotation(OnLifecycleEvent.class);
if (annotation != null) {
createInfo(klass, methods);
return true;
}
}
mHasLifecycleMethods.put(klass, false);
return false;
}
createInfo源码分析
private CallbackInfo createInfo(Class<?> klass, @Nullable Method[] declaredMethods) {
//MyLifecycleObserver的所有方法
Method[] methods = declaredMethods != null ? declaredMethods : getDeclaredMethods(klass);
boolean hasLifecycleMethods = false;
for (Method method : methods) {
//找到带有OnLifecycleEvent注解的方法
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");
}
}
Lifecycle.Event event = annotation.value();
//代码省略,参数判断
//callType=CALL_TYPE_NO_ARG=0
MethodReference methodReference = new MethodReference(callType, method);
verifyAndPutHandler(handlerToEvent, methodReference, event, klass);
}
//解析的数据全部封装到CallbackInfo
CallbackInfo info = new CallbackInfo(handlerToEvent);
mCallbackMap.put(klass, info);
mHasLifecycleMethods.put(klass, hasLifecycleMethods);
return info;
}
实际就是解析注解和方法并封装到CallbackInfo中
返回到lifecycleEventObserver的源码解析
static LifecycleEventObserver lifecycleEventObserver(Object object) {
//实际是自定义MyLifecycleObserver类
final Class<?> klass = object.getClass();
int type = getObserverConstructorType(klass);
//type实际是1
//所以会走到这里
return new ReflectiveGenericLifecycleObserver(object);
}
上面第一点的时候我们知道实际最终会走到onStateChanged方法
class ReflectiveGenericLifecycleObserver implements LifecycleEventObserver {
private final Object mWrapped;
private final CallbackInfo mInfo;
ReflectiveGenericLifecycleObserver(Object wrapped) {
mWrapped = wrapped;
mInfo = ClassesInfoCache.sInstance.getInfo(mWrapped.getClass());
}
@Override
public void onStateChanged(@NonNull LifecycleOwner source, @NonNull Event event) {
mInfo.invokeCallbacks(source, event, mWrapped);
}
}
void invokeCallbacks(LifecycleOwner source, Lifecycle.Event event, Object target) {
invokeMethodsForEvent(mEventToHandlers.get(event), source, event, target);
invokeMethodsForEvent(mEventToHandlers.get(Lifecycle.Event.ON_ANY), source, event,
target);
}
private static void invokeMethodsForEvent(List<MethodReference> handlers,
LifecycleOwner source, Lifecycle.Event event, Object mWrapped) {
//解析刚才封装到CallbackInfo中的handlerToEvent的Map集合
if (handlers != null) {
for (int i = handlers.size() - 1; i >= 0; i--) {
//event是onCreate方法
handlers.get(i).invokeCallback(source, event, mWrapped);
}
}
}
}
void invokeCallback(LifecycleOwner source, Lifecycle.Event event, Object target) {
//noinspection TryWithIdenticalCatches
try {
//mCallType是参数的个数
switch (mCallType) {
case CALL_TYPE_NO_ARG:
mMethod.invoke(target);
break;
case CALL_TYPE_PROVIDER:
mMethod.invoke(target, source);
break;
case CALL_TYPE_PROVIDER_WITH_EVENT:
mMethod.invoke(target, source, event);
break;
}
} catch (InvocationTargetException e) {
throw new RuntimeException("Failed to call observer method", e.getCause());
} catch (IllegalAccessException e) {
throw new RuntimeException(e);
}
}
上面我们分析到mCallType实际是0,所以执行到的是 mMethod.invoke(target);
实际最终是通过反射执行的继承于LifecycleObserver的类的所有带有@OnLifecycleEvent的方法
最后附上lifecycle源码有序图
image.png
网友评论