Lifecycle,LifecycleOwner,LiveData如何监听Activity生命周期?

Lifecycle是一个抽象类,里面有2个枚举类:
1.Event,对应Activity生命周期的各个方法
2.State,记录当前处于什么状态

public abstract class Lifecycle {

    @RestrictTo(RestrictTo.Scope.LIBRARY_GROUP)
    @NonNull
    AtomicReference 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();

    @SuppressWarnings("WeakerAccess")
    public enum Event {
        
        ON_CREATE,
       
        ON_START,
        
        ON_RESUME,
        
        ON_PAUSE,
     
        ON_STOP,
       
        ON_DESTROY,
 
        ON_ANY
    }

    @SuppressWarnings("WeakerAccess")
    public enum State {
        
        DESTROYED,

        INITIALIZED,

        CREATED,

        STARTED,

        RESUMED;

        public boolean isAtLeast(@NonNull State state) {
            return compareTo(state) >= 0;
        }
    }
}
 
 

LifecycleOwner 只是一个接口

@SuppressWarnings({"WeakerAccess", "unused"})
public interface LifecycleOwner {
    /**
     * Returns the Lifecycle of the provider.
     *
     * @return The lifecycle of the provider.
     */
    @NonNull
    Lifecycle getLifecycle();
}

来看看哪些Activity实现了这个接口

public class FragmentActivity  extends ComponentActivity 
public class ComponentActivity extends androidx.core.app.ComponentActivity implements
        LifecycleOwner,
        ViewModelStoreOwner
public class ComponentActivity extends Activity implements
        LifecycleOwner

可以看到FragmentActivity继承自ComponentActivity ,等于实现了LifecycleOwner
在ComponentActivity 中有一个成员变量

    private LifecycleRegistry mLifecycleRegistry = new LifecycleRegistry(this);

在ComponentActivity 的getLifecycle便是返回的这个变量

 @NonNull
    @Override
    public Lifecycle getLifecycle() {
        return mLifecycleRegistry;
    }

这里我们先看下LiveData平时是如何在Activity中使用的。

homeViewModel.getIsMineSel().observe(this, aBoolean -> {
            if (aBoolean) {
             xxxxxx
            } 
        });

在LiveData中的observe方法如下

 @MainThread
    public void observe(@NonNull LifecycleOwner owner, @NonNull Observer observer) {
        assertMainThread("observe");
        if (owner.getLifecycle().getCurrentState() == DESTROYED) {
            // ignore
            return;
        }
        LifecycleBoundObserver wrapper = new LifecycleBoundObserver(owner, observer);
        ObserverWrapper existing = mObservers.putIfAbsent(observer, wrapper);
        if (existing != null && !existing.isAttachedTo(owner)) {
            throw new IllegalArgumentException("Cannot add the same observer"
                    + " with different lifecycles");
        }
        if (existing != null) {
            return;
        }
        owner.getLifecycle().addObserver(wrapper);
    }

也就是说LiveData的注册监听器的方法,实际上是通过 owner.getLifecycle().addObserver(wrapper);来实现,即是通过这个LifecycleRegistry 的(@NonNull LifecycleObserver observer); LifecycleRegistry 就是继承了Lifecycle ,

public class LifecycleRegistry extends Lifecycle {

    /**
     * Custom list that keeps observers and can handle removals / additions during traversal.
     *
     * Invariant: at any moment of time for observer1 & observer2:
     * if addition_order(observer1) < addition_order(observer2), then
     * state(observer1) >= state(observer2),
     */
    private FastSafeIterableMap mObserverMap =
            new FastSafeIterableMap<>();
    /**
     * Current state
     */
    private State mState;
    
    private final WeakReference mLifecycleOwner;

    private int mAddingObserverCounter = 0;

    private boolean mHandlingEvent = false;
    private boolean mNewEventOccurred = false;

    private ArrayList mParentStates = new ArrayList<>();

    public LifecycleRegistry(@NonNull LifecycleOwner provider) {
        mLifecycleOwner = new WeakReference<>(provider);
        mState = INITIALIZED;
    }

    @Deprecated
    @MainThread
    public void markState(@NonNull State state) {
        setCurrentState(state);
    }

