Jetpack之Lifecycle应用与源码分析

news2025/1/10 3:30:12

Build lifecycle-aware components that can adjust behavior based on the current lifecycle state of an activity or fragment.

上面是源于官网的定义,简单翻译就是说Lifecycle的作用就是基于当前的Activity或者Fragment的生命周期当前状态构建可感知生命周期的组件。

Lifecycle组件涉及一个类和两个接口,一个类是Lifecycle,两个接口分别是LifecycleObserverLifecycleOwner

一、Lifecycle

在这里插入图片描述

1.1、源码

public abstract class Lifecycle {
    @RestrictTo(RestrictTo.Scope.LIBRARY_GROUP)
    @NonNull
    AtomicReference<Object> 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 {
        /**
         * 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;

        /**
         * Returns the {@link Lifecycle.Event} that will be reported by a {@link Lifecycle}
         * leaving the specified {@link Lifecycle.State} to a lower state, or {@code null}
         * if there is no valid event that can move down from the given state.
         *
         * @param state the higher state that the returned event will transition down from
         * @return the event moving down the lifecycle phases from state
         */
        @Nullable
        //从当前状态降级的事件
        public static Event downFrom(@NonNull State state) {
            switch (state) {
                //从CREATED降级的是ON_DESTROY事件
                case CREATED:
                    return ON_DESTROY;
               //从STARTED降级的是ON_STOP事件
                case STARTED:
                    return ON_STOP;
                //从RESUMED降级的是ON_PAUSE事件
                case RESUMED:
                    return ON_PAUSE;
                default:
                    return null;
            }
        }

        /**
         * Returns the {@link Lifecycle.Event} that will be reported by a {@link Lifecycle}
         * entering the specified {@link Lifecycle.State} from a higher state, or {@code null}
         * if there is no valid event that can move down to the given state.
         *
         * @param state the lower state that the returned event will transition down to
         * @return the event moving down the lifecycle phases to state
         */
        @Nullable
        //降级到当前状态的事件
        public static Event downTo(@NonNull State state) {
            switch (state) {
                //降级到DESTROYED状态的是ON_DESTROY事件
                case DESTROYED:
                    return ON_DESTROY;
                //降级到CREATED状态的是ON_STOP事件
                case CREATED:
                    return ON_STOP;
                //降级到STARTED状态的是ON_PAUSE事件
                case STARTED:
                    return ON_PAUSE;
                default:
                    return null;
            }
        }

        /**
         * Returns the {@link Lifecycle.Event} that will be reported by a {@link Lifecycle}
         * leaving the specified {@link Lifecycle.State} to a higher state, or {@code null}
         * if there is no valid event that can move up from the given state.
         *
         * @param state the lower state that the returned event will transition up from
         * @return the event moving up the lifecycle phases from state
         */
        @Nullable
        //从该状态升级的事件
        public static Event upFrom(@NonNull State state) {
            switch (state) {
               //从INITIALIZED状态升级的事件为ON_CREATE
                case INITIALIZED:
                    return ON_CREATE;
                //从CREATED状态升级的事件为ON_START
                case CREATED:
                    return ON_START;
                //从STARTED状态升级的事件为ON_RESUME
                case STARTED:
                    return ON_RESUME;
                default:
                    return null;
            }
        }

        /**
         * Returns the {@link Lifecycle.Event} that will be reported by a {@link Lifecycle}
         * entering the specified {@link Lifecycle.State} from a lower state, or {@code null}
         * if there is no valid event that can move up to the given state.
         *
         * @param state the higher state that the returned event will transition up to
         * @return the event moving up the lifecycle phases to state
         */
        @Nullable
        //升级到该状态的事件
        public static Event upTo(@NonNull State state) {
            switch (state) {
               //升级到CREATED状态是ON_CREATE事件
                case CREATED:
                    return ON_CREATE;
                //升级到STARTED状态是ON_START事件
                case STARTED:
                    return ON_START;
                //升级到RESUMED状态是ON_RESUME事件
                case RESUMED:
                    return ON_RESUME;
                default:
                    return null;
            }
        }

        /**
         * Returns the new {@link Lifecycle.State} of a {@link Lifecycle} that just reported
         * this {@link Lifecycle.Event}.
         *
         * Throws {@link IllegalArgumentException} if called on {@link #ON_ANY}, as it is a special
         * value used by {@link OnLifecycleEvent} and not a real lifecycle event.
         *
         * @return the state that will result from this event
         */
        @NonNull
        public State getTargetState() {
            switch (this) {
                case ON_CREATE:
                case ON_STOP:
                    return State.CREATED;
                case ON_START:
                case ON_PAUSE:
                    return State.STARTED;
                case ON_RESUME:
                    return State.RESUMED;
                case ON_DESTROY:
                    return State.DESTROYED;
                case ON_ANY:
                    break;
            }
            throw new IllegalArgumentException(this + " has no target state");
        }
    }

