• 2.1.1.Architecture components_Lifecycles


    参考

    https://developer.android.com/topic/libraries/architecture/lifecycle

    https://developer.android.com/jetpack/androidx/releases/lifecycle

    配置

    需要在本目录的build.gradle里添加google maven 仓库,

    allprojects {
        repositories {
            google()
            // If you're using a version of Gradle lower than 4.1, you must instead use:
            // maven {
            //     url 'https://maven.google.com'
            // }
            // An alternative URL is 'https://dl.google.com/dl/android/maven2/'
        }
    }

    lifecycle相关的库如下:

    dependencies {
        def lifecycle_version = "2.1.0"
    
        // ViewModel and LiveData
        implementation "androidx.lifecycle:lifecycle-extensions:$lifecycle_version"
        // alternatively - just ViewModel
        implementation "androidx.lifecycle:lifecycle-viewmodel:$lifecycle_version" // For Kotlin use lifecycle-viewmodel-ktx
        // alternatively - just LiveData
        implementation "androidx.lifecycle:lifecycle-livedata:$lifecycle_version"
        // alternatively - Lifecycles only (no ViewModel or LiveData). Some UI AndroidX libraries use this lightweight import for Lifecycle
        implementation "androidx.lifecycle:lifecycle-runtime:$lifecycle_version"
    
        annotationProcessor "androidx.lifecycle:lifecycle-compiler:$lifecycle_version" // For Kotlin use kapt instead of annotationProcessor
        // alternately - if using Java8, use the following instead of lifecycle-compiler
    使用Lifecycle-common-Java8库提供的Lifecycle Java8 API,而不是使用Lifecycle annotations,以获得更快的增量构建
        implementation "androidx.lifecycle:lifecycle-common-java8:$lifecycle_version"
    
        // optional - ReactiveStreams support for LiveData
        implementation "androidx.lifecycle:lifecycle-reactivestreams:$lifecycle_version" // For Kotlin use lifecycle-reactivestreams-ktx
    
        // optional - Test helpers for LiveData
        testImplementation "androidx.arch.core:core-testing:$lifecycle_version"
    }

    Lifecycle的Event和state

    Lifecycle是用两个枚举来管理生命周期组件的状态,一个是Event,一个是State,如下图:

    wps59

    所以操作ui需要是isAtLeast(STARTED)

    几个相关类

    Lifecycle

    Lifecycle类

    Lifecycle是一个抽象类,他的实现类为LifecycleRegistry。

        @MainThread
        public abstract void addObserver(@NonNull LifecycleObserver observer);
    
        @MainThread
        public abstract void removeObserver(@NonNull LifecycleObserver observer);
        
        @MainThread
        @NonNull
    public abstract State getCurrentState();

    LifecycleRegistry.addObserver

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

    可以看出是可以用同一个LifecycleObserver 重复调用的,mObserverMap.putIfAbsent表示如果没有添加过则添加,否则返回之前添加的value(并不会更新),里边会进行检查如果之前已经添加过了就直接return。

    Lifecycle.State

    public enum State {
        /**
    LifecycleOwner的Destroyed 状态。 此事件之后,此生命周期将不再分派任何事件。 
    例如,对于android.app.Activity,此状态在Activity的onDestroy调用之前就已经达到。
         */
        DESTROYED,
    
        /**
         * Initialized state for a LifecycleOwner. 
         * For an {@link android.app.Activity}, this is the state when it is constructed but has not received
         * Activity#onCreate yet.
         */
        INITIALIZED,
    
        /**
         * Created state for a LifecycleOwner. 
         * For an {@link android.app.Activity}, this state is reached in two cases:
         * <ul>
         *     <li>after Activity#onCreate call;
         *     <li>right before Activity#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 Activity#onStart() call;
         *     <li>right before Activity#onPause() call.
         * </ul>
         */
        STARTED,
    
        /**
         * Resumed state for a LifecycleOwner. 
         * For an {@link android.app.Activity}, this state is reached after Activity#onResume() is called.
         */
        RESUMED;
    
        /**
         * Compares if this State is greater or equal to the given {@code state}.
         * 这个方法表示State要大于等于当前的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;
        }
    }

    Lifecycle.Event

    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
    }

    其中ON_ANY事件是不管什么事件发生都会被调用。

    LifecycleRegistry

    他是Lifecycle的实现类,除了lifecycle接口定义的方法外还有几个public方法:

    l setCurrentState

    /**
     * Moves the Lifecycle to the given state and dispatches necessary events to the observers.
     *
     * @param state new state
     */
    @MainThread
    public void setCurrentState(@NonNull State state) {
        moveToState(state);
    }

    l handleLifecycleEvent

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

    l moveToState

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

    l getStateAfter

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

    LifecycleObserver

    public interface LifecycleObserver {
    }

    是一个空接口

    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());
    • 为了实现监听生命周期事件,那么可以implement lifecycleObserver,
    • 同时在相关方法上,要加上@OnLifecycleEvent(Lifecycle.Event.xxx),来表示什么时机要执行的方法,
    • 被@OnLifecycleEvent修饰的方法 不能有参数,不能是private的

    OnLifecycleEvent注解

    @Retention(RetentionPolicy.RUNTIME)
    @Target(ElementType.METHOD)
    public @interface OnLifecycleEvent {
        Lifecycle.Event value();
    }

    继承LifecycleObserver 的接口

    LifecycleObserver 单独使用的话,就必须要和OnLifecycleEvent注解一起用,如果不想用注解,那么可以用它的几个Lifecycle库支持的继承接口。

    LifecycleEventObserver

    public interface LifecycleEventObserver extends LifecycleObserver {
        /**
         * Called when a state transition event happens.
         *
         * @param source The source of the event
         * @param event The event
         */
        void onStateChanged(@NonNull LifecycleOwner source, @NonNull Lifecycle.Event event);
    }
    • 该类可以接收任何生命周期更改并将其分发给接收者。
    • 如果一个类同时实现了这个接口和DefaultLifecycleObserver,那么首先调用DefaultLifecycleObserver的方法,然后再调用LifecycleEventObserver.onStateChanged(LifecycleOwner, Lifecycle.Event)。
    • 如果一个类实现了这个接口,同时使用了OnLifecycleEvent注解,那么注解将被忽略。

    FullLifecycleObserver

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

    DefaultLifecycleObserver

    需要导入

    implementation "androidx.lifecycle:lifecycle-common-java8:$lifecycle_version"
    public interface DefaultLifecycleObserver extends FullLifecycleObserver {
    
        @Override
        default void onCreate(@NonNull LifecycleOwner owner) {
        }
    
        @Override
        default void onStart(@NonNull LifecycleOwner owner) {
        }
    
        @Override
        default void onResume(@NonNull LifecycleOwner owner) {
        }
    
        @Override
        default void onPause(@NonNull LifecycleOwner owner) {
        }
    
        @Override
        default void onStop(@NonNull LifecycleOwner owner) {
        }
    
        @Override
        default void onDestroy(@NonNull LifecycleOwner owner) {
        }
    }

    用于监听LifecycleOwner状态更改的回调接口。

    • l 如果您使用Java 8语言,请始终优先选择它而不是annotations。
    • l 如果一个类同时实现了这个接口和LifecycleEventObserver,那么首先调用DefaultLifecycleObserver的方法,然后再调用LifecycleEventObserver.onstatechange (LifecycleOwner Lifecycle.Event)。
    • l 如果一个类实现了这个接口,同时使用了OnLifecycleEvent注解,那么注解将被忽略。

    LifecycleOwner

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

    实现这个的类,生命周期的所有者,需要创建一个Lifecycle实例,通过这个来通知观察者状态改变。

    • l 如果要尝试管理整个应用程序流程的生命周期,请参阅ProcessLifecycleOwner。
    • l 在support库26.1.0及之后的Fragment和AppCompatActivity都已经实现了LifecycleOwner接口了,所以就可以直接在里边获取Lifecycle添加观察者。

    实现自定义的LifecycleOwner

    如果您有想要创建LifecycleOwner的自定义类,则可以使用LifecycleRegistry类,但是您需要将事件转发到该类中,如以下代码示例所示:

    public class MyActivity extends Activity implements LifecycleOwner {
        private LifecycleRegistry lifecycleRegistry;
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
    
            lifecycleRegistry = new LifecycleRegistry(this);
            lifecycleRegistry.setCurrentState(Lifecycle.State.CREATED);
        }
    
        @Override
        public void onStart() {
            super.onStart();
            lifecycleRegistry.setCurrentState(Lifecycle.State.STARTED);
        }
    
        @NonNull
        @Override
        public Lifecycle getLifecycle() {
            return lifecycleRegistry;
        }
    }

    处理onStop事件

    当Lifecycle 属于AppCompatActivity或Fragment时,在调用AppCompatActivity或Fragment的onSaveInstanceState()时,Lifecycle's 的状态更改为CREATED,并且调度ON_STOP事件。

    AppCompatActivity继承自FragmentActivity,FragmentActivity继承自ComponentActivity,

    在ComponentActivity.onSaveInstanceState中

    @CallSuper
    @Override
    protected void onSaveInstanceState(@NonNull Bundle outState) {
        Lifecycle lifecycle = getLifecycle();
        if (lifecycle instanceof LifecycleRegistry) {
            ((LifecycleRegistry) lifecycle).setCurrentState(Lifecycle.State.CREATED);
        }
        super.onSaveInstanceState(outState);
        mSavedStateRegistryController.performSave(outState);
    }

    对于fragment,在FragmentActivity

    @Override
    protected void onSaveInstanceState(@NonNull Bundle outState) {
        super.onSaveInstanceState(outState);
    // 会把此activity的所有fragment都标记为Lifecycle.State.CREATED
        markFragmentsCreated();
        mFragmentLifecycleRegistry.handleLifecycleEvent(Lifecycle.Event.ON_STOP);
    
    // 会调用fragment的onSaveInstanceState
        Parcelable p = mFragments.saveAllState();
        ...
    }
    
    private void markFragmentsCreated() {
        boolean reiterate;
        do {
            reiterate = markState(getSupportFragmentManager(), Lifecycle.State.CREATED);
        } while (reiterate);
    }
    
    private static boolean markState(FragmentManager manager, Lifecycle.State state) {
        boolean hadNotMarked = false;
        Collection<Fragment> fragments = manager.getFragments();
        for (Fragment fragment : fragments) {
            if (fragment == null) {
                continue;
            }
            if (fragment.getLifecycle().getCurrentState().isAtLeast(Lifecycle.State.STARTED)) {
                fragment.mLifecycleRegistry.setCurrentState(state);
                hadNotMarked = true;
            }
    
            if (fragment.getHost() != null) {
                FragmentManager childFragmentManager = fragment.getChildFragmentManager();
                hadNotMarked |= markState(childFragmentManager, state);
            }
        }
        return hadNotMarked;
    }

    activity的lifecycle

    activity的lifecycle的event是由lifecycle库中的ReportFragment来dispatch的,

    ReportFragment是在ComponentActivity的onCreate中加入的:

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

    在ReportFragment的各生命周期方法中会dispatch lifecycle event:

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        dispatchCreate(mProcessListener);
        dispatch(Lifecycle.Event.ON_CREATE);
    }
    
    @Override
    public void onStart() {
        super.onStart();
        dispatchStart(mProcessListener);
        dispatch(Lifecycle.Event.ON_START);
    }
    
    @Override
    public void onResume() {
        super.onResume();
        dispatchResume(mProcessListener);
        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);
        // just want to be sure that we won't leak reference to an activity
        mProcessListener = null;
    }
    
    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);
            }
        }
    }

    fragment的lifecycle

    fragment是有两套lifecycle。

    fragment的lifecycle

    是用来管理从onCreate-》onDestory的。

    可以通过fragment.getLifecycle()获得。

    它的Lifecycle的生命周期event调用顺序:

    • l onCreate 在fragment.onCreate 之后
    • l onStart 在fragment.onStart之后,先于view的lifecycle
    • l onResume 在fragment.onResume 之后,先于view的lifecycle
    • l onPause 在fragment.onPause 之前,后于view的lifecycle
    • l onStop 在fragment.onStop 之前,后于view的lifecycle
    • l onDestroy 在fragment.onDestroy 之前

    所以想要观察此lifecycle范围的 生命周期的对象(比如LiveData)时,可以在fragment.onCreate 中创建观察。

    view的lifecycle

    是用来管理从onCreateView-》onDestoryView的。

    fragment.getViewLifecycleOwner()获得LifecycleOwner,然后通过LifecycleOwner.getLifecycle()获取Lifecycle。

    它的Lifecycle的生命周期event调用顺序:

    • l onCreate 在fragment.onViewStateRestored之后,而fragment.onViewStateRestored是在fragment.onActivityCreated之后。
    • l onStart 在fragment.onStart之后,后于fragment的lifecycle
    • l onResume 在fragment.onResume 之后,后于fragment的lifecycle
    • l onPause 在fragment.onPause 之前,先于fragment的lifecycle
    • l onStop 在fragment.onStop 之前,先于fragment的lifecycle
    • l onDestroy 在fragment.onDestroyView之前

    所以想要观察此lifecycle范围的 生命周期的对象(比如LiveData)时,可以在fragment.onCreateView、onViewCreated 、onActivityCreated中创建观察。

    问题

    lifecycle.addObserver(this)后是否会立即回调observer

    会的,

    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);
    
        // 如果之前加入过就直接return
        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--;
    }

    在其中的wihle循环逻辑,表示一直正向dispatch到当前state状态为止,比如当前state时Resumed,那么就会回调observer的onCreate、onStart、onResume,

    所以当我们调用addObserver后会立马接收到回调。

    ObserverWithState.dispatchEvent

    void dispatchEvent(LifecycleOwner owner, Event event) {
        State newState = getStateAfter(event);
        mState = min(mState, newState);
        mLifecycleObserver.onStateChanged(owner, event);
        mState = newState;
    }

    LifecycleRegistry中有两个转换state为event的方法,需要结合状态图更好理解

    wps60

    downEvent表示反过程,即销毁过程

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

    upEvent表示正过程,即创建过程

    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);
    }
  • 相关阅读:
    HTML5之Canvas绘图——使用Canvas绘制图形的基本教程
    搭建EF6.0+MVC4搭建框架——之路由配置
    搭建EF6.0+MVC4搭建框架遇到的问题及解决方案
    Sql2008 全文索引应用(错误7625)
    Excel 导入并导出结果集
    SqlParameter设定的value值为0时、调用的存储过程获取到的值却为null解决方法
    JavaScript中知而不全的this (转)
    JavaScript 类定义常用方法(转)
    NPOI大数据量多个sheet导出源码(原)
    网页右下角固定图片(不随滚动条滑动,始终在固定位置)
  • 原文地址:https://www.cnblogs.com/muouren/p/12368153.html
Copyright © 2020-2023  润新知