源码进阶之lifecycle组件原理分析

移动开发 Android
如何利用 android.arch.lifecycle 包提供的类来控制数据、监听器等的 lifecycle。同时,LiveData 与 ViewModel 的 lifecycle 也依赖于 Lifecycle 框架;今天我们就来聊聊lifecycle的实现原理,来一波分析。

[[421728]]

前言

如何利用 android.arch.lifecycle 包提供的类来控制数据、监听器等的 lifecycle。同时,LiveData 与 ViewModel 的 lifecycle 也依赖于 Lifecycle 框架;

今天我们就来聊聊lifecycle的实现原理,来一波分析

一、为什么要引进Lifecycle?

1、没有引进Lifecycle做法

  • 在处理Activity或者Fragment组件的生命周期相关时,不可避免会遇到这样的问题;
  • 在Activity的onCreate()中初始化某些成员(比如MVP架构中的Presenter,或者AudioManager、MediaPlayer等),然后在onStop中对这些成员进行对应处理,在onDestroy中释放这些资源,这样导致我们的代码也许会像这样;
class MyPresenter{ 
    public MyPresenter() { 
    } 
    void create() { 
        //do something 
    } 
    void destroy() { 
        //do something 
    } 

class MyActivity extends AppCompatActivity { 
    private MyPresenter presenter; 
    public void onCreate(...) { 
        presenter= new MyPresenter (); 
        presenter.create(); 
    } 
    public void onDestroy() { 
        super.onDestroy(); 
        presenter.destory(); 
    } 

  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.
  • 19.
  • 20.
  • 21.

代码没有问题,关键问题是,实际生产环境中 ,这样的代码会非常复杂,你最终会有太多的类似调用并且会导致 onCreate() 和 onDestroy() 方法变的非常臃肿;

2、引进Lifecycle做法

Lifecycle 是一个类,它持有关于组件(如 Activity 或 Fragment)生命周期状态的信息,并且允许其他对象观察此状态;

代码如下:

Prestener继承LifecycleObserver接口

public interface IPresenter extends LifecycleObserver { 
    @OnLifecycleEvent(Lifecycle.Event.ON_CREATE) 
    void onCreate(@NotNull LifecycleOwner owner); 
    @OnLifecycleEvent(Lifecycle.Event.ON_DESTROY) 
    void onDestroy(@NotNull LifecycleOwner owner); 
    @OnLifecycleEvent(Lifecycle.Event.ON_ANY) 
    void onLifecycleChanged(@NotNull LifecycleOwner owner, 
                            @NotNull Lifecycle.Event event); 

public class BasePresenter implements IPresenter { 
    private static final String TAG = "com.qingmei2.module.base.BasePresenter";     
    @Override 
    public void onLifecycleChanged(@NotNull LifecycleOwner owner, @NotNull Lifecycle.Event event) { 
    } 
    @Override 
    public void onCreate(@NotNull LifecycleOwner owner) { 
        Log.d("tag""BasePresenter.onCreate" + this.getClass().toString()); 
    } 
    @Override 
    public void onDestroy(@NotNull LifecycleOwner owner) { 
        Log.d("tag""BasePresenter.onDestroy" + this.getClass().toString()); 
    } 

  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.
  • 19.
  • 20.
  • 21.
  • 22.
  • 23.

直接将我想要观察到Presenter的生命周期事件都列了出来,然后封装到BasePresenter 中,这样每一个BasePresenter 的子类都能感知到Activity容器对应的生命周期事件,并在子类重写的方法中,对应相应行为

在Activity/Fragment容器中添加Observer

public class MainActivity extends AppCompatActivity { 
    private IPresenter mPresenter; 
    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
        super.onCreate(savedInstanceState); 
        Log.d("tag""onCreate" + this.getClass().toString()); 
        setContentView(R.layout.activity_main); 
        mPresenter = new MainPresenter(this); 
        getLifecycle().addObserver(mPresenter);//添加LifecycleObserver 
    } 
    @Override 
    protected void onDestroy() { 
        Log.d("tag""onDestroy" + this.getClass().toString()); 
        super.onDestroy(); 
    } 

  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.

每当Activity发生了对应的生命周期改变,Presenter就会执行对应事件注解的方法

二、Lifecycle原理层层深入分析

在Activity 获取 Lifecycle,实际上是通过Activity的父类 ComponentActvitiy 获取,父类实现了 LifecycleOwner 接口,就能获取 Lifecycle ,最后注册 LifecycleObserver 就能拿到生命周期回调了

1、 onCreate

在ComponentActvitiy的 onCreate 方法里面可以看到 ReportFragment 的创建。 
    /* ComponentActvitiy */ 
    @Override 
    protected void onCreate(@Nullable Bundle savedInstanceState) { 
        ... 
        ReportFragment.injectIfNeededIn(this); 
        ... 
    } 
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.

2、 getLifecycle方法

/* ComponentActvitiy */ 
  private final LifecycleRegistry mLifecycleRegistry = new LifecycleRegistry(this); 
  @NonNull 
  @Override 
  public Lifecycle getLifecycle() { 
      return mLifecycleRegistry; 
  } 
 Life 
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.

3、 Lifecycle.Event

Lifecycle.Event 是个枚举类,这里的生命周期 Event 并不是Fragment的,在后面的生命周期处理时会用上的。

public enum Event { 
     ON_CREATE, 
     ON_START, 
     ON_RESUME, 
     ON_PAUSE, 
     ON_STOP, 
     ON_DESTROY, 
     ON_ANY; 
    ... 
 } 
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.

4、 ReportFragment的创建

ReportFragment 是一个 没有界面的Fragment,如果有了解过Glide原理的同学,应该也知道这个方法,就是通过看不见的Fragment,来感知生命周期,让使用者无需考虑生命周期的问题。

在SDK29以上的版本 使用的是 LifecycleCallbacks.registerIn(activity)。

/* ReportFragment */ 
  public static void injectIfNeededIn(Activity activity) { 
      if (Build.VERSION.SDK_INT >= 29) { 
          // On API 29+, we can register for the correct Lifecycle callbacks directly 
          LifecycleCallbacks.registerIn(activity); 
      } 
      // Prior to API 29 and to maintain compatibility with older versions of 
      // ProcessLifecycleOwner (which may not be updated when lifecycle-runtime is updated and 
      // need to support activities that don't extend from FragmentActivity from support lib), 
      // use a framework fragment to get the correct timing of Lifecycle events 
      android.app.FragmentManager manager = activity.getFragmentManager(); 
      if (manager.findFragmentByTag(REPORT_FRAGMENT_TAG) == null) { 
          manager.beginTransaction().add(new ReportFragment(), REPORT_FRAGMENT_TAG).commit(); 
          // Hopefully, we are the first to make a transaction
          manager.executePendingTransactions(); 
      } 
  } 
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.

5、 LifecycleCallbacks.registerIn(activity)

LifecycleCallbacks 实现了 Application.ActivityLifecycleCallbacks接口,在SDK29以上的生命周期分发是由Application 分发的,activity注册就能回调。

大名鼎鼎的LeakCanary在监听Activity生命周期,也是使用

Application.ActivityLifecycleCallbacks。 
    @RequiresApi(29) 
    static class LifecycleCallbacks implements Application.ActivityLifecycleCallbacks { 
        static void registerIn(Activity activity) { 
            activity.registerActivityLifecycleCallbacks(new LifecycleCallbacks()); 
        } 
        ... 
        @Override 
        public void onActivityPostCreated(@NonNull Activity activity, 
                @Nullable Bundle savedInstanceState) { 
            dispatch(activity, Lifecycle.Event.ON_CREATE); 
        } 
      ... 
    } 
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.

6、 ReportFragment.dispatch 版本兼容

如果SDK版本小于29,ReportFragment的各个生命周期方法里,会调用 dispatch 方法。

比如 onActivityCreated。

反正无论是使用 LifecycleCallbacks.registerIn(activity),还是 Fragment 的生命周期回调,最后都会dispatch。

@Override 
   public 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) { 
           // 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); 
           } 
       } 
   } 
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.
  • 19.
  • 20.
  • 21.
  • 22.
  • 23.
  • 24.
  • 25.
  • 26.

7、 Lifecycle.State

State只有5个但是生命周期可是不止5个,所以Google他们设计时,就创建流程正着走,销毁流程就反正走。

Lifecycle.State 
    /* Lifecycle.State */ 
    public enum State { 
        DESTROYED, 
        INITIALIZED, 
        CREATED, 
        STARTED, 
        RESUMED; 
        public boolean isAtLeast(@NonNull State state) { 
            return compareTo(state) >= 0; 
        } 
    } 
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.

8、 handleLifecycleEvent

LifecycleRegistryOwner 也是继承 LifecycleOwner,所以他们最后都会执行 LifecycleRegistry 的 handleLifecycleEvent 方法。

就是把 Lifecycle.Event处理一下,转化成 Lifecycle.State

/* Lifecycle.Event */ 
      @NonNull 
      public State getTargetState() { 
          switch (this) { 
              case ON_CREATE: 
              case ON_STOP: 
                  return State.CREATED; 
              case ON_START: 
              case ON_PAUSE: 
                  return State.STARTED; 
              case ON_RESUME: 
                  return State.RESUMED; 
              case ON_DESTROY: 
                  return State.DESTROYED; 
              case ON_ANY: 
                  break; 
          } 
          throw new IllegalArgumentException(this + " has no target state"); 
      } 
Lifecycle.State 继续往下传,先用 mState 保存,再 sync 方法处理。 
  /* LifecycleRegistry  */ 
  public void handleLifecycleEvent(@NonNull Lifecycle.Event event) { 
      enforceMainThreadIfNeeded("handleLifecycleEvent"); 
      moveToState(event.getTargetState()); 
  } 
  private void moveToState(State next) { 
      if (mState == next) { 
          return
      } 
      //保存state状态 
      mState = next
      if (mHandlingEvent || mAddingObserverCounter != 0) { 
          mNewEventOccurred = true
          // we will figure out what to do on upper level
          return
      } 
      mHandlingEvent = true
      sync(); 
      mHandlingEvent = false
  } 
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.
  • 19.
  • 20.
  • 21.
  • 22.
  • 23.
  • 24.
  • 25.
  • 26.
  • 27.
  • 28.
  • 29.
  • 30.
  • 31.
  • 32.
  • 33.
  • 34.
  • 35.
  • 36.
  • 37.
  • 38.
  • 39.
  • 40.

9、 sync

这里利用上一个方法保存的mState,用于比较,判断是正向执行还是反向执行生命周期

/* LifecycleRegistry  */ 
   private void sync() { 
       //这是弱引用包装过的LifecycleOwner  
       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. 
           //上一个方法保存的mState,跟组件之前的的mState对比 
           if (mState.compareTo(mObserverMap.eldest().getValue().mState) < 0) { 
               //返向执行流程 
               backwardPass(lifecycleOwner); 
           } 
           Map.Entry<LifecycleObserver, ObserverWithState> newest = mObserverMap.newest(); 
           if (!mNewEventOccurred && newest != null 
                   && mState.compareTo(newest.getValue().mState) > 0) { 
               //正向执行流程 
               forwardPass(lifecycleOwner); 
           } 
       } 
       mNewEventOccurred = false
   } 
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.
  • 19.
  • 20.
  • 21.
  • 22.
  • 23.
  • 24.
  • 25.

