Android Jetpack架構組件之 Lifecycle(源碼篇)

1、前言

最近簡單看了下google推出的框架Jetpack,感受此框架的內容能夠對平時的開發有很大的幫助,也能夠解決不少開發中的問題,對代碼的邏輯和UI界面實現深層解耦,打造數據驅動型UI界面。android

Android Architecture組件是Android Jetpack的一部分,它們是一組庫,旨在幫助開發者設計健壯、可測試和可維護的應用程序,包含一下組件:bash

本文從源碼和實現的角度分析一下,LifeCycle是如何實現感知活動生命週期的。架構

2、源碼分析

關於Lifecycle的使用考上一篇文章Android Jetpack框架之 Lifecycles(使用篇),從使用的方法中咱們知道Lifecycle的實現主要依賴:LifecycleObserver、LifecycleOwner;經過像Owner註冊Observer實現感知Owner的生命週期,下面一塊兒看看源碼是如何巧妙設計的;app

2.一、生命週期觀察者:LifecycleObserver框架

// 實現LifecycleObserver
class MyObserver(var lifecycle: Lifecycle, var callback: CallBack) : LifecycleObserver {

    @OnLifecycleEvent(Lifecycle.Event.ON_CREATE)
    public fun connectOnCreate() {
        p("connectOnCreate")
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_RESUME)
    public fun connectOnResume() {
        p("connectOnResume")

    }
}

// LifecycleObserver 是一個空接口
public interface LifecycleObserver {

}複製代碼

上面過程作了三件事情:ide

  1. 實現LifecycleObserver的接口
  2. 編寫要執行的方法
  3. 爲每一個方法添加註解,表示其執行的時機
  • @OnLifecycleEvent:運行註解
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface OnLifecycleEvent {
    Lifecycle.Event value();
}複製代碼

2.二、生命週期:Lifecycle.Event & State函數

// 生命週期Event
public enum Event {
        /**
         * Constant for onCreate event of the {@link LifecycleOwner}.
         */
        ON_CREATE,
        /**
         * Constant for onStart event of the {@link LifecycleOwner}.
         */
        ON_START,
        /**
         * Constant for onResume event of the {@link LifecycleOwner}.
         */
        ON_RESUME,
        /**
         * Constant for onPause event of the {@link LifecycleOwner}.
         */
        ON_PAUSE,
        /**
         * Constant for onStop event of the {@link LifecycleOwner}.
         */
        ON_STOP,
        /**
         * Constant for onDestroy event of the {@link LifecycleOwner}.
         */
        ON_DESTROY,
        /**
         * An {@link Event Event} constant that can be used to match all events.
         */
        ON_ANY
    }

//5個對應的生命週期狀態
 public enum State {

        DESTROYED,

        INITIALIZED,

        CREATED,

        STARTED,

        RESUMED;

        public boolean isAtLeast(@NonNull State state) {
            return compareTo(state) >= 0;
        }
    }
複製代碼

經過Lifecycle.Event和State的查看,系統提供了Activity每一個生命週期對應的Event,而Event有會有對應的State,此時 以大體猜測到上面的執行過程:源碼分析

  1. 使用LifeEvent標記每一個執行方法的Event
  2. 當活動狀態改變時,系統會判斷即將要改變成的狀態
  3. 根據狀態獲取要執行的Event
  4. 從註冊的Observer中獲取標註爲對應的Event,執行邏輯

2.三、生命週期的感知post

  • LifecycleOwner
class LifeCyclerActivity : AppCompatActivity() {
  ...
 var myObserver = MyObserver(lifecycle, object : CallBack { // 建立LifecyclerObserver
            override fun update() {
          ...
            }
        })
        lifecycle.addObserver(myObserver) // 添加觀察者
    }
}複製代碼

從上面的使用狀況看出,使用的活動須要調用getLifecycle()方法,返回LifecycleRegistry,這裏的getLifecycle()方法實際上是接口LifecycleOwner接口中的方法,測試

@SuppressWarnings({"WeakerAccess", "unused"})
public interface LifecycleOwner {
    /**
     * Returns the Lifecycle of the provider.
     *
     * @return The lifecycle of the provider.
     */
    @NonNull
    Lifecycle getLifecycle();
}複製代碼