    /**
     * Lifecycle states. You can consider the states as the nodes in a graph and
     * {@link Event}s as the edges between these nodes.
     */
    @SuppressWarnings("WeakerAccess")
    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;
        }
    }
}

从源码可以得知Lifecycle定义了三个方法和两个枚举:
三个方法:
1、addObserver 用于添加观察者
2、removeObserver 用于移除观察者
3、获取当前的状态
两个枚举:
1、Event 事件
2、State 状态

宿主的生命周期和状态转换的模型图如下:
在这里插入图片描述

1.2、直接子类LifecycleRegistry

1.2.1 源码

package androidx.lifecycle;

import static androidx.lifecycle.Lifecycle.State.DESTROYED;
import static androidx.lifecycle.Lifecycle.State.INITIALIZED;

import android.annotation.SuppressLint;

import androidx.annotation.MainThread;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.annotation.VisibleForTesting;
import androidx.arch.core.executor.ArchTaskExecutor;
import androidx.arch.core.internal.FastSafeIterableMap;

import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.Map;

public class LifecycleRegistry extends Lifecycle {
    private FastSafeIterableMap<LifecycleObserver, ObserverWithState> mObserverMap =
            new FastSafeIterableMap<>();
    private State mState;
    //弱引用宿主对象
    private final WeakReference<LifecycleOwner> mLifecycleOwner;

    private int mAddingObserverCounter = 0;

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

   
    private ArrayList<State> mParentStates = new ArrayList<>();
    private final boolean mEnforceMainThread;

    public LifecycleRegistry(@NonNull LifecycleOwner provider) {
        this(provider, true);
    }