10、 forwardPass

反向的逻辑差不多,只是执行 backwardPass ,先转换Stata,最后执行 observer.dispatchEvent。

这里又把 Lifecycle.State 转回 Lifecycle.Event,然后给观察者分发出去。

/* Lifecycle.Event */ 
     @Nullable 
     public static Event upFrom(@NonNull State state) { 
         switch (state) { 
             case INITIALIZED: 
                 return ON_CREATE; 
             case CREATED: 
                 return ON_START; 
             case STARTED: 
                 return ON_RESUME; 
             default
                 return null
         } 
     } 
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.

转换 Event.upFrom ,发送 observer.dispatchEvent。

/* LifecycleRegistry  */ 
  private void forwardPass(LifecycleOwner lifecycleOwner) { 
      Iterator<Map.Entry<LifecycleObserver, ObserverWithState>> ascendingIterator = 
              mObserverMap.iteratorWithAdditions(); 
      while (ascendingIterator.hasNext() && !mNewEventOccurred) { 
          Map.Entry<LifecycleObserver, ObserverWithState> entry = ascendingIterator.next(); 
          ObserverWithState observer = entry.getValue(); 
          while ((observer.mState.compareTo(mState) < 0 && !mNewEventOccurred 
                  && mObserverMap.contains(entry.getKey()))) { 
              pushParentState(observer.mState); 
              //转化 
              final Event event = Event.upFrom(observer.mState); 
              if (event == null) { 
                  throw new IllegalStateException("no event up from " + observer.mState); 
              } 
              //发送 
              observer.dispatchEvent(lifecycleOwner, event); 
              popParentState(); 
          } 
      } 
  } 
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.
  • 19.
  • 20.
  • 21.

