美文网首页
Jetpack之Lifecycle

Jetpack之Lifecycle

作者: Owen270 | 来源:发表于2024-10-21 17:58 被阅读0次

Lifecycle 使用及原理解析 一文搞懂Lifecycle是Android Architecture Compone - 掘金 (juejin.cn)
Lifecycle原理解析,人人都能看得懂 - 知乎

1.创建生命周期观察者
  • 实现 LifecycleObserver接口,并搭配使用@OnLifecycleEvent注解的方式
  • 如果使用注解,ObserverWithState会调用Lifecycling.lifecycleEventObserver(observer)生成对应的ReflectiveGenericLifecycleObserver,采用反射的方式解析成HashMap<Event, Method>集合,然后遍历HashMap,通过event拿到对应的method进行会调。
public class MyObserver implements LifecycleObserver {

    private static final String TAG = "MyObserver";

    @OnLifecycleEvent(Lifecycle.Event.ON_CREATE)  
    public void onCreate() {
        Log.w(TAG, "onCreate: ");
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_START)
    public void onStart() {
        Log.w(TAG, "onStart: ");
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_RESUME)
    public void onResume() {
        Log.w(TAG, "onResume: ");
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_PAUSE)
    public void onPause() {
        Log.w(TAG, "onPause: ");
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_STOP)
    public void onStop() {
        Log.w(TAG, "onStop: ");
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_DESTROY)
    public void onDestroy() {
        Log.w(TAG, "onDestroy: ");
    }
}

  • 实现 LifecycleEventObserver 接口,实现onStateChanged接口,不使用@OnLifecycleEvent注解
     public interface LifecycleEventObserver extends LifecycleObserver {
         void onStateChanged(LifecycleOwner source,  Lifecycle.Event event);
     }
    public interface LifecycleOwner {
        Lifecycle getLifecycle();
    }
   public class MyObserver2 implements  LifecycleEventObserver{
            @Override
            public void onStateChanged(LifecycleOwner source,Lifecycle.Event event) {
                if (event == Lifecycle.Event.ON_DESTROY) {
                    if (!isChangingConfigurations()) {
                        getViewModelStore().clear();
                    }
                }
            }
   }

2.观察生命周期
public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        //添加一个生命周期观察者    getLifecycle()是FragmentActivity中的方法
        MyObserver observer = new MyObserver();
        getLifecycle().addObserver(observer);
    }
}
3.LifeCycle原理解析
  • Activity的父类 ComponentActivity
public class ComponentActivity extends Activity implements LifecycleOwner{
  //实例化了一个被观察者
   private LifecycleRegistry mLifecycleRegistry = new LifecycleRegistry(this);
   protected void onCreate(@Nullable Bundle savedInstanceState) {
       //注入了一个ReportFragment用来感知Activity的生命周期
        ReportFragment.injectIfNeededIn(this);
        if (mContentLayoutId != 0) {
            setContentView(mContentLayoutId);
        }
    }


    @Override
    public Lifecycle getLifecycle() {
        return mLifecycleRegistry;
    }   
}
//接口,用来获取LicycleRegister 实例
public interface LifecycleOwner {
    Lifecycle getLifecycle();
}
//抽象类,LifecycleRegistry继承了Lifecycle
public abstract class Lifecycle {

    @MainThread
    public abstract void addObserver(@NonNull LifecycleObserver observer);
    @MainThread
    public abstract void removeObserver(@NonNull LifecycleObserver observer);
    @MainThread
    @NonNull
    public abstract State getCurrentState();
    @SuppressWarnings("WeakerAccess")
    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
    }
    @SuppressWarnings("WeakerAccess")
    public enum State {
        DESTROYED,
        INITIALIZED,
        CREATED,
        STARTED,
        RESUMED;
        public boolean isAtLeast(@NonNull State state) {
            return compareTo(state) >= 0;
        }
    }
}
//使用ReportFragment的生命周期来感知Activity的生命周期
public class ReportFragment extends Fragment {
  public void onActivityCreated(Bundle savedInstanceState) {
      getActivity().getLifecycle().handleLifecycleEvent(Lifecycle.Event.ON_CREATE);
    }
   public void onStart() {
        getActivity().getLifecycle().handleLifecycleEvent(Lifecycle.Event.ON_START);
    }
   public void onResume() {
        getActivity().getLifecycle().handleLifecycleEvent(Lifecycle.Event.ON_RESUME);
    }
    ...
}

image.png
  • Lifecycle实现类LifecycleRegistry 被观察者类(添加观察者,删除观察者,通知观察者)