    @MainThread
    public void setCurrentState(@NonNull State state) {
        moveToState(state);
    }

    public void handleLifecycleEvent(@NonNull Lifecycle.Event event) {
        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;
    }

    private boolean isSynced() {
        if (mObserverMap.size() == 0) {
            return true;
        }
        State eldestObserverState = mObserverMap.eldest().getValue().mState;
        State newestObserverState = mObserverMap.newest().getValue().mState;
        return eldestObserverState == newestObserverState && mState == newestObserverState;
    }

    private State calculateTargetState(LifecycleObserver observer) {
        Entry previous = mObserverMap.ceil(observer);

        State siblingState = previous != null ? previous.getValue().mState : null;
        State parentState = !mParentStates.isEmpty() ? mParentStates.get(mParentStates.size() - 1)
                : null;
        return min(min(mState, siblingState), parentState);
    }

    @Override
    public void addObserver(@NonNull LifecycleObserver observer) {
        State initialState = mState == DESTROYED ? DESTROYED : INITIALIZED;
        ObserverWithState statefulObserver = new ObserverWithState(observer, initialState);
        ObserverWithState previous = mObserverMap.putIfAbsent(observer, statefulObserver);

        if (previous != null) {
            return;
        }
        LifecycleOwner lifecycleOwner = mLifecycleOwner.get();
        if (lifecycleOwner == null) {
            // it is null we should be destroyed. Fallback quickly
            return;
        }

        boolean isReentrance = mAddingObserverCounter != 0 || mHandlingEvent;
        State targetState = calculateTargetState(observer);
        mAddingObserverCounter++;
        while ((statefulObserver.mState.compareTo(targetState) < 0
                && mObserverMap.contains(observer))) {
            pushParentState(statefulObserver.mState);
            statefulObserver.dispatchEvent(lifecycleOwner, upEvent(statefulObserver.mState));
            popParentState();
            // mState / subling may have been changed recalculate
            targetState = calculateTargetState(observer);
        }

        if (!isReentrance) {
            // we do sync only on the top level.
            sync();
        }
        mAddingObserverCounter--;
    }

    private void popParentState() {
        mParentStates.remove(mParentStates.size() - 1);
    }

    private void pushParentState(State state) {
        mParentStates.add(state);
    }

    @Override
    public void removeObserver(@NonNull LifecycleObserver observer) {
        mObserverMap.remove(observer);
    }

    @SuppressWarnings("WeakerAccess")
    public int getObserverCount() {
        return mObserverMap.size();
    }

    @NonNull
    @Override
    public State getCurrentState() {
        return mState;
    }

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

    private static Event downEvent(State state) {
        switch (state) {
            case INITIALIZED:
                throw new IllegalArgumentException();
            case CREATED:
                return ON_DESTROY;
            case STARTED:
                return ON_STOP;
            case RESUMED:
                return ON_PAUSE;
            case DESTROYED:
                throw new IllegalArgumentException();
        }
        throw new IllegalArgumentException("Unexpected state value " + state);
    }

    private static Event upEvent(State state) {
        switch (state) {
            case INITIALIZED:
            case DESTROYED:
                return ON_CREATE;
            case CREATED:
                return ON_START;
            case STARTED:
                return ON_RESUME;
            case RESUMED:
                throw new IllegalArgumentException();
        }
        throw new IllegalArgumentException("Unexpected state value " + state);
    }

    private void forwardPass(LifecycleOwner lifecycleOwner) {
        Iterator> ascendingIterator =
                mObserverMap.iteratorWithAdditions();
        while (ascendingIterator.hasNext() && !mNewEventOccurred) {
            Entry 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();
            }
        }
    }

    private void backwardPass(LifecycleOwner lifecycleOwner) {
        Iterator> descendingIterator =
                mObserverMap.descendingIterator();
        while (descendingIterator.hasNext() && !mNewEventOccurred) {
            Entry 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();
            }
        }
    }

    // happens only on the top of stack (never in reentrance),
    // so it doesn't have to take in account parents
    private void sync() {
        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.
            if (mState.compareTo(mObserverMap.eldest().getValue().mState) < 0) {
                backwardPass(lifecycleOwner);
            }
            Entry newest = mObserverMap.newest();
            if (!mNewEventOccurred && newest != null
                    && mState.compareTo(newest.getValue().mState) > 0) {
                forwardPass(lifecycleOwner);
            }
        }
        mNewEventOccurred = false;
    }

    static State min(@NonNull State state1, @Nullable State state2) {
        return state2 != null && state2.compareTo(state1) < 0 ? state2 : state1;
    }

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

