Android开发

Jetpack 之 Lifecycles 源码分析

本文主要是介绍Jetpack 之 Lifecycles 源码分析,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

LifecycleOwner

LifecycleOwner 是单一方法接口,实现此接口表明此类具有生命周期 Lifecycle

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

复制代码

LifecycleObserver

LifecycleObserver ,实现此接口的类,可以观察 LifecycleOwner 的生命周期 Lifecycle 状态。

public interface LifecycleObserver {

}
复制代码

这里了解一下它的几个常用实现类。

FullLifecycleObserver

实现了 LifecycleObserver,定义了一些常用的生命周期事件回调。

interface FullLifecycleObserver extends LifecycleObserver {

    void onCreate(LifecycleOwner owner);

    void onStart(LifecycleOwner owner);

    void onResume(LifecycleOwner owner);

    void onPause(LifecycleOwner owner);

    void onStop(LifecycleOwner owner);

    void onDestroy(LifecycleOwner owner);
}
复制代码

LifecycleEventObserver

实现了 LifecycleObserver,暴露生命周期变更时的回调。

public interface LifecycleEventObserver extends LifecycleObserver {
    /**
     * Called when a state transition event happens.
     *
     * @param source The source of the event
     * @param event The event
     */
    void onStateChanged(@NonNull LifecycleOwner source, @NonNull Lifecycle.Event event);
}
复制代码

ReflectiveGenericLifecycleObserver

实现了 LifecycleObserver。在构造器中,会通过反射将使用了 OnLifecycleEvent 注解的方法保存到 Map 中,当生命周期变动的时候,通过反射调用对应的方法。

class ReflectiveGenericLifecycleObserver implements LifecycleEventObserver {
    private final Object mWrapped;
    private final CallbackInfo mInfo;

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

    @Override
    public void onStateChanged(LifecycleOwner source, Event event) {
        mInfo.invokeCallbacks(source, event, mWrapped);
    }
}
复制代码

构造器里面接受一个 LifecycleObserver,然后所有的解析逻辑实际上都是 ClassesInfoCache完成的。

ClassesInfoCache

通过反射解析和存放使用了 OnLifecycleEvent 的方法,方便生命周期变动的时候回调对应的方法。

CallbackInfo getInfo(Class klass) {
    CallbackInfo existing = mCallbackMap.get(klass);
    // 已经存在,直接返回缓存的
    if (existing != null) {
        return existing;
    }
    // 解析
    existing = createInfo(klass, null);
    return existing;
}
复制代码

解析的过程主要是发生在 createInfo() 里面,我们来看看这个方法。

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

    // 开始解析自身
    
    // 1. 获取所有声明的方法
    Method[] methods = declaredMethods != null ? declaredMethods : getDeclaredMethods(klass);
    boolean hasLifecycleMethods = false;
    for (Method method : methods) {
        // 2. 找到所有使用了 OnLifecycleEvent 注解的方法
        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();

        // 这里是确定参数,除了ON_ANY事件可以接收两个参数,其他事件只能接收一个LifecycleOwner参数
        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");
        }
        
        // 3. 保存对应关系
        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

Lifecycle 用于存储有关组件(如 Activity 或 Fragment)的生命周期状态的信息,并允许其他对象观察此状态。

Lifecyce.State

Lifecycle.State 标记组件生命周期状态。

public enum State {
    // 标记 LifecycleOwner 是 DESTROYED 状态,这个状态之后,不会再分发任何事件。比如 Activity.onDestroy() 已经调用了。
    DESTROYED,

    // 标记 LifecycleOwner 是 INITIALIZED 状态。比如 Activity 已经创建,但是还没有走到 onCreate()。
    INITIALIZED,
    
    // 标记 LifecycleOwner 是 CREATED 状态。比如 Activity.onCreate() 或 Activity.onStop()。
    CREATED,

    // 标记 LifecycleOwner 是 STARTED 状态。比如 Activity.onStart() 或者 Activity.onPause()。
    STARTED,

    // 标记 LifecycleOwner 是 RESUMED 状态。比如 Activity.onResume()。
    RESUMED;

    public boolean isAtLeast(@NonNull State state) {
        return compareTo(state) >= 0;
    }
}
复制代码

