Android Jetpack之Lifecycles源碼分析

Android Jetpack之Lifecycles源碼分析

Android Jetpack簡介

Jetpack 是一套庫、工具和指南,可幫助開發者更輕鬆地編寫優質應用。這些組件可幫助您遵循最佳作法、讓您擺脫編寫樣板代碼的工做並簡化複雜任務,以便您將精力集中放在所需的代碼上。java

Jetpack 包含與平臺 API 解除捆綁的 androidx.* (android.*)軟件包庫。這意味着,它能夠提供向後兼容性,且比 Android 平臺的更新頻率更高,以此確保您始終能夠獲取最新且最好的 Jetpack 組件版本。 官方網址介紹:Android jetpack介紹android

Android Jetpack組件的優點:web

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.使用註解在每一個方法上標記相應的生命週期bash

注意定義的方法裏面的參數,Lifecycles對於參數是有要求的。具體緣由分析源碼的時候會具體分析(參考3.2.2) 1.若是參數個數大於0。第一個參數必須是LifecycleOwner或者是LifecycleOwner的超類 2.參數個數不大於1時,第一個參數同1第,二個參數必須是Lifecycle.Event或者是Lifecycle.Event的超類,並且註解的Event必須是Lifecycle.Event.ON_ANY 3.參數個數最大是2。不然會出現非法狀態異常session

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下面的。代碼以下app

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); } 複製代碼
相關文章
相關標籤/搜索