此時LifecycleActivity雖然沒有實現接口,由於他繼承的AppCompatActivity繼承了SupportActivity,而SupportActivity實現了接口

@RestrictTo(LIBRARY_GROUP)
public class SupportActivity extends Activity implements LifecycleOwner {

 private LifecycleRegistry mLifecycleRegistry = new LifecycleRegistry(this); //建立

 @Override
    public Lifecycle getLifecycle() { // 重寫方法返回LifecycleRegistry 
        return mLifecycleRegistry;
    }

}複製代碼

SupportActivity除了執行上述操做外,在onCrate的方法中還有一句重要的代碼,初始化了一個ReportFragment

protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ReportFragment.injectIfNeededIn(this);
    }
複製代碼
  • ReportFragment
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. 添加一個ReportFragment的實例
  2. 根據Fragment的每一個生命週期的回調,調用dispatch()處理回調事件

在dispatch()方法中根據LifecyclerOwner和LifecyclerRegistryOwner實例分別處理,由於LifecyclerRegistryOwner也是繼承LifecyclerOwner,而在咱們SupportActivity中的getLifecycler()中返回的是LifecycleRegistry,因此此處回調的都是LifecycleRegistry的handleLifecycleEvent;

2.四、生命週期處理

  • LifecycleRegistry

建立LifecycleRegistry實例

// 對LifecycleOwner使用了弱引用
private final WeakReference<LifecycleOwner> mLifecycleOwner;

 public LifecycleRegistry(@NonNull LifecycleOwner provider) {
        mLifecycleOwner = new WeakReference<>(provider);
        // 狀態爲初始化狀態
        mState = INITIALIZED;
    }複製代碼

接着上面的執行,咱們找到handleLifecycleEvent()

public void handleLifecycleEvent(@NonNull Lifecycle.Event event) {
        State next = getStateAfter(event);
        moveToState(next);
    }複製代碼

還記的上面的猜測嗎?和此處執行的邏輯徹底一致,對於getStateAfter()和moveToState(),從名字中能夠看出他們是執行響應生命週期的地方

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;
        // 當正在sync中處理改變狀態時 mHandlingEvent = true
        // 當咱們調用addObserver時 mAddingObserverCounter != 0
        // 這兩種狀態都是正在執行任務的狀態,因此此時直接return
        if (mHandlingEvent || mAddingObserverCounter != 0) {
            mNewEventOccurred = true;
            // we will figure out what to do on upper level.
            return;
        }
        mHandlingEvent = true;
        sync();
        mHandlingEvent = false;
    }複製代碼

在getStateAfter中首先根據執行的Lifecycle.Event,判斷執行事件後下一個到達的狀態,而後使用moveToState()中的sync()修改活動的生命週期:

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;
            // 比較的是出現的順序 若是下一個週期小於當前的週期 即向前back
            if (mState.compareTo(mObserverMap.eldest().getValue().mState) < 0) {
                backwardPass(lifecycleOwner); // 修改集合
            }
            //獲取新的Map的Entry
            Entry<LifecycleObserver, ObserverWithState> newest = mObserverMap.newest();
            if (!mNewEventOccurred && newest != null
                    && mState.compareTo(newest.getValue().mState) > 0) {
                forwardPass(lifecycleOwner);
            }
        }
        mNewEventOccurred = false;
    }複製代碼

在sync()方法中除了必要的條件和判斷外,主要的邏輯仍是生命週期的比較和處理,由前面咱們知道Lifecycle.Event和Lifecycle.State的聲明順序是和活動 的聲明週期執行順序一致的,因此對Lifecycle.State的先後順序的比較也就反應了聲明週期狀態的變換,好比活動此時的生命週期爲Resumed(此時mObserverMap中保存的狀態爲Resumed),而下一個變換的狀態爲Started(此時的mState爲Started),從聲明週期中能夠知道此時執行的時onPause(),對應的LIfecycle.Event爲ON_PAUSE,那麼上述邏輯中此時執行的是