11、 发送生命周期状态

ObserverWithState 发送出 Lifecycle.Event ,至此就结束了,有注册订阅关系的地方就能收到

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 = event.getTargetState(); 
          mState = min(mState, newState); 
          mLifecycleObserver.onStateChanged(owner, event); 
          mState = newState; 
      } 
  } 
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.

原理比较清晰:Activity/Fragment实现LifecycleOwner接口,通过LifecycleRegistry在对应生命周期分发事件Lifecycle.Event,回调到生命周期观察者LifecycleObserver对应订阅方法

图片

总结

Lifecycle还是有可取之处的,相对于其它架构组件之间的配合,Lifecycle更简单且独立;

LifecycleObserver接口( Lifecycle观察者):实现该接口的类,通过注解的方式,可以通过被LifecycleOwner类的addObserver(LifecycleObserver o)方法注册,被注册后,LifecycleObserver便可以观察到LifecycleOwner的生命周期事件;

LifecycleOwner接口(Lifecycle持有者):实现该接口的类持有生命周期(Lifecycle对象),该接口的生命周期(Lifecycle对象)的改变会被其注册的观察者LifecycleObserver观察到并触发其对应的事件;

Lifecycle(生命周期):和LifecycleOwner不同的是,LifecycleOwner本身持有Lifecycle对象,LifecycleOwner通过其Lifecycle getLifecycle()的接口获取内部Lifecycle对象;

