当前位置: 代码迷 >> 综合 >> JetPack框架组件1————Lifecycle 使用及源码
  详细解决方案

JetPack框架组件1————Lifecycle 使用及源码

热度:76   发布时间:2023-12-22 08:57:54.0

JetPack框架组件1————Lifecycle 使用及源码

文章目录

  • JetPack框架组件1————Lifecycle 使用及源码
      • 一.Lifecycle的使用
        • 1.lifecycle作用介绍
        • 2.实现LifecycleObserver
        • 3.注册LifecycleObserver
        • 4.自定义LifecycleOwner
        • 5.运行结果
      • 二.LifecycleObserver注册流程
      • 三.LifecycleOwner产生事件流程
      • 四.LifecycleRegister分发事件流程
      • 五.LifecycleObserver接收事件
        • 1.FullLifecycleObserverAdapter
        • 2.ReflectiveGenericLifecycleObserver
      • 六.源码类图
      • 七.参考资料

一.Lifecycle的使用

1.lifecycle作用介绍

lifecycle是Android jetpact提供的组件之一。

它的功能概括来说就是:感知另一个组件(如 Activity 和 Fragment)的生命周期状态的变化。可以将原本写在 Activity/Fragment生命周期回调代码,抽离出来。提高代码的可维护性。

原理是观察者模式:

在这里插入图片描述

观察者模型:

  • LifecycleObserver: 观察者
  • LifecycleOwner : 被观察者
  • 事件 : LifecycleOwner的生命周期信息
  • Lifecycle :存储LifecycleOwner(如 Activity 或 Fragment)的生命周期状态的信息,并允许LifecycleObserver观察

所以和大多数的观察者模式一样,它的使用分为下面几步

  1. 定义LifecycleObserver
  2. 定义LifecycleOwner(Activity/Fragment默认实现)
  3. 将LifecycleObserver注册在LifecycleOwner

2.实现LifecycleObserver

实现LifecycleObserver,有两种方式一种是使用注解,一种使用回调

使用注解

class MyObserver : LifecycleObserver {
    @OnLifecycleEvent(Lifecycle.Event.ON_RESUME)fun onResume() {
    Log.e("测试","ON_RESUME")}@OnLifecycleEvent(Lifecycle.Event.ON_PAUSE)fun onPause() {
    Log.e("测试","ON_PAUSE")}
}

使用回调

class MyObserverV2 : DefaultLifecycleObserver {
    override fun onResume(owner: LifecycleOwner) {
    super.onResume(owner)Log.e("测试","onResume")}override fun onPause(owner: LifecycleOwner) {
    super.onPause(owner)Log.e("测试","onPause")}}

3.注册LifecycleObserver

注册LifecycleObserver

myLifecycleOwner.getLifecycle().addObserver(MyObserver())

如果是在Activity或Fragment可以直接调用Lifecycle

class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)lifecycle.addObserver(MyObserver())}}

4.自定义LifecycleOwner

如果你不满足只监听Activity或Fragment,也可以自定义一个LifecycleOwner,同样可以让LifecycleObserver感知到

class MyLifecycleOwner : LifecycleOwner {
    private lateinit var lifecycleRegistry: LifecycleRegistryfun onCreate() {
    lifecycleRegistry = LifecycleRegistry(this)lifecycleRegistry.currentState = Lifecycle.State.CREATED}fun onStart() {
    lifecycleRegistry.currentState = Lifecycle.State.STARTED}override fun getLifecycle(): Lifecycle {
    return lifecycleRegistry}
}

5.运行结果

在这里插入图片描述

二.LifecycleObserver注册流程

入口代码:

lifecycle.addObserver(MyObserver())

具体实现:
lifecycle的实现类是LifecycleRegistry,直接看LifecycleRegistry中的代码
LifecycleRegistry#addObserver

class LifecycleRegistry{
    @Overridepublic void addObserver(@NonNull LifecycleObserver observer) {
    enforceMainThreadIfNeeded("addObserver");State initialState = mState == DESTROYED ? DESTROYED : INITIALIZED;ObserverWithState statefulObserver = new ObserverWithState(observer, initialState);//将statefulObserver放入map中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 quicklyreturn;}boolean isReentrance = mAddingObserverCounter != 0 || mHandlingEvent;State targetState = calculateTargetState(observer);mAddingObserverCounter++;//如果statefulObserver保存状态 在 statefulObserver之前,这循环进行,并分发之间相差的事件//当保存的状态 == 当前的状态时,停止分发。//所以Lifecycle是一个粘性时间while ((statefulObserver.mState.compareTo(targetState) < 0&& mObserverMap.contains(observer))) {
    pushParentState(statefulObserver.mState);final Event event = Event.upFrom(statefulObserver.mState);if (event == null) {
    throw new IllegalStateException("no event up from " + statefulObserver.mState);}statefulObserver.dispatchEvent(lifecycleOwner, event);popParentState();// mState / subling may have been changed recalculatetargetState = calculateTargetState(observer);}if (!isReentrance) {
    // we do sync only on the top level.sync();}mAddingObserverCounter--;}
}

小结:

