Lifecycler的源码分析

768 阅读5分钟

「这是我参与2022首次更文挑战的第1天,活动详情查看:2022首次更文挑战」。

前言

Lifecycle的目的:解决对于Activity中关于生命周期方法使用的耦合问题。

正文

1. Lifecycle的使用

过去的方法:写一个接口,在这个接口中定义耦合在生命周期中的相关方法,通过让Activity持有实现这个接口的类的对象,来将这部分代码抽离出Activity,体现单一职责原则。

缺点:

  1. 接口和Activity耦合严重。(每个Activity都必须持有该接口对象。)
  2. 容易产生内存泄漏问题(忘记释放内存:x=null。)

注意:内存泄漏的本质就是使用了内存,但是之后并没有释放。一旦接口对象x没有在onDeatory()调用之前没有x=null。那么就非常容易产生内存泄漏。

注意:null对象在堆中会被java的垃圾回收机制回收。

根据上面两个注意。我们使用其他的类对象作为全局对象的时候,最好在onDestroy()中设置x=null,将内存释放。

JetPack的方法 : Lifecycle。

基本思路原理:把Activity和Fragment 当作被观察者,把使用Lifecycle的当作观察者,再通过A/F 的生命周期通知Lifecycle即可。

优点:

  1. 不会产生内存泄漏。

使用

第一步,Activity和Fragment 继承LifecycleOwner ,就是被观察者。AppCompatActivity 的超类已经实现了这个接口。

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

第二步,任何类实现LifecycleObserver即可,就是观察者。

2.4.0版本之后,已经淘汰了使用注解OnLifecycleEvent。现在实现LifecycleEventObserver和DefaultLifecycleObserver任意一个接口。

第三步,将观察者和被观察者进行绑定。

getLifecycle().addObserver(observer);

2. Lifecycle的实现原理

1.addObserver() - 初始化

分析这部分的关键源码,addObserver()是Lifecycle里面的抽象方法,被LifecycleRegistry的同名方法给实现。LifecycleRegistry是抽象类Lifecycle的继承类。

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

根据上述代码可知,mObserverMap是一个保存LifecycleObserver观察者对象的Map。负责保存该被观察者当前所有的观察者。

//LifecycleRegistry
ObserverWithState statefulObserver = new ObserverWithState(observer, initialState);
//static class ObserverWithState(在LifecycleRegistry中)
ObserverWithState(LifecycleObserver observer, State initialState) {
    mLifecycleObserver = Lifecycling.lifecycleEventObserver(observer);
    mState = initialState;
}
//Lifecycling
return new ReflectiveGenericLifecycleObserver(object);

根据上述代码可知,我们在Lifecycle的实现类LifecycleRegistry中使用 内部类ObserverWithState对于观察者进行处理,最终通过Lifecycling得到通过反射后重新生成的新的mLifecycleObserver。这是为了使用到注解里面的内容。

//ReflectiveGenericLifecycleObserver(implements LifecycleEventObserver)
ReflectiveGenericLifecycleObserver(Object wrapped) {
    mWrapped = wrapped;
    mInfo = ClassesInfoCache.sInstance.getInfo(mWrapped.getClass());
}
//CallbackInfoCache
CallbackInfo getInfo(Class<?> klass) {
    CallbackInfo existing = mCallbackMap.get(klass);
    if (existing != null) {
        return existing;
    }
    existing = createInfo(klass, null);
    return existing;
}
//private CallbackInfo createInfo(Class<?> klass, @Nullable Method[] declaredMethods) (在CallbackInfoCache)
Method[] methods = declaredMethods != null ? declaredMethods : getDeclaredMethods(klass);
//得到class中的方法数组
private Method[] getDeclaredMethods(Class<?> klass) {
    try {
        return klass.getDeclaredMethods();
    } catch (NoClassDefFoundError e) {
        throw new IllegalArgumentException("The observer class has some methods that use "
                                           + "newer APIs which are not available in the current OS version. Lifecycles "
                                           + "cannot access even other methods so you should make sure that your "
                                           + "observer classes only access framework classes that are available "
                                           + "in your min API level OR use lifecycle:compiler annotation processor.", e);
    }
}
//遍历methods数组,从方法中拿到对应方法上的注释。
for (Method method : methods) {
    OnLifecycleEvent annotation = method.getAnnotation(OnLifecycleEvent.class);
    if (annotation == null) {
        continue;
    }
}
//得到方法中的形参数组
Class<?>[] params = method.getParameterTypes();
//
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");
}