Lifecycle.Event

Lifecycle.Event 是分发的生命周期事件,对应组件一系列生命周期回调。

public enum Event {
    ON_CREATE,
    ON_START,
    ON_RESUME,
    ON_PAUSE,
    ON_STOP,
    ON_DESTROY,
    ON_ANY
}
复制代码

ON_CREATE, ON_START, ON_RESUME 这三个事件是 LifecycleOwner 对应的生命周期方法返回之后被分发的;ON_PAUSE, ON_STOP, ON_DESTROY 这三个事件是在 LifecycleOwner 对应的生命周期事件调用之前被分发的。

下图显示了 Event 与 State 之间的关系。

lifecycle-states.png

LifecycleRegistry

LifecycleRegistryLifecycle 的实现类。

前面说了,Lifecycle 用来存放组件生命周期状态,且允许其他对象观察此状态。那么里面必然会存放 LifecycleOwnerLifecycle.State ,并提供 添加/移除 LifecycleObserver 的方法。

private State mState;

private final WeakReference<LifecycleOwner> mLifecycleOwner;

public LifecycleRegistry(@NonNull LifecycleOwner provider) {
    mLifecycleOwner = new WeakReference<>(provider);
    mState = INITIALIZED;
}

// 用来存放 LifecycleObserver
private FastSafeIterableMap<LifecycleObserver, ObserverWithState> mObserverMap =
            new FastSafeIterableMap<>();

@Override
public void addObserver(@NonNull LifecycleObserver observer) {
    State initialState = mState == DESTROYED ? DESTROYED : INITIALIZED;
    ObserverWithState statefulObserver = new ObserverWithState(observer, initialState);
    ObserverWithState previous = mObserverMap.putIfAbsent(observer, statefulObserver);
    // 已经被在 mObserverMap 里面了
    if (previous != null) {
        return;
    }
    
    LifecycleOwner lifecycleOwner = mLifecycleOwner.get();
    if (lifecycleOwner == null) {
        return;
    }

    boolean isReentrance = mAddingObserverCounter != 0 || mHandlingEvent;
    State targetState = calculateTargetState(observer);
    mAddingObserverCounter++;
    // 保证给新增加的 LifecycleObserver 分发对应的 Lifecycle.Event 让其到达最新的状态
    while ((statefulObserver.mState.compareTo(targetState) < 0
            && mObserverMap.contains(observer))) {
        pushParentState(statefulObserver.mState);
        statefulObserver.dispatchEvent(lifecycleOwner, upEvent(statefulObserver.mState));
        popParentState();
        // mState / subling may have been changed recalculate
        targetState = calculateTargetState(observer);
    }

    if (!isReentrance) {
        sync();
    }
    mAddingObserverCounter--;
}

@Override
public void removeObserver(@NonNull LifecycleObserver observer) {
    mObserverMap.remove(observer);
}
复制代码

这里需要注意一下 ObserverWithState,这个类是 LifecycleRegistry 的内部类,他在构造器中对 LifecycleObserver 进行了一次转换。

ObserverWithState(LifecycleObserver observer, State initialState) {
    // 这里通过 Lifecycling.lifecycleEventObserver()进行一次转换
    mLifecycleObserver = Lifecycling.lifecycleEventObserver(observer);
    mState = initialState;
}
复制代码

我们来看一下 Lifecycling.lifecycleEventObserver()

static LifecycleEventObserver lifecycleEventObserver(Object object) {
    boolean isLifecycleEventObserver = object instanceof LifecycleEventObserver;
    boolean isFullLifecycleObserver = object instanceof FullLifecycleObserver;
    // 1. 如果是 LifecycleEventObserver,FullLifecycleObserver 则返回 FullLifecycleObserverAdapter
    if (isLifecycleEventObserver && isFullLifecycleObserver) {
        return new FullLifecycleObserverAdapter((FullLifecycleObserver) object,
                (LifecycleEventObserver) object);
    }
    // 2. 如果是 FullLifecycleObserver 则返回 FullLifecycleObserverAdapter
    if (isFullLifecycleObserver) {
        return new FullLifecycleObserverAdapter((FullLifecycleObserver) object, null);
    }

    // 3. 如果是 LifecycleEventObserver 直接返回
    if (isLifecycleEventObserver) {
        return (LifecycleEventObserver) object;
    }

    // 4. 不是上面的情况,需要通过 getObserverConstructorType() 决定
    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);
}
复制代码