State(当前生命周期所处状态);

Event(当前生命周期改变对应的事件),当Lifecycle发生改变,如进入onCreate,会自动发出ON_CREATE事件;

后面会陆续介绍一些官方架构方面的知识点;

本文转载自微信公众号「Android开发编程」

 

责任编辑:姜华 来源: Android开发编程
相关推荐

2021-09-09 06:55:43

AndroidViewDragHel原理

2021-09-07 06:40:25

AndroidLiveData原理

2021-09-01 06:48:16

AndroidGlide缓存

2024-08-30 10:40:12

2021-08-12 16:28:10

AndroidHandleLooper

2021-09-08 06:51:52

AndroidRetrofit原理

2021-10-15 09:19:17

AndroidSharedPrefe分析源码

2021-05-17 09:50:06

Kubebuilde源码CURD

2022-01-05 08:53:13

Spring原理分析MVC

2019-09-20 08:54:38

KafkaBroker消息

2021-08-05 20:39:34

AndroidKotlinStandard.kt

2021-02-22 21:49:33

Vue动态组件

2021-08-09 11:15:28

MybatisJavaSpring

2021-11-26 17:17:43

Android广播运行原理源码分析

2011-05-26 10:05:48

MongoDB

2021-09-02 07:00:01

Glide流程Android

2021-03-23 09:17:58

SpringMVCHttpServletJavaEE

2021-07-06 09:29:38

Cobar源码AST

2024-06-13 07:55:19

2021-09-12 07:30:10

配置
点赞
收藏

51CTO技术栈公众号