Android——Lifecycle

重学Android——Lifecycle

image-20210513210136922

首先我们先对Lifecycle有个总体的认识

lifecycleObserver通过直接注册观察Lifecycleowner,当lifecycleowner对象生命周期发生变化的时候就可以直接通知observer,Activity以及Fragment都实现了LifecycleOwner接口。这样我们的生命周期相关的回调就可以不用全都写在Activity 或者Fragment的生命周期方法里边,避免代码过度耦合。

我们来深入了解Lifecycle

image-20210513210745122

其中Event,以及State都是枚举类

我们来看一下 Event中定义了啥

ON_CREATE	ON_START	ON_RESUME	ON_PAUSE	ON_STOP		ON_DESTROY		ON_ANY

一共七种事件类型

我们在来看一下State的内容

   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 Owner

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

Activity继承自ComponentActivity 这个Activity实现了LifecycleOwner接口,具体实现如下

public class ComponentActivity implements LifecycleOwner{
private final LifecycleRegistry mLifecycleRegistry = new LifecycleRegistry(this);

   	@NonNull
    @Override
    public Lifecycle getLifecycle() {
        return mLifecycleRegistry;
    }
      @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mSavedStateRegistryController.performRestore(savedInstanceState);
        ReportFragment.injectIfNeededIn(this);
        if (mContentLayoutId != 0) {
            setContentView(mContentLayoutId);
        }
    }
}
public class LifecycleRegistry extends Lifecycle{
  public LifecycleRegistry(@NonNull LifecycleOwner provider) {
        mLifecycleOwner = new WeakReference<>(provider);
        mState = INITIALIZED;
    }
}

actiivity怎么把生命周期传递出去

在调用onCreate方法的时候 调用了该方法ReportFragment.injectIfNeededIn(this),在该方法中会将这个reportFragment附在activity上边这样fragment就可以感知生命周期的变化。 并通过调用它自己的dispatch(),该方法又调用LifecycleRegistry里的sync方法并遍历观察者转告通知。fragment是直接在performStart()等方法中直接遍历传递观察者生命周期事件。

类似于以下示例代码 ↓:

void performStop() {
        mChildFragmentManager.dispatchStop();
        if (mView != null) {
            mViewLifecycleOwner.handleLifecycleEvent(Lifecycle.Event.ON_STOP);
        }
        mLifecycleRegistry.handleLifecycleEvent(Lifecycle.Event.ON_STOP);
        mState = ACTIVITY_CREATED;
        mCalled = false;
        onStop();
        if (!mCalled) {
            throw new SuperNotCalledException("Fragment " + this
                    + " did not call through to super.onStop()");
        }
    }
原文地址:https://www.cnblogs.com/FCY-LearningNotes/p/14799808.html