lifecycle组件库的理解

213 阅读2分钟

**lifecycle生命周期感知组件。它是一套组件,可以感知activity或者fragment生命周期,属于Google推出的jetpack组件库之一,同时它也是jetpack组件库的基础,如livedata,viewmodel,databinding都是建立在它的基础之上。理解它有助于我们更好的理解和运用jetpack。 **

lifecycle组件库主要包含三个类。

  1. LifecycleOwner:被观察者,它拥有生命周期
public interface LifecycleOwner {
    //  Returns the Lifecycle of the provider.
    @NonNull
    Lifecycle getLifecycle();
}
  1. lifecycleobserve,是生命周期观察者,实现该接口的类具有观察生命周期的能力;是一个接口,不包含任何方法,以来OnLifecycleEvent的注解方法;
public interface LifecycleObserver {

}
  1. lifecycle,沟通lifecycleowner和lifecycleobserve的中间件。它利用枚举类封装了生命周期的信息,Event 和 State :Event 表示生命周期事件,与 LifecycleOwner 的生命周期事件是相对应的。State 表示生命周期状态;DESTROYED: Activity.onDestroy() 之前;INITIALIZED: Activity 已经实例化但未 onCreate() 之前;CREATED: Activity 的 onCreate() 到 onStop() 之间;STARTED:Activity 的 onStart() 到 onPause() 之间;RESUMED: Activity 的 onResume() 之后。如下图非常直观的反映出Event和State的对应关系。 2669479-df0bb30ab769a55e.png

getLifecycle().addObserver(chronometer);

其中

  • chronometer是实现了LifecycleObserver的时间控件。
  • 分开分析:getLifecycle()和addObserver()

1.ComponentActivity实现了LifecycleOwner接口,getLifecycle()调用的是ComponentActivity的。返回的是 mLifecycleRegistry, 为ComponentActivity中的成员变量,LifecycleRegistry实现了Lifecycle

2.那么addObserver()调用的是LifecycleRegistry的那么addObserver() 该方法主要将chronometer添加到mObserverMap,并同步生命周期。

生命周期事件的分发: 3.ComponentActivity的oncreate方法中,通过ReportFragment.injectIfNeededIn(this),向 Activity 注入了一个没有页面的 Fragment ,通过注入的 Fragment 来代理权限请求,ReportFragment 才是真正分发生命周期的地方。

ReportFragment:dispatch(不同的事件)-->

LifecycleRegistry:handleLifecycleEvent(@NonNull Lifecycle.Event event)-->

LifecycleRegistry:getStateAfter(event)-->

LifecycleRegistry:moveToState(State next)-->

LifecycleRegistry:sync()-->

LifecycleRegistry:backwardPass(lifecycleOwner)-->

LifecycleRegistry:dispatchEvent(LifecycleOwner owner, Event event)-->

ReflectiveGenericLifecycleObserver:onStateChanged(@NonNull -->

LiReflectiveGenericLifecycleObserver:fecycleOwner source, @NonNull Event event)-->

ClassesInfoCache:invokeCallbacks(source, event, mWrapped)

: