Lifecycler详解

129 阅读5分钟

1.使用

Acitivty或者Fragment里面调用getLifecycle().addObserver(MyObserver())

//这些注解已经过时
class MyObserver : LifecycleObserver {
     
    @OnLifecycleEvent(Lifecycle.Event.ON_CREATE)
    fun onCreate() {}

    @OnLifecycleEvent(Lifecycle.Event.ON_START)
    fun onStart() {}

    @OnLifecycleEvent(Lifecycle.Event.ON_RESUME)
    fun onResume() {}

    @OnLifecycleEvent(Lifecycle.Event.ON_PAUSE)
    fun onPause() {}

    @OnLifecycleEvent(Lifecycle.Event.ON_STOP)
    fun onStop() {}

    @OnLifecycleEvent(Lifecycle.Event.ON_DESTROY)
    fun onDestroy() {}
}

最新的使用

public interface DefaultLifecycleObserver extends FullLifecycleObserver {

    //在onCreate之后调用
    @Override
    default void onCreate(@NonNull LifecycleOwner owner) {
    }

    //在onStart之后调用
    @Override
    default void onStart(@NonNull LifecycleOwner owner) {
    }

    //在onResume之后调用
    @Override
    default void onResume(@NonNull LifecycleOwner owner) {
    }

    //在onPause之前调用
    @Override
    default void onPause(@NonNull LifecycleOwner owner) {
    }

    //onStop
    @Override
    default void onStop(@NonNull LifecycleOwner owner) {
    }

    //onDestroy
    @Override
    default void onDestroy(@NonNull LifecycleOwner owner) {
    }
}

或者

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

2.源码解析

activity和fragment内通过

androidx.fragment.app.Fragment

androidx.activity.ComponentActivity

这两个类中的

    public Lifecycle getLifecycle() {
        return mLifecycleRegistry;
    }

获取mLifecycleRegistry。


//activity内

    private LifecycleRegistry mLifecycleRegistry = new LifecycleRegistry(this);

//fragment里面

    private void initLifecycle() {
        mLifecycleRegistry = new LifecycleRegistry(this);
//继承关系
自己的MainActivity

androidx.appcompat.app.AppCompatActivity

androidx.fragment.app.FragmentActivity

androidx.activity.ComponentActivity

androidx.core.app.ComponentActivity

android.app.Activity

ComponentActivity的onCreate里面 调用

ReportFragment.injectIfNeededIn(this);

可以看到往activity里面添加了一个无界面的ReportFragment

public static void injectIfNeededIn(Activity activity) {
  ...
    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();
    }
}

ReportFragment 的生命周期

@Override
public void onStart() {
    super.onStart();
    dispatchStart(mProcessListener);
    dispatch(Lifecycle.Event.ON_START);
}

@Override
public void onResume() {
    super.onResume();
    dispatchResume(mProcessListener);
    dispatch(Lifecycle.Event.ON_RESUME);
}

@Override
public void onPause() {
    super.onPause();
    dispatch(Lifecycle.Event.ON_PAUSE);
}

@Override
public void onStop() {
    super.onStop();
    dispatch(Lifecycle.Event.ON_STOP);
}

@Override
public void onDestroy() {
    super.onDestroy();
    dispatch(Lifecycle.Event.ON_DESTROY);
    // just want to be sure that we won't leak reference to an activity
    mProcessListener = null;
}

@SuppressWarnings("deprecation")
static void dispatch(@NonNull Activity activity, @NonNull Lifecycle.Event event) {
    if (activity instanceof LifecycleRegistryOwner) {
        ((LifecycleRegistryOwner) activity).getLifecycle().handleLifecycleEvent(event);
        return;
    }

    if (activity instanceof LifecycleOwner) {
        Lifecycle lifecycle = ((LifecycleOwner) activity).getLifecycle();
        if (lifecycle instanceof LifecycleRegistry) {
            ((LifecycleRegistry) lifecycle).handleLifecycleEvent(event);
        }
    }
}

上面调用了LifecycleRegistry的 handleLifecycleEvent

    public void handleLifecycleEvent(@NonNull Lifecycle.Event event) {
        enforceMainThreadIfNeeded("handleLifecycleEvent");
        moveToState(event.getTargetState());
    }

可以看到最后调用了moveToState,就跟FragmentActivity 的 onCreate方法里面调用handleLifecycleEvent后也调用了moveToState一样

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      mFragmentLifecycleRegistry.handleLifecycleEvent(Lifecycle.Event.ON_CREATE);
      mFragments.dispatchCreate();
    }
     

    public void handleLifecycleEvent(@NonNull Lifecycle.Event event) {
     enforceMainThreadIfNeeded("handleLifecycleEvent");
     moveToState(event.getTargetState());
    }

mState就是一个状态机


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

不管是backwardPass或者forwardPass都调用


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

observer是 LifecycleRegistry

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

onstateChanged有很多实现

image.png

看ComponentActivity 的构造函数

public ComponentActivity() {
   ......
    Lifecycle lifecycle = this.getLifecycle();
    if (lifecycle == null) {
        throw new IllegalStateException("getLifecycle() returned null in ComponentActivity's constructor. Please make sure you are lazily constructing your Lifecycle in the first call to getLifecycle() rather than relying on field initialization.");
    } else {
        if (VERSION.SDK_INT >= 19) {
            this.getLifecycle().addObserver(new LifecycleEventObserver() {
                public void onStateChanged(@NonNull LifecycleOwner source, @NonNull Lifecycle.Event event) {
                    if (event == Event.ON_STOP) {
                        Window window = ComponentActivity.this.getWindow();
                        View decor = window != null ? window.peekDecorView() : null;
                        if (decor != null) {
                            ComponentActivity.Api19Impl.cancelPendingInputEvents(decor);
                        }
                    }

                }
            });
        }

        this.getLifecycle().addObserver(new LifecycleEventObserver() {
            public void onStateChanged(@NonNull LifecycleOwner source, @NonNull Lifecycle.Event event) {
                if (event == Event.ON_DESTROY) {
                    ComponentActivity.this.mContextAwareHelper.clearAvailableContext();
                    if (!ComponentActivity.this.isChangingConfigurations()) {
                        ComponentActivity.this.getViewModelStore().clear();
                    }
                }

            }
        });
        this.getLifecycle().addObserver(new LifecycleEventObserver() {
            public void onStateChanged(@NonNull LifecycleOwner source, @NonNull Lifecycle.Event event) {
                ComponentActivity.this.ensureViewModelStore();
                ComponentActivity.this.getLifecycle().removeObserver(this);
            }
        });
       ....
    }
}

addObserver方法

ObserverWithState statefulObserver = new ObserverWithState(observer, initialState);
ObserverWithState(LifecycleObserver observer, State initialState) {
    mLifecycleObserver = Lifecycling.lifecycleEventObserver(observer);
    mState = initialState;
}
@SuppressWarnings("deprecation")
static LifecycleEventObserver lifecycleEventObserver(Object object) {
    boolean isLifecycleEventObserver = object instanceof LifecycleEventObserver;
    boolean isFullLifecycleObserver = object instanceof FullLifecycleObserver;
    if (isLifecycleEventObserver && isFullLifecycleObserver) {
        return new FullLifecycleObserverAdapter((FullLifecycleObserver) object,
                (LifecycleEventObserver) object);
    }
    if (isFullLifecycleObserver) {
        return new FullLifecycleObserverAdapter((FullLifecycleObserver) object, null);
    }

    if (isLifecycleEventObserver) {
        return (LifecycleEventObserver) object;
    }

    final Class<?> klass = object.getClass();
    int type = getObserverConstructorType(klass);
    if (type == GENERATED_CALLBACK) {
        List<Constructor<? extends GeneratedAdapter>> constructors =
                sClassToAdapters.get(klass);
        if (constructors.size() == 1) {
            GeneratedAdapter generatedAdapter = createGeneratedAdapter(
                    constructors.get(0), object);
            return new SingleGeneratedAdapterObserver(generatedAdapter);
        }
        GeneratedAdapter[] adapters = new GeneratedAdapter[constructors.size()];
        for (int i = 0; i < constructors.size(); i++) {
            adapters[i] = createGeneratedAdapter(constructors.get(i), object);
        }
        return new CompositeGeneratedAdaptersObserver(adapters);
    }
    return new ReflectiveGenericLifecycleObserver(object);
}