    private LifecycleRegistry(@NonNull LifecycleOwner provider, boolean enforceMainThread) {
        mLifecycleOwner = new WeakReference<>(provider);
        mState = INITIALIZED;
        mEnforceMainThread = enforceMainThread;
    }

    
    @Deprecated
    @MainThread
    public void markState(@NonNull State state) {
        enforceMainThreadIfNeeded("markState");
        setCurrentState(state);
    }
    //设置当前状态
    @MainThread
    public void setCurrentState(@NonNull State state) {
        enforceMainThreadIfNeeded("setCurrentState");
        moveToState(state);
    }
    //处理生命周期事件
    public void handleLifecycleEvent(@NonNull Lifecycle.Event event) {
        enforceMainThreadIfNeeded("handleLifecycleEvent");
        moveToState(event.getTargetState());
    }
    //状态转移
    private void moveToState(State next) {
        if (mState == next) {
            return;
        }
        if (mState == INITIALIZED && next == DESTROYED) {
            throw new IllegalStateException("no event down from " + mState);
        }
        mState = next;
        if (mHandlingEvent || mAddingObserverCounter != 0) {
            mNewEventOccurred = true;
            // we will figure out what to do on upper level.
            return;
        }
        mHandlingEvent = true;
        sync();
        mHandlingEvent = false;
        if (mState == DESTROYED) {
            mObserverMap = new FastSafeIterableMap<>();
        }
    }
    //是否同步
    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) {
        Map.Entry<LifecycleObserver, ObserverWithState> 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) {
        enforceMainThreadIfNeeded("addObserver");
        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);
            final Event event = Event.upFrom(statefulObserver.mState);
            if (event == null) {
                throw new IllegalStateException("no event up from " + statefulObserver.mState);
            }
            statefulObserver.dispatchEvent(lifecycleOwner, event);
            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) {
        enforceMainThreadIfNeeded("removeObserver");
        mObserverMap.remove(observer);
    }
    //获取观察者数量
    @SuppressWarnings("WeakerAccess")
    public int getObserverCount() {
        enforceMainThreadIfNeeded("getObserverCount");
        return mObserverMap.size();
    }
    //获取当前状态
    @NonNull
    @Override
    public State getCurrentState() {
        return mState;
    }
    //升级状态
    private void forwardPass(LifecycleOwner lifecycleOwner) {
        Iterator<Map.Entry<LifecycleObserver, ObserverWithState>> ascendingIterator =
                mObserverMap.iteratorWithAdditions();
        while (ascendingIterator.hasNext() && !mNewEventOccurred) {
            Map.Entry<LifecycleObserver, ObserverWithState> entry = ascendingIterator.next();
            ObserverWithState observer = entry.getValue();
            while ((observer.mState.compareTo(mState) < 0 && !mNewEventOccurred
                    && mObserverMap.contains(entry.getKey()))) {
                pushParentState(observer.mState);
                final Event event = Event.upFrom(observer.mState);
                if (event == null) {
                    throw new IllegalStateException("no event up from " + observer.mState);
                }
                observer.dispatchEvent(lifecycleOwner, event);
                popParentState();
            }
        }
    }
    //降级状态
    private void backwardPass(LifecycleOwner lifecycleOwner) {
        Iterator<Map.Entry<LifecycleObserver, ObserverWithState>> descendingIterator =
                mObserverMap.descendingIterator();
        while (descendingIterator.hasNext() && !mNewEventOccurred) {
            Map.Entry<LifecycleObserver, ObserverWithState> entry = descendingIterator.next();
            ObserverWithState observer = entry.getValue();
            while ((observer.mState.compareTo(mState) > 0 && !mNewEventOccurred
                    && mObserverMap.contains(entry.getKey()))) {
                Event event = Event.downFrom(observer.mState);
                if (event == null) {
                    throw new IllegalStateException("no event down from " + observer.mState);
                }
                pushParentState(event.getTargetState());
                observer.dispatchEvent(lifecycleOwner, event);
                popParentState();
            }
        }
    }
    //同步状态
    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);
            }
            Map.Entry<LifecycleObserver, ObserverWithState> newest = mObserverMap.newest();
            if (!mNewEventOccurred && newest != null
                    && mState.compareTo(newest.getValue().mState) > 0) {
                forwardPass(lifecycleOwner);
            }
        }
        mNewEventOccurred = false;
    }

    @SuppressLint("RestrictedApi")
    private void enforceMainThreadIfNeeded(String methodName) {
        if (mEnforceMainThread) {
            if (!ArchTaskExecutor.getInstance().isMainThread()) {
                throw new IllegalStateException("Method " + methodName + " must be called on the "
                        + "main thread");
            }
        }
    }
    @VisibleForTesting
    @NonNull
    public static LifecycleRegistry createUnsafe(@NonNull LifecycleOwner owner) {
        return new LifecycleRegistry(owner, 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 = event.getTargetState();
            mState = min(mState, newState);
            mLifecycleObserver.onStateChanged(owner, event);
            mState = newState;
        }
    }
}

该类实现了对观察者的增加和删除、状态的同步以及状态改变后对观察者的状态变化通知。

二、LifecycleObserver(生命周期观察者)

在这里插入图片描述

2.1、LifecycleObserver

package androidx.lifecycle;

/**
 * Marks a class as a LifecycleObserver. Don't use this interface directly. Instead implement either
 * {@link DefaultLifecycleObserver} or {@link LifecycleEventObserver} to be notified about
 * lifecycle events.
 *
 * @see Lifecycle Lifecycle - for samples and usage patterns.
 */
@SuppressWarnings("WeakerAccess")
public interface LifecycleObserver {

}

