美文网首页
Jetpack-Lifecycle

Jetpack-Lifecycle

作者: 有腹肌的豌豆Z | 来源:发表于2021-01-05 14:22 被阅读0次

    使用生命周期感知型组件处理生命周期

    生命周期感知型组件可执行操作来响应另一个组件(如 Activity 和 Fragment)的生命周期状态的变化。这些组件有助于您写出更有条理且往往更精简的代码,这样的代码更易于维护。

    一种常见的模式是在 Activity 和 Fragment 的生命周期方法中实现依赖组件的操作。但是,这种模式会导致代码条理性很差而且会扩散错误。通过使用生命周期感知型组件,您可以将依赖组件的代码从生命周期方法移入组件本身中。

    androidx.lifecycle 软件包提供了可用于构建生命周期感知型组件的类和接口 - 这些组件可以根据 Activity 或 Fragment 的当前生命周期状态自动调整其行为。

    注意:要将 androidx.lifecycle 导入 Android 项目,请参阅 Lifecycle 版本说明中关于声明依赖项的说明。

    在 Android 框架中定义的大多数应用组件都存在生命周期。生命周期由操作系统或进程中运行的框架代码管理。它们是 Android 运作方式的核心,应用必须遵循它们。如果不这样做,可能会引发内存泄露甚至应用崩溃。

    androidx.lifecycle 软件包提供的类和接口可帮助您以弹性和隔离的方式解决这些问题。

    生命周期

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

    Lifecycle 使用两种主要枚举跟踪其关联组件的生命周期状态:

    事件

    从框架和 Lifecycle 类分派的生命周期事件。这些事件映射到 Activity 和 Fragment 中的回调事件。

    状态

    Lifecycle 对象跟踪的组件的当前状态。

    您可以将状态看作图中的节点,将事件看作这些节点之间的边。

    类可以通过向其方法添加注解来监控组件的生命周期状态。然后,您可以通过调用 Lifecycle 类的 addObserver() 方法并传递观察者的实例来添加观察者,如以下示例中所示:

        public class MyObserver implements LifecycleObserver {
            @OnLifecycleEvent(Lifecycle.Event.ON_RESUME)
            public void connectListener() {
                ...
            }
    
            @OnLifecycleEvent(Lifecycle.Event.ON_PAUSE)
            public void disconnectListener() {
                ...
            }
        }
    
        myLifecycleOwner.getLifecycle().addObserver(new MyObserver());
        
    

    在上面的示例中,myLifecycleOwner 对象实现了 LifecycleOwner 接口,我们将在接下来的部分中对该接口进行说明。


    LifecycleOwner

    LifecycleOwner是单一方法接口,表示类具有 Lifecycle。它具有一种方法(即 getLifecycle()),该方法必须由类实现。如果您尝试管理整个应用进程的生命周期,请参阅ProcessLifecycleOwner

    此接口从各个类(如 Fragment和 AppCompatActivity)抽象化Lifecycle 的所有权,并允许编写与这些类搭配使用的组件。任何自定义应用类均可实现LifecycleOwner接口。

    实现 LifecycleObserver的组件可与实现 LifecycleOwner的组件无缝协同工作,因为所有者可以提供生命周期,而观察者可以注册以观察生命周期。

    对于位置跟踪示例,我们可以让 MyLocationListener 类实现LifecycleObserver,然后在 onCreate() 方法中使用 Activity 的 Lifecycle对其进行初始化。这样,MyLocationListener 类便可以“自给自足”,这意味着,对生命周期状态的变化做出响应的逻辑会在 MyLocationListener(而不是在 Activity)中进行声明。让各个组件存储自己的逻辑,可使 Activity 和 Fragment 逻辑更易于管理。

        class MyActivity extends AppCompatActivity {
            private MyLocationListener myLocationListener;
    
            public void onCreate(...) {
                myLocationListener = new MyLocationListener(this, getLifecycle(), location -> {
                    // update UI
                });
                Util.checkUserStatus(result -> {
                    if (result) {
                        myLocationListener.enable();
                    }
                });
          }
        }
        
    

    一个常见的用例是,如果 Lifecycle 现在未处于良好的状态,则应避免调用某些回调。例如,如果回调在 Activity 状态保存后运行 Fragment 事务,就会引发崩溃,因此我们绝不能调用该回调。

    为简化此用例,Lifecycle 类允许其他对象查询当前状态。

        class MyLocationListener implements LifecycleObserver {
            private boolean enabled = false;
            public MyLocationListener(Context context, Lifecycle lifecycle, Callback callback) {
               ...
            }
    
            @OnLifecycleEvent(Lifecycle.Event.ON_START)
            void start() {
                if (enabled) {
                   // connect
                }
            }
    
            public void enable() {
                enabled = true;
                if (lifecycle.getCurrentState().isAtLeast(STARTED)) {
                    // connect if not connected
                }
            }
    
            @OnLifecycleEvent(Lifecycle.Event.ON_STOP)
            void stop() {
                // disconnect if connected
            }
        }
        
    

    对于此实现,LocationListener 类可以完全感知生命周期。如果我们需要从另一个 Activity 或 Fragment 使用 LocationListener,只需对其进行初始化。所有设置和拆解操作都由类本身管理。

    如果库提供了需要使用 Android 生命周期的类,我们建议您使用生命周期感知型组件。库客户端可以轻松集成这些组件,而无需在客户端进行手动生命周期管理。


    实现自定义 LifecycleObserver

    /**
     * 生命周期
     */
    public class LifecycleActivity extends AppCompatActivity {
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_lifecycle);
    
            getLifecycle().addObserver(new MyObserver());
        }
    
    }
    
    public class MyObserver implements LifecycleObserver {
    
    
        @OnLifecycleEvent(Lifecycle.Event.ON_CREATE)
        public void onCreate() {
            log("onCreate()");
        }
    
        @OnLifecycleEvent(Lifecycle.Event.ON_START)
        public void onStart() {
            log("onStart()");
        }
    
        @OnLifecycleEvent(Lifecycle.Event.ON_RESUME)
        public void onResume() {
            log("onResume()");
        }
    
        @OnLifecycleEvent(Lifecycle.Event.ON_PAUSE)
        public void onPause() {
            log("onPause()");
        }
    
        @OnLifecycleEvent(Lifecycle.Event.ON_STOP)
        public void onStop() {
            log("onStop()");
        }
    
        @OnLifecycleEvent(Lifecycle.Event.ON_DESTROY)
        public void onDestroy() {
            log("onDestroy()");
        }
    
    
        /**
         * 日志输出
         *
         * @param msg
         */
        private void log(String msg) {
            Log.i("MyObserver", "log: --->" + msg);
        }
    
    }
    
    

    经过上面的操作 MyObserver 也有了Activity的生命周期

    实现原理源码分析

    一、Activity 实现 Lifecycle

    • LifecycleOwner 接口用于标记其实现类具备 Lifecycle 对象
      ComponentActivityFragment 都实现了该接口
     public interface LifecycleOwner {
        @NonNull
        Lifecycle getLifecycle();
     }
     
     class ComponentActivity implements LifecycleOwner{
     
        //LifecycleRegistry观察者添加和事件分发  
       private final LifecycleRegistry mLifecycleRegistry = new LifecycleRegistry(this);
        
          @NonNull
          @Override
          public Lifecycle getLifecycle() {
            return mLifecycleRegistry;
          }
    
          @SuppressLint("RestrictedApi")
          @Override
          protected void onCreate(@Nullable Bundle savedInstanceState) {
                super.onCreate(savedInstanceState);
                //往Activity上添加一个fragment,用以监听生命周期的变化
               //其目的是为了兼顾不是继承自AppCompactActivity的场景.
                ReportFragment.injectIfNeededIn(this);
          }
    
         public ComponentActivity() {
             //添加观察者
             getLifecycle().addObserver(new LifecycleEventObserver() {
                @Override
                public void onStateChanged(@NonNull LifecycleOwner source,
                        @NonNull Lifecycle.Event event) {
                }
            });
        }
    } 
    
    
    • Lifecycle接口Lifecycle 声明了 添加观察者 移除观察者等相关函数(抽象)
    public abstract class Lifecycle {
    
      @RestrictTo(RestrictTo.Scope.LIBRARY_GROUP)
      @NonNull
      AtomicReference<Object> mInternalScopeRef = new AtomicReference<>();
      
      @MainThread 
      public abstract void addObserver(@NonNull LifecycleObserver observer);
    
      @MainThread
      public abstract void removeObserver(@NonNull LifecycleObserver observer);
    
      @MainThread
      @NonNull
      public abstract State getCurrentState();
    }
    
    
    • Event类(Lifecycle内部静态类)用于抽象 Activity/Fragment 的生命周期事件发生变化时所触发的事件。例如,当 Activity 的每个生命周期事件回调函数(onCreate、onStart 等)被触发时都会被抽象为相应的 ON_CREATE、ON_START 两个 Event
    public enum Event {     
       ON_CREATE,      
       ON_START,      
       ON_RESUME,    
       ON_PAUSE,      
       ON_STOP,      
       ON_DESTROY,    
       ON_ANY  
    }
    
    
    • State(Lifecycle内部静态类) 类用于标记 Lifecycle 的当前生命周期状态
    public enum State {        
      //当处于 DESTROYED 状态时,Lifecycle 将不会发布其它 Event 值       
      //当 Activity 即将回调 onDestory 时则处于此状态       
      DESTROYED,        
      //已初始化的状态。例如,当 Activity 的构造函数已完成,
      //但还未回调 onCreate 时则处于此状态        
      INITIALIZED,   
      CREATED,       
      STARTED,        
      RESUMED;                
      //如果当前状态大于入参值 state 时,则返回 true    
      public boolean isAtLeast(@NonNull State state) {            
          return compareTo(state) >= 0;       
        } 
    }
    
    
    • LifecycleRegistry 观察者添加和事件分发
    public class LifecycleRegistry extends Lifecycle {
      private FastSafeIterableMap<LifecycleObserver, ObserverWithState>       
                       mObserverMap =new FastSafeIterableMap<>();
      //一般一个 LifecycleRegistry 对应一个 LifecycleOwner 对象(Activity/Fragment等)
      //mState 就用来标记 LifecycleOwner 对象所处的当前生命周期状态
      private State mState;
      // 持有对 LifecycleOwner 的弱引用,避免内存泄露
      private final WeakReference<LifecycleOwner> mLifecycleOwner;
    
      public LifecycleRegistry(@NonNull LifecycleOwner provider) {
        mLifecycleOwner = new WeakReference<>(provider);
        mState = INITIALIZED;
      }
    }
    
    
    • LifecycleRegistry addObserver 添加观察者 将观察者包装成ObserverWithState 对象 存储到 mObserverMap 中
    @Override
    public void addObserver(@NonNull LifecycleObserver observer) {
        //添加新的Observer时,会首先根据宿主的状态计算出它的初始状态,只要不是在onDestroy中注册
       // 的,它的初始状态都是INITIALIZED
        State initialState = mState == DESTROYED ? DESTROYED : INITIALIZED;
        //接着会把observer包装成ObserverWithState,这个类主要是包含了观察者及其状态。每个事
        //件都会经由这个对象类转发,这个类后面会来分析
        ObserverWithState statefulObserver = new ObserverWithState(observer, initialState);
        ObserverWithState previous = mObserverMap.putIfAbsent(observer, statefulObserver);
        //添加到集合,如果之前已经添加过了,则return
        if (previous != null) {
            return;
        }
        LifecycleOwner lifecycleOwner = mLifecycleOwner.get();
        if (lifecycleOwner == null) {
            // it is null we should be destroyed. Fallback quickly
            //如果 LifecycleOwner 对象已经被回收了,则直接返回
            return;
        }
        //如果 isReentrance 为 true,则说明此时以下两种情况至少有一个成立:     
        //1. mAddingObserverCounter != 0。会出现这种情况,是由于开发者先添加了一个        
        //   LifecycleObserver ,当还在向其回调事件的过程中,
        //在回调函数里又再次调用了 addObserver 方法添加了一个新的 LifecycleObserver       
       //2.mHandlingEvent 为 true。即此时正处于向外回调 Lifecycle.Event 的状态
    
        boolean isReentrance = mAddingObserverCounter != 0 || mHandlingEvent;
        State targetState = calculateTargetState(observer);
        //递增加一,标记当前正处于向新添加的 LifecycleObserver 回调 Event 值的过程
        mAddingObserverCounter++;
         
        //拿观察者的状态和宿主当前状态做比较,如果小于0,说明两者状态还没有对齐
        while ((statefulObserver.mState.compareTo(targetState) < 0
                && mObserverMap.contains(observer))) {
            //将 observer 已经遍历到的当前的状态值 mState 保存下来
            pushParentState(statefulObserver.mState);
            //向 observer 回调进入“statefulObserver.mState”前需要收到的 Event 值
            statefulObserver.dispatchEvent(lifecycleOwner, upEvent(statefulObserver.mState));
           //移除 mState
            popParentState();
            // mState / subling may have been changed recalculate
            targetState = calculateTargetState(observer);
        }
    
        if (!isReentrance) {
            // we do sync only on the top level.
            sync();
        }
        mAddingObserverCounter--;
    }
    
    
    • ObserverWithState 将外界传入的 LifecycleObserver 对象传给 Lifecycling 进行类型包装,将反射逻辑和接口回调逻辑都给汇总综合成一个新的 LifecycleEventObserver 对象,从而使得 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 = getStateAfter(event);
                mState = min(mState, newState);
                //把事件分发给被包装的对象,完成本次流程。
                mLifecycleObserver.onStateChanged(owner, event);
                mState = newState;
            }
        }
        
     //再一次根据需要分发的事件类型反推出该观察者的状态,这样的好处是事件与状态对应,不会出现跳跃   
    static State getStateAfter(Event event) {
            switch (event) {
                case ON_CREATE:
                case ON_STOP:
                    return CREATED;
                case ON_START:
                case ON_PAUSE:
                    return STARTED;
                case ON_RESUME:
                    return RESUMED;
                case ON_DESTROY:
                    return DESTROYED;
                case ON_ANY:
                    break;
            }
            throw new IllegalArgumentException("Unexpected event value " + event);
        }    
    
    
    • Lifecycling.lifecycleEventObserver 获取观察者对象类型 根据传入的不同观察者对象类型返回不同的观察者对象
     @NonNull
        static 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;
            }
        ......一些反射逻辑....
    }        
    
    
    • LifecycleEventObserver和FullLifecycleObserver 都实现了 LifecycleObserver (Java多态)
    public interface LifecycleObserver {
    
    }
    
    public interface LifecycleEventObserver extends LifecycleObserver {
    
        void onStateChanged(@NonNull LifecycleOwner source, @NonNull Lifecycle.Event event);
    }
    
    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);
    }
    
    
    • FullLifecycleObserverAdapter 实现了 LifecycleEventObserver 接口,用于在收到 Lifecycle 生命周期事件状态变化时,对其两个构造函数参数( FullLifecycleObserver、LifecycleEventObserver)进行生命周期事件做转发
    class FullLifecycleObserverAdapter implements LifecycleEventObserver {
    
        private final FullLifecycleObserver mFullLifecycleObserver;
        private final LifecycleEventObserver mLifecycleEventObserver;
    
        FullLifecycleObserverAdapter(FullLifecycleObserver fullLifecycleObserver,
                LifecycleEventObserver lifecycleEventObserver) {
            mFullLifecycleObserver = fullLifecycleObserver;
            mLifecycleEventObserver = lifecycleEventObserver;
        }
        //进行生命周期事件转发
        @Override
        public void onStateChanged(LifecycleOwner source, Lifecycle.Event event) {
            switch (event) {
                case ON_CREATE:
                    mFullLifecycleObserver.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);
            }
        }
    }
    
    
    • 以上对如何添加观察者以及这些观察者如何接受宿主生命周期变更事件做了分析,接下来分析宿主的生命周期变更是怎么分发出去的 还记得ComponentActivity中添加的那个ReportFragment吗
     class ComponentActivity implements LifecycleOwner{
     
        //LifecycleRegistry观察者添加和事件分发  
       private final LifecycleRegistry mLifecycleRegistry = new LifecycleRegistry(this);
        
          @NonNull
          @Override
          public Lifecycle getLifecycle() {
            return mLifecycleRegistry;
          }
    
          @SuppressLint("RestrictedApi")
          @Override
          protected void onCreate(@Nullable Bundle savedInstanceState) {
                super.onCreate(savedInstanceState);
                //往Activity上添加一个fragment,用以监听生命周期的变化
               //其目的是为了兼顾不是继承自AppCompactActivity的场景.
                ReportFragment.injectIfNeededIn(this);
          }
    }
    
    
    • ReportFragment 获取到 AppCompatActivity 的事件变化通知,最终调用 LifecycleRegistry 的 handleLifecycleEvent(Lifecycle.Event) 方法将 Lifecycle.Event 传递出去。此时,LifecycleRegistry 就拿到了 Lifecycle.Event
    public class ReportFragment extends Fragment {
       //添加到Activity
       public static void injectIfNeededIn(Activity activity) {
          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();
          }
       }
    
       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);
            }
         }
       }
      
       @Override
       public void onActivityCreated(Bundle savedInstanceState) {
          super.onActivityCreated(savedInstanceState);
          dispatch(Lifecycle.Event.ON_CREATE);
       }
    
       @Override
       public void onStart() {
          super.onStart();
          dispatch(Lifecycle.Event.ON_START);
       }
    
       @Override
       public void onResume() {
        super.onResume();
        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);
      }
    }
    
    
    • 分发宿状态的 handleLifecycleEvent 该方法会根据接收到的 Event 值换算出对应的 State 值,然后更新本地的 mState,再向所有 Observer 进行事件通知,最终还是会调用到 ObserverWithState 的 dispatchEvent 方法,所以后边重点关注 dispatchEvent 方法即可
    public class LifecycleRegistry extends Lifecycle {
      private FastSafeIterableMap<LifecycleObserver, ObserverWithState>       
                       mObserverMap =new FastSafeIterableMap<>();
    
       public void handleLifecycleEvent(@NonNull Lifecycle.Event event) {
        //根据接收到的 Event 值换算出对应的 State 值
        State next = getStateAfter(event);
        moveToState(next);
       }
    
       private void moveToState(State next) {
        if (mState == next) {
            return;
        }
        mState = next;
        if (mHandlingEvent || mAddingObserverCounter != 0) {
            mNewEventOccurred = true;
            // we will figure out what to do on upper level.
            return;
        }
        mHandlingEvent = true;
        sync();
        mHandlingEvent = false;
      }
    }
    
    

    -sync() 宿主生命周期状态同步和分发

    private void sync() {
            //mLifecycleOwner.get() 获取到的是宿主(Activity/Fragment)
            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;
                 //如果宿主当前转态 小于 mObserverMap集合中最先添加的那个观察者的状态
                //则说明宿主可能发生了状态回退,比如当前是RESUMED状态,执行了onPause则回退到
                //STARTED状态
               //此时调用backwardPass把集合中的每个一观察者分发一个on_pause事件,并同步它的状态。
                if (mState.compareTo(mObserverMap.eldest().getValue().mState) < 0) {
                    backwardPass(lifecycleOwner);
                }
                //如果宿主当前转态 大于 mObserverMap集合中最先添加的那个观察者的状态
            //则说明宿主可能发生了状态前进,比如当前是STARTED状态,执行了onResume则前进到
            //RESUMED状态
            //此时调用forwardPass把集合中的每个一观察者分发一个on_resume事件,并同步它的状态。
                Entry<LifecycleObserver, ObserverWithState> newest = mObserverMap.newest();
                if (!mNewEventOccurred && newest != null
                        && mState.compareTo(newest.getValue().mState) > 0) {
                    forwardPass(lifecycleOwner);
                }
            }
            mNewEventOccurred = false;
        }
    
    
    • backwardPass和forwardPass 遍历Map中保存的观察者 进行事件分发
      注意mNewEventOccurred 这个boolean值开关 是在有新的事件过来时能及时终止
      while循环分发没有意义的事件

    ···
    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.dispatchEvent(lifecycleOwner, event);
    popParentState();
    }
    }
    }

    ···

    二、 Fragment 实现 Lifecycle Fragment的实现和add到 AppCompatActivity中的 ReportFragment就打同小异了 一看就明白

    ···
    public class Fragment implements LifecycleOwner{

    LifecycleRegistry mLifecycleRegistry;

    public Fragment() {
    initLifecycle();
    }

    private void initLifecycle() {
    mLifecycleRegistry = new LifecycleRegistry(this);
    if (Build.VERSION.SDK_INT >= 19) {
    mLifecycleRegistry.addObserver(new LifecycleEventObserver() {
    @Override
    public void onStateChanged(@NonNull LifecycleOwner source,
    @NonNull Lifecycle.Event event) {
    if (event == Lifecycle.Event.ON_STOP) {
    if (mView != null) {
    mView.cancelPendingInputEvents();
    }
    }
    }
    });
    }
    }

    @Override
    @NonNull
    public Lifecycle getLifecycle() {
    return mLifecycleRegistry;
    }
    //事件分发
    void performCreate(){
    mLifecycleRegistry.handleLifecycleEvent(Lifecycle.Event.ON_CREATE);
    }

    void performStart(){
    mLifecycleRegistry.handleLifecycleEvent(Lifecycle.Event.ON_START);
    }

    void performResume(){
    mLifecycleRegistry.handleLifecycleEvent(Lifecycle.Event.ON_RESUME);
    }
    }

    ···

    总结

    • LifecycleOwner: Activity/Fragment 都实现了该接口,用以声明它是一个能够提供生命周期事件的宿主。同时必须复写getLifecycle()方法提供一个Lifecycle对象
    • Lifecycle:是一个抽象类,里面定义了两个枚举State宿主的状态,Event 需要分发的事件的类型
    • LifecycleRegistry: 是 Lifecycle 的唯一实现类,主要用来负责注册 Observer(观察者),以及分发宿主状态事件给它们

    使用场景介绍

    对平时开发中需要感知(Fragment/Activity)生命周期逻辑的地方 可以继承LifecycleEventObserver或者 DefaultLifecycleObserver 并添加到 (Fragment/Activity)的 LifecycleRegistry中来观察 (Fragment/Activity)生命周期的变化 而做出对应的业务逻辑变化 (Ps:以前我们可能是在BaseActivity 或者BaseFragment的onStart()和onStop()添加对应生命周期相关的逻辑 )

    class LocationObserver extends DefaultLifecycleObserver{
        //宿主执行了onstart时,会分发该事件
        void onStart(@NotNull LifecycleOwner owner){
            //开启定位
        }
      
       //宿主执行了onstop时 会分发该事件
       void onStop(@NotNull LifecycleOwner owner){
           //停止定位
       }
    }
    //2. 注册观察者,观察宿主生命周期状态变化
    class MyFragment extends Fragment{
      public void onCreate(Bundle bundle){
        LocationObserver observer =new LocationObserver()
        //添加观察者
        getLifecycle().addObserver(observer);
      }
     }
    
    

    相关文章

      网友评论

          本文标题:Jetpack-Lifecycle

          本文链接:https://www.haomeiwen.com/subject/oizfoktx.html