if (mState.compareTo(mObserverMap.eldest().getValue().mState) < 0) {
                backwardPass(lifecycleOwner); // 修改集合
            }複製代碼
  • backwardPass
private void backwardPass(LifecycleOwner lifecycleOwner) {
        Iterator<Entry<LifecycleObserver, ObserverWithState>> descendingIterator =
                mObserverMap.descendingIterator();
        while (descendingIterator.hasNext() && !mNewEventOccurred) {
            Entry<LifecycleObserver, ObserverWithState> entry = descendingIterator.next();
           // 獲取當前保存的 ObserverWithState  從中提取狀態
            ObserverWithState observer = entry.getValue(); 
            while ((observer.mState.compareTo(mState) > 0 && !mNewEventOccurred
                    && mObserverMap.contains(entry.getKey()))) {
               // 若是保存的狀態大於 要變化的狀態 向前修改
                Event event = downEvent(observer.mState); //查找對應週期變化的事件
                pushParentState(getStateAfter(event)); 
                observer.dispatchEvent(lifecycleOwner, event); // 發送事件
                popParentState();
            }
        }
    }
複製代碼

在backwardPass()方法中會將mObserverMap中保存的狀態與mState比較,而後調用downEvent()根據保存的狀態找出要執行的Event,並調用Observer的dispatEvent()方法發送事件,對於downEvent()還有個與之對應的方法upEvent():

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);
    }複製代碼

上面的判斷邏輯就是根據下一個目標生命週期的變化,與要執行的Event之間的轉換,邏輯以下圖:

按照咱們上面的舉例,從Resumed變爲Started,從上圖能夠看出執行的Event是ON_PAUSE,與咱們的猜測一致,總結一下Lifecycle對狀態的處理流程:

  1. 實現LifecycleOwner獲取LifecycleRegistry實例
  2. 綁定並存儲HolderFragment
  3. 當HolderFragment生命週期改變時,調用handleLifecycleEvent處理事件
  4. LifecycleRegistry根據要執行的Event獲取要改變的狀態和當前儲存的狀態
  5. 比較兩個狀態,獲取真正要執行的Lifecycle.Event
  6. 調用儲存的ObserverWithState的dispatchEvent()發送事件

事件的處理流程已經清楚了,那麼mState和ObserverWithState實例是何時存儲的?又執行了哪些操做呢?那如今就從第一步添加開始看

2.五、添加Observer

  • addObserver:添加觀察者Observer
@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);
         ...
 }複製代碼
  • ObserverWithState

上述過程當中獲取了要執行的Event後,調用了Observer的dispatchEvent()發送事件,我麼知道此時調用的就是ObserverWithState .dispatchEvent()方法,ObserverWithState封裝了State和GenericLifecycleObserver 實例,在dispatchEvent()又調用了mLifecycleObserver.onStateChanged(owner, event),因此事件真正的執行是從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;
        }
    }複製代碼

在ObserverWithState 的初始化過程當中,同時調用了Lifecycling.getCallback(observer)建立了GenericLifecycleObserver實例

  • GenericLifecycleObserver

GenericLifecycleObserver的經過Lifecycling.getCallback(observer) 建立實例

@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);
    }複製代碼

建立不一樣的GenericLifecycleObserver並傳入GeneratedAdapter實例,以SingleGeneratedAdapterObserver爲例,實現GenericLifecycleObserver的接口重寫onStateChange()方法,在方法內部調用GeneratedAdapter的callMethod()執行設定Observer的相關方法。

public class SingleGeneratedAdapterObserver implements GenericLifecycleObserver {

    private final GeneratedAdapter mGeneratedAdapter;

    SingleGeneratedAdapterObserver(GeneratedAdapter generatedAdapter) {
        mGeneratedAdapter = generatedAdapter;
    }

    @Override
    public void onStateChanged(LifecycleOwner source, Lifecycle.Event event) {
        mGeneratedAdapter.callMethods(source, event, false, null);
        mGeneratedAdapter.callMethods(source, event, true, null);
    }
}複製代碼

在使用Debug追蹤方法執行,在Lifecycling.getCallback(observer)中返回的是ReflectiveGenericLifecycleObserver,查看源碼

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);
    }
}複製代碼

