Android Jetpack之Lifecycles源码分析

Android Jetpack之Lifecycles源码分析

Android Jetpack简介

Jetpack 是一套库、工具和指南,可帮助开发者更轻松地编写优质应用。这些组件可帮助您遵循最佳做法、让您摆脱编写样板代码的工作并简化复杂任务,以便您将精力集中放在所需的代码上。

Jetpack 包含与平台 API 解除捆绑的 androidx.* (android.*)软件包库。这意味着,它可以提供向后兼容性,且比 Android 平台的更新频率更高,以此确保您始终可以获取最新且最好的 Jetpack 组件版本。
官方网址介绍:Android jetpack介绍

Android Jetpack组件的优势:

1.管理应用程序(Activity、Fragment)的生命周期(如后台任务、导航和生命周期管理)
2.构建可观察的数据对象,以便在基础数据库更改时通知视图(View)
3.存储在应用程序轮换中未销毁的UI相关数据,在界面重建后恢复数据
4.轻松的实现SQLite数据库
5.系统自动调度后台任务的执行,优化使用性能

Lifecycles的使用

2.1 状态转化图

Lifecycles是一个持有组件生命周期状态(Activity、Fragment)信息的类,用来解决生命周期管理问题的组件。通过监听生命周期的方式(Handling Lifecycles with Lifecycle-Aware Components),并允许其他对象观察此状态。生命周期使用两个主要枚举来跟踪其关联组件的生命周期状态:

1.Event:从框架和Lifecycle类派发的生命周期事件。 这些事件映射到活动和片段中的回调事件。
2.State:由Lifecycle对象跟踪的组件的当前状态。
Event和State的对应关系如下图:Android Developer官网关于State 的转化图
事件和状态转换图

2.2 Gradle引入Lifecycles

     def lifecycle_version = "2.0.0"
    // alternatively - Lifecycles only (no ViewModel or LiveData). Some UI
    // AndroidX libraries use this lightweight import for Lifecycle
    implementation "androidx.lifecycle:lifecycle-runtime:$lifecycle_version"
    // For Kotlin use kapt instead of annotationProcessor
    annotationProcessor "androidx.lifecycle:lifecycle-compiler:$lifecycle_version"
    // alternately - if using Java8, use the following instead of lifecycle-compiler
    implementation "androidx.lifecycle:lifecycle-common-java8:$lifecycle_version"

2.3创建观察者(Observer)

1.创建MyCustomLifecycles 继承 LifecycleObserver
2.使用注解在每个方法上标记相应的生命周期

注意定义的方法里面的参数,Lifecycles对于参数是有要求的。具体原因分析源码的时候会具体分析(参考3.2.2)
1.如果参数个数大于0。第一个参数必须是LifecycleOwner或者是LifecycleOwner的超类
2.参数个数不大于1时,第一个参数同1第,二个参数必须是Lifecycle.Event或者是Lifecycle.Event的超类,而且注解的Event必须是Lifecycle.Event.ON_ANY
3.参数个数最大是2。否则会出现非法状态异常

class MyCustomLifecycles() : LifecycleObserver{

    @OnLifecycleEvent(Lifecycle.Event.ON_ANY)
    fun onCreate(lifecycleOwner: LifecycleOwner,event :Lifecycle.Event = Lifecycle.Event.ON_ANY ){
    }

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

    }

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

interface MyCallback{
    fun test()
}