  1. 在LifecycleRegistry注册流程中,将lifecycleOwner放入 mObserverMap
  2. 在注册时,补齐之前没有分发的事件(粘性时间)

三.LifecycleOwner产生事件流程

我们以activity为例,实现LifecycleOwner的ComponentActivity类,看看它的onCreate方法

public class ComponentActivity extends androidx.core.app.ComponentActivity implementsLifecycleOwner,ViewModelStoreOwner,SavedStateRegistryOwner,OnBackPressedDispatcherOwner {
    protected void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);mSavedStateRegistryController.performRestore(savedInstanceState);//ReportFragment做的代理ReportFragment.injectIfNeededIn(this);if (mContentLayoutId != 0) {
    setContentView(mContentLayoutId);}}
}

再看看ReportFragment中的onCreate方法

public class ReportFragment extends Fragment {
    //....@Overridepublic void onActivityCreated(Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);dispatchCreate(mProcessListener);dispatch(Lifecycle.Event.ON_CREATE);}private void dispatch(@NonNull Lifecycle.Event event) {
    if (Build.VERSION.SDK_INT < 29) {
    dispatch(getActivity(), event);}}@SuppressWarnings("deprecation")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);}}}//....
}

我们可以看到,最后实际上是在ReportFragment中通过lifecycle.handleLifecycleEvent方法进行了分发

再看一下Lifecycle.Event的类别,即看一下,看一下Lifecycle可以分发那些事件

public abstract class Lifecycle {
    @SuppressWarnings("WeakerAccess")public enum Event {
    ON_CREATE,ON_START,ON_RESUME,ON_PAUSE,ON_STOP,ON_DESTROY,ON_ANY}@SuppressWarnings("WeakerAccess")public enum State {
    DESTROYED,INITIALIZED,CREATED,STARTED,RESUMED;public boolean isAtLeast(@NonNull State state) {
    return compareTo(state) >= 0;}}
}

state和event的区别
在这里插入图片描述
小结:

  1. ComponentActivity最终通过ReportFragment分发了各种生命周期事件
  2. ReportFragment中通过lifecycle.handleLifecycleEvent方法进行了分发

四.LifecycleRegister分发事件流程

上一节中,我们看到,最终LifecycleOwner通过调用lifecycle.handleLifecycleEvent方法进行了分发,这一节我们详细来看分发过程

public class LifecycleRegistry extends Lifecycle {
    public void handleLifecycleEvent(@NonNull Lifecycle.Event event) {
    State next = getStateAfter(event);moveToState(next);}private void moveToState(State next) {
    //....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;}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实际上ObserverWithState类型,所以最后的处理在ObserverWithState中observer.dispatchEvent(lifecycleOwner, event);popParentState();}}}
}

ObserverWithState#dispatchEvent
ObserverWithState是一个内部静态类

    static class ObserverWithState {
    State mState;LifecycleEventObserver mLifecycleObserver;ObserverWithState(LifecycleObserver observer, State initialState) {
    //获取mLifecycleObservermLifecycleObserver = 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;}}

这里看看最终获取mLifecycleObserver的方法

public class Lifecycling {
    @NonNullstatic 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;}//通过反射。找到Lifecycle 自动生成的类 XXX_LifecycleAdapterfinal 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);}    
}

这里我们可以看到,Lifecycling返回了4种LifecycleEventObserver:

