Lifecycle简介
lifecycle
是谷歌公司开发的jetpack系列的一个组件,它主要作用是管理Android生命周期,通过该组件,我们可以实现让一个类实例监听Activity
或者Fragment
的生命周期,例如在MVP架构中就可以使用Lifecycle
来实现P层监听V层的生命周期,相较于传统监听生命周期的方式,Lifecycle
可以减少大量的侵入代码,就拿MVP架构来说,传统监听生命周期的方式主要是通过重写Activity
或者Fragment
的生命周期方法,并且在方法内部调用Presenter
的对应方法来实现。而Lifecycle
就简单多了,下面说一下Lifecycle
用法;
Lifecycle用法
还是以MVP架构做示范:
Presenter:
//Presenter需要实现LifecycleObserver接口才能监听Activity的生命周期
public class Presenter implements LifecycleObserver {
private String TAG = "presenter";
@OnLifecycleEvent(Lifecycle.Event.ON_CREATE)
private void onCreate(){
Log.d(TAG,"onCreate");
}
@OnLifecycleEvent(Lifecycle.Event.ON_START)
private void onStart(){
Log.d(TAG,"onStart");
}
@OnLifecycleEvent(Lifecycle.Event.ON_RESUME)
private void onResume(){
Log.d(TAG, "onResume: ");
}
@OnLifecycleEvent(Lifecycle.Event.ON_PAUSE)
private void onPause(){
Log.d(TAG, "onPause: ");
}
@OnLifecycleEvent(Lifecycle.Event.ON_STOP)
private void onStop(){
Log.d(TAG, "onStop: ");
}
@OnLifecycleEvent(Lifecycle.Event.ON_DESTROY)
private void onDestroy(){
Log.d(TAG, "onDestroy: ");
}
@OnLifecycleEvent(Lifecycle.Event.ON_ANY)
private void onAny(LifecycleOwner owner,Lifecycle.Event event){
Log.d(TAG, "onAny: ");
}
}
Activity:
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//通过这一行代码就能让Presenter对象监听自己的生命周期
getLifecycle().addObserver(new Presenter());
}
}
Lifecycle
的基本用法很简单,监听Activity生命周期的对象需要实现LifecycleObserver
接口,想让方法监听Activity的某个生命周期只需要加上OnLifecycleEvent
注解:
该注解的value
有七种取值,与Activity生命周期的对应关系如下:
- Lifecycle.Event.ON_CREATE :onCreate;
- Lifecycle.Event.ON_START : onStart;
- Lifecycle.Event.ON_Resume :onResume;
- Lifecycle.Event.ON_PAUSE :onPause;
- Lifecycle.Event.ON_STOP :onStop;
- Lifecycle.Event.ON_DESTROY : onDestory;
- Lifecycle.Event.ON_ANY : Activity的所有生命周期。
而在Activity中只需调用getLifecycle().addObserver(new Presenter());
即可实现让Presenter监听Activity生命周期。
下面就通过Lifecycle
的源码了解其工作原理
原理剖析
Lifecycle
既然能够实现多个对象同时监听Activity的生命周期,其实就很容易想到观察者设计模式,Lifecycle整体框架就是一种典型的观察者模式,其实通过其用法中频繁出现的observer
就能看出来。
在进入源码之前,先要交代一下Lifecycle
中的两个概念:State和Event
顾名思义,State
表示状态,Event
表示事件,而他们之间的关系是完成某个事件达到某个状态,State
和Event
都是枚举类型,分别有5中取值和7种取值(上面讲过)
public enum State {
DESTROYED,
INITIALIZED,
CREATED,
STARTED,
RESUMED;
public boolean isAtLeast(@NonNull State state) {
return compareTo(state) >= 0;
}
}
public enum Event {
ON_CREATE,
ON_START,
ON_RESUME,
ON_PAUSE,
ON_STOP,
ON_DESTROY,
ON_ANY
}
它们之间的关系如下图所示(图源享学课堂)
接下来就正式进入源码,以这行代码为入口:
getLifecycle().addObserver(new Presenter());
getLifecycle()
返回的是LifecycleRegistry
的实例,LifecycleRegistry
是Lifecycle
抽象类的实现类
//mLifecycleRegistry和getLifecycle()都在ComponentActivity中
private final LifecycleRegistry mLifecycleRegistry = new LifecycleRegistry(this);
public Lifecycle getLifecycle() {
return mLifecycleRegistry;
}
我们看一下LifecycleRegistry的构造函数
public LifecycleRegistry(@NonNull LifecycleOwner provider) {
mLifecycleOwner = new WeakReference<>(provider);
mState = INITIALIZED;
}
这个provider
就是activity
,因为ComponentActivity
实现了LifecycleOwner接口,
可以看出LifecycleRegistry
对activity
的引用类型为弱引用,目的是防止内存泄漏,mState
表示当前的状态,初始值为INITIALIZED
;
addObserver
会调用到LifecycleRegistry
的addObserver
:
public void addObserver(@NonNull LifecycleObserver observer) {
State initialState = mState == DESTROYED ? DESTROYED : INITIALIZED;
ObserverWithState statefulObserver = new ObserverWithState(observer, initialState);
ObserverWithState previous = mObserverMap.putIfAbsent(observer, statefulObserver);
if (previous != null) {
return;
}
LifecycleOwner lifecycleOwner = mLifecycleOwner.get();
if (lifecycleOwner == null) {
return;
}
boolean isReentrance = mAddingObserverCounter != 0 || mHandlingEvent;
State targetState = calculateTargetState(observer);
mAddingObserverCounter++;
while ((statefulObserver.mState.compareTo(targetState) < 0
&& mObserverMap.contains(observer))) {
pushParentState(statefulObserver.mState);
statefulObserver.dispatchEvent(lifecycleOwner, upEvent(statefulObserver.mState));
popParentState();
targetState = calculateTargetState(observer);
}
if (!isReentrance) {
sync();
}
mAddingObserverCounter--;
}
一步步地来看(中间会跳到其他地方,希望各位记住代码是从什么地方跳出,回来从什么地方继续)
这里传入的参数observe
r就是监听activity生命周期的对象(PS:后面这个observer
会被作为各个方法的参数,可能会有很多变量名,我一律称为observer
);
State
对象initialState
用来表示observer
的当前初始状态;
这里会先将传进来的observer
和initialState
封装成一个ObserverWithState
对象,
我们再看一下ObserverWithState
中做了什么?
static class ObserverWithState {
State mState;
LifecycleEventObserver mLifecycleObserver;
ObserverWithState(LifecycleObserver observer, State initialState) {
mLifecycleObserver = Lifecycling.lifecycleEventObserver(observer);
mState = initialState;
}
void dispatchEvent(LifecycleOwner owner, Event event) {
State newState = getStateAfter(event);
mState = min(mState, newState);
mLifecycleObserver.onStateChanged(owner, event);
mState = newState;
}
}
ObserverWithState
是LifecycleRegistry
的一个静态内部类,在构造方法中,会将initialState
赋值给成员变量mState
,将observer
封装进一个LifecycleEventObserver
对象再赋值给成员变量mLifecycleObserver
,我们再看一看LifecycleEventObserver
这个类:
public interface LifecycleEventObserver extends LifecycleObserver {
void onStateChanged(@NonNull LifecycleOwner source, @NonNull Lifecycle.Event event);
}
它是一个接口,定义了一个onStateChanged
方法
而在ObserverWithState
的构造方法中,由Lifecycling.lifecycleEventObserver(observer)
实现:
static LifecycleEventObserver lifecycleEventObserver(Object object) {
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();
int type = getObserverConstructorType(klass);
if (type == GENERATED_CALLBACK) {
List<Constructor<? extends GeneratedAdapter>> 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);
}
return new ReflectiveGenericLifecycleObserver(object);
}
这里慢慢来看,首先根据observer
的是LifecycleObserver
的实例来看,前三个if
肯定不会命中,接下来获取observer
的Class
对象调用getObserverConstructorType(klass)
获取到一个int
类型的type
:
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;
}
这种代码很容易理解,首先从缓存中拿,能拿到就直接返回,否则调用resolveObserverCallbackType(klass)
获取,再放入缓存,最后返回,这里是第一次执行,缓存中肯定没有,进入resolveObserverCallbackType(klass)
方法:
private static int resolveObserverCallbackType(Class<?> klass) {
// anonymous class bug:35073837
if (klass.getCanonicalName() == null) {
return REFLECTIVE_CALLBACK;
}
Constructor<? extends GeneratedAdapter> constructor = generatedConstructor(klass);
if (constructor != null) {
sClassToAdapters.put(klass, Collections
.<Constructor<? extends GeneratedAdapter>>singletonList(constructor));
return GENERATED_CALLBACK;
}
boolean hasLifecycleMethods = ClassesInfoCache.sInstance.hasLifecycleMethods(klass);
if (hasLifecycleMethods) {
return REFLECTIVE_CALLBACK;
}
Class<?> superclass = klass.getSuperclass();
List<Constructor<? extends GeneratedAdapter>> adapterConstructors = null;
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;
}
我们看到这里所有的返回包括了两种值REFLECTIVE_CALLBACK
和GENERATED_CALLBACK
,从字面意思上感觉应该和反射和生成代码有关
首先是如果klass的类名为空,则返回REFLECTIVE_CALLBACK
;
否则会调用generatedConstructor(klass)
返回一个Constructor
实例constructor
,这是一个构造器,它所对应的类应该是GeneratedAdapter
的子类,我们先进这个方法看一下:
private static Constructor<? extends GeneratedAdapter> generatedConstructor(Class<?> klass) {
try {
Package aPackage = klass.getPackage();
String name = klass.getCanonicalName();
final String fullPackage = aPackage != null ? aPackage.getName() : "";
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);
}
}
public static String getAdapterName(String className) {
return className.replace(".", "_") + "_LifecycleAdapter";
}
它根据我们传入的Observer
的类名来反射获取一个类名为类名__LifecycleAdapter
的Class
对象,比如说我这里传入的是Presenter
,那么它就是要获取一个Presenter_LifecycleAdapter
的Class
对象,如果反射获取成功,就返回它的构造器,否则返回null
。
接下来就要细抠一下这个Presenter_LifecycleAdapter
类是怎么来的了,可能会跳得有点远。
首先这个类名是根据我们传入的observer
的类名动态生成的,不可能是我们自己写的,也不可能是框架里的,那么就只有可能是编译期生成的类,首先想到的就是注解处理器(APT),可是我找遍了工程依赖的Lifecycle
源码都没看到注解处理器,在build
的generated
包下也没找到Presenter_LifecycleAdapter
类,直到我机缘巧合之下看到了lifecycle-compiler
,然后再在工程中引入lifecycle-compiler
,终于看到了里面的LifecycleProcessor
:
@SupportedAnnotationTypes("androidx.lifecycle.OnLifecycleEvent")
class LifecycleProcessor : AbstractProcessor() {
override fun process(
annotations: MutableSet<out TypeElement>,
roundEnv: RoundEnvironment
): Boolean {
val input = collectAndVerifyInput(processingEnv, roundEnv)
writeModels(transformToOutput(processingEnv, input), processingEnv)
return true
}
override fun getSupportedSourceVersion(): SourceVersion {
return SourceVersion.latest()
}
}
它是通过JavaPoet生成代码,可以看到它支持的注解类型是androidx.lifecycle.OnLifecycleEvent
类型,那么我们就不看它是怎么生成代码的了,直接看生成的代码更直观,引入lifecycle-compiler
以后再编译,可以看到generated
包下出现了Presenter_LifecycleAdapter
类:
public class Presenter_LifecycleAdapter implements GeneratedAdapter {
final Presenter mReceiver;
Presenter_LifecycleAdapter(Presenter receiver) {
this.mReceiver = receiver;
}
@Override
public void callMethods(LifecycleOwner owner, Lifecycle.Event event, boolean onAny,
MethodCallsLogger logger) {
boolean hasLogger = logger != null;
if (onAny) {
if (!hasLogger || logger.approveCall("onAny", 4)) {
mReceiver.onAny(owner, event);
}
return;
}
if (event == Lifecycle.Event.ON_CREATE) {
if (!hasLogger || logger.approveCall("onCreate", 1)) {
mReceiver.onCreate();
}
return;
}
if (event == Lifecycle.Event.ON_START) {
if (!hasLogger || logger.approveCall("onStart", 1)) {
mReceiver.onStart();
}
return;
}
if (event == Lifecycle.Event.ON_RESUME) {
if (!hasLogger || logger.approveCall("onResume", 1)) {
mReceiver.onResume();
}
return;
}
if (event == Lifecycle.Event.ON_PAUSE) {
if (!hasLogger || logger.approveCall("onPause", 1)) {
mReceiver.onPause();
}
return;
}
if (event == Lifecycle.Event.ON_STOP) {
if (!hasLogger || logger.approveCall("onStop", 1)) {
mReceiver.onStop();
}
return;
}
if (event == Lifecycle.Event.ON_DESTROY) {
if (!hasLogger || logger.approveCall("onDestroy", 1)) {
mReceiver.onDestroy();
}
return;
}
}
}
Presenter_LifecycleAdapter
实现了GeneratedAdapter
接口,而GeneratedAdapter
只有一个GeneratedAdapter
方法:
public interface GeneratedAdapter {
void callMethods(LifecycleOwner source, Lifecycle.Event event, boolean onAny,
MethodCallsLogger logger);
}
Presenter_LifecycleAdapter
有一个构造函数,构造函数中只有一个Presenter
类型的参数receiver
,会赋值给成员常量mReceiver
,而在callMethods
方法中根据传入的event
来调用mReceiver
的各个监听生命周期方法,所以这就得保证Presenter
中的监听生命周期方法必须是public
的,否则就会报错。
那么此时上面的Lifecycling.generatedConstructor(klass)
返回的构造器就是这个类的类对象的构造器了,那么再回到Lifecycling.resolveObserverCallbackType
方法,此时我会分两步走,第一步讲解通过lifecycle的APT生成
Presenter_LifecycleAdapter
时的处理方式,第二步讲解项目没有依赖lifecycle的APT的处理方式,先讲第一步:
通过ATP生成类执行观察者的生命周期方法
resolveObserverCallbackType
方法中的constructor
肯定不为null
,首先会将constructor
装入一个只存一个元素的List中,再和observer
的Class类型缓存入一个HashMap
变量sClassToAdapters
中,再返回GENERATED_CALLBACK
,
紧接着回到lifecycleEventObserver
方法,此时会命中第四个if
:
if (type == GENERATED_CALLBACK) {
List<Constructor<? extends GeneratedAdapter>> 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);
}
首先从缓存中根据传入对象的类型拿到存放构造器的List,如果List里面只有一个元素,那么直接拿出来和传入的observer
一起调用createGeneratedAdapter
方法得到一个GeneratedAdapter
接口实例generatedAdapter
:
private static GeneratedAdapter createGeneratedAdapter(
Constructor<? extends GeneratedAdapter> constructor, Object object) {
//noinspection TryWithIdenticalCatches
try {
return constructor.newInstance(object);
} catch (IllegalAccessException e) {
throw new RuntimeException(e);
} catch (InstantiationException e) {
throw new RuntimeException(e);
} catch (InvocationTargetException e) {
throw new RuntimeException(e);
}
}
其实就是通过构造器创建一个Presenter_LifecycleAdapter
实例,此时该实例里的成员mReceiver
就是observer
,这个Presenter_LifecycleAdapter
实例就是generatedAdapter
,然后再将generatedAdapter
作为参数创建一个SingleGeneratedAdapterObserver
对象并返回;
我们再看一下SingleGeneratedAdapterObserver
:
class SingleGeneratedAdapterObserver implements LifecycleEventObserver {
private final GeneratedAdapter mGeneratedAdapter;
SingleGeneratedAdapterObserver(GeneratedAdapter generatedAdapter) {
mGeneratedAdapter = generatedAdapter;
}
@Override
public void onStateChanged(LifecycleOwner source, Lifecycle.Event event) {
mGeneratedAdapter.callMethods(source, event, false, null);
mGeneratedAdapter.callMethods(source, event, true, null);
}
}
实现了LifecycleEventObserver
接口,重写的方法onStateChanged
中调用了两次mGeneratedAdapter.callMethods();
方法,后面再说,而这个mGeneratedAdapter
就是构造函数传入的generatedAdapter
,可以将这个SingleGeneratedAdapterObserver
对象和observer
对应起来。
到这里再回到LifecycleRegistry.ObserverWithState
,成员变量mLifecycleObserver
就是这个SingleGeneratedAdapterObserver
实例
再回到LifecycleRegistry.addObserver
方法,此时第二行代码终于执行完了,接着再将ObserverWithState
实例statefulObserver
缓存用mObserverMap
起来,mObserverMap
是 FastSafeIterableMap
类型,它的每个结点都有前驱结点和后继结点,每个新加入的结点都放在最后,更多细节就不赘述了,紧接着便是同步observer
的状态,首先会调用calculateTargetState(observer);
获取目标状态:
private State calculateTargetState(LifecycleObserver observer) {
Entry<LifecycleObserver, ObserverWithState> previous = mObserverMap.ceil(observer);
State siblingState = previous != null ? previous.getValue().mState : null;
State parentState = !mParentStates.isEmpty() ? mParentStates.get(mParentStates.size() - 1)
: null;
return min(min(mState, siblingState), parentState);
}
这里先获取到mObserverMap
中的最后一个观察者也就是observer
的前驱结点的当前状态siblingState
,
然后还有一个数组变量mParentStates
,如果当前有其它观察者正在分发状态(同步状态),就会存放在这个mParentStates
中,数组前面的观察者状态肯定大于后面的状态,拿到数组里的最后一个元素与被观察者的当前状态以及siblingState
对比,返回最小值,就是observer
当前需要同步的目标状态targetState
,这样做的目的应该是如果添加新的观察者的时候,正好有生命周期正在发生,而同步操作还未完成,为了安全考虑只能先将新的观察者同步到最小状态。
而observer
的同步操作是在一个while
循环中进行的,每分发一次状态以后都会重新获取一次targetState
,再将observer
的当前状态与targetState
比较,看是否需要同步,最终所有的观察者都会进入同一状态。
再看一下observer
分发状态的过程:
statefulObserver.dispatchEvent(lifecycleOwner, upEvent(statefulObserver.mState));
upEvent
方法是根据observer
当前的状态推出observer
接下来的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);
}
调用到ObserverWithState
的dispatchEvent
方法:
void dispatchEvent(LifecycleOwner owner, Event event) {
State newState = getStateAfter(event);
mState = min(mState, newState);
mLifecycleObserver.onStateChanged(owner, event);
mState = newState;
}
可以看到,现根据event
推导出接下来的state
,调用mLifecycleObserver.onStateChanged(owner, event);
以后再修改observer
的当前状态;
根据上面的解读过程,observer
所对应的mLifecycleObserver
是SingleGeneratedAdapterObserver
的实例,而在该实例的onStateChanged
方法中调用了两次mGeneratedAdapter
的callMethods
方法,一次onAny
参数值为false
,一次为true
,这个mGeneratedAdapter
是Presenter_LifecycleAdapter
的实例,onAny
参数值为false
时最终会根据event
执行mReceiver
也就是observer
的对应生命周期方法,onAny
参数值为false
时则会执行onAny
方法。
这就是将观察者添加到Lifecycle
以后,观察者同步自己的状态再分发执行自己的对用生命周期的过程。
接下来再进入第二步,看是如何通过反射来分发执行观察者的对应生命周期方法的。
通过反射执行观察者生命周期方法
我们还是得先回到Lifecycling.resolveObserverCallbackType
方法,如果没有引入Lifecycle
的APT,那么就不会生成Presenter_LifecycleAdapter
类,那么该方法中的constructor
值也一定为null
,接下来就会执行:
boolean hasLifecycleMethods = ClassesInfoCache.sInstance.hasLifecycleMethods(klass);
从字面上来理解ClassesInfoCache.sInstance.
应该是一个单例,hasLifecycleMethods(klass)
返回一个boolean
类型的值作用应该是判断klass
是否有生命周期方法,点进去:
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(klass, methods);
return true;
}
}
mHasLifecycleMethods.put(klass, false);
return false;
}
这种形式的代码前面已经见到过一次了,先从缓存里拿,拿不到就调用相关方法获取,再存入缓存,这里是反射拿到klass
的所有方法以后,再遍历获取方法上的注解,如果有OnLifecycleEvent
注解则说明klass
有生命周期方法,执行createInfo(klass, methods)
以后返回true
,再看一下createInfo(klass, methods)
中做了什么:
private CallbackInfo createInfo(Class klass, @Nullable Method[] declaredMethods) {
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()) {
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;
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();
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");
}
MethodReference methodReference = new MethodReference(callType, method);
verifyAndPutHandler(handlerToEvent, methodReference, event, klass);
}
CallbackInfo info = new CallbackInfo(handlerToEvent);
mCallbackMap.put(klass, info);
mHasLifecycleMethods.put(klass, hasLifecycleMethods);
return info;
}
这里首先创建了一个HashMap
变量handlerToEvent
,它是用来存储方法和生命周期的对应关系的,接下来对它的父类及接口的一些操作主要就是获取到其父类以及接口的handlerToEvent
,再合并到自己的handlerToEvent
中
,先往下看,首先是判断如果传入的方法数组是为空就反射获取,接着遍历所有的方法,如果方法上面有OnLifecycleEvent
注解则反射获取方法的参数个数和类型,根据个数和类型来确定方法的callType
,这里对方法的参数个数以及类型要求很严格,规则如下:
如果参数长度为0,callType= CALL_TYPE_NO_ARG
如果参数长度大于0,那么第一个参数类型必须为LifecycleOwner,否则抛出异常;
如果参数长度为1,则callType = CALL_TYPE_PROVIDER;
如果参数长度为2,则callType = CALL_TYPE_PROVIDER,第二个参数必须为Lifecycle.Event类型,且OnLifecycleEvent注解的value值不能为Lifecycle.Event.ON_ANY,否则抛出异常;
如果参数长度大于2,则直接抛出异常。
接着就会将callType
和method
封装到一个MethodReference
对象中,调用verifyAndPutHandler
方法:
private void verifyAndPutHandler(Map<MethodReference, Lifecycle.Event> handlers,
MethodReference newHandler, Lifecycle.Event newEvent, Class klass) {
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);
}
}
这里主要是做一些容错处理,排除一些重复添加的情况,比如说父类中已经加入该方法了,在子类中有加入一次,这时就会抛出异常。确认没错以后就将这个MethodReference
对象添加到handlerToEvent
中,遍历完所有的方法以后就会将handlerToEvent
封装进一个CallbackInfo
对象中去,再将该对象缓存起来,一个klass
对应一个CallbackInfo
对象。
再回到Lifecycling.resolveObserverCallbackType
方法,hasLifecycleMethods
为true
则返回REFLECTIVE_CALLBACK
,再回到lifecycleEventObserver
方法,四个if
都不会被命中,最后则返回一个ReflectiveGenericLifecycleObserver
对象,看一下这个类的成员属性以及构造方法:
private final Object mWrapped;
private final CallbackInfo mInfo;
ReflectiveGenericLifecycleObserver(Object wrapped) {
mWrapped = wrapped;
mInfo = ClassesInfoCache.sInstance.getInfo(mWrapped.getClass());
}
它保存了observer
以及observer
对应的CallbackInfo
对象。
这时LifecycleRegistry.ObserverWithState
对象里面的mLifecycleObserver
就是这个ReflectiveGenericLifecycleObserver
对象,当observer
同步状态的时候就会执行ReflectiveGenericLifecycleObserver
对象的onStateChanged
方法:
@Override
public void onStateChanged(LifecycleOwner source, Event event) {
mInfo.invokeCallbacks(source, event, mWrapped);
}
执行了CallbackInfo
的invokeCallbacks
方法,直接看整个CallbackInfo的代码:
static class CallbackInfo {
final Map<Lifecycle.Event, List<MethodReference>> mEventToHandlers;
final Map<MethodReference, Lifecycle.Event> mHandlerToEvent;
CallbackInfo(Map<MethodReference, Lifecycle.Event> handlerToEvent) {
mHandlerToEvent = handlerToEvent;
mEventToHandlers = new HashMap<>();
for (Map.Entry<MethodReference, Lifecycle.Event> entry : handlerToEvent.entrySet()) {
Lifecycle.Event event = entry.getValue();
List<MethodReference> methodReferences = mEventToHandlers.get(event);
if (methodReferences == null) {
methodReferences = new ArrayList<>();
mEventToHandlers.put(event, methodReferences);
}
methodReferences.add(entry.getKey());
}
}
@SuppressWarnings("ConstantConditions")
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) {
if (handlers != null) {
for (int i = handlers.size() - 1; i >= 0; i--) {
handlers.get(i).invokeCallback(source, event, mWrapped);
}
}
}
}
首先看它的构造函数,它将我们传入的handlerToEvent
,转化了一下,之前是<MethodReference, Lifecycle.Event>
的存储方式,转化成<Lifecycle.Event, List<MethodReference>>
的存储方式;在invokeCallbacks
中执行了两次invokeMethodsForEvent
方法,首先是拿到生命周期所对应的所有MethodReference
对象,调用其invokeCallback
方法:
void invokeCallback(LifecycleOwner source, Lifecycle.Event event, Object target) {
try {
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
来选择反射执行observer
的的方法。
至此,添加观察者之后,观察者如何同步自己的状态以及如何调用观察者的生命周期方法已经全部看完了,
至于这两种方式从性能上来讲肯定是第一种更优,毕竟后者是通过反射执行的,不过第一种要求相对严苛,比如要求观察者生命周期方法必须是public
的,需要引入额外的依赖,这是一种典型的以空间换时间。
接下来就看看被观察者生命周期改变时是如何分发给观察者的。
生命周期的分发
首先进入ComponentActivity
,看一下它的onCreate
生命周期:
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mSavedStateRegistryController.performRestore(savedInstanceState);
ReportFragment.injectIfNeededIn(this);
if (mContentLayoutId != 0) {
setContentView(mContentLayoutId);
}
}
有一行重要的代码ReportFragment.injectIfNeededIn(this)
,再进入ReportFragment
类中看一下这个方法:
public static void injectIfNeededIn(Activity activity) {
android.app.FragmentManager manager = activity.getFragmentManager();
if (manager.findFragmentByTag(REPORT_FRAGMENT_TAG) == null) {
manager.beginTransaction().add(new ReportFragment(), REPORT_FRAGMENT_TAG).commit();
manager.executePendingTransactions();
}
}
看到这里,如果之前看过其他开源框架如glide的源码,应该就能大致猜到是怎么一回事了,这里就是新建了一个没有界面的Fragment
,宿主Activity
生命周期变化时,Fragment
的生命周期也会发生变化,再在Fragment
的对应生命周期中将事件分发给观察者们,比如随便看一个onResume
生命周期:
@Override
public void onResume() {
super.onResume();
dispatchResume(mProcessListener);
dispatch(Lifecycle.Event.ON_RESUME);
}
主要看这个dispatch(Lifecycle.Event.ON_RESUME)
:
private void dispatch(Lifecycle.Event event) {
Activity activity = getActivity();
if (activity instanceof LifecycleRegistryOwner) {
((LifecycleRegistryOwner) activity).getLifecycle().handleLifecycleEvent(event);
return;
}
if (activity instanceof LifecycleOwner) {
Lifecycle lifecycle = ((LifecycleOwner) activity).getLifecycle();
if (lifecycle instanceof LifecycleRegistry) {
((LifecycleRegistry) lifecycle).handleLifecycleEvent(event);
}
}
}
最后会调用LifecycleRegistry..handleLifecycleEvent(event)
方法:
public void handleLifecycleEvent(@NonNull Lifecycle.Event event) {
State next = getStateAfter(event);
moveToState(next);
}
它会根据event
获取到需要进入的状态next
,再将当前状态mState
的值改为next
在执行moveToState
方法同步到该状态:
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;
}
里面会执行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.");
}
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;
}
这里首先会做一些容错处理,然后会通过while
循环判断观察者状态是否已经同步,判断函数是isSynced
:
private boolean isSynced() {
if (mObserverMap.size() == 0) {
return true;
}
State eldestObserverState = mObserverMap.eldest().getValue().mState;
State newestObserverState = mObserverMap.newest().getValue().mState;
return eldestObserverState == newestObserverState && mState == newestObserverState;
}
将mObserverMap
中第一个观察者的状态,最后一个观察者的状态,以及mState
进行比较,如果相等的话就说明当前状态已经同步,否则就会进入while
循环,在循环中,首先如果mObserverMap
中第一个观察者的状态大于当前状态mState
,就会执行backwardPass
将所有的观察者的状态往回推(状态回退),具体规则前面的图中有展示,先如果mObserverMap
中最后一个观察者的状态小于于当前状态mState
,就会执行forwardPass
将所有的观察者的状态往前推(状态前进),为什么是这样呢,先看一下backwardPass
做了什么:
private void backwardPass(LifecycleOwner lifecycleOwner) {
Iterator<Entry<LifecycleObserver, ObserverWithState>> descendingIterator =
mObserverMap.descendingIterator();
while (descendingIterator.hasNext() && !mNewEventOccurred) {
Entry<LifecycleObserver, ObserverWithState> 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();
}
}
}
可以看到,这里通过迭代器将mObserverMap
的观察者依次取出,再通过downEvent
得到观察者当前状态回退的所需要执行的event
,再分发该event
来执行观察者的对应生命周期方法。不过这里的迭代器是从后往前取的,第一个观察者的状态是最后同步的,所以如果第一个观察者的状态同步了那么其他的观察者状态也就一定同步了,所以'sync'方法的while
循环中会拿第一个观察者的状态和当前状态比较,而forwardPass
也是如此:
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();
}
}
}
这里的迭代器是从前往后取的,在依次拿到观察者状态前推多需要执行的event
,再分发event
来执行观察者对应的生命周期方法。
这就是Lifecycle
中被观察者生命周期发生变化以后分发给观察者的过程,ReportFragment
类是在lifecycle-runtime
依赖文件下的,不过我这里是2.1.0的版本,我看了下2.2.0的版本又有了变化,injectIfNeededIn
方法中在创建Fragment
之前会先判断如果当前Android版本大于29,就会先执行这样一行代码:
activity.registerActivityLifecycleCallbacks(new LifecycleCallbacks());
再看一下LifecycleCallbacks
类:
static class LifecycleCallbacks implements Application.ActivityLifecycleCallbacks {
@Override
public void onActivityCreated(@NonNull Activity activity,
@Nullable Bundle bundle) {
}
@Override
public void onActivityPostCreated(@NonNull Activity activity,
@Nullable Bundle savedInstanceState) {
dispatch(activity, Lifecycle.Event.ON_CREATE);
}
@Override
public void onActivityStarted(@NonNull Activity activity) {
}
@Override
public void onActivityPostStarted(@NonNull Activity activity) {
dispatch(activity, Lifecycle.Event.ON_START);
}
@Override
public void onActivityResumed(@NonNull Activity activity) {
}
@Override
public void onActivityPostResumed(@NonNull Activity activity) {
dispatch(activity, Lifecycle.Event.ON_RESUME);
}
@Override
public void onActivityPrePaused(@NonNull Activity activity) {
dispatch(activity, Lifecycle.Event.ON_PAUSE);
}
@Override
public void onActivityPaused(@NonNull Activity activity) {
}
@Override
public void onActivityPreStopped(@NonNull Activity activity) {
dispatch(activity, Lifecycle.Event.ON_STOP);
}
@Override
public void onActivityStopped(@NonNull Activity activity) {
}
@Override
public void onActivitySaveInstanceState(@NonNull Activity activity,
@NonNull Bundle bundle) {
}
@Override
public void onActivityPreDestroyed(@NonNull Activity activity) {
dispatch(activity, Lifecycle.Event.ON_DESTROY);
}
@Override
public void onActivityDestroyed(@NonNull Activity activity) {
}
}
其实就是向activity注册一个生命周期回调,也是一种观察者模式,当activity生命周期发生变化时会通知所有的callback
,callback
会回调自己的对应生命周期方法,而这里的LifecycleCallbacks
又会执行dispatch
方法将事件分发给Lifecycle
的所有观察者。而dispatch
方法又发生了改变:
private void dispatch(@NonNull Lifecycle.Event event) {
if (Build.VERSION.SDK_INT < 29) {
// Only dispatch events from ReportFragment on API levels prior
// to API 29. On API 29+, this is handled by the ActivityLifecycleCallbacks
// added in ReportFragment.injectIfNeededIn
dispatch(getActivity(), event);
}
}
static void dispatch(@NonNull Activity activity, @NonNull Lifecycle.Event event) {
if (activity instanceof LifecycleRegistryOwner) {
((LifecycleRegistryOwner) activity).getLifecycle().handleLifecycleEvent(event);
return;
}
if (activity instanceof LifecycleOwner) {
Lifecycle lifecycle = ((LifecycleOwner) activity).getLifecycle();
if (lifecycle instanceof LifecycleRegistry) {
((LifecycleRegistry) lifecycle).handleLifecycleEvent(event);
}
}
}
所以当Android版本低于29的时候,才会通过fragment来分发生命周期,高于29时就通过activity生命周期回调来分发了。
以上就是Lifecycle
工作的基本流程和原理,如果有什么不正确的地方欢迎指正。