如果是支持Java8的话,并且gradle引用了** implementation “androidx.lifecycle:lifecycle-common-java8:$lifecycle_version”` **也可以这么声明

class MyCustomj8Lifecycles : DefaultLifecycleObserver{
    override fun onCreate(owner: LifecycleOwner) {
        super.onCreate(owner)
    }

    override fun onResume(owner: LifecycleOwner) {
        super.onResume(owner)
    }
}

/**
**已经弃用了
**/
public class MyGenericLifecycles : GenericLifeCycleObserver {
        }

2.4 创建被观测的Activity

class DataBindingActivity : AppCompatActivity(),LifecycleOwner{

}

2.5 创建LifecycleRegistry

在v4包中SupportActivity已经实现了LifecycleOwner。注意是v4包下,不是androidX下面的。代码如下

public class SupportActivity extends Activity implements LifecycleOwner, Component {
    private SimpleArrayMap<Class<? extends SupportActivity.ExtraData>, SupportActivity.ExtraData> mExtraDataMap = new SimpleArrayMap();
    private LifecycleRegistry mLifecycleRegistry = new LifecycleRegistry(this);

    public SupportActivity() {
    }
}

所以如果你的Activity已经继承SupportActivity,因为在v4包中SupportActivity已经实现了LifecycleOwner。可以省略如下代码

private lateinit var lifeCycleRegistry: LifecycleRegistry
    private lateinit var myCustomLifecycles: MyCustomLifecycles
    override fun getLifecycle(): Lifecycle {
        return lifeCycleRegistry
    }

2.5 实例化创建MyObserver并且绑定Lifecycles

在addObserver方法中会涉及到自定义Observer的解析。

myCustomLifecycles = MyCustomLifecycles()
lifecycle.addObserver(myCustomLifecycles)

2.7 设置生命周期中的标记

注意点:如果你的Activity继承的是v4包下的AppCompatActivity可以忽略该步骤,observer依旧可以相应Observer的Event注解的方法。但是如果是androidx.appcompat.app.AppCompatActivity,必须在Activity的生命周期中使用markState方法,否则注解的方法无法得到执行。不可以忽略该步骤,具体原因后面会分析。

lifeCycleRegistry.markState(Lifecycle.State.CREATED)

lifeCycleRegistry.markState(Lifecycle.State.RESUMED)

完整类代码如下:

class DataBindingActivity : AppCompatActivity(),LifecycleOwner{
    private lateinit var lifeCycleRegistry: LifecycleRegistry
    private lateinit var myCustomLifecycles: MyCustomLifecycles
    override fun getLifecycle(): Lifecycle {
        return lifeCycleRegistry
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        lifeCycleRegistry = LifecycleRegistry(this)

        myCustomLifecycles = MyCustomLifecycles()
        lifecycle.addObserver(myCustomLifecycles)
        lifeCycleRegistry.markState(Lifecycle.State.CREATED)
    }

    override fun onResume() {
        lifeCycleRegistry.markState(Lifecycle.State.RESUMED)
        super.onResume()
    }
}

源码分析

我们都知道Lifecycles是感应Activity的生命周期的,那么在使用Lifecycles时主要有一下几个疑问:
1.在Activity的生命周期发生变化的时候,LifecycleObserver声明的注解方法是怎么被触发的。
2.触发注解方法以后,注解的方法怎么被执行的。
下面就带着这几个疑问分析一下源码

3.1 SafeIterableMap分析

在分析源代码之前,先了解一下SafeIterableMap类(非线程安全),因为在类LifecycleRegistry中会用到FastSafeIterableMap<LifecycleObserver, ObserverWithState>,而FastSafeIterableMap的父类就是SafeIterableMap。SafeIterableMap类实际是个双向链表,支持键值对存储,并且能够能在遍历中删除元素(interface SupportRemove<K, V> { void supportRemove(@NonNull Entry<K, V> entry); })。适用于数据量存储不大的场景。
具有如下优点:
1.SafeIterableMap 的插入操作是时间复杂度O(1)直接通过指针的移动插入数据,而且不需要执行hash算法,效率高。
2.遍历的过程中删除元素而不触发ConcurrentModifiedException。
3.使用双向链表来存储会比 HashMap (java 8 红黑树)节省内存空间。
数据结构图
介绍SafeIterableMap中get、put、remove、putIfAbsent方法

  1. get方法
    get操作是通过从头指针(Entry<K, V> mStart)开始,一直往后找直到key对应的Entry。
protected Entry<K, V> get(K k) {
    Entry<K, V> currentNode = mStart;
    while (currentNode != null) {
        if (currentNode.mKey.equals(k)) {
            break;
        }
        currentNode = currentNode.mNext;
    }
    return currentNode;
}
  1. put方法
    put操作是插入到链表尾部(Entry<K, V> mEnd)并且改变mStart、mEnd的指向位置。

protected Entry<K, V> put(@NonNull K key, @NonNull V v) {
    Entry<K, V> newEntry = new Entry<>(key, v);
    mSize++;
    if (mEnd == null) {
        mStart = newEntry;
        mEnd = mStart;
        return newEntry;
    }

    mEnd.mNext = newEntry;
    newEntry.mPrevious = mEnd;
    mEnd = newEntry;
    return newEntry;
}

  1. putIfAbsent方法
    如过没有key对应的value,执行put方法,否则直接返回之前存储的数据。
public V putIfAbsent(@NonNull K key, @NonNull V v) {
        Entry<K, V> entry = get(key);
        if (entry != null) {
            return entry.mValue;
        }
        put(key, v);
        return null;
    }

  1. remove方法
    删除主要是通过移动entry的Next、Previous的指针进行数据删除,如果在删除的时候有数据的遍历即(!mIterators.isEmpty()),需要执行supportRemove方法。
public V remove(@NonNull K key) {
        Entry<K, V> toRemove = get(key);
        if (toRemove == null) {
            return null;
        }
        mSize--;
        if (!mIterators.isEmpty()) {
            for (SupportRemove<K, V> 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;
    }

  1. supportRemove方法
    遍历时删除,mIterators 是弱引用,防止遍历结束后对象没有释放造成内存泄漏。mIterators数据是在执行遍历方法的时候put数据的。在执行删除(remove方法)元素时会遍历mIterators,对数据删除。
private WeakHashMap<SupportRemove<K, V>, Boolean> mIterators = new WeakHashMap<>();

public Iterator<Map.Entry<K, V>> iterator() {
    ListIterator<K, V> iterator = new AscendingIterator<>(mStart, mEnd);
    mIterators.put(iterator, false);
    return iterator;
}

public Iterator<Map.Entry<K, V>> descendingIterator() {
    DescendingIterator<K, V> iterator = new DescendingIterator<>(mEnd, mStart);
    mIterators.put(iterator, false);
    return iterator;
}

public IteratorWithAdditions iteratorWithAdditions() {
    IteratorWithAdditions iterator = new IteratorWithAdditions();
    mIterators.put(iterator, false);
    return iterator;
}

SupportRemove接口有两个实现类,每当删除元素,而且mIterators不是空时,会调用这个方法对entry进行删除。SupportRemove通过调整尾指针和下一个元素的指针,达到安全遍历的效果。

IteratorWithAdditions

private class IteratorWithAdditions implements Iterator<Map.Entry<K, V>>, SupportRemove<K, V> {
     
        @Override
        public void supportRemove(@NonNull Entry<K, V> entry) {
        }
    }

ListIterator有两个子类

private abstract static class ListIterator<K, V> implements Iterator<Map.Entry<K, V>>,
            SupportRemove<K, V> {
        @Override
        public void supportRemove(@NonNull Entry<K, V> entry) {
        }
    }
private static class AscendingIterator<K, V> extends ListIterator<K, V> {
    }

private static class DescendingIterator<K, V> extends ListIterator<K, V> {
   
    }

3.2 解析观察者:LifecycleObserver

3.2.1 类关系

以网上比较全的一张图来说明,其中设计到的主要类的类关系图。
Lifecycle组件成员Lifecycle被定义成了抽象类,LifecycleOwner、LifecycleObserver被定义成了接口。
组件(Activity、Fragment)实现了LifecycleOwner接口,该只有一个返回Lifecycle对象的方法getLifecyle(): LifecycleRegistry。
Lifecycle的内部类State标明状态、Event表示事件
ObserverWithState的成员变量GenericLifecycleObserver继承自LifecycleObserver
Fragment中getLifecycle()方法返回的是继承了抽象类Lifecycle的LifecycleRegistry。

在这里插入图片描述

3.2.2 .解析Observer
  1. LifecycleRegistry初始化
    负责控制state的转换、接受分发event事件。LifecycleRegistry构造方法中通过弱引用持有LifecycleOwner,通过上面的使用我们知道,主要是Activity、Fragment实现LifecycleOwner。
 public LifecycleRegistry(@NonNull LifecycleOwner provider) {
        mLifecycleOwner = new WeakReference<>(provider);
        mState = INITIALIZED;
    }
  1. 通过lifecycle.addObserver(myCustomLifecycles)中为组件添加观察者Observer
public void addObserver(@NonNull LifecycleObserver observer) {
        State initialState = mState == DESTROYED ? DESTROYED : INITIALIZED;
        ObserverWithState statefulObserver = new ObserverWithState(observer, initialState);
        ObserverWithState previous = mObserverMap.putIfAbsent(observer, statefulObserver);
        ...........
    }
  1. 生成ObserverWithState ,里面存储状态(State)和观察者(GenericLifecycleObserver),并将存入LifecycleObserver,ObserverWithState作为键值对存储在FastSafeIterableMap中,FastSafeIterableMap继承自SafeIterableMap,内部通过hashMap存储数据。
static class ObserverWithState {
        State mState;
        GenericLifecycleObserver mLifecycleObserver;

        ObserverWithState(LifecycleObserver observer, State initialState) {
            mLifecycleObserver = Lifecycling.getCallback(observer);
            mState = initialState;
        }

        void dispatchEvent(LifecycleOwner owner, Event event) {
            State newState = getStateAfter(event);
            mState = min(mState, newState);
            mLifecycleObserver.onStateChanged(owner, event);
            mState = newState;
        }
    }
  1. 在ObserverWithState 的构造方法中,调用了Lifecycling.getCallback(observer)创建了GenericLifecycleObserver。这里返回的是ReflectiveGenericLifecycleObserver对象
 @NonNull
    static GenericLifecycleObserver getCallback(Object object) {
        if (object instanceof FullLifecycleObserver) {
            return new FullLifecycleObserverAdapter((FullLifecycleObserver) object);
        }
        if (object instanceof GenericLifecycleObserver) {
            return (GenericLifecycleObserver) 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);
    }

在getCallback根据我们在传入类不同构建不同的GenericLifecycleObserver子类,通过上下文知道,我们传入的是LifecycleObserver的子类,所以下面两个条件都不成立。

 if (object instanceof FullLifecycleObserver) {
            return new FullLifecycleObserverAdapter((FullLifecycleObserver) object);
        }

 if (object instanceof GenericLifecycleObserver) {
            return (GenericLifecycleObserver) object;
        }

s在getObserverConstructorType方法中会继续调用resolveObserverCallbackType方法,下面我们来分析该方法。
(1)代码块1:主要是看有没有生成XXX_LifecycleAdapter的类,XXX表示自定义的Observer类。在2.0.0的版本是没有的。可能是为了兼容老代码
(2)代码块2:是否有OnLifecycleEvent注解的方法。显然我们是通过注解的方式实现的。


    private static int resolveObserverCallbackType(Class<?> klass) {
        // anonymous class bug:35073837
        //肯定不为null
        if (klass.getCanonicalName() == null) {
            return REFLECTIVE_CALLBACK;
        }
		//代码块1
        Constructor<? extends GeneratedAdapter> constructor = generatedConstructor(klass);
        if (constructor != null) {
            sClassToAdapters.put(klass, Collections
                    .<Constructor<? extends GeneratedAdapter>>singletonList(constructor));
            return GENERATED_CALLBACK;
        }
		//代码块2
        boolean hasLifecycleMethods = ClassesInfoCache.sInstance.hasLifecycleMethods(klass);
        if (hasLifecycleMethods) {
            return REFLECTIVE_CALLBACK;
        }

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

  1. 在ReflectiveGenericLifecycleObserver构造函数中,通过ClassesInfoCache(单例模式)初始化CallbackInfo实例。
class ReflectiveGenericLifecycleObserver implements GenericLifecycleObserver {
    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);
    }
}
  1. CallbackInfo、MethodReference类
    MethodReference封装了Method的参数类型和方法
 MethodReference(int callType, Method method) {
            mCallType = callType;
            mMethod = method;
            mMethod.setAccessible(true);
        }

CallbackInfo里面主要是两个HashMap。
mEventToHandlers以Event作为KeyList作为value。这样存储的好处是,根据Event事件,可以快速的找到对应的所有注解方法。
mHandlerToEvent以MethodReference,Event键值对的形式存储,意识是某个注解方法对应的Event事件。

 final Map<Lifecycle.Event, List<MethodReference>> mEventToHandlers;
 final Map<MethodReference, Lifecycle.Event> mHandlerToEvent;
  1. createInfo方法
    在getInfo方法中获取Observer的所有方法,在CallbackInfo中通过HashMap储存了Observer中定义的所有方法注解和对应的Event事件。前面说到的对Observer的定义注解方法参数的限制就在createInfo方法中抛出了异常,详细的异常对应情况看下面的代码注解。
    (1)或去Method和对应的参数类型,并且对参数类型做校验,然后将参数类型和method存储在MethodReference。
    (2)调用的verifyAndPutHandler()就是将MethodReference和Lifecycle.Event放进Map集合中。
    (3)mCallbackMap:Map<Class, CallbackInfo>,储存Observer的类对应的CallbackInfo信息,避免重复解析,如果mCallbackMap存在Observer对应的CallbackInfo信息则直接返回
    (4)mHasLifecycleMethods:用于标注Observer类是否有注解的方法
    小结:通过以上7个步骤分析,我们已经知道Observer 的注解方法是如何被解析的。在ReflectiveGenericLifecycleObserver中有个onStateChanged方法,我们猜测如果在生命周期改变时,在执行到相应Event事件的时候,就会执行该方法,在该方法内获取CallbackInfo中的方法并调用mInfo.invokeCallbacks(source, event, mWrapped)执行相应的方法。
 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;
                //1.如果参数个数大于0。第一个参数必须是LifecycleOwner或者是LifecycleOwner的超类
                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;
               // 2.参数个数不大于1时,第一个参数同1第,二个参数必须是Lifecycle.Event或者是Lifecycle.Event的超类,而且注解
               //Event必须是Lifecycle.Event.ON_ANY

                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");
                }
            }
            //3.参数个数最大是2。否则会出现非法状态异常
            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;
    }

3.3 分发流程

在上面我们分析了自定义的Observer是如何被解析的,那么解析出来的方法method是在哪里触发执行的呢。下面我们开始分析。首先说明,如果你继承的类要是v4包中AppCompatActivity,因为在androidx中的继承关系和v4包是有区别的。在androidx下AppCompatActivity超类没有SupportActivity。 注意是v4包下,不是androidX下面的

  1. SupportActivity
    上面我们知道在SupportActivity类中实现了接口LifecycleOwner。并且在在onCrate的方法中初始化了一个ReportFragment
@RestrictTo(LIBRARY_GROUP)
public class SupportActivity extends Activity implements LifecycleOwner {
 
 private LifecycleRegistry mLifecycleRegistry = new LifecycleRegistry(this); 
 
 @Override
    public Lifecycle getLifecycle() { 
        return mLifecycleRegistry;
    }
protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ReportFragment.injectIfNeededIn(this);
    }
}
  1. ReportFragment
    (1)添加一个ReportFragment的实例,使用fragment的侵入型小,并且在Fragment 的生命周期中调用dispatch(Event)方法。
    (2)在用dispatch()调用LifecycleRegistry的handleLifecycleEvent方法,流程又回到了LifecycleRegistry类中。
    看到这儿我们就可以解释一个疑问了:继承v4包下的SupportActivity由于有ReportFragment的存在,会执行handleLifecycleEvent所以会触发Event事件,而androidx下的由于没有ReportFragment的继承,所以无法感知生命周期的变化,需要在Activity的生命周期中markState才可以
    所以在这儿我们猜测:
    在observer中使用LifeEvent标记Event的方法,在Activity状态改变时(实际上是通过ReportFragment触发的),系统会判断即将要改变成的状态,根据前后两个状态获取确定要执行的Event事件
    然后执行ReflectiveGenericLifecycleObserver中onStateChanged方法,根据上面解析出来的method执行逻辑
public class ReportFragment extends Fragment {
    private static final String REPORT_FRAGMENT_TAG = "android.arch.lifecycle"
            + ".LifecycleDispatcher.report_fragment_tag";
 
    public static void injectIfNeededIn(Activity activity) { //初始化Fragment
        android.app.FragmentManager manager = activity.getFragmentManager();
        if (manager.findFragmentByTag(REPORT_FRAGMENT_TAG) == null) {
            manager.beginTransaction().add(new ReportFragment(), REPORT_FRAGMENT_TAG).commit();
            manager.executePendingTransactions();
        }
    }
 
  @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);
        mProcessListener = null;
    }
 
    private void dispatch(Lifecycle.Event event) {
        Activity activity = getActivity();
        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);
            }
        }
    }
}
  1. handleLifecycleEvent()
    在handleLifecycleEvent方法中根据Event获取到下一个状态,状态转化在3.2.1。然后根据下一个状态,执行Event。markState执行流程和handleLifecycleEvent基本一直,只不过少了getStateAfter方法。
public void handleLifecycleEvent(@NonNull Lifecycle.Event event) {
        State next = getStateAfter(event);
        moveToState(next);
    }
static State getStateAfter(Event event) {
        switch (event) {
            case ON_CREATE:
            case ON_STOP:
                return CREATED;
            case ON_START:
            case ON_PAUSE:
                return STARTED;
            case ON_RESUME:
                return RESUMED;
            case ON_DESTROY:
                return DESTROYED;
            case ON_ANY:
                break;
        }
        throw new IllegalArgumentException("Unexpected event value " + event);
    }
 
private void moveToState(State next) {
        if (mState == next) {
            return;
        }
        mState = next;
        //代码1
        if (mHandlingEvent || mAddingObserverCounter != 0) {
            mNewEventOccurred = true;
            // we will figure out what to do on upper level.
            return;
        }
        mHandlingEvent = true;
        sync();
        mHandlingEvent = false;
    }

对于代码1处的解释: 当正在sync中处理改变状态时 mHandlingEvent = true;当我们调用addObserver时 mAddingObserverCounter != 0以上这两种状态都是正在执行任务的状态,所以此时直接return
在getStateAfter中首先根据执行的Lifecycle.Event,判断执行事件后下一个到达的状态,然后使用moveToState()中的sync()修改活动的生命周期:
4. sync()
顾名思义是用来同步事件的。
(1)判断是否有LifecycleOwner对象,LifecycleOwner是在构造方法通过若引用初始化的。判断当前时候有其他的sync操作
2 )我们知道Lifecycle.Event和Lifecycle.State的声明顺序是和活动 的声明周期执行顺序一致的,所以对Lifecycle.State的前后顺序的比较也就反应了声明周期状态的变换,比较下一个状态和之前状态集合里面的状态大小,mObserverMap.eldest()获取的是双向链表里面的第一个数据,mObserverMap.newest()获取的是尾部数据,这样的数据结构好处就凸显出来了,可以直接获取头部和尾部指针。比如活动此时的生命周期为CREATED(此时mObserverMap中保存的状态为CREATED),而下一个变换的状态为Started(此时的mState为Started),从声明周期中可以知道此时执行的时onStart(),对应的LIfecycle.Event为onStart。


private void sync() {
        LifecycleOwner lifecycleOwner = mLifecycleOwner.get();
        if (lifecycleOwner == null) {
            Log.w(LOG_TAG, "LifecycleOwner is garbage collected, you shouldn't try dispatch "
                    + "new events from it.");
            return;
        }
        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);
            }
            Entry<LifecycleObserver, ObserverWithState> newest = mObserverMap.newest();
            if (!mNewEventOccurred && newest != null
                    && mState.compareTo(newest.getValue().mState) > 0) {
                forwardPass(lifecycleOwner);
            }
        }
        mNewEventOccurred = false;
    }
  1. forwardPass方法

while循环是因为有多个Observer的存在。在forwardPass()方法中会将ObserverWithState中保存的状态与mState比较,如果小于目标State。然后调用upEvent()根据保存的状态找出要执行的Event,并调用Observer的dispatEvent()方法发送事件。

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);
                observer.dispatchEvent(lifecycleOwner, upEvent(observer.mState));
                popParentState();
            }
        }
    }
    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);
    }
  1. dispatchEvent方法
    由上面的解析Observer可知,mLifecycleObserver是ReflectiveGenericLifecycleObserver的对象。所以最终会执行到ReflectiveGenericLifecycleObserver.onStateChanged方法。这就和我们上面的分析对应起来了。
 static class ObserverWithState {
        State mState;
        GenericLifecycleObserver mLifecycleObserver;

        ObserverWithState(LifecycleObserver observer, State initialState) {
            mLifecycleObserver = Lifecycling.getCallback(observer);
            mState = initialState;
        }

        void dispatchEvent(LifecycleOwner owner, Event event) {
            State newState = getStateAfter(event);
            mState = min(mState, newState);
            mLifecycleObserver.onStateChanged(owner, event);
            mState = newState;
        }
    }
  1. 真正的方法执行
    (1)invokeCallbacks 通过mEventToHandlers获取MethodReference结合
    (2)invokeMethodsForEvent 倒叙执行MethodReference里面的method
    (3)invokeCallback根据参数类型,进行invoke。CALL_TYPE是在解析Observer时初始化的
 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);
            }
        }
  1. 注销Observer
    直接执行LifecycleRegistry的remove方法。
@Override
    public void removeObserver(@NonNull LifecycleObserver observer) {
        // 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);
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值