  • FullLifecycleObserverAdapter
  • SingleGeneratedAdapterObserver
  • CompositeGeneratedAdaptersObserver
  • ReflectiveGenericLifecycleObserver

下一节我们着重分析第一和第四,因为我们在开头的使用中注解和回调,分别对应的是FullLifecycleObserverAdapter和ReflectiveGenericLifecycleObserver

五.LifecycleObserver接收事件

1.FullLifecycleObserverAdapter

FullLifecycleObserverAdapter

class FullLifecycleObserverAdapter implements LifecycleEventObserver {
    private final FullLifecycleObserver mFullLifecycleObserver;private final LifecycleEventObserver mLifecycleEventObserver;FullLifecycleObserverAdapter(FullLifecycleObserver fullLifecycleObserver,LifecycleEventObserver lifecycleEventObserver) {
    mFullLifecycleObserver = fullLifecycleObserver;mLifecycleEventObserver = lifecycleEventObserver;}@Overridepublic void onStateChanged(@NonNull LifecycleOwner source, @NonNull Lifecycle.Event event) {
    switch (event) {
    case ON_CREATE://DefaultLifecycleObserver的父类是mFullLifecycleObserver//所以这里面实质调用的是DefaultLifecycleObservermFullLifecycleObserver.onCreate(source);break;case ON_START:mFullLifecycleObserver.onStart(source);break;case ON_RESUME:mFullLifecycleObserver.onResume(source);break;case ON_PAUSE:mFullLifecycleObserver.onPause(source);break;case ON_STOP:mFullLifecycleObserver.onStop(source);break;case ON_DESTROY:mFullLifecycleObserver.onDestroy(source);break;case ON_ANY:throw new IllegalArgumentException("ON_ANY must not been send by anybody");}if (mLifecycleEventObserver != null) {
    mLifecycleEventObserver.onStateChanged(source, event);}}
}

2.ReflectiveGenericLifecycleObserver

ReflectiveGenericLifecycleObserver这种情况下对应的就是,使用注解时调用

我们先看看@onLifecycleEvent的定义

@SuppressWarnings("unused")
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface OnLifecycleEvent {
    Lifecycle.Event value();
}

注解参考文章
元注解的使用
注解的解析

所以我们要关注一下,在什么时候解析的OnLifecycleEvent

class ReflectiveGenericLifecycleObserver implements LifecycleEventObserver {
    private final Object mWrapped;private final CallbackInfo mInfo;ReflectiveGenericLifecycleObserver(Object wrapped) {
    mWrapped = wrapped;//mInfo的构造mInfo = ClassesInfoCache.sInstance.getInfo(mWrapped.getClass());}@Overridepublic void onStateChanged(@NonNull LifecycleOwner source, @NonNull Event event) {
    //事件分发mInfo.invokeCallbacks(source, event, mWrapped);}
}

mInfo的构造:

class ClassesInfoCache {
    CallbackInfo getInfo(Class<?> klass) {
    CallbackInfo existing = mCallbackMap.get(klass);if (existing != null) {
    return existing;}existing = createInfo(klass, null);return existing;}private CallbackInfo createInfo(Class<?> klass, @Nullable Method[] declaredMethods) {
    ...//反射获取Methods listMethod[] methods = declaredMethods != null ? declaredMethods : getDeclaredMethods(klass);boolean hasLifecycleMethods = false;for (Method method : methods) {
    //获取OnLifecycleEvent注解OnLifecycleEvent annotation = method.getAnnotation(OnLifecycleEvent.class);if (annotation == null) {
    continue;}...//获取注解值Lifecycle.Event event = annotation.value();...MethodReference methodReference = new MethodReference(callType, method);//将method和event放入handlerToEvent中verifyAndPutHandler(handlerToEvent, methodReference, event, klass);}//mInfo的构造CallbackInfo info = new CallbackInfo(handlerToEvent);mCallbackMap.put(klass, info);mHasLifecycleMethods.put(klass, hasLifecycleMethods);return info;}private void verifyAndPutHandler(Map<MethodReference, Lifecycle.Event> handlers,MethodReference newHandler, Lifecycle.Event newEvent, Class<?> klass) {
    ...Lifecycle.Event event = handlers.get(newHandler);if (event == null) {
    //放入handlers中handlers.put(newHandler, newEvent);}}//mInfo的构造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<>();//info中mEventToHandlers中保存的 event-method键值对mEventToHandlers.put(event, methodReferences);}methodReferences.add(entry.getKey());}}}
}

最后来看事件的分发

    static class CallbackInfo {
    final Map<Lifecycle.Event, List<MethodReference>> mEventToHandlers;final Map<MethodReference, Lifecycle.Event> mHandlerToEvent;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--) {
    //handle 是MethodReference类型handlers.get(i).invokeCallback(source, event, mWrapped);}}}}static class MethodReference {
    final int mCallType;final Method mMethod;void invokeCallback(LifecycleOwner source, Lifecycle.Event event, Object target) {
    //noinspection TryWithIdenticalCatchestry {
    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);}}}

六.源码类图

在这里插入图片描述

七.参考资料

官方文档
Lifecycle 使用与源码分析——彻底搞懂Lifecycle原理