问题来了,那么,LiveData是怎么做到监听Activity生命周期,LifecycleRegistry是怎么监听到Activity生命周期的。

关键要看ComponentActivity的onCreate方法,里面调用了个 ReportFragment.injectIfNeededIn(this);这个ReportFragment就是监听生命周期的关键所在

   protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        this.mSavedStateRegistryController.performRestore(savedInstanceState);
        ReportFragment.injectIfNeededIn(this);
        if (this.mContentLayoutId != 0) {
            this.setContentView(this.mContentLayoutId);
        }
    }

ReportFragment.injectIfNeededIn(this)这个方法的实现如下,这边是在activity中注册了个ActivityLifecycleCallbacks

public static void injectIfNeededIn(Activity activity) {
        if (Build.VERSION.SDK_INT >= 29) {
            // On API 29+, we can register for the correct Lifecycle callbacks directly
            activity.registerActivityLifecycleCallbacks(
                    new Application.ActivityLifecycleCallbacks() {
                        @Override
                        public void onActivityCreated(@NonNull Activity activity,
                                @Nullable Bundle bundle) {
                        }

                        @Override
                        public void onActivityPostCreated(@NonNull Activity activity,
                                @Nullable Bundle savedInstanceState) {
                            dispatch(activity, Lifecycle.Event.ON_CREATE);
                        }

                        @Override
                        public void onActivityStarted(@NonNull Activity activity) {
                        }

                        @Override
                        public void onActivityPostStarted(@NonNull Activity activity) {
                            dispatch(activity, Lifecycle.Event.ON_START);
                        }

                        @Override
                        public void onActivityResumed(@NonNull Activity activity) {
                        }

                        @Override
                        public void onActivityPostResumed(@NonNull Activity activity) {
                            dispatch(activity, Lifecycle.Event.ON_RESUME);
                        }

                        @Override
                        public void onActivityPrePaused(@NonNull Activity activity) {
                            dispatch(activity, Lifecycle.Event.ON_PAUSE);
                        }

                        @Override
                        public void onActivityPaused(@NonNull Activity activity) {
                        }

                        @Override
                        public void onActivityPreStopped(@NonNull Activity activity) {
                            dispatch(activity, Lifecycle.Event.ON_STOP);
                        }

                        @Override
                        public void onActivityStopped(@NonNull Activity activity) {
                        }

                        @Override
                        public void onActivitySaveInstanceState(@NonNull Activity activity,
                                @NonNull Bundle bundle) {
                        }

                        @Override
                        public void onActivityPreDestroyed(@NonNull Activity activity) {
                            dispatch(activity, Lifecycle.Event.ON_DESTROY);
                        }

                        @Override
                        public void onActivityDestroyed(@NonNull Activity activity) {
                        }
                    });
        }

在activity中维护了 一个ArrayList,这个ArrayList就是记录了ActivityLifecycleCallbacks,观察者模式就是这里。

private final ArrayList mActivityLifecycleCallbacks =
            new ArrayList();

举个例子看下Activity执行onStart方法时会做什么

 protected void onStart() {
        if (DEBUG_LIFECYCLE) Slog.v(TAG, "onStart " + this);
        mCalled = true;

        mFragments.doLoaderStart();

        dispatchActivityStarted();

        if (mAutoFillResetNeeded) {
            getAutofillManager().onVisibleForAutofill();
        }
    }

   private void dispatchActivityStarted() {
        getApplication().dispatchActivityStarted(this);
        Object[] callbacks = collectActivityLifecycleCallbacks();
        if (callbacks != null) {
            for (int i = 0; i < callbacks.length; i++) {
                ((Application.ActivityLifecycleCallbacks) callbacks[i]).onActivityStarted(this);
            }
        }
    }
    private void dispatchActivityPostStarted() {
        Object[] callbacks = collectActivityLifecycleCallbacks();
        if (callbacks != null) {
            for (int i = 0; i < callbacks.length; i++) {
                ((Application.ActivityLifecycleCallbacks) callbacks[i])
                        .onActivityPostStarted(this);
            }
        }
        getApplication().dispatchActivityPostStarted(this);
    }


      private Object[] collectActivityLifecycleCallbacks() {
        Object[] callbacks = null;
        synchronized (mActivityLifecycleCallbacks) {
            if (mActivityLifecycleCallbacks.size() > 0) {
                callbacks = mActivityLifecycleCallbacks.toArray();
            }
        }
        return callbacks;
    }

可以看到,activity调用生命周期回调方法onStart的时候会去遍历mActivityLifecycleCallbacks,然后调用callback的onActivityStarted方法。这就是监听了activity的声明周期方法,现在回头看看ReportFragment里的
方法, onActivityStarted是空实现,onActivityPostStarted里面才分发了onstart生命周期事件。

                        public void onActivityStarted(@NonNull Activity activity) {
                        }
                     @Override
                        public void onActivityPostStarted(@NonNull Activity activity) {
                            dispatch(activity, Lifecycle.Event.ON_START);
                        }

这个和Activity的启动流程有关系,Activity.performResume->performRestart->performStart->dispatchActivityPostStarted();-> dispatchActivityPostStarted();这个不影响,大概意思就是通过注册了Application.ActivityLifecycleCallbacks,通过观察者模式实现监听回调

private void dispatchActivityPostStarted() {
        Object[] callbacks = collectActivityLifecycleCallbacks();
        if (callbacks != null) {
            for (int i = 0; i < callbacks.length; i++) {
                ((Application.ActivityLifecycleCallbacks) callbacks[i])
                        .onActivityPostStarted(this);
            }
        }
        getApplication().dispatchActivityPostStarted(this);
    }

接着往下看在ReportFragment中的onActivityPostCreated方法中继续分发事件,可以看到最终是调用了((LifecycleRegistry) lifecycle).handleLifecycleEvent(event);来继续分发事件的

                    @Override
                        public void onActivityPostStarted(@NonNull Activity activity) {
                            dispatch(activity, Lifecycle.Event.ON_START);
                        }

           @SuppressWarnings("deprecation")
            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);
                    }
                }
            }