此时,mWrapped就是从外面传递进来的LifecycleObserver对象。methods 数组里面装的是LifecycleObserver实现类的所有方法。遍历methods数组,从方法中拿到对应方法上的注释。如果没有被OnLifecycleEvent.class注释所标记。就跳过这个方法。之后拿到方法中的形参数组。

之后的条件判断就是对于不同参数个数进行不同的判断。

一个参数:参数必须是LifecycleOwner的实例。

两个参数:参数必须是LifecycleOwner 和 Lifecycle.Event 对象。

三个参数:抛出异常,不能超过三个参数。

CallbackInfo info = new CallbackInfo(handlerToEvent);
Map<MethodReference, Lifecycle.Event> handlerToEvent = new HashMap<>();

最后,将保存了方法反射内容和注解信息的handlerToEvent保存到info中,返回给mInfo即可。初始化进行到这一步就已经基本完成了。

此时,基本的业务流程是:观察者模式的被观察者订阅观察者。在订阅方法中进行对于观察者的操作。主要是mObserverMap保存当前的所有观察者。已经拿到当前的观察者进行反射,拿到注解信息。将反射得到的方法和注解保存到mInfo。这样初始化就完成了。

addObserver()的大致过程:

addObserver()的大致过程.png 补充:2.4.0版本之后,进行了初始化中的修改。

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

根据上述代码,当观察者通过实现LifecycleEventObserver、FullLifecycleObserver(DefaultLifecycleObserver extends FullLifecycleObserver)或者两者的共同子类来实现的时候。我们可以直接返回向下转型的结果,得到对应的观察者对象。不再需要通过反射来获得。

2.关联生命周期的源码分析

第一部分关于addObserver()的源码分析明确讲述了观察者模式的构建过程。但是还有一个问题没有解决,那就是到底是通过什么方式得到的关于当前Activity的生命周期回调。

我们已知AppCompatActivity 的超类ComponentActivity实现了LifecycleOwner接口。这是为了完成观察者模式的构建。

我们找到ComponentActivity类的onCreate方法。可以看到如下一行代码。

ReportFragment.injectIfNeededIn(this);

顺藤摸瓜,我们可以得到关联生命周期的基本逻辑。

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

在这个方法中我们就能得到关联生命周期的两套基本逻辑:通过Application的LifecycleCallbacks接口或者通过ReportFragment来执行。

下面我们分别梳理一下。首先来梳理一下API<29(Android 10) 之前,通过ReportFragment来执行的这一套方案。

基于下图,我们可知A和F的对应关系,在A的生命周期变化的时候,会自动变化F的生命周期。

A和F生命周期对应图.webp

查看ReportFragment的生命周期代码

@Override
public void onActivityCreated(Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);
    dispatchCreate(mProcessListener);
    dispatch(Lifecycle.Event.ON_CREATE);
}
​
@Override
public void onStart() {
    super.onStart();
    dispatchStart(mProcessListener);
    dispatch(Lifecycle.Event.ON_START);
}
​
@Override
public void onResume() {
    super.onResume();
    dispatchResume(mProcessListener);
    dispatch(Lifecycle.Event.ON_RESUME);
}
​
@Override
public void onPause() {
    super.onPause();
    dispatch(Lifecycle.Event.ON_PAUSE);
}
​
@Override
public void onStop() {
    super.onStop();
    dispatch(Lifecycle.Event.ON_STOP);
}
​
@Override
public void onDestroy() {
    super.onDestroy();
    dispatch(Lifecycle.Event.ON_DESTROY);
    // just want to be sure that we won't leak reference to an activity
    mProcessListener = null;
}

找到了分发生命周期事件的方法dispatch(Event);

private void dispatch(@NonNull Lifecycle.Event event) {
    if (Build.VERSION.SDK_INT < 29) {
        // Only dispatch events from ReportFragment on API levels prior
        // to API 29. On API 29+, this is handled by the ActivityLifecycleCallbacks
        // added in ReportFragment.injectIfNeededIn
        dispatch(getActivity(), event);
    }
}

从中我们可以看出dispatch(Event)只对API<29(Android 10) 之前生效。

@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);
        }
    }
}
//dispatch(getActivity(), event);最终都会执行handleLifecycleEvent(event);方法
public void handleLifecycleEvent(@NonNull 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;
}
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;
}
private void forwardPass(LifecycleOwner lifecycleOwner) {
    Iterator<Map.Entry<LifecycleObserver, ObserverWithState>> ascendingIterator =
        mObserverMap.iteratorWithAdditions();
    while (ascendingIterator.hasNext() && !mNewEventOccurred) {
        Map.Entry<LifecycleObserver, ObserverWithState> entry = ascendingIterator.next();
        ObserverWithState observer = entry.getValue();
        while ((observer.mState.compareTo(mState) < 0 && !mNewEventOccurred
                && mObserverMap.contains(entry.getKey()))) {
            pushParentState(observer.mState);
            final Event event = Event.upFrom(observer.mState);
            if (event == null) {
                throw new IllegalStateException("no event up from " + observer.mState);
            }
            observer.dispatchEvent(lifecycleOwner, event);
            popParentState();
        }
    }
}
private void backwardPass(LifecycleOwner lifecycleOwner) {
    Iterator<Map.Entry<LifecycleObserver, ObserverWithState>> descendingIterator =
        mObserverMap.descendingIterator();
    while (descendingIterator.hasNext() && !mNewEventOccurred) {
        Map.Entry<LifecycleObserver, ObserverWithState> entry = descendingIterator.next();
        ObserverWithState observer = entry.getValue();
        while ((observer.mState.compareTo(mState) > 0 && !mNewEventOccurred
                && mObserverMap.contains(entry.getKey()))) {
            Event event = Event.downFrom(observer.mState);
            if (event == null) {
                throw new IllegalStateException("no event down from " + observer.mState);
            }
            pushParentState(event.getTargetState());
            observer.dispatchEvent(lifecycleOwner, event);
            popParentState();
        }
    }
}
void dispatchEvent(LifecycleOwner owner, Event event) {
    State newState = event.getTargetState();
    mState = min(mState, newState);
    mLifecycleObserver.onStateChanged(owner, event);
    mState = newState;
}
//API<29(Android 10) 之前
@Override
public void onStateChanged(@NonNull LifecycleOwner source, @NonNull Event event) {
    mInfo.invokeCallbacks(source, event, mWrapped);
}
​
void invokeCallbacks(LifecycleOwner source, Lifecycle.Event event, Object target) {
    invokeMethodsForEvent(mEventToHandlers.get(event), source, event, target);
    invokeMethodsForEvent(mEventToHandlers.get(Lifecycle.Event.ON_ANY), source, event,
                          target);
}
private static void invokeMethodsForEvent(List<MethodReference> handlers,
                                          LifecycleOwner source, Lifecycle.Event event, Object mWrapped) {
    if (handlers != null) {
        for (int i = handlers.size() - 1; i >= 0; i--) {
            handlers.get(i).invokeCallback(source, event, mWrapped);
        }
    }
}
//
void invokeCallback(LifecycleOwner source, Lifecycle.Event event, Object target) {
    //noinspection TryWithIdenticalCatches
    try {
        switch (mCallType) {
            case CALL_TYPE_NO_ARG:
                mMethod.invoke(target);
                break;
            case CALL_TYPE_PROVIDER:
                mMethod.invoke(target, source);
                break;
            case CALL_TYPE_PROVIDER_WITH_EVENT:
                mMethod.invoke(target, source, event);
                break;
        }
    } catch (InvocationTargetException e) {
        throw new RuntimeException("Failed to call observer method", e.getCause());
    } catch (IllegalAccessException e) {
        throw new RuntimeException(e);
    }
}

由上述源码一路梳理下来,最终结果如下:

API<29(Android 10) 之前,通过给Activity绑定一个空的Fragment,从而在执行Fragment的生命周期的时候执行所有标记过当前Activity的生命周期的方法。然后通过dispatch(event) 进行分发。通过状态机进行分发之后,执行onStateChanged()方法。在API<29的情况下,我们通过反射执行invokeCallback->mMerhod.invoke()

关于API>29(Android 10)之后的流程梳理大致如下,具体代码分析我放到下一篇文章中详细叙述。

API>29(Android 10)之后,第一是分发的原理进行了改变,不是通过F和A的生命周期关系进行的分发,而是通过Application的Activitylifecyclecallbacks接口进行的分发。第二是执行的onStateChanged()方法,不通过反射执行。直接调用LifecycleEventObserver的onStateChanged()方法。

3. Lifecycle中的状态机管理生命周期;

lifecycle-states-2.svg

通过两个枚举类构建起如上图的状态模型。

状态机的好处就是可以简化条件语句的执行。

在状态机的模型之下,通过mState、mActive等变量判断当前的生命周期状态。比每次判断都要单独列出6个生命周期的情况要高效很多。

后记

下一篇博客,我再继续深挖,研究一下Application的Activitylifecyclecallbacks接口的使用对于Lifecycle版本2.4.0之后的影响。