美文网首页
Android Lifecycle

Android Lifecycle

作者: 东土也 | 来源:发表于2022-03-02 10:46 被阅读0次

Lifecycle是一个具有Android生命周期的组件
文章介绍一下几点
1.Fragment, Activity是怎样实现生命周期的分发的
2.Lifecycle是怎么完整的分发事件的
3.LifecycleObserver实现的几种方式

下面是Lifecycle使用的代码

/**
 * 第一种实现LifecycleObserver
 *需要用注解来实现事件的接受
 * 这种方式会通过反射或者编译时生成代码来实现事件分发,不建议使用
 */
class TestLifecycleObserver : LifecycleObserver{
    private val TAG = "TestLifecycleObserver"
    @OnLifecycleEvent(Lifecycle.Event.ON_STOP)
    fun onStart(){
        Log.e(TAG, "ON_STOP")
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_ANY)
    fun onAny(){
        Log.e(TAG, "ON_ANY")
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_CREATE)
    fun onCreate(){
        Log.e(TAG, "ON_CREATE")
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_DESTROY)
    fun onDestroy(){
        Log.e(TAG, "ON_DESTROY")
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_PAUSE)
    fun onPause(){
        Log.e(TAG, "ON_PAUSE")
    }


    @OnLifecycleEvent(Lifecycle.Event.ON_RESUME)
    fun onResume(){
        Log.e(TAG, "ON_RESUME")
    }

}

/**
 * 第二种
 * 通过实现LifecycleEventObserver来接受事件分发,需要自己解析是那种事件
 */
class TestLifecycleEventObserver : LifecycleEventObserver {
    private val TAG = "TestLifecycleEventObserver"
    @SuppressLint("LongLogTag")
    override fun onStateChanged(source: LifecycleOwner, event: Lifecycle.Event) {
        when(event){
            Lifecycle.Event.ON_RESUME->{
                Log.e(TAG, "ON_RESUME")
            }
            Lifecycle.Event.ON_PAUSE->{
                Log.e(TAG, "ON_PAUSE")
            }
            Lifecycle.Event.ON_DESTROY->{
                Log.e(TAG, "ON_DESTROY")
            }
            Lifecycle.Event.ON_ANY->{
                Log.e(TAG, "ON_ANY")
            }
            Lifecycle.Event.ON_START->{
                Log.e(TAG, "ON_START")
            }
            Lifecycle.Event.ON_CREATE->{
                Log.e(TAG, "ON_CREATE")
            }
        }
    }

}

/**
 * 第三种
 * 实现DefaultLifecycleObserver, 需要添加androidx.lifecycle:common-java8:<version>依赖
 * 这种方式事件分发比较清楚
 */
class TestFullLifecycleObserver : DefaultLifecycleObserver{
    private val TAG = "TestFullLifecycleObserver"
    @SuppressLint("LongLogTag")
    override fun onCreate(owner: LifecycleOwner) {
        Log.e(TAG, "onCreate")
    }

    @SuppressLint("LongLogTag")
    override fun onDestroy(owner: LifecycleOwner) {
        Log.e(TAG, "onDestroy")
    }

    @SuppressLint("LongLogTag")
    override fun onPause(owner: LifecycleOwner) {
        Log.e(TAG, "onPause")
    }

    @SuppressLint("LongLogTag")
    override fun onResume(owner: LifecycleOwner) {
        Log.e(TAG, "onResume")
    }

    @SuppressLint("LongLogTag")
    override fun onStart(owner: LifecycleOwner) {
        Log.e(TAG, "ON_RESUME")
    }

    @SuppressLint("LongLogTag")
    override fun onStop(owner: LifecycleOwner) {
        Log.e(TAG, "ON_RESUME")
    }
}

上面是Lifecycle观察者的三种创建方式

/**
Activity创建时的日志
E/TestLifecycleObserver: ON_CREATE
E/TestLifecycleObserver: ON_ANY
E/TestLifecycleObserver: ON_ANY
E/TestLifecycleEventObserver: ON_CREATE
E/TestLifecycleEventObserver: ON_START
E/TestLifecycleObserver: ON_RESUME
ON_ANY
E/TestLifecycleEventObserver: ON_RESUME
Activity销毁时的日志

E/TestLifecycleEventObserver: ON_PAUSE
E/TestFullLifecycleObserver: onPause
E/TestLifecycleEventObserver: ON_PAUSE
E/TestLifecycleObserver: ON_PAUSE
ON_ANY
E/TestFullLifecycleObserver: onCreate
E/TestFullLifecycleObserver: ON_RESUME
E/TestFullLifecycleObserver: ON_RESUME
ON_RESUME
E/TestLifecycleObserver: ON_STOP
E/TestLifecycleObserver: ON_ANY
E/TestFullLifecycleObserver: onDestroy
E/TestLifecycleEventObserver: ON_DESTROY
E/TestFullLifecycleObserver: onDestroy
E/TestLifecycleEventObserver: ON_DESTROY
E/TestLifecycleObserver: ON_DESTROY
ON_ANY
 */
class LifecycleActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.frament_test)
        lifecycle.addObserver(TestLifecycleObserver())
    }

    override fun onResume() {
        super.onResume()
        lifecycle.addObserver(TestLifecycleEventObserver())
    }

    override fun onPause() {
        super.onPause()
        lifecycle.addObserver(TestFullLifecycleObserver())
    }
}

上面是观察者在不同生命周期方法中被注册进去的日志
用日志我们可以发现,在不同时期注册的观察者,会完整的收到注册之前的消息
比如在onResume()中注册的TestLifecycleEventObserver他也会收到之前的create事件
在onPause()中注册的TestFullLifecycleObserver也会收到之前完整的事件消息。

Lifecycle中类的关系
LifecycleOwner生命周期宿主
LifecycleRegistry处理观察者的累,继承自Lifecycle
LifecycleObserver,LifecycleEventObserver,DefaultLifecycleObserver观察者类

1.在Fragment中是怎么将生命周期传递出来的
Fragment实现了LifecycleOwner接口,成为Lifecycle宿主,实现了


public Lifecycle getLifecycle() {
        return mLifecycleRegistry;
    }

我们所有的观察者都是注册到了mLifecycleRegistry中,在Fragment中每个生命周期都会调用

mLifecycleRegistry.handleLifecycleEvent(Lifecycle.Event.ON_CREATE);

方法来分发事件

2.AppCompatActivity继承了FragmentActivity, FragmentActivity继承了ComponentActivity类,
在ComponentActivity中onCreate方法创建了一个透明的Fragment将生命周期的分发交给了Fragment

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

3.Lifecycle是怎么分发事件的
Lifecycle中的事件Event代表Lifecycle生命周期对应的事件,这些事件会映射到Activity和Fragment中的回调事件中。

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
    }

Lifecycle中的状态State指的是Lifecycle的生命周期所处的状态

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
         * <b>right before</b> 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:
         * <ul>
         *     <li>after {@link android.app.Activity#onCreate(android.os.Bundle) onCreate} call;
         *     <li><b>right before</b> {@link android.app.Activity#onStop() onStop} call.
         * </ul>
         */
        CREATED,

        /**
         * Started state for a LifecycleOwner. For an {@link android.app.Activity}, this state
         * is reached in two cases:
         * <ul>
         *     <li>after {@link android.app.Activity#onStart() onStart} call;
         *     <li><b>right before</b> {@link android.app.Activity#onPause() onPause} call.
         * </ul>
         */
        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;
        }
    }

在LifecycleRegistry文件中我们首先来看

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

mState表示的是当前宿主的状态,如果宿主的观察者是在宿主Destory状态下注册,则观察者的状态会直接跳跃到DESTORY,如果不是则会赋予观察者INITIALIZED状态。第二步将观察者包装成ObserverWithState对象,calculateTargetState()方法会判断观察者需要前进到的目标状态,之后通过while循环不断的将观察者的状态往目标状态上追赶,通过upEvent方法分发追赶事件。

4.事件的分发
在Fragment或者Activity等宿主的在生命周期改变时会调用mLifecycleRegistry.handleLifecycleEvent(Lifecycle.Event.ON_CREATE);
方法,通知观察者

/**
     * Sets the current state and notifies the observers.
     * <p>
     * Note that if the {@code currentState} is the same state as the last call to this method,
     * calling this method has no effect.
     *
     * @param event The event that was received
     */
    public void handleLifecycleEvent(@NonNull Lifecycle.Event event) {
        State next = getStateAfter(event);
        moveToState(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()方法开始同步所有观察者

// 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<LifecycleObserver, ObserverWithState> newest = mObserverMap.newest();
            if (!mNewEventOccurred && newest != null
                    && mState.compareTo(newest.getValue().mState) > 0) {
                forwardPass(lifecycleOwner);
            }
        }
        mNewEventOccurred = false;
    }

同步方法会对比观察者和宿主的状态是否一致,不一致通过判断是需要前进还是倒退状态,在状态变化时在发送事件。backwardPass(lifecycleOwner);倒退生命周期 forwardPass(lifecycleOwner);前进生命周期.
5.Lifecycle中的包装器模式
传入Lifecycle的观察者最终会被包装成

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

Lifecycling.lifecycleEventObserver(observer)会更具传入的观察者时继承自LifecycleEventObserver,
FullLifecycleObserver还是LifecycleObserver将他们同一包装成LifecycleEventObserver

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

        final Class<?> klass = object.getClass();
        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的观察者会被反射或者编译时生成代码最终调用
注意,若接口同时实现LifecycleEventObserver, 和FullLifecycleObserver,所有方法都会被调用

相关文章

网友评论

      本文标题:Android Lifecycle

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