2.2、FullLifecycleObserver

package androidx.lifecycle;

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

FullLifecycleObserver定义了所有生命周期的事件,如果我们实现了该接口,就要重写所有的事件方法

2.3、DefaultLifecycleObserver

package androidx.lifecycle;

import androidx.annotation.NonNull;


@SuppressWarnings("unused")
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) {
    }
}

FullLifecycleObserver定义了生命周期的所有事件方法,为了不用重写所有的方法,就新增了DefaultLifecycleObserver接口,该接口继承了FullLifecycleObserver,并且重写了所有的事件函数,这样我们在自定义LifecycleObserver的时候可以直接实现DefaultLifecycleObserver重写需要用到的事件函数即可

2.4、LifecycleEventObserver

package androidx.lifecycle;

import androidx.annotation.NonNull;

public interface LifecycleEventObserver extends LifecycleObserver {
    void onStateChanged(@NonNull LifecycleOwner source, @NonNull Lifecycle.Event event);
}

如果一个自定义观察者既实现了LifecycleEventObserver接口,也实现了DefaultLifecycleObserver接口,当宿主的生命周期有变化的时候,会优先调用DefaultLifecycleObserver的方法,然后再调用LifecycleEventObserver的onStateChanged方法

2.4.1 示例

package com.anniljing.lifecyclecorestudy;

import android.util.Log;

import androidx.annotation.NonNull;
import androidx.lifecycle.DefaultLifecycleObserver;
import androidx.lifecycle.Lifecycle;
import androidx.lifecycle.LifecycleEventObserver;
import androidx.lifecycle.LifecycleOwner;

public class MyObserver implements DefaultLifecycleObserver, LifecycleEventObserver {
    private static final String TAG="MyObserver";

    @Override
    public void onCreate(@NonNull LifecycleOwner owner) {
        Log.e(TAG,"DefaultLifecycleObserver onCreate");
    }

    @Override
    public void onStart(@NonNull LifecycleOwner owner) {
        Log.e(TAG,"DefaultLifecycleObserver onStart");
    }

    @Override
    public void onResume(@NonNull LifecycleOwner owner) {
        Log.e(TAG,"DefaultLifecycleObserver onResume");
    }

    @Override
    public void onStop(@NonNull LifecycleOwner owner) {
        Log.e(TAG,"DefaultLifecycleObserver onStop");
    }

    @Override
    public void onStateChanged(@NonNull LifecycleOwner source, @NonNull Lifecycle.Event event) {
        Log.e(TAG,"LifecycleEventObserver onStateChanged:"+event.name());
    }
}

在这里插入图片描述

三、LifecycleOwner(生命周期宿主)

3.1、源码

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

为宿主返回一个Lifecycle。

四、Fragment实现

在这里插入图片描述

  • 在Fragment的构造方法里面,创建了LifecycleRegistry
  • 在performCreate里面首先注册了一个LifecycleEventObserver观察者,重写了onStateChanged方法,用来接收Fragment的生命周期的状态,这样就完成了观察者的注册
  • 在performCreate里面调用onCreate方法
  • 后续就是Fragment生命周期变化时,通知LifecycleObserver的过程:Fragment的performXXX()、onXXX()方法;LifecycleRegistry的handleLifecycleEvent()方法;LifecycleObserver的onStateChanged()方法
  • LifecycleRegistry里面通过调用sync方法,通过比较大小的方式,来判断是状态升级,还是状态降级,来调整后面的状态
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;
            //如果下一个状态小于最早的,则说明要降级
            if (mState.compareTo(mObserverMap.eldest().getValue().mState) < 0) {
                backwardPass(lifecycleOwner);
            }
            Map.Entry<LifecycleObserver, ObserverWithState> newest = mObserverMap.newest();
            //如果下一个状态的值大于最新的,则说明需要升级
            if (!mNewEventOccurred && newest != null
                    && mState.compareTo(newest.getValue().mState) > 0) {
                forwardPass(lifecycleOwner);
            }
        }
        mNewEventOccurred = false;
    }

五、Activity的实现