回头看上面LifecycleRegistry的源码,我们可以发现lifecycleRegistry.handleLifecycleEvent执行流程是

handleLifecycleEvent()->moveToState()->sync()->
根据判断调用
backwardPass(lifecycleOwner);->observer.dispatchEvent(lifecycleOwner, event);
或者
forwardPass(lifecycleOwner);->  observer.dispatchEvent(lifecycleOwner, upEvent(observer.mState));
最终走到
 void dispatchEvent(LifecycleOwner owner, Event event) {
            State newState = getStateAfter(event);
            mState = min(mState, newState);
            mLifecycleObserver.onStateChanged(owner, event);
            mState = newState;
        }

这个 mLifecycleObserver.onStateChanged(owner, event);,就是我们 调用Livdedata.observe方法的时候, 在public void observe(@NonNull LifecycleOwner owner, @NonNull Observer observer) 的方法里,将我们写好的回调,包装成了LifecycleBoundObserver,传递给了owner.getLifecycle().addObserver方法

  LifecycleBoundObserver wrapper = new LifecycleBoundObserver(owner, observer);
         ***其他的不管***
        owner.getLifecycle().addObserver(wrapper);

LifecycleBoundObserver类是LiveData的内部类:也就是说,最终调用 mLifecycleObserver.onStateChanged(owner, event);方法,我们要在LiveData的内部类LifecycleBoundObserver中看onStateChanged的回调实现

   class LifecycleBoundObserver extends ObserverWrapper implements LifecycleEventObserver {
        @NonNull
        final LifecycleOwner mOwner;

        LifecycleBoundObserver(@NonNull LifecycleOwner owner, Observer observer) {
            super(observer);
            mOwner = owner;
        }

        @Override
        boolean shouldBeActive() {
            return mOwner.getLifecycle().getCurrentState().isAtLeast(STARTED);
        }

        @Override
        public void onStateChanged(@NonNull LifecycleOwner source,
                @NonNull Lifecycle.Event event) {
            if (mOwner.getLifecycle().getCurrentState() == DESTROYED) {
                removeObserver(mObserver);
                return;
            }
            activeStateChanged(shouldBeActive());
        }

        @Override
        boolean isAttachedTo(LifecycleOwner owner) {
            return mOwner == owner;
        }

        @Override
        void detachObserver() {
            mOwner.getLifecycle().removeObserver(this);
        }
    }