在構造函數中,初始化CallbackInfo實例,儲存了Observer中定義的方法註解,在CallbackInfo的類中有一段代碼比較明顯:

//獲取Observer的全部方法
 Method[] methods = declaredMethods != null ? declaredMethods : getDeclaredMethods(klass);
        boolean hasLifecycleMethods = false;
        for (Method method : methods) {
            // 獲取方法的註解
            OnLifecycleEvent annotation = method.getAnnotation(OnLifecycleEvent.class);
            if (annotation == null) {
                continue;
            }
            hasLifecycleMethods = true;
            //方法的參數
            Class<?>[] params = method.getParameterTypes();
            int callType = CALL_TYPE_NO_ARG;
            if (params.length > 0) {
                callType = CALL_TYPE_PROVIDER;
                if (!params[0].isAssignableFrom(LifecycleOwner.class)) {
                    throw new IllegalArgumentException(
                            "invalid parameter type. Must be one and instanceof LifecycleOwner");
                }
            }
             // 獲取註解對應的Lifecycle.Event 
            Lifecycle.Event event = annotation.value();

            if (params.length > 1) {
                callType = CALL_TYPE_PROVIDER_WITH_EVENT;
              ...
             }
              //建立MethodReference 封裝了參數和方法
            MethodReference methodReference = new MethodReference(callType, method);
            verifyAndPutHandler(handlerToEvent, methodReference, event, klass);
        }
         // 建立並保存CallbackInfo實例
        CallbackInfo info = new CallbackInfo(handlerToEvent);
        mCallbackMap.put(klass, info);
        mHasLifecycleMethods.put(klass, hasLifecycleMethods);
        return info;複製代碼

上述執行的邏輯很清楚,裏面的幾個屬性須要簡單說明:

  1. MethodReference:封裝了Method的參數類型和方法
  2. handlerToEvent:是一個Map<MethodReference, Lifecycle.Event>,保存MethodReference和對應的Lifecycle.Event事件,上述調用的verifyAndPutHandler()就是將MethodReference和Lifecycle.Event放進Map
  3. mCallbackMap:Map<Class, CallbackInfo>,儲存Observer的類對應的CallbackInfo
  4. mHasLifecycleMethods:用於標註Observer類是否有註解的方法

因此在ReflectiveGenericLifecycleObserver中的CallbackInfo是儲存了Observer中方法信息的實例,咱們只須要在使用的時候獲取並調用其中的方法,因此ReflectiveGenericLifecycleObserver的onStateChange()中調用mInfo.invokeCallbacks(source, event, mWrapped)執行相應的方法,對於添加執行的邏輯總結:

  1. 初始化State爲INITIALIZED或Destroy狀態
  2. 調用ClassesInfoCache.sInstance.getInfo(),遍歷獲取Observer中的全部註解、參數和方法,並對應儲存
  3. 建立ObserverWithState保存狀態和CallbackInfo


到此結束,執行的時候只是按照上面的執行邏輯取出存儲的ObserverWithState中的信息,便可在生命週期改變時,提取儲存的方法和註解,找到目標方法,執行咱們註解的Observer中的邏輯了。

3、實戰

由於前面使用篇已經介紹過用法了,此處至簡單看一下內部執行時的數據

  • MyObserver:簡單建立了LifecyclerObserver子類,並定義兩個方法
class MyLifeObserver : LifecycleObserver {

    @OnLifecycleEvent(Lifecycle.Event.ON_START)
    fun start() {
        Log.e("LifecycleObserver = ", "Start")
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_RESUME)
    fun resume() {
        Log.e("LifecycleObserver = ", "Resume")
    }

}複製代碼
  • 添加時初始化ObserverWithState時儲存的信息:獲取到的正是咱們定義的方法

  • 事件變化時的處理 onStateChange(),最終調用方法以下:

其中handlers的數據就是根據Lifecycler.Event獲取到的註解方法:

到此Lifecycler組件的使用和源碼分析到此結束了,但願有助於對此組件的理解和使用。

相關文章
相關標籤/搜索