您总说梦想遥不可及,可您却从不早睡。也不早起——《狼道》
目录
一、前言
二、源码分析
(1)添加观察者
(2)通知观察者
(3)何时通知
三、总结
四、内容推荐
五、项目参考
——回顾了一下之前学习过的东西并打算把这些东西整理成文章,加深映像和理解,同时也传达自己的见解供大家参考,若存在错误或不足的地方,希望您能指出。
本篇续《Android Jetpack架构组件之Lifecycle入门》文章之后,上一篇介绍了Lifecycle。由于篇幅太长拆成两篇。这篇主要是分析Lifecycle源码,理解其实现原理。回顾一下Lifecycle结构图
LifeCycle相关链接——官方文档、接口文档、相关依赖文档
——通过上面的使用过程,大体理解为创建一个观察者,当组件生命周期发生变化时,通知观察者有LifeCycle注解的方法做出响应。那么实现原理分成两部分来分析
(1)怎么通知观察者响应生命周期的变化(怎么通知)
(2)生命周期更改的时候是如何通知观察者的(何时通知)
1.使用入口**getLifecycle().addObserver()** (不同版本Lifecycle源码各有差异,这边引用的是'androidx.appcompat:appcompat:1.1.0)
/*
* 通过查看源码得出MainActivity继承了AppCompatActivity,AppCompatActivity继承了FragmentActivity ,FragmentActivity 继ComponentActivity
* 并实现了LifecycleOwner接口的getLifecycle()方法 ,返回生命周期的提供者 ,而FragmentActivity重写了ComponentActivity的getLifecycle()方法
* 所以这边调用的是FragmentActivity里面的getLifecycle()方法得到LifecycleRegistry实例
*/
final LifecycleRegistry mFragmentLifecycleRegistry = new LifecycleRegistry(this);
public Lifecycle getLifecycle() {
//这里返回LifecycleRegistry对象
return mFragmentLifecycleRegistry;
}
2.FragmentActivity里面创建了LifecycleRegistry 实例,下面看下LifecycleRegistry构造源码
// 给生命周期的提供者创建一个LifecycleRegistry
public LifecycleRegistry(@NonNull LifecycleOwner provider) {
mLifecycleOwner = new WeakReference<>(provider);
mState = INITIALIZED;
}
3.LifecycleRegistry继承了Lifecycle抽象类,并重写了addObserver()方法。主要作用是添加一个生命周期的观察者,当生命周期的提供者发生状态改变的时候,通知观察者做出响应
//保存观察者的自定义列表
private FastSafeIterableMap mObserverMap =
new FastSafeIterableMap<>();
@Override
public void addObserver(@NonNull LifecycleObserver observer) {
//设置lifecycle的初始状态 ,State是个生命周期的枚举类型
State initialState = mState == DESTROYED ? DESTROYED : INITIALIZED;
//创建ObserverWithState实例,并将LifecycleObserver 转化为LifecycleEventObserver,详情看(4)
ObserverWithState statefulObserver = new ObserverWithState(observer, initialState);
//保存生命周期的观察者与ObserverWithState(观察者的生命状态),保存成功返回NULL,否则说明已经保存过,返回ObserverWithState对象
ObserverWithState previous = mObserverMap.putIfAbsent(observer, statefulObserver);
//拦截已经保存过的观察者
if (previous != null) {
return;
}
//生命周期的提供者被回收则返回不继续执行
LifecycleOwner lifecycleOwner = mLifecycleOwner.get();
if (lifecycleOwner == null) {
return;
}
// 判断是否连续添加了观察者 或者 正在处理事件 是返回true
boolean isReentrance = mAddingObserverCounter != 0 || mHandlingEvent;
//获取状态 详情看(5)
State targetState = calculateTargetState(observer);
//正在添加的观察者数量+1
mAddingObserverCounter++;
//如果观察者生命周期状态比前面添加进来的小,说明生命周期发生变化,执行以下步骤
//比如: onCreate()方法中与onResume()方法中同时调用了 addObserver()方法
while ((statefulObserver.mState.compareTo(targetState) < 0
&& mObserverMap.contains(observer))) {
//存储添加进来的观察者状态,详情看(7)
pushParentState(statefulObserver.mState);
//分发事件 dispatchEvent详情看(4) upEvent详情看(8)
statefulObserver.dispatchEvent(lifecycleOwner, upEvent(statefulObserver.mState));
//移除最后一个添加进去的观察者,详情看(7)
popParentState();
//获取状态 详情看(5)
targetState = calculateTargetState(observer);
}
// 当isReentrance为false时 进行同步
if (!isReentrance) {
// we do sync only on the top level.
sync();
}
//添加完成时正在处理的观察者数量减一
mAddingObserverCounter--;
}
4.ObserverWithState主要是将LifecycleObserver 转化为LifecycleEventObserver
//将LifecycleObserver 转化为LifecycleEventObserver
static class ObserverWithState {
State mState;
LifecycleEventObserver mLifecycleObserver;
//将LifecycleObserver 转化为LifecycleEventObserver
ObserverWithState(LifecycleObserver observer, State initialState) {
//lifecycleEventObserver将LifecycleObserver 转化成LifecycleEventObserver
mLifecycleObserver = Lifecycling.lifecycleEventObserver(observer);
mState = initialState;
}
//将生命周期的提供者与Event
void dispatchEvent(LifecycleOwner owner, Event event) {
//获取生命周期状态
State newState = getStateAfter(event);
//对比两个状态
mState = min(mState, newState);
//在发生生命周期状态转换事件时调用 FullLifecycleObserverAdapter实现了LifecycleEventObserver接口的该方法
mLifecycleObserver.onStateChanged(owner, event);
mState = newState;
}
}
5.给定观察者对比观察者列表前后的生命周期状态,calculateTargetState返回State最小的生命周期状态
private State calculateTargetState(LifecycleObserver observer) {
//返回前一个观察者的保存节点
Entry previous = mObserverMap.ceil(observer);
//获取前一个观察者的生命周期状态,若无前一个观察者则返null
State siblingState = previous != null ? previous.getValue().mState : null;
//获取上一个保存的生命周期状态
State parentState = !mParentStates.isEmpty() ? mParentStates.get(mParentStates.size() - 1): null;
//返回State更小的生命周期状态 详情请看(6)
return min(min(mState, siblingState), parentState);
}
6.min() 对比两个生命周期状态,返回State更小的周期值
static State min(@NonNull State state1, @Nullable State state2) {
return state2 != null && state2.compareTo(state1) < 0 ? state2 : state1;
}
7.pushParentState保存生命周期状态 popParentState移除最后一个状态(最后一个添加进来的值)
private ArrayList mParentStates = new ArrayList<>();
private void pushParentState(State state) {
mParentStates.add(state);
}
private void popParentState() {
mParentStates.remove(mParentStates.size() - 1);
}
8.upEvent 根据生命周期状态 返回对应的Event 值
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);
}
9.sync()同步生命周期状态
//同步生命周期状态
private void sync() {
//判断生命周期是否已经被回收
LifecycleOwner lifecycleOwner = mLifecycleOwner.get();
if (lifecycleOwner == null) {
throw new IllegalStateException("LifecycleOwner of this LifecycleRegistry is already"
+ "garbage collected. It is too late to change lifecycle state.");
}
//生命周期非同步状态时执行 详情看(10)
while (!isSynced()) {
mNewEventOccurred = false;
// 当前生命周期状态小于最早添加进来的观察者生命周期状态时 调用backwardPass()
if (mState.compareTo(mObserverMap.eldest().getValue().mState) < 0) {
//遍历观察者集合 ,不一致时分发事件 详情看(12)
backwardPass(lifecycleOwner);
}
//获取观察者集合最新添加进来的条目
Entry newest = mObserverMap.newest();
// 当前生命周期状态大于最新添加进来的观察者生命周期状态时 调用forwardPass() 详情看(11)
if (!mNewEventOccurred && newest != null
&& mState.compareTo(newest.getValue().mState) > 0) {
//遍历观察者集合,当观察者生命周期状态小于当前生命周期状态时 分发事件
forwardPass(lifecycleOwner);
}
}
mNewEventOccurred = false;
}
10.isSynced()返回当前生命周期状态是否一致
//返回当前生命状态是否一致 不相同为false
private boolean isSynced() {
//没有观察者时返回true
if (mObserverMap.size() == 0) {
return true;
}
//获取最先添加进来的观察者生命周期状态
State eldestObserverState = mObserverMap.eldest().getValue().mState;
//获取最后(最近)添加进来的观察者生命周期状态
State newestObserverState = mObserverMap.newest().getValue().mState;
//如果最先的和最后的Observer的状态不一致或者当前的状态和最新的状态不一致时,那么需要进行状态同步
return eldestObserverState == newestObserverState && mState == newestObserverState;
}
11.forwardPass() 遍历观察者集合,当观察者生命周期状态小于当前生命周期状态时 分发事件
private void forwardPass(LifecycleOwner lifecycleOwner) {
Iterator> ascendingIterator =
mObserverMap.iteratorWithAdditions();
//遍历迭代器
while (ascendingIterator.hasNext() && !mNewEventOccurred) {
Entry 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();
}
}
}
12.backwardPass() 遍历观察者集合,当观察者生命周期状态大于当前生命周期状态时 分发事件
private void backwardPass(LifecycleOwner lifecycleOwner) {
//得到一个递减的迭代器
Iterator> descendingIterator =
mObserverMap.descendingIterator();
//遍历迭代器
while (descendingIterator.hasNext() && !mNewEventOccurred) {
Entry entry = descendingIterator.next();
ObserverWithState observer = entry.getValue();
//观察者生命周期状态大于当前生命周期状态时 分发事件
while ((observer.mState.compareTo(mState) > 0 && !mNewEventOccurred
&& mObserverMap.contains(entry.getKey()))) {
Event event = downEvent(observer.mState);
pushParentState(getStateAfter(event));
observer.dispatchEvent(lifecycleOwner, event);
popParentState();
}
}
}
小结:
到这里并没有完,才刚开始...。刚分析完添加观察者的源码,下一步分析是如何通知观察者的。
1.从ObserverWithState类的Lifecycling.lifecycleEventObserver(observer)方法说起,这一步是将LifecycleObserver转化为LifecycleEventObserver那么具体如何转化看下源码
// 利用反射获取LifecycleObserver的信息,创建一个类实现LifecycleEventObserver接口。并返回该类的实例
@NonNull
static LifecycleEventObserver lifecycleEventObserver(Object object) {
// instanceof是判断其左边对象是否为其右边类的实例 以下都返回false
boolean isLifecycleEventObserver = object instanceof LifecycleEventObserver;
boolean isFullLifecycleObserver = object instanceof FullLifecycleObserver;
if (isLifecycleEventObserver && isFullLifecycleObserver) {
return new FullLifecycleObserverAdapter((FullLifecycleObserver) object,
(LifecycleEventObserver) object);
}
if (isFullLifecycleObserver) {
return new FullLifecycleObserverAdapter((FullLifecycleObserver) object, null);
}
if (isLifecycleEventObserver) {
return (LifecycleEventObserver) object;
}
//获取类
final Class> klass = object.getClass();
//利用反射getObserverConstructorType方法根据不同情况反馈回来不同的类型 详情看(2)
int type = getObserverConstructorType(klass);
//GENERATED_CALLBACK 表示有APT生成的观察者适配器,则执行下面方法
if (type == GENERATED_CALLBACK) {
List> constructors =
sClassToAdapters.get(klass);
if (constructors.size() == 1) {
GeneratedAdapter generatedAdapter = createGeneratedAdapter(
constructors.get(0), object);
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);
}
return new CompositeGeneratedAdaptersObserver(adapters);
}
//若不是创建下面实例实现LifecycleEventObserver接口 详情看(10)
return new ReflectiveGenericLifecycleObserver(object);
}
2.lifecycleEventObserver()判断集合中是否有缓存观察者对应的反馈类型 否则通过resolveObserverCallbackType()方法获取
private static int getObserverConstructorType(Class> klass) {
//如果观察者的类已保存则返回指定键映射到的值
Integer callbackCache = sCallbackCache.get(klass);
if (callbackCache != null) {
return callbackCache;
}
//resolveObserverCallbackType()根据观察者的信息反馈回不同的类型 详情看(3)
int type = resolveObserverCallbackType(klass);
//把观察者的类和type以键值对的形式保存在集合中
sCallbackCache.put(klass, type);
return type;
}
3.resolveObserverCallbackType()根据观察者的信息返回不同的类型
private static int resolveObserverCallbackType(Class> klass) {
// 若基础类的规范名称为null 返回REFLECTIVE_CALLBACK
if (klass.getCanonicalName() == null) {
return REFLECTIVE_CALLBACK;
}
// 获取观察者适配类的构造函数
Constructor extends GeneratedAdapter> constructor = generatedConstructor(klass);
if (constructor != null) {
// 把观察者的类和适配类的构造函数列表以键值对的形式保存在集合中
sClassToAdapters.put(klass, Collections
.>singletonList(constructor));
return GENERATED_CALLBACK;
}
//判断该观察者是否有监听生命周期的方法 查看详情(6)
boolean hasLifecycleMethods = ClassesInfoCache.sInstance.hasLifecycleMethods(klass);
if (hasLifecycleMethods) {
return REFLECTIVE_CALLBACK;
}
Class> superclass = klass.getSuperclass();
List> adapterConstructors = null;
//判断是否是LifecycleObserver
if (isLifecycleParent(superclass)) {
if (getObserverConstructorType(superclass) == REFLECTIVE_CALLBACK) {
return REFLECTIVE_CALLBACK;
}
adapterConstructors = new ArrayList<>(sClassToAdapters.get(superclass));
}
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;
}
4.generatedConstructor(),利用反射获取到观察者的信息,通过信息组成的名字获取到观察者的适配类。返回该类的构造函数
@Nullable
private static Constructor extends GeneratedAdapter> generatedConstructor(Class> klass) {
try {
//利用反射可以获取到类的信息
Package aPackage = klass.getPackage();
String name = klass.getCanonicalName();
//获取包名
final String fullPackage = aPackage != null ? aPackage.getName() : "";
//创建一个适配器名称 详情看(5)
final String adapterName = getAdapterName(fullPackage.isEmpty() ? name :
name.substring(fullPackage.length() + 1));
//加载指定名称的类
@SuppressWarnings("unchecked") final Class extends GeneratedAdapter> aClass =
(Class extends GeneratedAdapter>) Class.forName(
fullPackage.isEmpty() ? adapterName : fullPackage + "." + adapterName);
//获取类的构造函数
Constructor extends GeneratedAdapter> constructor =
aClass.getDeclaredConstructor(klass);
//设置标志
if (!constructor.isAccessible()) {
constructor.setAccessible(true);
}
return constructor;
} catch (ClassNotFoundException e) {
return null;
} catch (NoSuchMethodException e) {
// this should not happen
throw new RuntimeException(e);
}
}
5.getAdapterName()创建一个适配器名称
public static String getAdapterName(String className) {
return className.replace(".", "_") + "_LifecycleAdapter";
}
6.ClassesInfoCache.sInstance.hasLifecycleMethods(klass),判断该观察者是否有监听生命周期的方法
//创建一个缓存类
static ClassesInfoCache sInstance = new ClassesInfoCache();
boolean hasLifecycleMethods(Class klass) {
//判断传入的观察者类是否已经缓存过
Boolean hasLifecycleMethods = mHasLifecycleMethods.get(klass);
if (hasLifecycleMethods != null) {
return hasLifecycleMethods;
}
//获取所有观察者的公开方法
Method[] methods = getDeclaredMethods(klass);
for (Method method : methods) {
//获取方法的注解信息
OnLifecycleEvent annotation = method.getAnnotation(OnLifecycleEvent.class);
if (annotation != null) {
// createInfo()获取CallbackInfo实例 查看详情(7)
createInfo(klass, methods);
return true;
}
}
mHasLifecycleMethods.put(klass, false);
return false;
}
7.createInfo()获取CallbackInfo实例。通过declaredMethods获取观察者监听生命周期的方法,利用反射持有这些方法的引用并封装在CallbackInfo类中
private CallbackInfo createInfo(Class klass, @Nullable Method[] declaredMethods) {
//获取观察者的父类LifecycleObserver
Class superclass = klass.getSuperclass();
Map handlerToEvent = new HashMap<>();
if (superclass != null) {
//从集合获取CallbackInfo 详情看(8)
CallbackInfo superInfo = getInfo(superclass);
if (superInfo != null) {
handlerToEvent.putAll(superInfo.mHandlerToEvent);
}
}
//返回一个数组,其中包含表示该类实现的所有接口的对象
Class[] interfaces = klass.getInterfaces();
for (Class intrfc : interfaces) {
for (Map.Entry entry : getInfo(
intrfc).mHandlerToEvent.entrySet()) {
//verifyAndPutHandler()保存保存了方法的引用与生命周期的事件类型 查看详情(9)
verifyAndPutHandler(handlerToEvent, entry.getKey(), entry.getValue(), klass);
}
}
Method[] methods = declaredMethods != null ? declaredMethods : getDeclaredMethods(klass);
boolean hasLifecycleMethods = false;
//遍历所有公共方法
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;
//若方法带有参数则判断第一个参数是否是属于LifecycleOwner的 否则抛出无效参数异常
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
Lifecycle.Event event = annotation.value();
//判断第二个参数是不是一个Event或On_ANY类型 否则抛出异常
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");
}
}
//参数超过2个抛出异常
if (params.length > 2) {
throw new IllegalArgumentException("cannot have more than 2 params");
}
//MethodReference类利用反射,封装了一个把参数传递到公共方法的函数
MethodReference methodReference = new MethodReference(callType, method);
//verifyAndPutHandler()保存了方法的引用与生命周期的事件类型 查看详情(9)
verifyAndPutHandler(handlerToEvent, methodReference, event, klass);
}
//创建一个CallbackInfo实例,CallbackInfo存储着生命周期方法的引用与对应的Lifecycle.Event
CallbackInfo info = new CallbackInfo(handlerToEvent);
//保存CallbackInfo实例
mCallbackMap.put(klass, info);
//保存方法引用
mHasLifecycleMethods.put(klass, hasLifecycleMethods);
return info;
}
8.getInfo()从集合中获取CallbackInfo对象,若未存储则从createInfo获取
CallbackInfo getInfo(Class klass) {
//若CallbackInfo是否已经存储过 则返回CallbackInfo对象
CallbackInfo existing = mCallbackMap.get(klass);
if (existing != null) {
return existing;
}
//未存储则重新执行createInfo
existing = createInfo(klass, null);
return existing;
}
9.verifyAndPutHandler()保存保存了方法的引用与生命周期的事件类型
private void verifyAndPutHandler(Map handlers,
MethodReference newHandler, Lifecycle.Event newEvent, Class klass) {
//判断newHandler,newEvent是否已经保存过
Lifecycle.Event event = handlers.get(newHandler);
if (event != null && newEvent != event) {
Method method = newHandler.mMethod;
throw new IllegalArgumentException(
"Method " + method.getName() + " in " + klass.getName()
+ " already declared with different @OnLifecycleEvent value: previous"
+ " value " + event + ", new value " + newEvent);
}
if (event == null) {
handlers.put(newHandler, newEvent);
}
}
10.ReflectiveGenericLifecycleObserver实现了LifecycleEventObserver接口的onStateChanged方法,通过CallbackInfo实例拿到了观察者中监听生命周期方法的引用。利用反射执行了方法。所以外部通过调用LifecycleEventObserver.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(LifecycleOwner source, Event event) {
//调用了ClassesInfoCache的invokeCallbacks方法,该方法利用反射调用了观察者的对应方法
mInfo.invokeCallbacks(source, event, mWrapped);
}
}
小结:
1.为何Activity生命周期方法发生变化时,观察者可以做出相同的响应。主要是在FragmentActivity各个生命周期方法都调用了LifecycleRegistry.handleLifecycleEvent(Lifecycle.Event event)方法,下面我们看下源码
//设置当前状态并通知观察者
public void handleLifecycleEvent(@NonNull Lifecycle.Event event) {
//获取Lifecycle的state
State next = getStateAfter(event);
//调用了 sync()同步生命周期状态并发送通知 查看详情(2)
moveToState(next);
}
2.moveToState()调用了 sync()同步生命周期状态并发送通知
private void moveToState(State next) {
//当前状态与参数状态相同时返回
if (mState == next) {
return;
}
//更改当前状态
mState = next;
//正在执行操作
if (mHandlingEvent || mAddingObserverCounter != 0) {
mNewEventOccurred = true;
// we will figure out what to do on upper level.
return;
}
mHandlingEvent = true;
//当生命周期状态不同将必要的事件分派给观察者,并同步生命周期状态
sync();
mHandlingEvent = false;
}
简单的叙述源码实现的总体流程,按照使用的步骤顺序叙述:
这边只算粗俗简单的总结一下,写的详情又感觉是在重复。具体还请看源码 ,都有详细注释。
建议:自己去看一遍源码,比别人分析理解的会更痛彻。不懂的再参考本文
Demo例子镶嵌到下面Demo中
Github—— apk下载体验地址