这个方法对 LifecycleObserver 进行了如下转换。

  1. 如果是 LifecycleEventObserverFullLifecycleObserver,则转换成 FullLifecycleObserverAdapter
  2. 如果是 FullLifecycleObserver ,则转换成 FullLifecycleObserverAdapter
  3. 如果是 LifecycleEventObserver ,直接返回;
  4. 如果 getObserverConstructorType() 是 GENERATED_CALLBACK,则转换成对应的 GeneratedAdapterObserver;
  5. 其他情况则转换成 ReflectiveGenericLifecycleObserver

这里主要分析一下 getObserverConstructorType() 这个方法,其他的几种情况都比较简单,可以自行查看源码,这里就不赘述了。

private static int getObserverConstructorType(Class<?> klass) {
    // 缓存有,直接返回缓存里面的
    Integer callbackCache = sCallbackCache.get(klass);
    if (callbackCache != null) {
        return callbackCache;
    }
    // 这里调用了 resolveObserverCallbackType()
    int type = resolveObserverCallbackType(klass);
    sCallbackCache.put(klass, type);
    return type;
}
复制代码

这个方法调用了 resolveObserverCallbackType() 来解析 callBack 类型。

private static int resolveObserverCallbackType(Class<?> klass) {
    // anonymous class bug:35073837
    if (klass.getCanonicalName() == null) {
        return REFLECTIVE_CALLBACK;
    }

    // 1. generatedConstructor() 获取构造器
    Constructor<? extends GeneratedAdapter> constructor = generatedConstructor(klass);
    if (constructor != null) {
        sClassToAdapters.put(klass, Collections
                .<Constructor<? extends GeneratedAdapter>>singletonList(constructor));
        return GENERATED_CALLBACK;
    }

    // 2. 使用了 OnLifecycleEvent 注解的
    boolean hasLifecycleMethods = ClassesInfoCache.sInstance.hasLifecycleMethods(klass);
    if (hasLifecycleMethods) {
        return REFLECTIVE_CALLBACK;
    }

    // 3. 递归看父类
    Class<?> superclass = klass.getSuperclass();
    List<Constructor<? extends GeneratedAdapter>> 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;
}
复制代码

这里我们主要看下返回 GENERATED_CALLBACK 的情况,它通过 generatedConstructor() 获取构造器。

private static Constructor<? extends GeneratedAdapter> 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<? extends GeneratedAdapter> aClass =
                (Class<? extends GeneratedAdapter>) Class.forName(
                        fullPackage.isEmpty() ? adapterName : fullPackage + "." + adapterName);
        Constructor<? extends GeneratedAdapter> 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);
    }
}
复制代码

这个代码看着就很奇怪,我们没有去定义一个 xxx_LifecycleAdapter 的类,这是哪来的?这个比较有意思,它是 apt 在编译的时候自动生成的,我们可以在 build/generated/source/kapt 下面找到。

这里我们看一下定义的 LifecycleObserver 和它的生成类。

// 我们定义的 LifecycleObserver
class LifecycleObserverA
    : LifecycleObserver {

    @OnLifecycleEvent(Lifecycle.Event.ON_CREATE)
    fun onCreate(owner: LifecycleOwner) {
    }

}

// apt 的生成类
public class LifecycleObserverA_LifecycleAdapter implements GeneratedAdapter {
  final LifecycleObserverA mReceiver;

  LifecycleObserverA_LifecycleAdapter(LifecycleObserverA receiver) {
    this.mReceiver = receiver;
  }

  @Override
  public void callMethods(LifecycleOwner owner, Lifecycle.Event event, boolean onAny,
      MethodCallsLogger logger) {
    boolean hasLogger = logger != null;
    if (onAny) {
      return;
    }
    if (event == Lifecycle.Event.ON_CREATE) {
      if (!hasLogger || logger.approveCall("onCreate", 2)) {
        mReceiver.onCreate(owner);
      }
      return;
    }
  }
}
复制代码