public class LifecycleRegistry extends Lifecycle {
     public LifecycleRegistry(@NonNull LifecycleOwner provider) {
        mLifecycleOwner = new WeakReference<>(provider);//弱引用
        mState = INITIALIZED;//初始state为Initialized  枚举序值为1
    }
     public void addObserver(@NonNull LifecycleObserver observer) {
        State initialState = mState == DESTROYED ? DESTROYED : INITIALIZED;
        //把observer封装成ObserverWithState类作为value值
        ObserverWithState statefulObserver = new ObserverWithState(observer, initialState);
        // 使用map集合存储观察者   
        ObserverWithState previous = mObserverMap.putIfAbsent(observer, statefulObserver);
      }
 
     public void removeObserver(@NonNull LifecycleObserver observer) {
         mObserverMap.remove(observer);
     }


       public void handleLifecycleEvent(@NonNull Lifecycle.Event event) {
        State next = getStateAfter(event);//把event转换成对应的state
        mState=next;//把当前event对应的状态赋值给mState
        sync();
    }
      private void sync() {
        LifecycleOwner lifecycleOwner = mLifecycleOwner.get();

      /*当 mObserverMap 中存储的ObserverWhitState最新的状态(刚插入的) 与 
       最老的状态(最先插入的) 一致,并且当前状态等于 最新的状态,停止同步。 */
        while (!isSynced()) {
            mNewEventOccurred = false; 
            //生命周期后退
            if (mState.compareTo(mObserverMap.eldest().getValue().mState) < 0) {
                backwardPass(lifecycleOwner);
            }
           //生命周期前进
            Entry<LifecycleObserver, ObserverWithState> newest = mObserverMap.newest();
            if (!mNewEventOccurred && newest != null
                    && mState.compareTo(newest.getValue().mState) > 0) {
                forwardPass(lifecycleOwner);
            }
        }
    }
  //生命周期后退
    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();
            }
        }
    }
 //生命周期前进
private void forwardPass(LifecycleOwner lifecycleOwner) {
        Iterator<Entry<LifecycleObserver, ObserverWithState>> ascendingIterator =
                mObserverMap.iteratorWithAdditions();
        while (ascendingIterator.hasNext() && !mNewEventOccurred) {
            Entry<LifecycleObserver, ObserverWithState> entry = ascendingIterator.next();
            ObserverWithState observer = entry.getValue();
            while ((observer.mState.compareTo(mState) < 0 && !mNewEventOccurred
                    && mObserverMap.contains(entry.getKey()))) {
                pushParentState(observer.mState);
               //分发事件
                observer.dispatchEvent(lifecycleOwner, upEvent(observer.mState));
                popParentState();
            }
        }
    }
}

这里会通过LifeRegistry中当前状态mState和存储的状态进行比较操作,判断当然流程是向正在可见发展 还是正在向不可见发展,例如当前执行的状态是mState=START,与上个状态相比,如果上个状态是CREATE,相比结果就是>0 ,说明是正在可见,调用forwardPass();如果上个状态是RESUME ,相比结果<0 ,说明是正在不可见,backwardPass()

  • backwardPass 和 forwardPass 主要有两点不同

1.在对mObserverMap 存储的状态进行遍历时,backwardPass 是以 栈的形式遍历,forwardPass是以队列的形式遍历。

2.对状态还原的时候,backwardPass 是不可见方向还原,也就是上图的粉色箭头方向,forwardPass 是以可见方向还原,也就是上图的 青绿色箭头方向。

  • ObserverWithState是对观察者对象和状态进行了一个包装,在这里我们来详细看一下。
    static class ObserverWithState {
        State mState;
        LifecycleEventObserver mLifecycleObserver;

        ObserverWithState(LifecycleObserver observer, State initialState) {
 //如果观察是实现了onStateChange()或者使用@OnLifecycleEvent注解的方式,就会生成对应的Observer
            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;
        }
    }

总结
  • 首先我们定义观察者,实现LifecycleEventObserver接口,实现了onStateChanged(event)方法.
  • Activity的父类ComponentActivity实现了LifecycleOwner,通过getLifecycle可以获取被观察者对象lifecycleRegistry实例,可以添加删除观察者,遍历观察者, getLifecycle().addObserver()添加观察者的时候,会通过一个map把observer作为key,然后把observer 和状态state【正在可见就是,INITIALIZED,正在消失DESTROY】封装成observerWithState类,作为值存储到一个hashMap里面。
  • Activity在创建的时候,调用父类ComponentActivity的onCreate()方法,注入了一个ReportFragment方法用来感知自身的生命周期,所以ReportFragment对应生命周期方法中,onActivityCreate,onResume方法
    getActivity.getLifecycle.handleLifecycleEvent(event)对事件进行分发,然后遍历map观察者集合,拿到每个ObserverWithState对象,调用dispatchEvent()分发时间,最终调用observer的onStateChanged方法会调.【在分发过程中,Lifecycle 通过内部维护的状态机 将生命周期事件转化为State状态,并进行存储,在 分发过程中,通过状态比较来判断 当前过程是正在可见还是正在不可见,不同过程采用不同策略】

相关文章

网友评论

      本文标题:Jetpack之Lifecycle

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