activeStateChanged(shouldBeActive());方法在LifecycleBoundObserver 的父类ObserverWrapper 中,


    private abstract class ObserverWrapper {
        final Observer mObserver;
        boolean mActive;
        int mLastVersion = START_VERSION;

        ObserverWrapper(Observer observer) {
            mObserver = observer;
        }

        abstract boolean shouldBeActive();

        boolean isAttachedTo(LifecycleOwner owner) {
            return false;
        }

        void detachObserver() {
        }

        void activeStateChanged(boolean newActive) {
            if (newActive == mActive) {
                return;
            }
            // immediately set active state, so we'd never dispatch anything to inactive
            // owner
            mActive = newActive;
            boolean wasInactive = LiveData.this.mActiveCount == 0;
            LiveData.this.mActiveCount += mActive ? 1 : -1;
            if (wasInactive && mActive) {
                onActive();
            }
            if (LiveData.this.mActiveCount == 0 && !mActive) {
                onInactive();
            }
            if (mActive) {
                dispatchingValue(this);
            }
        }
    }

最终方法执行到 dispatchingValue(this);里

 @SuppressWarnings("WeakerAccess") /* synthetic access */
    void dispatchingValue(@Nullable ObserverWrapper initiator) {
        if (mDispatchingValue) {
            mDispatchInvalidated = true;
            return;
        }
        mDispatchingValue = true;
        do {
            mDispatchInvalidated = false;
            if (initiator != null) {
                considerNotify(initiator);
                initiator = null;
            } else {
                for (Iterator, ObserverWrapper>> iterator =
                        mObservers.iteratorWithAdditions(); iterator.hasNext(); ) {
                    considerNotify(iterator.next().getValue());
                    if (mDispatchInvalidated) {
                        break;
                    }
                }
            }
        } while (mDispatchInvalidated);
        mDispatchingValue = false;
    }

这个方法最核心的地方就是调用了considerNotify(initiator)方法。

  @SuppressWarnings("unchecked")
    private void considerNotify(ObserverWrapper observer) {
        if (!observer.mActive) {
            return;
        }
        // Check latest state b4 dispatch. Maybe it changed state but we didn't get the event yet.
        //
        // we still first check observer.active to keep it as the entrance for events. So even if
        // the observer moved to an active state, if we've not received that event, we better not
        // notify for a more predictable notification order.
        if (!observer.shouldBeActive()) {
            observer.activeStateChanged(false);
            return;
        }
        if (observer.mLastVersion >= mVersion) {
            return;
        }
        observer.mLastVersion = mVersion;
        observer.mObserver.onChanged((T) mData);
    }

看到最后一句代码 observer.mObserver.onChanged((T) mData);,这个onChange回调,就是我们给LiveData对象添加回调的时候写的回调方法,

总结一下:
通过CompentActivity中的ReportFragment,注册了监听activity的生命周期回调方法,然后分发事件交给LifecycleRegistry的handleLifecycleEvent处理,经过一系列判断,执行到observer.dispatchEvent(lifecycleOwner, upEvent(observer.mState));——》走mLifecycleObserver.onStateChanged(owner, event);回调,在LiveData里有个内部类实现了这个回调接口,在我们使用livedata.observer方法的时候已经将传入的回调包装成了LifecycleBoundObserver对象,最终通过这个类的父类ObserverWrapper 的onStateChanged——>执行了dispatchingValue方法——>considerNotify方法,最终执行了传入给livedata.observer方法的回调对象的onChanged。
这就是activity生命周期,和LifecycleRegistry(Lifecycle的子类),LiveData对象如何绑定的关键代码,基本原理还是观察者模式

你可能感兴趣的:(Lifecycle,LifecycleOwner,LiveData如何监听Activity生命周期?)