分析完这个过程,我们回到 LifecycleRegistry

状态同步

LifecycleOwner 的生命周期状态发生变化的时候,LifecycleRegistry 主要是通过 sync() 方法来给 LifecycleObserver 进行状态同步的。

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;
        // LifecycleOwner 状态 比 LifecycleObserver 对应的状态小,则同步 LifecycleObserver downEvent()
        if (mState.compareTo(mObserverMap.eldest().getValue().mState) < 0) {
            backwardPass(lifecycleOwner);
        }
        Entry<LifecycleObserver, ObserverWithState> newest = mObserverMap.newest();
        // LifecycleOwner 状态比 LifecycleObserver 对应的状态大,则同步 LifecycleObserver upEvent()
        if (!mNewEventOccurred && newest != null
                && mState.compareTo(newest.getValue().mState) > 0) {
            forwardPass(lifecycleOwner);
        }
    }
    mNewEventOccurred = false;
}

// 当 LifecycleOwner 里面存在状态与 mState 不一致,或者 LifecycleOwner 之间存在状态不一致的时候,需要进行状态同步
private boolean isSynced() {
    if (mObserverMap.size() == 0) {
        return true;
    }
    State eldestObserverState = mObserverMap.eldest().getValue().mState;
    State newestObserverState = mObserverMap.newest().getValue().mState;
    return eldestObserverState == newestObserverState && mState == newestObserverState;
}
复制代码

isSynced() 方法决定了是否需要进行状态同步。然后在 while 循环里面,通过 LifecycleOwnerLifecycleObserver 状态的比较,决定是应该走 backwardPass(),还是 forwardPass()backwardPass()forwardPass() 方法也比较简单,就是遍历所有的 LifecycleObserver ,然后进行一层层的事件分发,直到 LifecycleObserver 的状态和 LifecycleOwner 的状态平齐。

private void forwardPass(LifecycleOwner lifecycleOwner) {
    Iterator<Entry<LifecycleObserver, ObserverWithState>> ascendingIterator =
            mObserverMap.iteratorWithAdditions();
    while (ascendingIterator.hasNext() && !mNewEventOccurred) {
        Entry<LifecycleObserver, ObserverWithState> entry = ascendingIterator.next();
        ObserverWithState observer = entry.getValue();
        while ((observer.mState.compareTo(mState) < 0 && !mNewEventOccurred
                && mObserverMap.contains(entry.getKey()))) {
            pushParentState(observer.mState);
            // 分发 upEvent()
            observer.dispatchEvent(lifecycleOwner, upEvent(observer.mState));
            popParentState();
        }
    }
}

private void backwardPass(LifecycleOwner lifecycleOwner) {
    Iterator<Entry<LifecycleObserver, ObserverWithState>> descendingIterator =
            mObserverMap.descendingIterator();
    while (descendingIterator.hasNext() && !mNewEventOccurred) {
        Entry<LifecycleObserver, ObserverWithState> entry = descendingIterator.next();
        ObserverWithState observer = entry.getValue();
        while ((observer.mState.compareTo(mState) > 0 && !mNewEventOccurred
                && mObserverMap.contains(entry.getKey()))) {
            Event event = downEvent(observer.mState);
            pushParentState(getStateAfter(event));
            // 分发 downEvent()
            observer.dispatchEvent(lifecycleOwner, event);
            popParentState();
        }
    }
}

private static Event downEvent(State state) {
    switch (state) {
        case INITIALIZED:
            throw new IllegalArgumentException();
        case CREATED:
            return ON_DESTROY;
        case STARTED:
            return ON_STOP;
        case RESUMED:
            return ON_PAUSE;
        case DESTROYED:
            throw new IllegalArgumentException();
    }
    throw new IllegalArgumentException("Unexpected state value " + state);
}

private static Event upEvent(State state) {
    switch (state) {
        case INITIALIZED:
        case DESTROYED:
            return ON_CREATE;
        case CREATED:
            return ON_START;
        case STARTED:
            return ON_RESUME;
        case RESUMED:
            throw new IllegalArgumentException();
    }
    throw new IllegalArgumentException("Unexpected state value " + state);
}
复制代码
这篇关于Jetpack 之 Lifecycles 源码分析的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!