onCreate()

protected void onCreate(@Nullable Bundle savedInstanceState) {
        // Restore the Saved State first so that it is available to
        // OnContextAvailableListener instances
        mSavedStateRegistryController.performRestore(savedInstanceState);
        mContextAwareHelper.dispatchOnContextAvailable(this);
        super.onCreate(savedInstanceState);
        ReportFragment.injectIfNeededIn(this);
        if (BuildCompat.isAtLeastT()) {
            mOnBackPressedDispatcher.setOnBackInvokedDispatcher(
                    Api33Impl.getOnBackInvokedDispatcher(this)
            );
        }
        if (mContentLayoutId != 0) {
            setContentView(mContentLayoutId);
        }
    }

ReportFragment.injectIfNeededIn()

public static void injectIfNeededIn(Activity activity) {
        if (Build.VERSION.SDK_INT >= 29) {
            // On API 29+, we can register for the correct Lifecycle callbacks directly
            LifecycleCallbacks.registerIn(activity);
        }
        // Prior to API 29 and to maintain compatibility with older versions of
        // ProcessLifecycleOwner (which may not be updated when lifecycle-runtime is updated and
        // need to support activities that don't extend from FragmentActivity from support lib),
        // use a framework fragment to get the correct timing of Lifecycle events
        android.app.FragmentManager manager = activity.getFragmentManager();
        if (manager.findFragmentByTag(REPORT_FRAGMENT_TAG) == null) {
            manager.beginTransaction().add(new ReportFragment(), REPORT_FRAGMENT_TAG).commit();
            // Hopefully, we are the first to make a transaction.
            manager.executePendingTransactions();
        }
    }

Activity源码中,把宿主的生命周期的感知放到了ReportFragment里面,Fragment是依附在activity的,能够同步到Activity的生命周期的事件。

六、示例

6.1、MyObserver

package com.anniljing.lifecyclecorestudy;

import android.util.Log;

import androidx.annotation.NonNull;
import androidx.lifecycle.DefaultLifecycleObserver;
import androidx.lifecycle.Lifecycle;
import androidx.lifecycle.LifecycleEventObserver;
import androidx.lifecycle.LifecycleOwner;

public class MyObserver implements DefaultLifecycleObserver, LifecycleEventObserver {
    private static final String TAG="MyObserver";

    @Override
    public void onCreate(@NonNull LifecycleOwner owner) {
        Log.e(TAG,"DefaultLifecycleObserver onCreate");
    }

    @Override
    public void onStart(@NonNull LifecycleOwner owner) {
        Log.e(TAG,"DefaultLifecycleObserver onStart");
    }

    @Override
    public void onResume(@NonNull LifecycleOwner owner) {
        Log.e(TAG,"DefaultLifecycleObserver onResume");
    }

    @Override
    public void onStop(@NonNull LifecycleOwner owner) {
        Log.e(TAG,"DefaultLifecycleObserver onStop");
    }

    @Override
    public void onStateChanged(@NonNull LifecycleOwner source, @NonNull Lifecycle.Event event) {
        Log.e(TAG,"LifecycleEventObserver onStateChanged:"+event.name());

    }
}

6.2、LifecycleMainActivity

package com.anniljing.lifecyclecorestudy;

import android.os.Bundle;

import androidx.appcompat.app.AppCompatActivity;

public class LifecycleMainActivity extends AppCompatActivity {
    private MyObserver mObserver;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mObserver = new MyObserver();
        getLifecycle().addObserver(mObserver);
    }
}

在这里插入图片描述
自定义的MyObserver 实现了DefaultLifecycleObserver,同时也实现了LifecycleEventObserver,从打印结果验证了如果既实现了DefaultLifecycleObserver,也实现了LifecycleEventObserver,会优先调用DefaultLifecycleObserver的事件回调,后面才调用LifecycleEventObserver的onStateChanged

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/333168.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

CHAPTER 3 Jenkins SVN GItlab

