Android Jetpack 组建介绍——Lifecycler
Posted xl_phoenix
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Android Jetpack 组建介绍——Lifecycler相关的知识,希望对你有一定的参考价值。
参考Android Jetpack架构组件之 Lifecycle(源码篇)
源码分析
关于Lifecycle的使用考上一篇文章android Jetpack框架之 Lifecycles(使用篇),从使用的方法中我们知道Lifecycle的实现主要依赖:LifecycleObserver、LifecycleOwner;通过像Owner注册Observer实现感知Owner的生命周期,下面一起看看源码是如何巧妙设计的;
生命周期观察者:LifecycleObserver
// 实现LifecycleObserver
class MyObserver(var lifecycle: Lifecycle, var callback: CallBack) : LifecycleObserver {
@OnLifecycleEvent(Lifecycle.Event.ON_CREATE)
public fun connectOnCreate() {
p("connectOnCreate")
}
@OnLifecycleEvent(Lifecycle.Event.ON_RESUME)
public fun connectOnResume() {
p("connectOnResume")
}
}
// LifecycleObserver 是一个空接口
public interface LifecycleObserver {
}
上面过程做了三件事情:
- 实现LifecycleObserver的接口
- 编写要执行的方法
- 为每个方法添加注解,表示其执行的时机
@OnLifecycleEvent:运行注解
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface OnLifecycleEvent {
Lifecycle.Event value();
}
生命周期:Lifecycle.Event & State
// 生命周期Event
public enum Event {
/**
* Constant for onCreate event of the {@link LifecycleOwner}.
*/
ON_CREATE,
/**
* Constant for onStart event of the {@link LifecycleOwner}.
*/
ON_START,
/**
* Constant for onResume event of the {@link LifecycleOwner}.
*/
ON_RESUME,
/**
* Constant for onPause event of the {@link LifecycleOwner}.
*/
ON_PAUSE,
/**
* Constant for onStop event of the {@link LifecycleOwner}.
*/
ON_STOP,
/**
* Constant for onDestroy event of the {@link LifecycleOwner}.
*/
ON_DESTROY,
/**
* An {@link Event Event} constant that can be used to match all events.
*/
ON_ANY
}
//5个对应的生命周期状态
public enum State {
DESTROYED,
INITIALIZED,
CREATED,
STARTED,
RESUMED;
public boolean isAtLeast(@NonNull State state) {
return compareTo(state) >= 0;
}
}
通过Lifecycle.Event和State的查看,系统提供了Activity每个生命周期对应的Event,而Event有会有对应的State,此时 以大致猜想到上面的执行过程:
- 使用LifeEvent标记每个执行方法的Event
- 当活动状态改变时,系统会判断即将要改变成的状态
- 根据状态获取要执行的Event
- 从注册的Observer中获取标注为对应的Event,执行逻辑
生命周期的感知
LifecycleOwner
class LifeCyclerActivity : AppCompatActivity() {
...
var myObserver = MyObserver(lifecycle, object : CallBack { // 创建LifecyclerObserver
override fun update() {
...
}
})
lifecycle.addObserver(myObserver) // 添加观察者
}
}
从上面的使用情况看出,使用的活动需要调用getLifecycle()方法,返回LifecycleRegistry,这里的getLifecycle()方法其实是接口LifecycleOwner接口中的方法,
@SuppressWarnings({"WeakerAccess", "unused"})
public interface LifecycleOwner {
/**
* Returns the Lifecycle of the provider.
*
* @return The lifecycle of the provider.
*/
@NonNull
Lifecycle getLifecycle();
}
此时LifecycleActivity虽然没有实现接口,因为他继承的AppCompatActivity继承了SupportActivity,而SupportActivity实现了接口
@RestrictTo(LIBRARY_GROUP)
public class SupportActivity extends Activity implements LifecycleOwner {
private LifecycleRegistry mLifecycleRegistry = new LifecycleRegistry(this); //创建
@Override
public Lifecycle getLifecycle() { // 重写方法返回LifecycleRegistry
return mLifecycleRegistry;
}
}
SupportActivity除了执行上述操作外,在onCrate的方法中还有一句重要的代码,初始化了一个ReportFragment
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ReportFragment.injectIfNeededIn(this);
}
ReportFragment
public class ReportFragment extends Fragment {
private static final String REPORT_FRAGMENT_TAG = "android.arch.lifecycle"
+ ".LifecycleDispatcher.report_fragment_tag";
public static void injectIfNeededIn(Activity activity) { //初始化Fragment
android.app.FragmentManager manager = activity.getFragmentManager();
if (manager.findFragmentByTag(REPORT_FRAGMENT_TAG) == null) {
manager.beginTransaction().add(new ReportFragment(), REPORT_FRAGMENT_TAG).commit();
manager.executePendingTransactions();
}
}
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
dispatchCreate(mProcessListener);
dispatch(Lifecycle.Event.ON_CREATE);
}
@Override
public void onStart() {
super.onStart();
dispatchStart(mProcessListener);
dispatch(Lifecycle.Event.ON_START);
}
@Override
public void onResume() {
super.onResume();
dispatchResume(mProcessListener);
dispatch(Lifecycle.Event.ON_RESUME);
}
@Override
public void onPause() {
super.onPause();
dispatch(Lifecycle.Event.ON_PAUSE);
}
@Override
public void onStop() {
super.onStop();
dispatch(Lifecycle.Event.ON_STOP);
}
@Override
public void onDestroy() {
super.onDestroy();
dispatch(Lifecycle.Event.ON_DESTROY);
mProcessListener = null;
}
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);
}
}
}
}
上面代码中做了两件事:
- 添加一个ReportFragment的实例
- 根据Fragment的每个生命周期的回调,调用dispatch()处理回调事件
在dispatch()方法中根据LifecyclerOwner和LifecyclerRegistryOwner实例分别处理,因为LifecyclerRegistryOwner也是继承LifecyclerOwner,而在我们SupportActivity中的getLifecycler()中返回的是LifecycleRegistry,所以此处回调的都是LifecycleRegistry的handleLifecycleEvent;
以上是关于Android Jetpack 组建介绍——Lifecycler的主要内容,如果未能解决你的问题,请参考以下文章
7. JetpackNote---基于Jetpack的学习笔记APP
7. JetpackNote---基于Jetpack的学习笔记APP
7. JetpackNote---基于Jetpack的学习笔记APP