Jetpack之Lifecycle

2024-10-21  本文已影响0人  Owen270

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

1.创建生命周期观察者
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: ");
    }
}

     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原理解析
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
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()

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

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

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

总结
上一篇 下一篇

猜你喜欢

热点阅读