Jenkins SVN GItlab3.1 JenkinsSVN3.1.1 搭建SVN服务器1. 安装svn server2. 查看svn安装位置3. 创建版本库目录4. 创建svn版本库5. 配置修改6. 防火墙开启3690端口7. 启动SVN-server8. 客户端访问svn服务器3.1.2 测试脚本提交3.1.3 jenkins下载代码配置1. 安装Subversion插件2.…

mac:彻底解决-安装应用后提示:无法打开“XXX”,因为无法验证开发者的问题;无法验证此App不包含恶意软件

mac从浏览器或其他电脑接收了应用&#xff0c;但是打开报错 目录报错解决办法一次性方法永久解决方法验证恢复应用验证报错 截图如下&#xff1a; 错误信息 无法打开“XXX”&#xff0c;因为无法验证开发者的问题&#xff1b;无法验证此App不包含恶意软件 解决办法 一次性方…

微信小程序 java 校园快递代取配送系统 uniapp mysql

园快递代取系统&#xff0c;用户和配送员室基于微信小程序端&#xff0c;管理员是基于后台网页端&#xff0c;本系统是基于java编程语言&#xff0c;mysql数据库&#xff0c;idea开发工具&#xff0c;ssm框架开发&#xff0c;本系统分为用户&#xff0c;管理员和配送员三个角色…

易基因|猪肠道组织的表观基因组功能注释增强对复杂性状和人类疾病的生物学解释:Nature子刊

大家好&#xff0c;这里是专注表观组学十余年&#xff0c;领跑多组学科研服务的易基因。2021年10月6日&#xff0c;《Nat Commun》杂志发表了题为“Pig genome functional annotation enhances the biological interpretation of complex traits and human disease”的研究论文…

爽文,Redis分布式锁的实现和原理

为什么需要分布式锁我们知道&#xff0c;当多个线程并发操作某个对象时&#xff0c;可以通过synchronized来保证同一时刻只能有一个线程获取到对象锁进而处理synchronized关键字修饰的代码块或方法。既然已经有了synchronized锁&#xff0c;为什么这里又要引入分布式锁呢&#…

2023数字中国创新大赛·数据开发赛道首批赛题启动报名

由数字中国建设峰会组委会主办的2023数字中国创新大赛&#xff08;DCIC 2023&#xff09;已正式启幕&#xff0c;本届大赛结合当下数字技术发展的热点和业界关注的焦点&#xff0c;面向产业实际需求设置了九大赛道。其中&#xff0c;数据开发赛道2月8日正式上线首批赛题&#x…

跨域小样本系列2:常用数据集与任务设定详解

来源&#xff1a;投稿 作者&#xff1a;橡皮 编辑&#xff1a;学姐 带你学习跨域小样本系列1-简介篇 跨域小样本系列2-常用数据集与任务设定详解&#xff08;本篇&#xff09; 跨域小样本系列3&#xff1a;元学习方法解决CDFSL以及两篇SOTA论文讲解 跨域小样本系列4&#xf…

Unity 如何实现游戏Avatar角色头部跟随视角转动

文章目录功能简介实现步骤获取看向的位置获取头部的位置修改头部的朝向限制旋转角度超出限制范围时自动回正如何让指定动画不受影响功能简介 如图所示&#xff0c;当相机的视角转动时&#xff0c;Avatar角色的头部会同步转动&#xff0c;看向视角的方向。 实现步骤 获取看向的…

企业数字化转型的产品设计思路

数字化转型的核心是全面重塑企业的管理模式和经营模式&#xff0c;是迈向数字经济时代的方式。一、到底什么是数字化转型&#xff1f;数字化转型并不神秘。数字化转型是一种经营方式、一种经营理念&#xff0c;是将企业相关的人、物料、设备、资金等要素进行系统运转&#xff0…

命令模式包含哪些主要角色?怎样实现命令?

命令模式包含以下主要角色&#xff1a;抽象命令类&#xff08;Command&#xff09;角色&#xff1a; 定义命令的接口&#xff0c;声明执行的方法。具体命令&#xff08;Concrete Command&#xff09;角色&#xff1a;具体的命令&#xff0c;实现命令接口&#xff1b;通常会持有…