这些return的就是保存了Observer的方法,比如我们看 ReflectiveGenericLifecycleObserver(object);

ReflectiveGenericLifecycleObserver(Object wrapped) {
    mWrapped = wrapped;
    mInfo = ClassesInfoCache.sInstance.getInfo(mWrapped.getClass());
}

实际上就是把有注解的方法都加进来

private CallbackInfo createInfo(Class<?> klass, @Nullable Method[] declaredMethods) {
    Class<?> superclass = klass.getSuperclass();
    Map<MethodReference, Lifecycle.Event> handlerToEvent = new HashMap<>();
    if (superclass != null) {
        CallbackInfo superInfo = getInfo(superclass);
        if (superInfo != null) {
            handlerToEvent.putAll(superInfo.mHandlerToEvent);
        }
    }

    Class<?>[] interfaces = klass.getInterfaces();
    for (Class<?> intrfc : interfaces) {
        for (Map.Entry<MethodReference, Lifecycle.Event> entry : getInfo(
                intrfc).mHandlerToEvent.entrySet()) {
            verifyAndPutHandler(handlerToEvent, entry.getKey(), entry.getValue(), klass);
        }
    }

//把观察者有注解的方法都加进来
    Method[] methods = declaredMethods != null ? declaredMethods : getDeclaredMethods(klass);
    boolean hasLifecycleMethods = false;
    for (Method method : methods) {
        OnLifecycleEvent annotation = method.getAnnotation(OnLifecycleEvent.class);
        if (annotation == null) {
            continue;
        }
        hasLifecycleMethods = true;
        Class<?>[] params = method.getParameterTypes();
        int callType = CALL_TYPE_NO_ARG;
        if (params.length > 0) {
            callType = CALL_TYPE_PROVIDER;
            if (!params[0].isAssignableFrom(LifecycleOwner.class)) {
                throw new IllegalArgumentException(
                        "invalid parameter type. Must be one and instanceof LifecycleOwner");
            }
        }
        Lifecycle.Event event = annotation.value();

        if (params.length > 1) {
            callType = CALL_TYPE_PROVIDER_WITH_EVENT;
            if (!params[1].isAssignableFrom(Lifecycle.Event.class)) {
                throw new IllegalArgumentException(
                        "invalid parameter type. second arg must be an event");
            }
            if (event != Lifecycle.Event.ON_ANY) {
                throw new IllegalArgumentException(
                        "Second arg is supported only for ON_ANY value");
            }
        }
        if (params.length > 2) {
            throw new IllegalArgumentException("cannot have more than 2 params");
        }
        MethodReference methodReference = new MethodReference(callType, method);
        verifyAndPutHandler(handlerToEvent, methodReference, event, klass);
    }
    CallbackInfo info = new CallbackInfo(handlerToEvent);
    mCallbackMap.put(klass, info);
    mHasLifecycleMethods.put(klass, hasLifecycleMethods);
    return info;
}

我们回到状态机 Lifecycle.java里面定义的

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;
    }
}
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) {
            case CREATED:
                return ON_DESTROY;
            case STARTED:
                return ON_STOP;
            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) {
            case DESTROYED:
                return ON_DESTROY;
            case CREATED:
                return ON_STOP;
            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) {
            case INITIALIZED:
                return ON_CREATE;
            case CREATED:
                return ON_START;
            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) {
            case CREATED:
                return ON_CREATE;
            case STARTED:
                return ON_START;
            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");
    }
}

根据顺序和状态机,找到state对应的event然后分发给Observer

image.png

image.png

3.全部流程

activity在创建的时候会被add进一个空白的fragment,而activity的生命周期发生变化的时候,fragment的生命周期也会发生变化,在fragment的相关生命周期方法中会dispatch对应的event,event与state又有着某种关系。而event中对应的state与mState不一致时,会根据event参数通过反射去执行lifecyclerobserver里面的方法。