jetpack之Lifecycle复习
Android Jetpack组件Lifecycle基本使用和原理分析
Jetpack 的 Android Architecture Components 中Lifecycle 分析。
什么是 Lifecycle,然后通过一个例子,来验证 Lifecycle特性!最后Lifecycle源码!
1.Lifecycle简介
什么是Lifecycle
Lifecycle提供可用于构建生命周期感知型组件的类和接口,可以根据Activity或Fragment的当前生命周期状态自动调整其行为。
一句话:可以感知Activity、Fragment 的生命周期并且可以在相应回调事件中处理,非常方便。
Lifecycle 库避免内存泄漏和解决常见的Android 生命周期难题。
总结:
1)Lifecycle是怎样感知生命周期的?
在ReportFragment中的各个生命周期都调用了dispatch(Lifecycle.Event event) 方法,传递了不同Event值
2)Lifecycle是如何处理生命周期的?
通过调用了((LifecycleRegistry) lifecycle).handleLifecycleEvent(event)方法,也就是LifecycleRegistry 类来处理这些生命周期。
3)LifecycleObserver的方法是怎么回调是的呢?
LifecycleRegistry 的 handleLifecycleEvent方法,然后会通过层层调用最后通过反射到LifecycleObserver方法上的@OnLifecycleEvent(Lifecycle.Event.XXX)注解值,来调用对应的方法
4)为什么LifecycleObserver可以感知到Activity的生命周期
LifecycleRegistry调用handleLifecycleEvent()时会传递Event类型,然后会通过层层调用,最后是通过反射获取注解的值,到LifecycleObserver方法上的@OnLifecycleEvent(Lifecycle.Event.XXX)注解上对应的Event的值,Event值和Activity/Fragment的生命周期一一对应。所以可感知Activity、Fragment的生命周期。
2.Lifecycle基本用法
需求:提供一个接口可以感知Activity的生命周期,并且实现回调,用 Lifecycle 是怎么实现的?
1. 定义观察者类, 可以观察Activity、Fragment的生命周期。
1)定义BaseLifecycle类实现DefaultLifecycleObserver接口(Google更推荐)
2)ILifecycleObserver实现LifecycleObserver 并重写方法,用上OnLifecycleEvent注解。
在Activity的onCreate(): lifecycle.addObserver(MyObserver())
interface ILifecycleObserver : LifecycleObserver {
@OnLifecycleEvent(Lifecycle.Event.ON_CREATE)
fun onCreate(owner: LifecycleOwner)
@OnLifecycleEvent(Lifecycle.Event.ON_START)
fun onStart(owner: LifecycleOwner)
...
@OnLifecycleEvent(Lifecycle.Event.ON_ANY)
fun onLifecycleChanged(owner: LifecycleOwner, event: Lifecycle.Event)
}
你可以在build.gradle 中依赖,然后就能使用了
def lifecycle_version = "2.2.0"
implementation "androidx.lifecycle:lifecycle-common-java8:$lifecycle_version"
2.2.定义ActivityLifecycleObserver类
定义ActivityLifecycleObserver类去实现我们定义好的ILifecycleObserver接口
class ActivityLifecycleObserver : ILifecycleObserver {
override fun onCreate(owner: LifecycleOwner) {}
override fun onLifecycleChanged(owner: LifecycleOwner, event: Lifecycle.Event) {
"onLifecycleChanged owner = $owner event = $event".logWithTag(mTag)
}}
2.3.定义LifecycleActivity
LifecycleActivity类onCreate()中通过getLifecycle()获取一个Lifecycle,然后把我们的ActivityLifecycleObserver添加进来:
lifecycle.addObserver(ActivityLifecycleObserver());
Lifecycle是被观察者,通过Add的方式把LifecycleObserver这个观察者添加进来,然后在Activity 执行到对应生命周期时通知观察者,
此时ActivityLifecycleObserver就可以感知Activity的生命周期。
每当LifecycleActivity发生了对应的生命周期改变,ActivityLifecycleObserver就会执行对应事件注解方法,其中onLifecycleChanged的注解是@OnLifecycleEvent(Lifecycle.Event.ON_ANY)所以每次都会调用。
总结上面的现象:
声明ILifecycleObserver接口,并在方法中加入了 @OnLifecycleEvent(Lifecycle.Event.XXX)注解,在BaseActivity的onCreate方法中通过lifecycle.addObserver(ActivityLifecycleObserver())这行代码,然后就可以在 ActivityLifecycleObserver 对应的方法中实现对具体Activity的生命周期回调了。为什么会是这样呢?
阅读源码,从源码中寻找答案
4.Lifecycle的原理分析的前置准备(分析Lifecycle源码前,先对重要类认识,方便看源码)
总结:
• LifecycleOwner:可获取Lifecycle的接口,activity和fragment实现此接口。可以在Activity、Fragment生命周期改变时,通过LifecycleRegistry类处理对应生命周期事件,并通知LifecycleObserver这个观察者
• Lifecycle:是被观察者,用于存储有关组件( 如Activity或Fragment) 的生命周期状态的信息,并允许其他对象观察此状态。
LifecycleRegistry类实现Lifecycle抽象类;
• LifecycleObserver:观察者,可以通过被LifecycleRegistry类通过 addObserver(LifecycleObserver o)方法注册, 被注册后LifecycleObserver便可以观察到LifecycleOwner对应的生命周期事件
• Lifecycle.Event:分派的生命周期事件。这些事件映射到 Activity 和 Fragment 中的回调事件。
• Lifecycle.State:Lifecycle组件的当前状态。
了解上面的基本内容,就进行具体的源码分析,就能知道整个流程。
4.1.LifecycleOwner接口:
生命周期持有者,返回一个Lifecycle对象。如果AndroidX(Jetpack一部分)在这Activity 、Fragment 默认实现了LifecycleOwner接口。
ComponentActivity 和Fragment类默认实现LifecycleOwner 接口,并在getLifecycle()返回LifecycleRegistry,此时Activity和Fragment分别持有Lifecycle;
public interface LifecycleOwner {
Lifecycle getLifecycle();
}
public class ComponentActivity extends androidx.core.app.ComponentActivity implements LifecycleOwner {
private final LifecycleRegistry mLifecycleRegistry = new LifecycleRegistry(this);
public Lifecycle getLifecycle() {
return mLifecycleRegistry;
}}
public class Fragment implements LifecycleOwner,XXX {
private final LifecycleRegistry mLifecycleRegistry;
public Fragment() {
initLifecycle();
}
private void initLifecycle() {
mLifecycleRegistry = new LifecycleRegistry(this);
//....
}
public Lifecycle getLifecycle() {
return mLifecycleRegistry;}}
4.2.Lifecycle
在Lifecycle类定义添加观察者和移除观察者的方法,并定义了两个枚举类。
LifecycleRegistry类是Lifecycl的实现,可以处理多个观察者,如果你自定义 LifecycleOwner可以直接使用它。
public abstract class Lifecycle {
@MainThread
public abstract void addObserver(LifecycleObserver observer);
@MainThread
public abstract void removeObserver(LifecycleObserver observer);
@MainThread
public abstract State getCurrentState();
public enum Event {
ON_CREATE,
ON_START,
ON_RESUME,
ON_PAUSE,
ON_STOP,
ON_DESTROY,
ON_ANY
}
public enum State {
DESTROYED,
INITIALIZED,
CREATED,
STARTED,
RESUMED;
public boolean isAtLeast(@NonNull State state) {
return compareTo(state) >= 0;
}}}
4.3.LifecycleObserver
public interface LifecycleObserver {}
只是标志这个是对Lifecycle的观察者,内部没有任何方法,全部都依赖于OnLifecycleEvent注解
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface OnLifecycleEvent {
Lifecycle.Event value();
}
注解的值是一个 Lifecycle.Event ,接下来去看下Lifecycle中的两个枚举类。
4.4.Lifecycle.Event和Lifecycle.State
public abstract class Lifecycle {
public enum Event {}
public enum State {
public boolean isAtLeast(@NonNull State state) {
return compareTo(state) >= 0;
}}}
Event:定一个一些枚举常量,和 Activity、Fragment 的生命周期是一一对应的,可以响应其生命周期,其中多了一个ON_ANY,它是可以匹配任何事件的,Event 的使用是和 LifecycleObserver 配合使用的,
* class TestObserver implements LifecycleObserver {
* @OnLifecycleEvent(ON_STOP)
* void onStopped() {}
* }
State:当前Lifecycle的自己的目前的状态,它是和Event配合使用的
Event和State之间的关系
5.Lifecycle的源码解析
5.1.分析的入口BaseActivity
在Activity中的一行代码就能实现对应生命周期的回调
lifecycle.addObserver(ActivityLifecycleObserver())
我们先看下getLifecycle() 方法,然后在看addObserver(ActivityLifecycleObserver())的内容,我们先看getLifecycle(),
点进去这个getLifecycle()方法
5.2.ComponentActivity 类
public class ComponentActivity extends xxx implements LifecycleOwner,xxx {//1
private final LifecycleRegistry mLifecycleRegistry = new LifecycleRegistry(this);//2
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ReportFragment.injectIfNeededIn(this);//4
}
public Lifecycle getLifecycle() {
return mLifecycleRegistry;//3
}}
在onCreate有一行ReportFragment.injectIfNeededIn(this);
注释4:在onCreate方法中,看到初始化了一个ReportFragment,接下来看一下ReportFragment的源码
5.3.ReportFragment 类
ReportFragment 各个生命周期都调用dispatch(Lifecycle.Event event) ,传递了不同的Event的值,这个就是在Activity、Fragment的各个生命周期回调时,Lifecycle 所要处理的生命周期方法。
在dispatch(Lifecycle.Event event)最终调用了((LifecycleRegistry) lifecycle).handleLifecycleEvent(event);
1.Lifecycle是怎样感知生命周期的?
就是在ReportFragment中的各个生命周期都调用了dispatch(Lifecycle.Event event) 方法,传递了不同的Event的值
2.Lifecycle是如何处理生命周期的?
通过调用了((LifecycleRegistry) lifecycle).handleLifecycleEvent(event)方法,也就是LifecycleRegistry 类来处理这些生命周期。
此时,就应该看 LifecycleRegistry 的 handleLifecycleEvent的代码
public class ReportFragment extends Fragment {
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
dispatchCreate(mProcessListener);
dispatch(Lifecycle.Event.ON_CREATE);·
}
@Override
public void onStart() {
dispatchStart(mProcessListener);
dispatch(Lifecycle.Event.ON_START);
}
@Override
public void onResume() {
dispatchResume(mProcessListener);
dispatch(Lifecycle.Event.ON_RESUME);
}
@Override
public void onPause() {
dispatch(Lifecycle.Event.ON_PAUSE);
}
@Override
public void onStop() {
dispatch(Lifecycle.Event.ON_STOP);
}
@Override
public void onDestroy() {
dispatch(Lifecycle.Event.ON_DESTROY);
mProcessListener = null;
}
private void dispatch(Lifecycle.Event event) {
Activity activity = getActivity();
//1
if (activity instanceof LifecycleRegistryOwner) {
((LifecycleRegistryOwner) activity).getLifecycle().handleLifecycleEvent(event);
return;
}
//2
if (activity instanceof LifecycleOwner) {
Lifecycle lifecycle = ((LifecycleOwner) activity).getLifecycle();
if (lifecycle instanceof LifecycleRegistry) {
((LifecycleRegistry) lifecycle).handleLifecycleEvent(event);
}
}}}
5.4.LifecycleRegistry # handleLifecycleEvent 方法
public void handleLifecycleEvent(Lifecycle.Event event) {
State next = getStateAfter(event);
moveToState(next);
}
根据当前Lifecycle.Event的值,其实也就是 Activity、Fragment 生命周期回调的值,来获取下一个 Lifecycle.State 的状态,也就是 Lifecycle 将要到什么状态
//LifecycleRegistry.java
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;
}
}
上面代码结合这个图看,食用效果更加
不同的 Lifecycle.Event 的生命周期状态对 Lifecycle.State 的当前状态的取值。
继续跟代码,看下当到下一个状态时,要发生什么事情
//LifecycleRegistry.java
private void moveToState(State next) {
if (mState == next) {
return;}
mState = next;
if (mHandlingEvent || mAddingObserverCounter != 0) {
mNewEventOccurred = true;
return;
}
mHandlingEvent = true;
sync();//1
mHandlingEvent = false;
}
注释1: sync()方法。 然后看 LifecycleRegistry 的 sync 方法
//LifecycleRegistry.java
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);//1
}
Entry<LifecycleObserver, ObserverWithState> newest = mObserverMap.newest();
if (!mNewEventOccurred && newest != null
&& mState.compareTo(newest.getValue().mState) > 0) {
forwardPass(lifecycleOwner);//2
}
}
mNewEventOccurred = false;
}
如果没有同步过,会比较mState当前的状态和mObserverMap中的eldest和newest的状态做对比,看是往前还是往后;比如mState由STARTED到RESUMED是状态向前,反过来就是状态向后。这个是和 Lifecycle 生命周期有关系,但不是一个东西,具体的看上面贴的图,一目了然!
注释2:往后这里看下往后的代码forwardPass(lifecycleOwner);
然后看 LifecycleRegistry 的 forwardPass 方法
//LifecycleRegistry.java
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();//1
while ((observer.mState.compareTo(mState) < 0 && !mNewEventOccurred&& mObserverMap.contains(entry.getKey()))) {
pushParentState(observer.mState);
observer.dispatchEvent(lifecycleOwner, upEvent(observer.mState));//2
popParentState();
}
}}
注释1:获取 ObserverWithState 实例
注释2:调用 ObserverWithState 的 dispatchEvent 方法
接下来看下ObserverWithState的代码
6.ObserverWithState
这个类名很直接,观察者并且带着 State,
//ObserverWithState.java
static class ObserverWithState {
State mState;
LifecycleEventObserver mLifecycleObserver;
ObserverWithState(LifecycleObserver observer, State initialState) {
mLifecycleObserver = Lifecycling.lifecycleEventObserver(observer);//1
mState = initialState;
}
void dispatchEvent(LifecycleOwner owner, Event event) {
State newState = getStateAfter(event);
mState = min(mState, newState);
mLifecycleObserver.onStateChanged(owner, event);//2
mState = newState;
}
}
在看dispatchEvent方法之前,先看下构造,ObserverWithState 是怎么初始化的?这里提一句,是在Lifecycle.addObserver(@NonNull LifecycleObserver observer);方法时候初始化的。
也就是lifecycle.addObserver(ActivityLifecycleObserver())
open class BaseActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
lifecycle.addObserver(ActivityLifecycleObserver()) }
}
在这里初始化的。
ObserverWithState 内部包括了State 和LifecycleEventObserver,LifecycleEventObserver 是一个接口,它继承了 LifecycleObserver 接口。
注释1:mLifecycleObserver这个的获取的实例其实是ReflectiveGenericLifecycleObserver,具体的点进去看一眼就明白了,但是得注意在实例化 ReflectiveGenericLifecycleObserver(object);时候把LifecycleObserver,传入ReflectiveGenericLifecycleObserver的构造中了,此时ReflectiveGenericLifecycleObserver持有LifecycleObserver的实例
注释2:关键代码 mLifecycleObserver.onStateChanged(owner, event),这里其实调用的是ReflectiveGenericLifecycleObserver的onStateChanged方法
接下来看下 ReflectiveGenericLifecycleObserver 的 onStateChanged 方法
7.ReflectiveGenericLifecycleObserver
//ReflectiveGenericLifecycleObserver.java
class ReflectiveGenericLifecycleObserver implements LifecycleEventObserver {
private final Object mWrapped;
private final CallbackInfo mInfo;
ReflectiveGenericLifecycleObserver(Object wrapped) {
mWrapped = wrapped;//LifecycleObserver的实例
mInfo = ClassesInfoCache.sInstance.getInfo(mWrapped.getClass());//1
}
@Override
public void onStateChanged(@NonNull LifecycleOwner source, @NonNull Event event) {
mInfo.invokeCallbacks(source, event, mWrapped);//2
}}
mWrapped其实是LifecycleObserver的实例
注释 1:接下来看mInfo的初始化过程,这个是最关键的代码了
注意此时要兵分两路,先看注释 1 的代码,此时注释 2 的代码是被回调的代码
8.ClassesInfoCache 的 getInfo 方法
//ClassesInfoCache.java
CallbackInfo getInfo(Class<?> klass) {
CallbackInfo existing = mCallbackMap.get(klass);
if (existing != null) {
return existing;
}
existing = createInfo(klass, null);//1
return existing;
}
这个klass是LifecycleObserver的字节码文件对象(LifecycleObserver.class)字节码?反射味道继续看下去马上就有结果了。
继续跟代码
private CallbackInfo createInfo(Class<?> klass, @Nullable Method[] declaredMethods) {
...
//1
Method[] methods = declaredMethods != null ? declaredMethods : getDeclaredMethods(klass);
boolean hasLifecycleMethods = false;
for (Method method : methods) {
//2
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");
}
}
//3
Lifecycle.Event event = annotation.value();
//4
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");
}
//5
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;
}
上面代码比较长,但都有用其实就是反射获取方法获取注解值的过程,我们挨个看
注释1:获取LifecycleObserver.class 声明的方法,也即是我们例子中ILifecycleObserver接口中声明的方法
注释2:遍历方法,获取方法上声明的OnLifecycleEvent注解
注释3:获取OnLifecycleEvent注解上的value
注释4:给callType = CALL_TYPE_PROVIDER_WITH_EVENT 赋值
注释5:把callType和当前的method 存储到 MethodReference 中,方便接下来取用
看一下MethodReference中的代码
//MethodReference.java
static class MethodReference {
final int mCallType;
final Method mMethod;
MethodReference(int callType, Method method) {
mCallType = callType;
mMethod = method;
mMethod.setAccessible(true);
}}
好的,以上的mInfo 赋值的问题就看完了
当初在第 7 节在看注释 1 的代码是兵分两路了,现在继续看第 7 节注释 2 的代码吧,也即是就是mInfo的invokeCallbacks方法
继续看ClassesInfoCache的invokeCallbacks方法,点进去来到了 ClassesInfoCache 的 invokeCallbacks方法中
//ClassesInfoCache.java
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);//ON_ANY也会调用
}
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);//1
}
}
}
注释 1:继续看MethodReference 的invokeCallback方法
//MethodReference.java
void invokeCallback(LifecycleOwner source, Lifecycle.Event event, Object target) {
//noinspection TryWithIdenticalCatches
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://1
mMethod.invoke(target, source, event);
break;
}
}
看到最后是用反射调用了mMethod.invoke(target);这里的target就是LifecycleObserver之前解释过了
mCallType和mMethod的值分别是什么呢?就是在前面初始化mInfo存的值,再看下源码
static class MethodReference {
final int mCallType;
final Method mMethod;
MethodReference(int callType, Method method) {
mCallType = callType;
mMethod = method;
mMethod.setAccessible(true);
}
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) {
} catch (IllegalAccessException e) {
}}}
由前面分析可以知道mCallType = CALL_TYPE_PROVIDER_WITH_EVENT,mMethod就是当时遍历时当前的方法
由于之前通过Map存储过,所以invokeCallback会被遍历调用,最终会反射调用对方法和注解。
当然其他mCallType的值也会被反射调用