LifeCycleLean

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

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

import android.annotation.NonNull;

import android.annotation.Nullable;

import android.annotation.SuppressLint;

import android.app.Activity;

import android.app.Application;

import android.content.Context;

import android.os.Build;

import android.os.Bundle;

import android.os.Handler;

import androidx.annotation.MainThread;

import androidx.annotation.RequiresApi;

import androidx.annotation.RestrictTo;

import androidx.annotation.VisibleForTesting;

import androidx.arch.core.executor.ArchTaskExecutor;

import androidx.arch.core.internal.FastSafeIterableMap;

import androidx.arch.core.internal.SafeIterableMap;

import androidx.lifecycle.ClassesInfoCache;

import androidx.lifecycle.CompositeGeneratedAdaptersObserver;

import androidx.lifecycle.EmptyActivityLifecycleCallbacks;

import androidx.lifecycle.GeneratedAdapter;

import androidx.lifecycle.GenericLifecycleObserver;

import androidx.lifecycle.LifecycleRegistry;

import androidx.lifecycle.ReflectiveGenericLifecycleObserver;

import androidx.lifecycle.ReportFragment;

import androidx.lifecycle.SingleGeneratedAdapterObserver;

import java.lang.ref.WeakReference;

import java.lang.reflect.Constructor;

import java.lang.reflect.InvocationTargetException;

import java.util.ArrayList;

import java.util.Collections;

import java.util.HashMap;

import java.util.Iterator;

import java.util.List;

import java.util.Map;

import java.util.WeakHashMap;

import java.util.concurrent.atomic.AtomicBoolean;

/**

* 1.LifeCycle几个相关的类

* */

public

/**

* 1.1 LifeCycle 事件定义

* 1.怎么实现自己的类拥有声明周期  实现接口 owner来生成装饰拓展的代码

* 2.规定了cycleEvent 下发的时机 .  一个是在..之前  一种是在..之后

* 3.定义了几个枚举类

* 4.这里从哪个状态到哪个状态不太理解; 因为没有用到地方,暂时先不关注.

* 5.总体理解就是,这个是声明周期类型的定义. 需要配合 lfowner(拥有者,下发) 和 DefaultLifecycleObserver(观察者,接受)

* */

/**

* Defines an object that has an Android Lifecycle. {@link androidx.fragment.app.Fragment Fragment}

* and {@link androidx.fragment.app.FragmentActivity FragmentActivity} classes implement

* {@link LifecycleOwner} interface which has the {@link LifecycleOwner#getLifecycle()

* getLifecycle} method to access the Lifecycle. You can also implement {@link LifecycleOwner}

* in your own classes.

*

* {@link androidx.lifecycle.Lifecycle.Event#ON_CREATE}, {@link androidx.lifecycle.Lifecycle.Event#ON_START}, {@link androidx.lifecycle.Lifecycle.Event#ON_RESUME} events in this class

* are dispatched <b>after</b> the {@link LifecycleOwner}'s related method returns.

* {@link androidx.lifecycle.Lifecycle.Event#ON_PAUSE}, {@link androidx.lifecycle.Lifecycle.Event#ON_STOP}, {@link androidx.lifecycle.Lifecycle.Event#ON_DESTROY} events in this class

* are dispatched <b>before</b> the {@link LifecycleOwner}'s related method is called.

* For instance, {@link androidx.lifecycle.Lifecycle.Event#ON_START} will be dispatched after

* {@link android.app.Activity#onStart onStart} returns, {@link androidx.lifecycle.Lifecycle.Event#ON_STOP} will be dispatched

* before {@link android.app.Activity#onStop onStop} is called.

* This gives you certain guarantees on which state the owner is in.

*

* To observe lifecycle events call {@link #addObserver(LifecycleObserver)} passing an object

* that implements either {@link DefaultLifecycleObserver} or {@link LifecycleEventObserver}.

* */

public abstract class Lifecycle {

/**

* Lifecycle coroutines extensions stashes the CoroutineScope into this field.

*

    * @hide used by lifecycle-common-ktx

*/

    @RestrictTo(RestrictTo.Scope.LIBRARY_GROUP)

@NonNull

AtomicReference mInternalScopeRef =new AtomicReference<>();

    /**

* Adds a LifecycleObserver that will be notified when the LifecycleOwner changes

* state.

    *

    * The given observer will be brought to the current state of the LifecycleOwner.

    * For example, if the LifecycleOwner is in {@link androidx.lifecycle.Lifecycle.State#STARTED} state, the given observer

    * will receive {@link androidx.lifecycle.Lifecycle.Event#ON_CREATE}, {@link androidx.lifecycle.Lifecycle.Event#ON_START} events.

*

    * @param observer The observer to notify.

*/

    @MainThread

public abstract void addObserver(@NonNull LifecycleObserver observer);

    /**

* Removes the given observer from the observers list.

    *

    * If this method is called while a state change is being dispatched,

    *

        * <li>If the given observer has not yet received that event, it will not receive it.

        * <li>If the given observer has more than 1 method that observes the currently dispatched

    * event and at least one of them received the event, all of them will receive the event and

    * the removal will happen afterwards.

        *

        *

        * @param observer The observer to be removed.

    */

        @MainThread

    public abstract void removeObserver(@NonNull LifecycleObserver observer);

        /**

    * Returns the current state of the Lifecycle.

    *

        * @return The current state of the Lifecycle.

    */

        @MainThread

    @NonNull

    public abstract androidx.lifecycle.Lifecycle.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 androidx.lifecycle.Lifecycle.Event Event} constant that can be used to match all events.

    */

            ON_ANY;

            /**

    *

            * Returns the {@link androidx.lifecycle.Lifecycle.Event} that will be reported by a {@link androidx.lifecycle.Lifecycle}

            * leaving the specified {@link androidx.lifecycle.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 androidx.lifecycle.Lifecycle.Event downFrom(@NonNull androidx.lifecycle.Lifecycle.State state) {

    switch (state) {

    case CREATED:

    return ON_DESTROY;

                    case STARTED:

    return ON_STOP;

                    case RESUMED:

    return ON_PAUSE;

                    default:

    return null;

                }

    }

    /**

            * Returns the {@link androidx.lifecycle.Lifecycle.Event} that will be reported by a {@link androidx.lifecycle.Lifecycle}

            * entering the specified {@link androidx.lifecycle.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 androidx.lifecycle.Lifecycle.Event downTo(@NonNull androidx.lifecycle.Lifecycle.State state) {

    switch (state) {

    case DESTROYED:

    return ON_DESTROY;

                    case CREATED:

    return ON_STOP;

                    case STARTED:

    return ON_PAUSE;

                    default:

    return null;

                }

    }

    /**

            * Returns the {@link androidx.lifecycle.Lifecycle.Event} that will be reported by a {@link androidx.lifecycle.Lifecycle}

            * leaving the specified {@link androidx.lifecycle.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 androidx.lifecycle.Lifecycle.Event upFrom(@NonNull androidx.lifecycle.Lifecycle.State state) {

    switch (state) {

    case INITIALIZED:

    return ON_CREATE;

                    case CREATED:

    return ON_START;

                    case STARTED:

    return ON_RESUME;

                    default:

    return null;

                }

    }

    /**

            * Returns the {@link androidx.lifecycle.Lifecycle.Event} that will be reported by a {@link androidx.lifecycle.Lifecycle}

            * entering the specified {@link androidx.lifecycle.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 androidx.lifecycle.Lifecycle.Event upTo(@NonNull androidx.lifecycle.Lifecycle.State state) {

    switch (state) {

    case CREATED:

    return ON_CREATE;

                    case STARTED:

    return ON_START;

                    case RESUMED:

    return ON_RESUME;

                    default:

    return null;

                }

    }

    /**

            * Returns the new {@link androidx.lifecycle.Lifecycle.State} of a {@link androidx.lifecycle.Lifecycle} that just reported

            * this {@link androidx.lifecycle.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 androidx.lifecycle.Lifecycle.State getTargetState() {

    switch (this) {

    case ON_CREATE:

    case ON_STOP:

    return androidx.lifecycle.Lifecycle.State.CREATED;

                    case ON_START:

    case ON_PAUSE:

    return androidx.lifecycle.Lifecycle.State.STARTED;

                    case ON_RESUME:

    return androidx.lifecycle.Lifecycle.State.RESUMED;

                    case ON_DESTROY:

    return androidx.lifecycle.Lifecycle.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 androidx.lifecycle.Lifecycle.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:

            *

              *    <li>after {@link android.app.Activity#onCreate(android.os.Bundle) onCreate} call;

              *    <li><b>right before</b> {@link android.app.Activity#onStop() onStop} call.

              *

              */

              CREATED,

              /**

              * Started state for a LifecycleOwner. For an {@link android.app.Activity}, this state

      * is reached in two cases:

              *

                *    <li>after {@link android.app.Activity#onStart() onStart} call;

                *    <li><b>right before</b> {@link android.app.Activity#onPause() onPause} call.

                *

                */

                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 androidx.lifecycle.Lifecycle.State state) {

        return compareTo(state) >=0;

                }

        }

        }

        /**

        * 1.2 LifeOwner 事件下发者

        * */

        /**

        * A class that has an Android lifecycle. These events can be used by custom components to

        * handle lifecycle changes without implementing any code inside the Activity or the Fragment.

        *

        * @see androidx.lifecycle.Lifecycle

        * @see ViewTreeLifecycleOwner

        */

        @SuppressWarnings({"WeakerAccess", "unused"})

        public interface LifecycleOwner {

        /**

        * Returns the Lifecycle of the provider.

        *

            * @return The lifecycle of the provider.

        */

            @NonNull

        androidx.lifecycle.Lifecycle getLifecycle();

        }

        /**

        * 1.3 LifeCycleObserver 和 LifeCycleEventObserver  两种事件观察者

        * lifeCycleObserver 不是直接拿来用的

        * eventObserver  或者  DefaultLifecycleObserver 这两个

        * */

        /**

        * 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 androidx.lifecycle.Lifecycle Lifecycle - for samples and usage patterns.

        */

        @SuppressWarnings("WeakerAccess")

        public interface LifecycleObserver {

        }

        /**

        * Class that can receive any lifecycle change and dispatch it to the receiver.

        *

        * If a class implements both this interface and

        * {@link androidx.lifecycle.DefaultLifecycleObserver}, then

        * methods of {@code DefaultLifecycleObserver} will be called first, and then followed by the call

        * of {@link androidx.lifecycle.LifecycleEventObserver#onStateChanged(androidx.lifecycle.LifecycleOwner, androidx.lifecycle.Lifecycle.Event)}

        *

        * If a class implements this interface and in the same time uses {@link OnLifecycleEvent}, then

        * annotations will be ignored.

        */

        public interface LifecycleEventObserverextends androidx.lifecycle.LifecycleObserver {

        /**

        * Called when a state transition event happens.

        *

            * @param source The source of the event

            * @param event The event

        */

            void onStateChanged(@NonNull androidx.lifecycle.LifecycleOwner source, @NonNull androidx.lifecycle.Lifecycle.Event event);

        }

        /**

        * 1.4  FullLifecycleObserver 和 DefalutLifeCycleObserver 两者的关系

        * */

        /**

        * 正常activity几个声明周期的回调.

        * */

        interface FullLifecycleObserverextends androidx.lifecycle.LifecycleObserver {

        void onCreate(androidx.lifecycle.LifecycleOwner owner);

            void onStart(androidx.lifecycle.LifecycleOwner owner);

            void onResume(androidx.lifecycle.LifecycleOwner owner);

            void onPause(androidx.lifecycle.LifecycleOwner owner);

            void onStop(androidx.lifecycle.LifecycleOwner owner);

            void onDestroy(androidx.lifecycle.LifecycleOwner owner);

        }

        /**

        * DefaultLifeCycleObserver  下面的两点声明  ==>>  注意这里还有一个注解 OnLifecycleEvent  todo 这里进行一下验证,官方已经把这个废弃了

        * 1. 单实现这个接口 并且同时实现 LifecycleEventObserver event接口, 那么先是onCreate() onStart() 这种接口 然后才是 onStateChange();

        * 2. 这个接口 ,和 注解 OnLifecycleEvent 一起使用时, 以接口回调为主. 注解不生效了就.

        * */

        public interface DefaultLifecycleObserverextends androidx.lifecycle.FullLifecycleObserver {

        /**

            * Notifies that {@code ON_CREATE} event occurred.

            *

            * This method will be called after the {@link androidx.lifecycle.LifecycleOwner}'s {@code onCreate}

        * method returns.

        *

            * @param owner the component, whose state was changed

        */

            @Override

        default void onCreate(@NonNull androidx.lifecycle.LifecycleOwner owner) {

        }

        /**

            * Notifies that {@code ON_START} event occurred.

            *

            * This method will be called after the {@link androidx.lifecycle.LifecycleOwner}'s {@code onStart} method returns.

        *

            * @param owner the component, whose state was changed

        */

            @Override

        default void onStart(@NonNull androidx.lifecycle.LifecycleOwner owner) {

        }

        /**

            * Notifies that {@code ON_RESUME} event occurred.

            *

            * This method will be called after the {@link androidx.lifecycle.LifecycleOwner}'s {@code onResume}

        * method returns.

        *

            * @param owner the component, whose state was changed

        */

            @Override

        default void onResume(@NonNull androidx.lifecycle.LifecycleOwner owner) {

        }

        /**

            * Notifies that {@code ON_PAUSE} event occurred.

            *

            * This method will be called before the {@link androidx.lifecycle.LifecycleOwner}'s {@code onPause} method

        * is called.

        *

            * @param owner the component, whose state was changed

        */

            @Override

        default void onPause(@NonNull androidx.lifecycle.LifecycleOwner owner) {

        }

        /**

            * Notifies that {@code ON_STOP} event occurred.

            *

            * This method will be called before the {@link androidx.lifecycle.LifecycleOwner}'s {@code onStop} method

        * is called.

        *

            * @param owner the component, whose state was changed

        */

            @Override

        default void onStop(@NonNull androidx.lifecycle.LifecycleOwner owner) {

        }

        /**

            * Notifies that {@code ON_DESTROY} event occurred.

            *

            * This method will be called before the {@link androidx.lifecycle.LifecycleOwner}'s {@code onDestroy} method

        * is called.

        *

            * @param owner the component, whose state was changed

        */

            @Override

        default void onDestroy(@NonNull androidx.lifecycle.LifecycleOwner owner) {

        }

        }

        /**

        * FullLifecycleObserverAdapter  ==>> states 发生变化时通知  ==>> fullLifeCycleObserver 这个是oncreate  onstart  onresume 这几种状态变化的监听

        * 1. 和上面的解释  defaultLifecycleObserver 对应  这里一会儿看activity中是怎么通知的.

        * */

        class FullLifecycleObserverAdapterimplements androidx.lifecycle.LifecycleEventObserver {

        private final androidx.lifecycle.FullLifecycleObserver mFullLifecycleObserver;

            private final androidx.lifecycle.LifecycleEventObserver mLifecycleEventObserver;

            FullLifecycleObserverAdapter(androidx.lifecycle.FullLifecycleObserver fullLifecycleObserver,

                                        androidx.lifecycle.LifecycleEventObserver lifecycleEventObserver) {

        mFullLifecycleObserver = fullLifecycleObserver;

                mLifecycleEventObserver = lifecycleEventObserver;

            }

        @Override

        public void onStateChanged(@NonNull androidx.lifecycle.LifecycleOwner source, @NonNull androidx.lifecycle.Lifecycle.Event event) {

        switch (event) {

        case ON_CREATE:

        mFullLifecycleObserver.onCreate(source);

        break;

                    case ON_START:

        mFullLifecycleObserver.onStart(source);

        break;

                    case ON_RESUME:

        mFullLifecycleObserver.onResume(source);

        break;

                    case ON_PAUSE:

        mFullLifecycleObserver.onPause(source);

        break;

                    case ON_STOP:

        mFullLifecycleObserver.onStop(source);

        break;

                    case ON_DESTROY:

        mFullLifecycleObserver.onDestroy(source);

        break;

                    case ON_ANY:

        throw new IllegalArgumentException("ON_ANY must not been send by anybody");

                }

        if (mLifecycleEventObserver !=null) {

        mLifecycleEventObserver.onStateChanged(source, event);

                }

        }

        }

        /**

        * 分析一下系统中 Application.ActivityLifecycleCallback 的使用

        * 针对几种acticity生命周期提供了 **前  **中 **后的回调

        *

        * */

        public interface ActivityLifecycleCallbacks {

        /**

        * Called as the first step of the Activity being created. This is always called before

            * {@link Activity#onCreate}.

        */

            default void onActivityPreCreated(@NonNull Activity activity,

                                              @Nullable Bundle savedInstanceState) {

        }

        /**

            * Called when the Activity calls {@link Activity#onCreate super.onCreate()}.

        */

            void onActivityCreated(@NonNull Activity activity, @Nullable Bundle savedInstanceState);

            /**

        * Called as the last step of the Activity being created. This is always called after

            * {@link Activity#onCreate}.

        */

            default void onActivityPostCreated(@NonNull Activity activity,

                                              @Nullable Bundle savedInstanceState) {

        }

        /**

        * Called as the first step of the Activity being started. This is always called before

            * {@link Activity#onStart}.

        */

            default void onActivityPreStarted(@NonNull Activity activity) {

        }

        /**

            * Called when the Activity calls {@link Activity#onStart super.onStart()}.

        */

            void onActivityStarted(@NonNull Activity activity);

            /**

        * Called as the last step of the Activity being started. This is always called after

            * {@link Activity#onStart}.

        */

            default void onActivityPostStarted(@NonNull Activity activity) {

        }

        /**

        * Called as the first step of the Activity being resumed. This is always called before

            * {@link Activity#onResume}.

        */

            default void onActivityPreResumed(@NonNull Activity activity) {

        }

        /**

            * Called when the Activity calls {@link Activity#onResume super.onResume()}.

        */

            void onActivityResumed(@NonNull Activity activity);

            /**

        * Called as the last step of the Activity being resumed. This is always called after

            * {@link Activity#onResume} and {@link Activity#onPostResume}.

        */

            default void onActivityPostResumed(@NonNull Activity activity) {

        }

        /**

        * Called as the first step of the Activity being paused. This is always called before

            * {@link Activity#onPause}.

        */

            default void onActivityPrePaused(@NonNull Activity activity) {

        }

        /**

            * Called when the Activity calls {@link Activity#onPause super.onPause()}.

        */

            void onActivityPaused(@NonNull Activity activity);

            /**

        * Called as the last step of the Activity being paused. This is always called after

            * {@link Activity#onPause}.

        */

            default void onActivityPostPaused(@NonNull Activity activity) {

        }

        /**

        * Called as the first step of the Activity being stopped. This is always called before

            * {@link Activity#onStop}.

        */

            default void onActivityPreStopped(@NonNull Activity activity) {

        }

        /**

            * Called when the Activity calls {@link Activity#onStop super.onStop()}.

        */

            void onActivityStopped(@NonNull Activity activity);

            /**

        * Called as the last step of the Activity being stopped. This is always called after

            * {@link Activity#onStop}.

        */

            default void onActivityPostStopped(@NonNull Activity activity) {

        }

        /**

        * Called as the first step of the Activity saving its instance state. This is always

            * called before {@link Activity#onSaveInstanceState}.

        */

            default void onActivityPreSaveInstanceState(@NonNull Activity activity,

                                                        @NonNull Bundle outState) {

        }

        /**

        * Called when the Activity calls

            * {@link Activity#onSaveInstanceState super.onSaveInstanceState()}.

        */

            void onActivitySaveInstanceState(@NonNull Activity activity, @NonNull Bundle outState);

            /**

        * Called as the last step of the Activity saving its instance state. This is always

            * called after{@link Activity#onSaveInstanceState}.

        */

            default void onActivityPostSaveInstanceState(@NonNull Activity activity,

                                                        @NonNull Bundle outState) {

        }

        /**

        * Called as the first step of the Activity being destroyed. This is always called before

            * {@link Activity#onDestroy}.

        */

            default void onActivityPreDestroyed(@NonNull Activity activity) {

        }

        /**

            * Called when the Activity calls {@link Activity#onDestroy super.onDestroy()}.

        */

            void onActivityDestroyed(@NonNull Activity activity);

            /**

        * Called as the last step of the Activity being destroyed. This is always called after

            * {@link Activity#onDestroy}.

        */

            default void onActivityPostDestroyed(@NonNull Activity activity) {

        }

        /**

        * Called when the Activity configuration was changed.

            * @hide

            */

            default void onActivityConfigurationChanged(@NonNull Activity activity) {

        }

        }

        /**

        *  Activity 中的注册方法  他和application中的方法调用时序问题  ==>> 验证成功,这里嵌套流程确实如此...

        * */

        /**

            * Register an {@link Application.ActivityLifecycleCallbacks} instance that receives

            * lifecycle callbacks for only this Activity.  /// 仅仅对这个activity 注册一个声明周期观察者实例

            *

            * In relation to any  //// 这里 涉及到了Application 的registerActivityLifecycleCallbacks方法... 介绍两者之间的关系

            * {@link Application#registerActivityLifecycleCallbacks Application registered callbacks},

        * the callbacks registered here will always occur nested within those callbacks.

        *

            * 这里注册的监听会嵌套在application中注册的监听之中

            *

        * This means:

        *

            *

              *

              *      //  先给application,然后再给到这里

              *    <li>Pre events will first be sent to Application registered callbacks, then to callbacks

              *    registered here.

              *

              *    //  三个事件application先收到.  其他的事件,这里先收到

              *    <li>{@link Application.ActivityLifecycleCallbacks#onActivityCreated(Activity, Bundle)},

              *    {@link Application.ActivityLifecycleCallbacks#onActivityStarted(Activity)}, and

              *    {@link Application.ActivityLifecycleCallbacks#onActivityResumed(Activity)} will

          *    be sent first to Application registered callbacks, then to callbacks registered here.

              *    For all other events, callbacks registered here will be sent first.

              *

              *    //  还有一种 PostEv ents  这个是啥???  todo 等待验证

              *    <li>Post events will first be sent to callbacks registered here, then to

              *    Application registered callbacks.

              *

              *

              * If multiple callbacks are registered here, they receive events in a first in (up through

              * {@link Application.ActivityLifecycleCallbacks#onActivityPostResumed}, last out

          * ordering.

              *

              * It is strongly recommended to register this in the constructor of your Activity to ensure

          * you get all available callbacks. As this callback is associated with only this Activity,

              * it is not usually necessary to {@link #unregisterActivityLifecycleCallbacks unregister} it

          * unless you specifically do not want to receive further lifecycle callbacks.

          *

              * @param callback The callback instance to register

          */

              public void registerActivityLifecycleCallbacks(

          @NonNull Application.ActivityLifecycleCallbacks callback) {

          synchronized (mActivityLifecycleCallbacks) {

          mActivityLifecycleCallbacks.add(callback);

                  }

          }

          /**

              *  Application 中的注册方法

              * */

              public void registerActivityLifecycleCallbacks(Application.ActivityLifecycleCallbacks callback) {

          synchronized (mActivityLifecycleCallbacks) {

          mActivityLifecycleCallbacks.add(callback);

                  }

          }

          /**

          *  Lifecycling observer的类型转换判断

          *  这里配合 singleGFeneratedAdapterObserver 暂时不关注这个

          * */

          /**

          * Internal class to handle lifecycle conversion etc.

          *

          * @hide

          */

          @RestrictTo(RestrictTo.Scope.LIBRARY_GROUP_PREFIX)

          public class Lifecycling {

          private static final int REFLECTIVE_CALLBACK =1;

              private static final int GENERATED_CALLBACK =2;

              private static Map, Integer> sCallbackCache =new HashMap<>();

              private static Map, List>> sClassToAdapters =

          new HashMap<>();

              // Left for binary compatibility when lifecycle-common goes up 2.1 as transitive dep

          // but lifecycle-runtime stays 2.0

              /**

              * @deprecated Left for compatibility with lifecycle-runtime:2.0

          */

              @SuppressWarnings("deprecation")

          @Deprecated

          @androidx.annotation.NonNull

          static GenericLifecycleObserver getCallback(final Object object) {

          final androidx.lifecycle.LifecycleEventObserver observer = lifecycleEventObserver(object);

                  return new GenericLifecycleObserver() {

          @Override

          public void onStateChanged(@androidx.annotation.NonNull androidx.lifecycle.LifecycleOwner source,

                                                @androidx.annotation.NonNull androidx.lifecycle.Lifecycle.Event event) {

          observer.onStateChanged(source, event);

                      }

          };

              }

          @androidx.annotation.NonNull

          @SuppressWarnings("deprecation")

          static androidx.lifecycle.LifecycleEventObserver lifecycleEventObserver(Object object) {

          boolean isLifecycleEventObserver = objectinstanceof androidx.lifecycle.LifecycleEventObserver;

                  boolean isFullLifecycleObserver = objectinstanceof androidx.lifecycle.FullLifecycleObserver;

                  if (isLifecycleEventObserver && isFullLifecycleObserver) {

          return new androidx.lifecycle.FullLifecycleObserverAdapter((androidx.lifecycle.FullLifecycleObserver) object,

                              (androidx.lifecycle.LifecycleEventObserver) object);

                  }

          if (isFullLifecycleObserver) {

          return new androidx.lifecycle.FullLifecycleObserverAdapter((androidx.lifecycle.FullLifecycleObserver) object, null);

                  }

          if (isLifecycleEventObserver) {

          return (androidx.lifecycle.LifecycleEventObserver) object;

                  }

          final Class klass = object.getClass();

                  int type = getObserverConstructorType(klass);

                  if (type == GENERATED_CALLBACK) {

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

              }

          private static GeneratedAdapter createGeneratedAdapter(

          Constructor constructor, Object object) {

          //noinspection TryWithIdenticalCatches

                  try {

          return constructor.newInstance(object);

                  }catch (IllegalAccessException e) {

          throw new RuntimeException(e);

                  }catch (InstantiationException e) {

          throw new RuntimeException(e);

                  }catch (InvocationTargetException e) {

          throw new RuntimeException(e);

                  }

          }

          @SuppressWarnings("deprecation")

          @androidx.annotation.Nullable

          private static Constructor generatedConstructor(Class klass) {

          try {

          Package aPackage = klass.getPackage();

                      String name = klass.getCanonicalName();

                      final String fullPackage = aPackage !=null ? aPackage.getName() :"";

                      final String adapterName = getAdapterName(fullPackage.isEmpty() ? name :

          name.substring(fullPackage.length() +1));

                      @SuppressWarnings("unchecked")final Class aClass =

          (Class) Class.forName(

          fullPackage.isEmpty() ? adapterName : fullPackage +"." + adapterName);

                      Constructor constructor =

          aClass.getDeclaredConstructor(klass);

                      if (!constructor.isAccessible()) {

          constructor.setAccessible(true);

                      }

          return constructor;

                  }catch (ClassNotFoundException e) {

          return null;

                  }catch (NoSuchMethodException e) {

          // this should not happen

                      throw new RuntimeException(e);

                  }

          }

          private static int getObserverConstructorType(Class klass) {

          Integer callbackCache = sCallbackCache.get(klass);

                  if (callbackCache !=null) {

          return callbackCache;

                  }

          int type = resolveObserverCallbackType(klass);

                  sCallbackCache.put(klass, type);

                  return type;

              }

          private static int resolveObserverCallbackType(Class klass) {

          // anonymous class bug:35073837

                  if (klass.getCanonicalName() ==null) {

          return REFLECTIVE_CALLBACK;

                  }

          Constructor constructor = generatedConstructor(klass);

                  if (constructor !=null) {

          sClassToAdapters.put(klass, Collections

          .>singletonList(constructor));

                      return GENERATED_CALLBACK;

                  }

          @SuppressWarnings("deprecation")

          boolean hasLifecycleMethods = ClassesInfoCache.sInstance.hasLifecycleMethods(klass);

                  if (hasLifecycleMethods) {

          return REFLECTIVE_CALLBACK;

                  }

          Class superclass = klass.getSuperclass();

                  List> adapterConstructors =null;

                  if (isLifecycleParent(superclass)) {

          if (getObserverConstructorType(superclass) == REFLECTIVE_CALLBACK) {

          return REFLECTIVE_CALLBACK;

                      }

          adapterConstructors =new ArrayList<>(sClassToAdapters.get(superclass));

                  }

          for (Class intrface : klass.getInterfaces()) {

          if (!isLifecycleParent(intrface)) {

          continue;

                      }

          if (getObserverConstructorType(intrface) == REFLECTIVE_CALLBACK) {

          return REFLECTIVE_CALLBACK;

                      }

          if (adapterConstructors ==null) {

          adapterConstructors =new ArrayList<>();

                      }

          adapterConstructors.addAll(sClassToAdapters.get(intrface));

                  }

          if (adapterConstructors !=null) {

          sClassToAdapters.put(klass, adapterConstructors);

                      return GENERATED_CALLBACK;

                  }

          return REFLECTIVE_CALLBACK;

              }

          private static boolean isLifecycleParent(Class klass) {

          return klass !=null && androidx.lifecycle.LifecycleObserver.class.isAssignableFrom(klass);

              }

          /**

          * Create a name for an adapter class.

          */

              public static String getAdapterName(String className) {

          return className.replace(".", "_") +"_LifecycleAdapter";

              }

          private Lifecycling() {

          }

          }

          /**

          * LifecycleDispatcher  ==>> 这个需要借助文章来对比一下这个用法.  todo ==>> 等待验证

          * // 这个是为了 child-fragments设计的.

          * a.hook了application的 callback

          * b.当一个activity不能再执行一个fragment 的事务的时候,停止掉所有的provider

          * */

          /**

          * When initialized, it hooks into the Activity callback of the Application and observes

          * Activities. It is responsible to hook in child-fragments to activities and fragments to report

          * their lifecycle events. Another responsibility of this class is to mark as stopped all lifecycle

          * providers related to an activity as soon it is not safe to run a fragment transaction in this

          * activity.

          */

          class LifecycleDispatcher {

          private static AtomicBoolean sInitialized =new AtomicBoolean(false);

              static void init(Context context) {

          if (sInitialized.getAndSet(true)) {

          return;

                  }

          ((Application) context.getApplicationContext())

          .registerActivityLifecycleCallbacks(new androidx.lifecycle.LifecycleDispatcher.DispatcherActivityCallback());

              }

          @SuppressWarnings("WeakerAccess")

          @VisibleForTesting

          static class DispatcherActivityCallbackextends EmptyActivityLifecycleCallbacks {

          @Override

          public void onActivityCreated(Activity activity, Bundle savedInstanceState) {

          ReportFragment.injectIfNeededIn(activity);

                  }

          @Override

          public void onActivityStopped(Activity activity) {

          }

          @Override

          public void onActivitySaveInstanceState(Activity activity, Bundle outState) {

          }

          }

          private LifecycleDispatcher() {

          }

          }

          /**

          * ProcessLifecycleOwner    todo:// 等待验证 和 application.activitylifecycleCallback 之间的关系

          * 应用进程相关 ===>>> 前后台

          * */

          /**

          * Class that provides lifecycle for the whole application process.

          *

          * You can consider this LifecycleOwner as the composite of all of your Activities, except that

          * {@link androidx.lifecycle.Lifecycle.Event#ON_CREATE} will be dispatched once and {@link androidx.lifecycle.Lifecycle.Event#ON_DESTROY}

          * will never be dispatched. Other lifecycle events will be dispatched with following rules:

          *

          * // 第一个activity下发 onstart ,onresume 时,触发. 并且只下发一次.

          * ProcessLifecycleOwner will dispatch {@link androidx.lifecycle.Lifecycle.Event#ON_START},

          * {@link androidx.lifecycle.Lifecycle.Event#ON_RESUME} events, as a first activity moves through these events.

          *

          *

          * // 最后一个activity 下发完以后,延迟一会再触发.

          * {@link androidx.lifecycle.Lifecycle.Event#ON_PAUSE}, {@link androidx.lifecycle.Lifecycle.Event#ON_STOP}, events will be dispatched with

          * a <b>delay</b> after a last activity

          * passed through them.

          *

          * // 考虑到了 configuration

          * This delay is long enough to guarantee that ProcessLifecycleOwner

          * won't send any events if activities are destroyed and recreated due to a

          * configuration change.

          *

          *

          *

          * // 前后台判断 ==>> 有毫秒级别的误差.

          * It is useful for use cases where you would like to react on your app coming to the foreground or

          * going to the background and you don't need a milliseconds accuracy in receiving lifecycle

          * events.

          */

          @SuppressWarnings("WeakerAccess")

          public class ProcessLifecycleOwnerimplements androidx.lifecycle.LifecycleOwner {

          @VisibleForTesting

          static final long TIMEOUT_MS =700; //mls

          // ground truth counters

              private int mStartedCounter =0;

              private int mResumedCounter =0;

              private boolean mPauseSent =true;

              private boolean mStopSent =true;

              private Handler mHandler;

              private final LifecycleRegistry mRegistry =new LifecycleRegistry(this);

              private Runnable mDelayedPauseRunnable =new Runnable() {

          @Override

          public void run() {

          dispatchPauseIfNeeded();

                      dispatchStopIfNeeded();

                  }

          };

              ReportFragment.ActivityInitializationListener mInitializationListener =

          new ReportFragment.ActivityInitializationListener() {

          @Override

          public void onCreate() {

          }

          @Override

          public void onStart() {

          activityStarted();

                          }

          @Override

          public void onResume() {

          activityResumed();

                          }

          };

              private static final androidx.lifecycle.ProcessLifecycleOwner sInstance =new androidx.lifecycle.ProcessLifecycleOwner();

              /**

          * The LifecycleOwner for the whole application process. Note that if your application

          * has multiple processes, this provider does not know about other processes.

          *

              * @return {@link androidx.lifecycle.LifecycleOwner} for the whole application.

          */

              @androidx.annotation.NonNull

          public static androidx.lifecycle.LifecycleOwner get() {

          return sInstance;

              }

          static void init(Context context) {

          sInstance.attach(context);

              }

          void activityStarted() {

          mStartedCounter++;

                  if (mStartedCounter ==1 && mStopSent) {

          mRegistry.handleLifecycleEvent(androidx.lifecycle.Lifecycle.Event.ON_START);

                      mStopSent =false;

                  }

          }

          void activityResumed() {

          mResumedCounter++;

                  if (mResumedCounter ==1) {

          if (mPauseSent) {

          mRegistry.handleLifecycleEvent(androidx.lifecycle.Lifecycle.Event.ON_RESUME);

                          mPauseSent =false;

                      }else {

          mHandler.removeCallbacks(mDelayedPauseRunnable);

                      }

          }

          }

          void activityPaused() {

          mResumedCounter--;

                  if (mResumedCounter ==0) {

          mHandler.postDelayed(mDelayedPauseRunnable, TIMEOUT_MS);

                  }

          }

          void activityStopped() {

          mStartedCounter--;

                  dispatchStopIfNeeded();

              }

          void dispatchPauseIfNeeded() {

          if (mResumedCounter ==0) {

          mPauseSent =true;

                      mRegistry.handleLifecycleEvent(androidx.lifecycle.Lifecycle.Event.ON_PAUSE);

                  }

          }

          void dispatchStopIfNeeded() {

          if (mStartedCounter ==0 && mPauseSent) {

          mRegistry.handleLifecycleEvent(androidx.lifecycle.Lifecycle.Event.ON_STOP);

                      mStopSent =true;

                  }

          }

          private ProcessLifecycleOwner() {

          }

          @SuppressWarnings("deprecation")

          void attach(Context context) {

          mHandler =new Handler();

                  mRegistry.handleLifecycleEvent(androidx.lifecycle.Lifecycle.Event.ON_CREATE);

                  Application app = (Application) context.getApplicationContext();

                  app.registerActivityLifecycleCallbacks(new EmptyActivityLifecycleCallbacks() {

          @RequiresApi(29)

          @Override

          public void onActivityPreCreated(@androidx.annotation.NonNull Activity activity,

                                                      @androidx.annotation.Nullable Bundle savedInstanceState) {

          // We need the ProcessLifecycleOwner to get ON_START and ON_RESUME precisely

          // before the first activity gets its LifecycleOwner started/resumed.

          // The activity's LifecycleOwner gets started/resumed via an activity registered

          // callback added in onCreate(). By adding our own activity registered callback in

          // onActivityPreCreated(), we get our callbacks first while still having the

          // right relative order compared to the Activity's onStart()/onResume() callbacks.

                          activity.registerActivityLifecycleCallbacks(new EmptyActivityLifecycleCallbacks() {

          @Override

          public void onActivityPostStarted(@androidx.annotation.NonNull Activity activity) {

          activityStarted();

                              }

          @Override

          public void onActivityPostResumed(@androidx.annotation.NonNull Activity activity) {

          activityResumed();

                              }

          });

                      }

          @Override

          public void onActivityCreated(Activity activity, Bundle savedInstanceState) {

          // Only use ReportFragment pre API 29 - after that, we can use the

          // onActivityPostStarted and onActivityPostResumed callbacks registered in

          // onActivityPreCreated()

                          if (Build.VERSION.SDK_INT <29) {

          ReportFragment.get(activity).setProcessListener(mInitializationListener);

                          }

          }

          @Override

          public void onActivityPaused(Activity activity) {

          activityPaused();

                      }

          @Override

          public void onActivityStopped(Activity activity) {

          activityStopped();

                      }

          });

              }

          @androidx.annotation.NonNull

          @Override

          public androidx.lifecycle.Lifecycle getLifecycle() {

          return mRegistry;

              }

          }

          /**

          * LifecycleRegistry lifecycle 注册表和调度器  todo  目前接触到了 processlifeCycle  activity  application  就剩下 fragment了  todo:// 这里工具类===>> 还有一个fragment

          * */

          /**

          * An implementation of {@link androidx.lifecycle.Lifecycle} that can handle multiple observers.

          *

          * It is used by Fragments and Support Library Activities. You can also directly use it if you have

          * a custom LifecycleOwner.

          */

          public class LifecycleRegistryextends androidx.lifecycle.Lifecycle {

          /**

          * // removals/additions during traversal.

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

              /**

          * The provider that owns this Lifecycle.

          * Only WeakReference on LifecycleOwner is kept, so if somebody leaks Lifecycle, they won't leak

          * the whole Fragment / Activity. However, to leak Lifecycle object isn't great idea neither,

          * because it keeps strong references on all other listeners, so you'll leak all of them as

          * well.

          */

              private final WeakReference mLifecycleOwner;

              private int mAddingObserverCounter =0;//???

              private boolean mHandlingEvent =false;

              private boolean mNewEventOccurred =false; //有没有新的event?

          //

          // we have to keep it for cases:

          // void onStart() {

          //    mRegistry.removeObserver(this);

          //    mRegistry.add(newObserver);

          // }

          // newObserver should be brought only to CREATED state during the execution of

          // this onStart method. our invariant with mObserverMap doesn't help, because parent observer

          // is no longer in the map.

              private ArrayList mParentStates =new ArrayList<>();

              private final boolean mEnforceMainThread;

              /**

          * Creates a new LifecycleRegistry for the given provider.

              *

              * // 创建的时候注意点

              * You should usually create this inside your LifecycleOwner class's constructor and hold

          * onto the same instance.

          *

              * @param provider The owner LifecycleOwner

          */

              public LifecycleRegistry(@androidx.annotation.NonNull androidx.lifecycle.LifecycleOwner provider) {

          this(provider, true);

              }

          private LifecycleRegistry(@androidx.annotation.NonNull androidx.lifecycle.LifecycleOwner provider, boolean enforceMainThread) {

          mLifecycleOwner =new WeakReference<>(provider);

                  mState = INITIALIZED; // 初始化状态,

                  mEnforceMainThread = enforceMainThread;

              }

          /**

          * Moves the Lifecycle to the given state and dispatches necessary events to the observers.

          *

              * @param state new state

              * @deprecated Use {@link #setCurrentState(State)}.

          */

              @Deprecated

          @MainThread

          public void markState(@androidx.annotation.NonNull State state) {

          enforceMainThreadIfNeeded("markState");

                  setCurrentState(state);

              }

          /**

          * Moves the Lifecycle to the given state and dispatches necessary events to the observers.

          *

              * @param state new state

          */

              @MainThread

          public void setCurrentState(@androidx.annotation.NonNull State state) {

          enforceMainThreadIfNeeded("setCurrentState");

                  moveToState(state);

              }

          /**

          * Sets the current state and notifies the observers.

              *

              * 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(@androidx.annotation.NonNull androidx.lifecycle.Lifecycle.Event event) {

          enforceMainThreadIfNeeded("handleLifecycleEvent");

                  moveToState(event.getTargetState());

              }

          /**

              * 状态变化

              *

          * */

              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;

              }

          /**

              * 当前lifecycleOwner 状态是否下发完毕.......

          * */

              private boolean isSynced() {

          // 没有观察者的时候,

                  if (mObserverMap.size() ==0) {

          return true;

                  }

          // 最早添加的observer

                  State eldestObserverState = mObserverMap.eldest().getValue().mState;

                  State newestObserverState = mObserverMap.newest().getValue().mState;

                  // 后来添加的observer

                  return eldestObserverState == newestObserverState && mState == newestObserverState;

              }

          private State calculateTargetState(androidx.lifecycle.LifecycleObserver observer) {

          // 本次key键值对中之前添加的, 还是链表中之前的那个?????

                  Map.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(@androidx.annotation.NonNull androidx.lifecycle.LifecycleObserver observer) {

          enforceMainThreadIfNeeded("addObserver");

                  State initialState = mState == DESTROYED ? DESTROYED : INITIALIZED;

                  // 新增加的时候,不是 initialized  就是destroyed

                  androidx.lifecycle.LifecycleRegistry.ObserverWithState statefulObserver =new androidx.lifecycle.LifecycleRegistry.ObserverWithState(observer, initialState);

                  androidx.lifecycle.LifecycleRegistry.ObserverWithState previous = mObserverMap.putIfAbsent(observer, statefulObserver);

                  // 已经添加过 不再继续

                  if (previous !=null) {

          return;

                  }

          // 销毁了,不再继续使用

                  androidx.lifecycle.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))) {

          // parent中添加

                      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(@androidx.annotation.NonNull androidx.lifecycle.LifecycleObserver observer) {

          enforceMainThreadIfNeeded("removeObserver");

                  // we consciously decided not to send destruction events here in opposition to addObserver.

          // Our reasons for that:

          // 1. These events haven't yet happened at all. In contrast to events in addObservers, that

          // actually occurred but earlier.

          // 2. There are cases when removeObserver happens as a consequence of some kind of fatal

          // event. If removeObserver method sends destruction events, then a clean up routine becomes

          // more cumbersome. More specific example of that is: your LifecycleObserver listens for

          // a web connection, in the usual routine in OnStop method you report to a server that a

          // session has just ended and you close the connection. Now let's assume now that you

          // lost an internet and as a result you removed this observer. If you get destruction

          // events in removeObserver, you should have a special case in your onStop method that

          // checks if your web connection died and you shouldn't try to report anything to a server.

                  mObserverMap.remove(observer);

              }

          /**

          * The number of observers.

          *

              * @return The number of observers.

          */

              @SuppressWarnings("WeakerAccess")

          public int getObserverCount() {

          enforceMainThreadIfNeeded("getObserverCount");

                  return mObserverMap.size();

              }

          @androidx.annotation.NonNull

          @Override

          public State getCurrentState() {

          return mState;

              }

          //向前传递

              private void forwardPass(androidx.lifecycle.LifecycleOwner lifecycleOwner) {

          Iterator> ascendingIterator =

          mObserverMap.iteratorWithAdditions();

                  while (ascendingIterator.hasNext() && !mNewEventOccurred) {

          Map.Entry entry = ascendingIterator.next();

                      //当前遍历的值

                      //这里不好理解...

                      androidx.lifecycle.LifecycleRegistry.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(androidx.lifecycle.LifecycleOwner lifecycleOwner) {

          Iterator> descendingIterator =

          mObserverMap.descendingIterator();

                  // 最新的observer来进行通知

                  while (descendingIterator.hasNext() && !mNewEventOccurred) {

          Map.Entry entry = descendingIterator.next();

                      androidx.lifecycle.LifecycleRegistry.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();

                      }

          }

          }

          // happens only on the top of stack (never in reentrance),

          // so it doesn't have to take in account parents

          //

              private void sync() {

          //

                  androidx.lifecycle.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.");

                  }

          //如果有observer没有完成同步

                  while (!isSynced()) {

          mNewEventOccurred =false;

                      // no need to check eldest for nullability, because isSynced does it for us.

                      // 当前的状态如果比最初的状态还要小

                      // 之前observer里面状态还没有同步过来, 就是还没下发 ==>> 需要进行下发

                      if (mState.compareTo(mObserverMap.eldest().getValue().mState) <0) {

          backwardPass(lifecycleOwner);

                      }

          Map.Entry 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");

                      }

          }

          }

          /**

          * Creates a new LifecycleRegistry for the given provider, that doesn't check

          * that its methods are called on the threads other than main.

              *

              *

              *    // 这里是说非同步,外部方法要保持同步

              * LifecycleRegistry is not synchronized: if multiple threads access this {@code

              * LifecycleRegistry}, it must be synchronized externally.

              *

              * Another possible use-case for this method is JVM testing, when main thread is not present.

          */

              @VisibleForTesting

          @androidx.annotation.NonNull

          public static androidx.lifecycle.LifecycleRegistry createUnsafe(@androidx.annotation.NonNull androidx.lifecycle.LifecycleOwner owner) {

          return new androidx.lifecycle.LifecycleRegistry(owner, false);

              }

          static State min(@androidx.annotation.NonNull State state1, @androidx.annotation.Nullable State state2) {

          return state2 !=null && state2.compareTo(state1) <0 ? state2 : state1;

              }

          /**

              * 有之前状态的一个observer

          * */

              static class ObserverWithState {

          State mState;

                  androidx.lifecycle.LifecycleEventObserver mLifecycleObserver;

                  ObserverWithState(androidx.lifecycle.LifecycleObserver observer, State initialState) {

          mLifecycleObserver = androidx.lifecycle.Lifecycling.lifecycleEventObserver(observer);

                      mState = initialState;

                  }

          void dispatchEvent(androidx.lifecycle.LifecycleOwner owner, Event event) {

          // 当前代表的状态

                      State newState = event.getTargetState();

                      // 最小的状态

                      mState = min(mState, newState);

                      // 分发

                      mLifecycleObserver.onStateChanged(owner, event);

                      // 更替state状态

                      mState = newState;

                  }

          }

          }

          /// 这里有一个原则 : 后添加的观察者的状态必须不大于之前添加的观察者的状态。

          /**

          *  LinkedList 来进行数据的保存.

          * */

          public class SafeIterableMapimplements Iterable> {

          @SuppressWarnings("WeakerAccess")/* synthetic access */

                      androidx.arch.core.internal.SafeIterableMap.Entry mStart;  //最早添加的

              private androidx.arch.core.internal.SafeIterableMap.Entry mEnd;    //最近添加的

              // using WeakHashMap over List, so we don't have to manually remove

          // WeakReferences that have null in them.

              private WeakHashMap, Boolean> mIterators =new WeakHashMap<>();

              private int mSize =0;

              // 从最早添加的一个对象向后遍历,然后找到相同的key就添加.

              protected androidx.arch.core.internal.SafeIterableMap.Entry get(K k) {

          androidx.arch.core.internal.SafeIterableMap.Entry currentNode = mStart;

                  while (currentNode !=null) {

          if (currentNode.mKey.equals(k)) {

          break;

                      }

          currentNode = currentNode.mNext;

                  }

          return currentNode;

              }

          /**

          * If the specified key is not already associated

          * with a value, associates it with the given value.

          *

              * @param key key with which the specified value is to be associated

              * @param v  value to be associated with the specified key

              * @return the previous value associated with the specified key,

              * or {@code null} if there was no mapping for the key

          */

              public V putIfAbsent(@androidx.annotation.NonNull K key, @androidx.annotation.NonNull V v) {

          androidx.arch.core.internal.SafeIterableMap.Entry entry = get(key);

                  if (entry !=null) {

          return entry.mValue;

                  }

          put(key, v);

          return null;

              }

          /**

              * LinkedList 来进行数据的保存.

          * */

              protected androidx.arch.core.internal.SafeIterableMap.Entry put(@androidx.annotation.NonNull K key, @androidx.annotation.NonNull V v) {

          androidx.arch.core.internal.SafeIterableMap.Entry newEntry =new androidx.arch.core.internal.SafeIterableMap.Entry<>(key, v);

                  mSize++;

                  // 最近没有添加.进行更新

                  if (mEnd ==null) {

          mStart = newEntry;

                      mEnd = mStart;

                      return newEntry;

                  }

          /**

                  * 1.几个节点的前后指代都更新过来

                  * */

                  mEnd.mNext = newEntry;

                  newEntry.mPrevious = mEnd;

                  mEnd = newEntry;

                  return newEntry;

              }

          /**

          * Removes the mapping for a key from this map if it is present.

          *

              * @param key key whose mapping is to be removed from the map

              * @return the previous value associated with the specified key,

              * or {@code null} if there was no mapping for the key

          */

              public V remove(@androidx.annotation.NonNull K key) {

          // 索性,map里面的entry也看一下呗;

                  androidx.arch.core.internal.SafeIterableMap.Entry toRemove = get(key);

                  if (toRemove ==null) {

          return null;

                  }

          mSize--;

                  // 这里链表部分不太明白

                  if (!mIterators.isEmpty()) {

          for (androidx.arch.core.internal.SafeIterableMap.SupportRemove iter : mIterators.keySet()) {

          iter.supportRemove(toRemove);

                      }

          }

          // 这里就是对双向链表移除一个节点的算法... 简单

                  if (toRemove.mPrevious !=null) {

          toRemove.mPrevious.mNext = toRemove.mNext;

                  }else {

          mStart = toRemove.mNext;

                  }

          if (toRemove.mNext !=null) {

          toRemove.mNext.mPrevious = toRemove.mPrevious;

                  }else {

          mEnd = toRemove.mPrevious;

                  }

          toRemove.mNext =null;

                  toRemove.mPrevious =null;

                  return toRemove.mValue;

              }

          /**

              * @return the number of elements in this map

          */

              public int size() {

          return mSize;

              }

          /**

              * @return an ascending iterator, which doesn't include new elements added during an

          * iteration.

          */

              @androidx.annotation.NonNull

          @Override

          public Iterator> iterator() {

          androidx.arch.core.internal.SafeIterableMap.ListIterator iterator =new androidx.arch.core.internal.SafeIterableMap.AscendingIterator<>(mStart, mEnd);

                  mIterators.put(iterator, false);

                  return iterator;

              }

          /**

              * @return an descending iterator, which doesn't include new elements added during an

          * iteration.

          */

              public Iterator> descendingIterator() {

          androidx.arch.core.internal.SafeIterableMap.DescendingIterator iterator =new androidx.arch.core.internal.SafeIterableMap.DescendingIterator<>(mEnd, mStart);

                  mIterators.put(iterator, false);

                  return iterator;

              }

          /**

          * return an iterator with additions.

          */

              public androidx.arch.core.internal.SafeIterableMap.IteratorWithAdditions iteratorWithAdditions() {

          @SuppressWarnings("unchecked")

          androidx.arch.core.internal.SafeIterableMap.IteratorWithAdditions iterator =new androidx.arch.core.internal.SafeIterableMap.IteratorWithAdditions();

                  mIterators.put(iterator, false);

                  return iterator;

              }

          /**

              * @return eldest added entry or null

          */

              public Map.Entry eldest() {

          return mStart;

              }

          /**

              * @return newest added entry or null

          */

              public Map.Entry newest() {

          return mEnd;

              }

          @Override

          public boolean equals(Object obj) {

          if (obj ==this) {

          return true;

                  }

          if (!(objinstanceof androidx.arch.core.internal.SafeIterableMap)) {

          return false;

                  }

          androidx.arch.core.internal.SafeIterableMap map = (androidx.arch.core.internal.SafeIterableMap) obj;

                  if (this.size() != map.size()) {

          return false;

                  }

          Iterator> iterator1 = iterator();

                  Iterator iterator2 = map.iterator();

                  while (iterator1.hasNext() && iterator2.hasNext()) {

          Map.Entry next1 = iterator1.next();

                      Object next2 = iterator2.next();

                      if ((next1 ==null && next2 !=null)

          || (next1 !=null && !next1.equals(next2))) {

          return false;

                      }

          }

          return !iterator1.hasNext() && !iterator2.hasNext();

              }

          @Override

          public int hashCode() {

          int h =0;

                  Iterator> i = iterator();

                  while (i.hasNext()) {

          h += i.next().hashCode();

                  }

          return h;

              }

          @Override

          public String toString() {

          StringBuilder builder =new StringBuilder();

                  builder.append("[");

                  Iterator> iterator = iterator();

                  while (iterator.hasNext()) {

          builder.append(iterator.next().toString());

                      if (iterator.hasNext()) {

          builder.append(", ");

                      }

          }

          builder.append("]");

                  return builder.toString();

              }

          private abstract static class ListIteratorimplements Iterator>,

                      androidx.arch.core.internal.SafeIterableMap.SupportRemove {

          androidx.arch.core.internal.SafeIterableMap.Entry mExpectedEnd;

                  androidx.arch.core.internal.SafeIterableMap.Entry mNext;

                  ListIterator(androidx.arch.core.internal.SafeIterableMap.Entry start, androidx.arch.core.internal.SafeIterableMap.Entry expectedEnd) {

          this.mExpectedEnd = expectedEnd;

                      this.mNext = start;

                  }

          @Override

          public boolean hasNext() {

          return mNext !=null;

                  }

          @SuppressWarnings("ReferenceEquality")

          @Override

          public void supportRemove(@androidx.annotation.NonNull androidx.arch.core.internal.SafeIterableMap.Entry entry) {

          if (mExpectedEnd == entry && entry == mNext) {

          mNext =null;

                          mExpectedEnd =null;

                      }

          if (mExpectedEnd == entry) {

          mExpectedEnd = backward(mExpectedEnd);

                      }

          if (mNext == entry) {

          mNext = nextNode();

                      }

          }

          @SuppressWarnings("ReferenceEquality")

          private androidx.arch.core.internal.SafeIterableMap.Entry nextNode() {

          if (mNext == mExpectedEnd || mExpectedEnd ==null) {

          return null;

                      }

          return forward(mNext);

                  }

          @Override

          public Map.Entry next() {

          Map.Entry result = mNext;

                      mNext = nextNode();

                      return result;

                  }

          abstract androidx.arch.core.internal.SafeIterableMap.Entry forward(androidx.arch.core.internal.SafeIterableMap.Entry entry);

                  abstract androidx.arch.core.internal.SafeIterableMap.Entry backward(androidx.arch.core.internal.SafeIterableMap.Entry entry);

              }

          static class AscendingIteratorextends androidx.arch.core.internal.SafeIterableMap.ListIterator {

          AscendingIterator(androidx.arch.core.internal.SafeIterableMap.Entry start, androidx.arch.core.internal.SafeIterableMap.Entry expectedEnd) {

          super(start, expectedEnd);

                  }

          @Override

          androidx.arch.core.internal.SafeIterableMap.Entry forward(androidx.arch.core.internal.SafeIterableMap.Entry entry) {

          return entry.mNext;

                  }

          @Override

          androidx.arch.core.internal.SafeIterableMap.Entry backward(androidx.arch.core.internal.SafeIterableMap.Entry entry) {

          return entry.mPrevious;

                  }

          }

          private static class DescendingIteratorextends androidx.arch.core.internal.SafeIterableMap.ListIterator {

          DescendingIterator(androidx.arch.core.internal.SafeIterableMap.Entry start, androidx.arch.core.internal.SafeIterableMap.Entry expectedEnd) {

          super(start, expectedEnd);

                  }

          @Override

          androidx.arch.core.internal.SafeIterableMap.Entry forward(androidx.arch.core.internal.SafeIterableMap.Entry entry) {

          return entry.mPrevious;

                  }

          @Override

          androidx.arch.core.internal.SafeIterableMap.Entry backward(androidx.arch.core.internal.SafeIterableMap.Entry entry) {

          return entry.mNext;

                  }

          }

          private class IteratorWithAdditionsimplements Iterator>, androidx.arch.core.internal.SafeIterableMap.SupportRemove {

          private androidx.arch.core.internal.SafeIterableMap.Entry mCurrent;

                  private boolean mBeforeStart =true;

                  IteratorWithAdditions() {

          }

          @SuppressWarnings("ReferenceEquality")

          @Override

          public void supportRemove(@androidx.annotation.NonNull androidx.arch.core.internal.SafeIterableMap.Entry entry) {

          if (entry == mCurrent) {

          mCurrent = mCurrent.mPrevious;

                          mBeforeStart = mCurrent ==null;

                      }

          }

          @Override

          public boolean hasNext() {

          if (mBeforeStart) {

          return mStart !=null;

                      }

          return mCurrent !=null && mCurrent.mNext !=null;

                  }

          @Override

          public Map.Entry next() {

          if (mBeforeStart) {

          mBeforeStart =false;

                          mCurrent = mStart;

                      }else {

          mCurrent = mCurrent !=null ? mCurrent.mNext :null;

                      }

          return mCurrent;

                  }

          }

          interface SupportRemove {

          void supportRemove(@androidx.annotation.NonNull androidx.arch.core.internal.SafeIterableMap.Entry entry);

              }

          // 这里维护了 双向链表的一个节点;

              // 上面的使用就是  mStart  mEnd  头部 和尾部LinkedHasMap ==>>

              static class Entryimplements Map.Entry {

          @androidx.annotation.NonNull

          final K mKey;

                  @androidx.annotation.NonNull

          final V mValue;

                  androidx.arch.core.internal.SafeIterableMap.Entry mNext;

                  androidx.arch.core.internal.SafeIterableMap.Entry mPrevious;

                  Entry(@androidx.annotation.NonNull K key, @androidx.annotation.NonNull V value) {

          mKey = key;

                      this.mValue = value;

                  }

          @androidx.annotation.NonNull

          @Override

          public K getKey() {

          return mKey;

                  }

          @androidx.annotation.NonNull

          @Override

          public V getValue() {

          return mValue;

                  }

          @Override

          public V setValue(V value) {

          throw new UnsupportedOperationException("An entry modification is not supported");

                  }

          @Override

          public String toString() {

          return mKey +"=" + mValue;

                  }

          @SuppressWarnings("ReferenceEquality")

          @Override

          public boolean equals(Object obj) {

          if (obj ==this) {

          return true;

                      }

          if (!(objinstanceof androidx.arch.core.internal.SafeIterableMap.Entry)) {

          return false;

                      }

          androidx.arch.core.internal.SafeIterableMap.Entry entry = (androidx.arch.core.internal.SafeIterableMap.Entry) obj;

                      return mKey.equals(entry.mKey) && mValue.equals(entry.mValue);

                  }

          @Override

          public int hashCode() {

          return mKey.hashCode() ^ mValue.hashCode();

                  }

          }

          }

          /**

          * FastSafeIterableMap  基于linkedList的结构,又增加了一个hasmap的数据结构.

          * */

          /**

          * Poor's man LinkedHashMap, which supports modifications during iterations.

          * Takes more memory that {@link androidx.arch.core.internal.SafeIterableMap}

          * It is NOT thread safe.

          *

          * @param Key type

          * @param Value type

          * @hide

          */

          @RestrictTo(RestrictTo.Scope.LIBRARY_GROUP_PREFIX)

          public class FastSafeIterableMapextends androidx.arch.core.internal.SafeIterableMap {

          private HashMap> mHashMap =new HashMap<>();

              @Override

          protected Entry get(K k) {

          return mHashMap.get(k);

              }

          @Override

          public V putIfAbsent(@androidx.annotation.NonNull K key, @androidx.annotation.NonNull V v) {

          Entry current = get(key);

                  if (current !=null) {

          return current.mValue;

                  }

          mHashMap.put(key, put(key, v));

          return null;

              }

          @Override

          public V remove(@androidx.annotation.NonNull K key) {

          V removed =super.remove(key);

                  mHashMap.remove(key);

                  return removed;

              }

          /**

              * Returns {@code true} if this map contains a mapping for the specified

          * key.

          */

              public boolean contains(K key) {

          return mHashMap.containsKey(key);

              }

          /**

          * Return an entry added to prior to an entry associated with the given key.

          *

              * @param k the key

          */

              public Map.Entry ceil(K k) {

          if (contains(k)) {

          return mHashMap.get(k).mPrevious;

                  }

          return null;

              }

          }

          ©著作权归作者所有,转载或内容合作请联系作者
          【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
          平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

          相关阅读更多精彩内容

          友情链接更多精彩内容