flex 布局相关属性的使用

简单概述 为元素添加 display:flex; 的属性后&#xff0c;当前元素被视为弹性布局的盒子容器(box)&#xff0c;其子元素被视为弹性布局项目(item)。item 会在 box 内灵活布局&#xff0c;解决了对齐、分布、尺寸等响应式问题。 演示 demo <template><div class&quo…

软中断在bottom-half中调用

https://www.bilibili.com/read/cv20785285/简介软中断可以在两个位置得到机会执行&#xff1a;硬中断返回前 irq_exit中断下半部 Bottom-half Enable后情景分析情景1spin_unlock_bh__raw_spin_unlock_bh__local_bh_enable_ip 打开Bottom-half&#xff0c;并让softirq有机会…

【NGINX入门指北】 进阶篇

nginx 进阶篇 文章目录nginx 进阶篇一、Nginx Proxy 服务器1、代理原理2、proxy代理3、proxy缓存一、Nginx Proxy 服务器 1、代理原理 正向代理 内网客户机通过代理访问互联网&#xff0c;通常要设置代理服务器地址和端口。 反向代理 外网用户通过代理访问内网服务器&…

xpath注入[NPUCTF2020]ezlogin

[NPUCTF2020]ezlogin 打开界面 如果发现自己输入的信息由这样构成&#xff0c;可以往xpath注入上靠一下。 不管输入什么&#xff0c;很容易发现登陆就超时了&#xff0c;说明这里token是不断刷新的。 这样构造也是一样的目的都是为了闭合后面的&#xff0c;为啥有两个or呢 us…

Redis中有常见数据类型

Redis的数据类型 string数据类型 string是redis最基本的类型&#xff0c;而且string类型是二进制安全的。意思是redis的string可以包含任何 数据&#xff0c;比如jpg图片或者序列化的对象 String类型是最基本的数据类型&#xff0c;一个redis中字符串value最多可以是512M r…

Allegro如何使用Snake命令走蛇形线操作指导

Allegro如何使用Snake命令走蛇形线操作指导 在做PCB设计的时候,遇到不规则BGA的时候,蛇形走线是惯用的走线方式,类似下图 Allegro支持蛇形走线,具体操作如下 首先把过孔打好,尽量上下左右间距一致,不容易出现偏差,如下图在Command命令栏下方输入snake,然后回车

常见字符串函数的使用,你确定不进来看看吗?

&#x1f466;个人主页&#xff1a;Weraphael ✍&#x1f3fb;作者简介&#xff1a;目前是C语言学习者 ✈️专栏&#xff1a;C语言航路 &#x1f40b; 希望大家多多支持&#xff0c;咱一起进步&#xff01;&#x1f601; 如果文章对你有帮助的话 欢迎 评论&#x1f4ac; 点赞&a…

2023年最强大的12款数据可视化工具,值得收藏

做数据分析也有年头了&#xff0c;好的坏的工具都用过&#xff0c;推荐几个觉得很好用的&#xff0c;避坑必看&#xff01; PS&#xff1a;一般比较成熟的公司里&#xff0c;数据分析工具不只是满足业务分析和报表制作&#xff0c;像我现在给我们公司选型BI工具&#xff0c;是做…

差分模拟信号转单端输出电路设计

需求分析&#xff1a; 1.差分输入0~16V -Vpp电压量&#xff1b; 2.输入频率0~1.2KHz&#xff1b; 3.单端对应输出0~3V的模拟量&#xff1b; 4.输出频率对应0~1.2KHz&#xff1b; 5.供电范围3~5V。 针对以上需求&#xff0c;设计如下图所示电路。 1.电路功能&#xff1a; …

Spring为什么这么火 之 Bean的6种作用域和Bean的生命周期

1、Bean的作用域 1.1、什么是作用域&#xff1f; 限定程序中变量的可用范围叫做作用域&#xff0c;或者说在源代码中定义变量的某个区域就叫做作用域 1.2、Bean的6种作用域 singleton&#xff1a;单例作用域prototype&#xff1a;原型作用域【多例作用域】request&#xff1…