ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

Android Jetpack 之 Lifecycle - 2,已开源

2022-01-28 13:33:57  阅读:50  来源: 互联网

标签:LifecycleOwner Jetpack void state LifecycleObserver link Activity Android Lifecy


  • The given observer will be brought to the current state of the LifecycleOwner.

  • For example, if the LifecycleOwner is in {@link State#STARTED} state, the given observer

  • will receive {@link Event#ON_CREATE}, {@link Event#ON_START} events.

  • @param observer The observer to notify.

*/

@MainThread

public abstract void addObserver(@NonNull LifecycleObserver observer);

/**

  • Removes the given observer from the observers list.

  • If this method is called while a state change is being dispatched,

    • If the given observer has not yet received that event, it will not receive it.
    • If the given observer has more than 1 method that observes the currently dispatched
    • event and at least one of them received the event, all of them will receive the event and

    • the removal will happen afterwards.

    • @param observer The observer to be removed.

    • */

      @MainThread

      public abstract void removeObserver(@NonNull LifecycleObserver observer);

      /**

      • Returns the current state of the Lifecycle.

      • @return The current state of the Lifecycle.

      */

      @MainThread

      @NonNull

      public abstract State getCurrentState();

      // Event 对应 activity 的各个生命周期

      //ON_ANY事件可以代表前面任意一种。

      //举个例子,当Activity的onCreate()生命周期方法被调用时会产生ON_CREATE事件,观察者可以监听该事件以便处理Activity此时的生命周期。

      @SuppressWarnings(“WeakerAccess”)

      public enum Event {

      ON_CREATE, //用于匹配生命周期所有者的onCreate事件.

      ON_START, //用于匹配生命周期所有者的onStart事件.

      ON_RESUME, //用于匹配生命周期所有者的onResume事件.

      ON_PAUSE, //用于匹配生命周期所有者的onCreate事件.

      ON_STOP, //用于匹配生命周期所有者的onStop事件.

      ON_DESTROY, //用于匹配生命周期所有者的onDestroy事件.

      ON_ANY //用于匹配生命周期所有者的所有事件.

      }

      /**

      • Lifecycle states. You can consider the states as the nodes in a graph and

      • {@link Event}s as the edges between these nodes.

      */

      @SuppressWarnings(“WeakerAccess”)

      public enum State {

      /**

      • Destroyed state for a LifecycleOwner. After this event, this Lifecycle will not dispatch

      • any more events. For instance, for an {@link android.app.Activity}, this state is reached

      • right before Activity’s {@link android.app.Activity#onDestroy() onDestroy} call.

      */

      DESTROYED,

      /**

      • Initialized state for a LifecycleOwner. For an {@link android.app.Activity}, this is

      • the state when it is constructed but has not received

      • {@link android.app.Activity#onCreate(android.os.Bundle) onCreate} yet.

      */

      INITIALIZED,

      /**

      • Created state for a LifecycleOwner. For an {@link android.app.Activity}, this state

      • is reached in two cases:

        • <li>after {@link android.app.Activity#onCreate(android.os.Bundle) onCreate} call;
          
        • <li><b>right before</b> {@link android.app.Activity#onStop() onStop} call.
          

        */

        CREATED,

        /**

        • Started state for a LifecycleOwner. For an {@link android.app.Activity}, this state

        • is reached in two cases:

          • <li>after {@link android.app.Activity#onStart() onStart} call;
            
          • <li><b>right before</b> {@link android.app.Activity#onPause() onPause} call.
            

          */

          STARTED,

          /**

          • Resumed state for a LifecycleOwner. For an {@link android.app.Activity}, this state

          • is reached after {@link android.app.Activity#onResume() onResume} is called.

          */

          RESUMED;

          /**

          • Compares if this State is greater or equal to the given {@code state}.

          • @param state State to compare with

          • @return true if this State is greater or equal to the given {@code state}

          */

          public boolean isAtLeast(@NonNull State state) {

          return compareTo(state) >= 0;

          }

          }

          }

          Lifecycle 类表示Android应用组件的生命周期,是被观察者。这是一个抽象类,它的实现是 LifecycleRegistry 类。

          Lifecycle 对象有3个方法:

          • 添加观察者:void addObserver(LifecycleObserver observ![](https://www.hualigs.cn/image/61dba891ed8ee.jpg) er)

          • 删除观察者:void removeObserver(LifecycleObserver observer)。-

          • 获取当前状态:State getCurrentState()

          Lifecycle的2个关键方法中参数都是LifecycleObserver

          所以在分析 LifecycleRegistry之前我们先看下LifecycleObserver

          生命周期观察者 (LifecycleObserver)

          LifecycleObserver 基本介绍

          标记接口 LifecycleObserver 表示生命周期观察者,是 lifecycle-aware 组件。

          public interface LifecycleObserver {

          }

          这个接口用来声明它的实现类是生命周期观察者 ,我们要在这个类里接收到LifecycleOwner的生命周期变化事件,然后做自身逻辑。

          但当我们看到LifecycleObserver这个接口时,第一感觉是比较奇怪:这个接口竟然是空的。那我们如何去接受生命周期变化的事件呢?(通常正常的是回调接口)

          其实开头就介绍过用法了,google的做法是配合注解 OnLifecycleEvent 使用,LifecycleObserver 只是起一个声明和约束作用。其内部继承数如下图:

          看到这么多类似的接口,我猜或许这是因为生命周期钩子比较多,如果全都放在接口里,那么实现者需要添加很多空实现方法,可阅读性降低。

          比如FullLifecycleObserver

          interface FullLifecycleObserver extends LifecycleObserver {

          void onCreate(LifecycleOwner owner);

          void onStart(LifecycleOwner owner);

          void onResume(LifecycleOwner owner);

          void onPause(LifecycleOwner owner);

          void onStop(LifecycleOwner owner);

          void onDestroy(LifecycleOwner owner);

          }

          这个接口就将所有的生命周期函数声明了,如果我们实现这个接口,就得重写所有接口,然而我们不一定要用这么多接口。(其实你想用也用不了,这个接口不是public,我们不能实现)

          我们知道用注解的话大多数是反射解析的,这就涉及到性能问题,当然使用apt可以在编译期解决这个问题。这点后文会详细分析。

          如果我们不想用注解,又不想一下子实现所有的方法,可以吗? 答案是肯定的。java8的接口default方法。而且google也鼓励我们用这种方式,那就是DefaultLifecycleObserver

          DefaultLifecycleObserver

          注意:在androidx.lifecycle.Lifecycle类的顶部注释里有一段

          /**

          • If you use Java 8 Language, then observe events with {@link DefaultLifecycleObserver}.

          • To include it you should add {@code “androidx.lifecycle:common-java8:”} to your

          • build.gradle file.

          • class TestObserver implements DefaultLifecycleObserver {

          • {@literal @}Override
            
          • public void onCreate(LifecycleOwner owner) {
            
          •     // your code
            
          • }
            
          • }

          • If you use Java 7 Language, Lifecycle events are observed using annotations.

          • Once Java 8 Language becomes mainstream on Android, annotations will be deprecated, so between

          • {@link DefaultLifecycleObserver} and annotations,

          • you must always prefer {@code DefaultLifecycleObserver}.

          • class TestObserver implements LifecycleObserver {

          • {@literal @}OnLifecycleEvent(ON_STOP)

          • void onStopped() {}

          • }

          • Observer methods can receive zero or one argument.

          • If used, the first argument must be of type {@link LifecycleOwner}.

          • Methods annotated with {@link Event#ON_ANY} can receive the second argument, which must be

          • of type {@link Event}.

          • class TestObserver implements LifecycleObserver {

          • {@literal @}OnLifecycleEvent(ON_CREATE)

          • void onCreated(LifecycleOwner source) {}

          • {@literal @}OnLifecycleEvent(ON_ANY)

          • void onAny(LifecycleOwner source, Event event) {}

          • }

          • These additional parameters are provided to allow you to conveniently observe multiple providers

          • and events without tracking them manually.

          */

          public abstract class Lifecycle {

          }

          意思就是一旦Java 8成为Android的主流,注解将被弃用,所以介于DefaultLifecycleObserver和注解两者之间,更推荐使用 DefaultLifecycleObserver

          使用方式如下

          implementation “androidx.lifecycle:lifecycle-common-java8:$lifecycle_version”

          这个库里其实就一个 DefaultLifecycleObserver.java 接口类。之后我们需要 LifecycleObserver 的时候,一般实现 DefaultLifecycleObserver 接口即可(不用再去直接实现 LifecycleObserver 接口),使用方式变成了下面这样:

          class NormalActivity : Activity(), LifecycleOwner {

          private var lifecycleRegistry: LifecycleRegistry = LifecycleRegistry(this)

          override fun getLifecycle(): Lifecycle {

          return lifecycleRegistry

          }

          override fun onCreate(savedInstanceState: Bundle?) {

          super.onCreate(savedInstanceState)

          setContentView(R.layout.activity_normal)

          lifecycle.addObserver(object : DefaultLifecycleObserver {

          //下面的方法视自身情况选择实现

          override fun onCreate(owner: LifecycleOwner) {

          }

          override fun onStart(owner: LifecycleOwner) {

          }

          override fun onResume(owner: LifecycleOwner) {

          }

          override fun onPause(owner: LifecycleOwner) {

          }

          override fun onStop(owner: LifecycleOwner) {

          }

          override fun onDestroy(owner: LifecycleOwner) {

          }

          })

          }

          }

          可以看到,这里我们直接在覆写我们需要的生命周期对应回调方法中写入我们的逻辑代码即可。更加简洁。

          LifecycleObserver 之间的转换

          我们在使用 LifecycleObserver时,框架内部会将其转换为GenericLifecycleObserver 或其子类。 其转换行为在类 androidx.lifecycle.Lifecycling#getCallback 中。至于这个方法何时触发,我们后续会分析。

          现在先看下这个转换过程

          @NonNull

          static GenericLifecycleObserver getCallback(Object object) {

          // 如果是 FullLifecycleObserver, 转换为 FullLifecycleObserverAdapter

          if (object instanceof FullLifecycleObserver) {

          return new FullLifecycleObserverAdapter((FullLifecycleObserver) object);

          }

          // 如果是 GenericLifecycleObserver, 不转换

          if (object instanceof GenericLifecycleObserver) {

          return (GenericLifecycleObserver) object;

          }

          final Class<?> klass = object.getClass();

          // 获取转换type, GENERATED_CALLBACK 为使用代码生成,REFLECTIVE_CALLBACK 为使用反射调用

          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);

          }

          这个方法的本质,其实就是根据传进来的一个LifecycleObserver 对象,构造出来一个 GenericLifecycleObserver 对象(目前有四个子类:FullLifecycleObserverAdapterSingleGeneratedAdapterObserverCompositeGeneratedAdaptersObserverReflectiveGenericLifecycleObserver),而最终构造出来的对象,就包含了我们创建的 LifecycleObserver 的所有信息,包括各种回调方法等。

          当我们通过注解的方式来自定义LifecycleObserver 的时候,按照传统方式,必定要通过反射来对注解进行解析,这样就会对性能造成影响。那么如何优化呢?

          • 通过缓存,来避免每次都通过反射获取构造器。

          • 通过注解处理器,在编译时对那些被@OnLifecycleEvent注解标注的普通方法,进行预处理,生成以“类名_LifecycleAdapter”命名的类,将各种回调方法直接进行逻辑转换,避免反射,进而来提高性能。

          我们先看下仅用反射的情况下google是如何优化的

          不引入注解处理器时,Lifecycling.getCallback(observer)返回的是ReflectiveGenericLifecycleObserver

          package androidx.lifecycle;

          class ReflectiveGenericLifecycleObserver implements GenericLifecycleObserver {

          private final Object mWrapped;

          private final CallbackInfo mInfo;

          ReflectiveGenericLifecycleObserver(Object wrapped) {

          mWrapped = wrapped;

          mInfo = ClassesInfoCache.sInstance.getInfo(mWrapped.getClass());

          }

          @Override

          public void onStateChanged(LifecycleOwner source, Event event) {

          mInfo.invokeCallbacks(source, event, mWrapped);

          }

          }

          这里我们主要关注回调信息 CallbackInfo 的获取方式的代码:

          mInfo = ClassesInfoCache.sInstance.getInfo(mWrapped.getClass());

          因为反射的代价是比较大的,所以又通过 ClassesInfoCache.java这个单例类,为 ReflectiveGenericLifecycleObserver 类要调用的各种方法的相关信息进行了缓存。

          点进去看下它的 getInfo(...) 方法内部,是如何获取方法信息的。

          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) {

          // 先提取父类的 CallbackInfo

          Class superclass = klass.getSuperclass();

          Map<MethodReference, Lifecycle.Event> handlerToEvent = new HashMap<>();

          if (superclass != null) {

          CallbackInfo superInfo = getInfo(superclass);

          if (superInfo != null) {

          handlerToEvent.putAll(superInfo.mHandlerToEvent);

          }

          }

          // 再提取接口的 CallbackInfo

          Class[] interfaces = klass.getInterfaces();

        标签:LifecycleOwner,Jetpack,void,state,LifecycleObserver,link,Activity,Android,Lifecy
        来源: https://blog.csdn.net/m0_66144992/article/details/122729979

        专注分享技术,共同学习,共同进步。侵权联系[admin#icode9.com]

        Copyright (C)ICode9.com, All Rights Reserved.

        ICode9版权所有