Lifecycle原始碼淺析

我啥時候說啦jj發表於2019-05-06

之前用過一些android架構元件,但也僅限於api呼叫,知其然也該知其所以然,所以嘗試瞭解下其原始碼實現;

本文主要想簡單探究下以下問題:

  1. Lifecycle 如何知曉 Activity 的生命週期變化;
  2. LifecycleObserver 的註解如何生效;

本文基於: macOS 10.13/AS 3.4/support-v7 28.0.0

demo專案

使用方法簡介

以前拆分業務邏輯到獨立的 presenter 中時,需要重寫 Activity/Fragment 各生命週期,然後告知 presenter, 寫起來麻煩, 有沒有比較簡單的方式能把這些"髒活"給處理掉呢?

我們看看 Lifecycle 的用法:

// MainActiviy.kt
class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        lifecycle.addObserver(MainActObserver())
    }
}

// MainActObserver.kt
class MainActObserver : LifecycleObserver {
    @OnLifecycleEvent(Lifecycle.Event.ON_CREATE)
    fun onCreate() {
        Logger.d("MainActObserver $this onCreate")
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_RESUME)
    fun onResume() {
        Logger.d("MainActObserver onResume")
    }
    // 其他生命週期回撥,此處省略
}
複製程式碼

可以看到就簡單一句 lifecycle.addObserver(MainActObserver()) 就完成了 Activity 各生命週期的監聽;

P.S. 由於 Android Studio 建立專案時預設匯入了 support 的 appcompat-v7 包,已經把 Lifecycle 相關程式碼匯入進來了, 因此我們可以直接使用,不需要額外新增依賴;

以下就從 lifecycle.addObserver(MainActObserver()) 展開:

先認識下 Lifecycle

// package android.arch.lifecycle;
// Lifecycle.java
public abstract class Lifecycle {
    @MainThread
    public abstract void addObserver(@NonNull LifecycleObserver observer);

    @MainThread
    public abstract void removeObserver(@NonNull LifecycleObserver observer);

    @MainThread
    @NonNull
    public abstract State getCurrentState();

    // 生命週期事件
    public enum Event {
        ON_CREATE, ON_START, ON_RESUME, ON_PAUSE, ON_STOP, ON_DESTROY, ON_ANY
    }

    // 生命週期狀態
    public enum State {
        // 以下均已 Activity 為例,介紹各狀態值,具體請看原始碼註釋
        DESTROYED,
        INITIALIZED, // 物件建立後但尚未收到 onCreate() 通知之前
        CREATED,// onCreate()/onStop() 之後
        STARTED, // onStart()/onPause() 之後
        RESUMED; // onResume() 之後
        public boolean isAtLeast(@NonNull State state) {
            return compareTo(state) >= 0;
        }
    }
}
複製程式碼

可以發現: Lifecycle 只是個抽象類,也沒有對生命週期的變化做出響應的方法,只是簡單定義了生命週期事件及狀態, 因此應該有個實現類對生命週期事件作出處理;

順便看下 MainActObserver

它實現了 LifecycleObserver 介面,而 LifecycleObserver 僅是一個標記介面:

/**
 * Marks a class as a LifecycleObserver. It does not have any methods, instead, relies on {@link OnLifecycleEvent} annotated methods.
 * 這是個標記性介面,沒有任何方法
 */
public interface LifecycleObserver {
}

/**
 * 通過上面 LifecycleObserver 的註釋,可以發現,最終是通過本註解來實現生命週期感知的
 */
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface OnLifecycleEvent {
    Lifecycle.Event value();
}
複製程式碼

通過程式碼註釋我們也可大概猜到:各生命週期事件應該是通過遍歷 LifecycleObserver 實現類,查詢帶有 OnLifecycleEvent 註解的方法,然後進行回撥的;

言歸正傳,探究下 getLifecycle()

activity類圖

// package android.support.v4.app;
// FragmentActivity.java
public class FragmentActivity extends SupportActivity {
    public Lifecycle getLifecycle() {
        return super.getLifecycle();
    }
}

// package android.support.v4.app;
// SupportActivity.java
public class SupportActivity extends Activity implements LifecycleOwner, Component {
    // LifecycleRegistry 是 Lifecycle 的實現類,所有邏輯由其來完成
    private LifecycleRegistry mLifecycleRegistry = new LifecycleRegistry(this);
    public Lifecycle getLifecycle() {
        return this.mLifecycleRegistry;
    }
}
複製程式碼

lifecycle

從上圖可知, LifecycleRegistry 應能會接收並處理各生命週期事件/狀態,並通過 sync() 同步到各observer;

生命週期狀態的變化順序

回看 Lifecycle 原始碼,發現生命週期狀態(State)的個數小於事件(Event)的個數,因此應該有多個事件歸屬於同一個狀態,並且狀態之間的變化規律應該也定義在 LifecycleRegistry 中:

// package android.arch.lifecycle;
// LifecycleRegistry.java
public class LifecycleRegistry extends Lifecycle {
    private State mState; // 當前狀態

    // 使用弱引用,避免影響Activity的GC
    public LifecycleRegistry(@NonNull LifecycleOwner provider) {
        mLifecycleOwner = new WeakReference<>(provider);
        mState = INITIALIZED;
    }

    // 計算髮生某個生命週期時間後應有的狀態
    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 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);
    }
}
複製程式碼

可得出下圖(圖片來自官網):

狀態圖

生命週期事件/狀態的處理

// package android.arch.lifecycle;
// LifecycleRegistry.java
public class LifecycleRegistry extends Lifecycle {

    /**
     * 由於實際生命週期事件多於lifecycle定義的數量,可能有部分生命週期回撥需要直接指定其當前的狀態,
     * 如: SupportActivity 的 onSaveInstanceState(Bundle) 事件, 就被直接標記為 CREATED 狀態
    */
    @MainThread
    public void markState(@NonNull State state) {
        moveToState(state);
    }

   public void handleLifecycleEvent(@NonNull Lifecycle.Event event) {
        State next = getStateAfter(event); // 計算事件發生後的狀態
        moveToState(next); // 更新當前狀態
    }

    // Activity 生命週期事件變化時都會走到這裡, 最終通過 sync() 方法通知各 observer
    private void moveToState(State next) {
        if (mState == next) {
            return;
        }
        mState = next; // 更新當前狀態
        if (mHandlingEvent || mAddingObserverCounter != 0) {
            mNewEventOccurred = true;
            return;
        }
        mHandlingEvent = true;
        sync(); // 通知各 LifecycleObserver 更新狀態
        mHandlingEvent = false;
    }

    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.
            // 如果當前狀態比observerMap中最小的狀態值還小,則回退狀態
            if (mState.compareTo(mObserverMap.eldest().getValue().mState) < 0) {
                backwardPass(lifecycleOwner);
            }

            // 如果當前狀態比observerMap中最大的狀態值還大,則前移狀態
            Entry<LifecycleObserver, ObserverWithState> newest = mObserverMap.newest();
            if (!mNewEventOccurred && newest != null
                    && mState.compareTo(newest.getValue().mState) > 0) {
                forwardPass(lifecycleOwner);
            }
        }
        mNewEventOccurred = false;
    }
}
複製程式碼

無論 backwardPass(LifecycleOwner) 還是 forwardPass(LifecycleOwner) 最終都是呼叫 ObserverWithState 類的 dispatchEvent(LifecycleOwner, Event) 方法, 我們來看下這個類:

// LifecycleRegistry.java
public class LifecycleRegistry extends Lifecycle {
    private FastSafeIterableMap<LifecycleObserver, ObserverWithState> mObserverMap =
            new FastSafeIterableMap<>();

    @Override
    public void addObserver(@NonNull LifecycleObserver observer) {
        State initialState = mState == DESTROYED ? DESTROYED : INITIALIZED;
        // 我們定義的 LifecycleObserver 被包裝成 ObserverWithState
        ObserverWithState statefulObserver = new ObserverWithState(observer, initialState);
        // 快取所有的observer,後續用於遍歷回撥通知
        ObserverWithState previous = mObserverMap.putIfAbsent(observer, statefulObserver);
        // 省略部分程式碼
    }

    static class ObserverWithState {
        State mState;
        GenericLifecycleObserver mLifecycleObserver;

        ObserverWithState(LifecycleObserver observer, State initialState) {
            // GenericLifecycleObserver 繼承自 LifecycleObserver,此處又做了一次包裝
            mLifecycleObserver = Lifecycling.getCallback(observer);
            mState = initialState;
        }

        // 當 LifecycleOwner 生命週期變化時,通過本方法來通知各 LifeObserver
        void dispatchEvent(LifecycleOwner owner, Event event) {
            State newState = getStateAfter(event);
            mState = min(mState, newState);
            mLifecycleObserver.onStateChanged(owner, event);
            mState = newState;
        }
    }
}
複製程式碼

到此,我們知道了 LifecycleRegistry 通知 LifecycleOwner 的大體流程,但我們仍然沒看到我們的註解如何發生作用,如何收到生命週期事件,接下來我們就來看看

生命週期註解的使用

// package android.arch.lifecycle;
// Lifecycling.java
public class Lifecycling {

   @NonNull
    static GenericLifecycleObserver getCallback(Object object) {
        if (object instanceof FullLifecycleObserver) {
            return new FullLifecycleObserverAdapter((FullLifecycleObserver) object);
        }

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

        // 由於我沒有使用 LifeCycleCompiler ,因此不會生成  MainActObserver_LifecycleAdapter 類, 此if判斷不滿足
        // P.S. MainActObserver_LifecycleAdapter 位於: app/build/generated/source/kapt/debug/***
        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);
        }

        // 最終是通過反射獲取 LifecycleObserver 的方法
        // 但反射比較耗效能, 因此可以猜想應該有做快取優化
        return new ReflectiveGenericLifecycleObserver(object);
    }
}
複製程式碼
// package android.arch.lifecycle;
// ReflectiveGenericLifecycleObserver.java
class ReflectiveGenericLifecycleObserver implements GenericLifecycleObserver {
    private final Object mWrapped;
    private final CallbackInfo mInfo;

    ReflectiveGenericLifecycleObserver(Object wrapped) {
        mWrapped = wrapped;
        // 可以猜想 ClassesInfoCache 是用於快取 包含lifecycle生命週期事件方法的
        mInfo = ClassesInfoCache.sInstance.getInfo(mWrapped.getClass());
    }

    @Override
    public void onStateChanged(LifecycleOwner source, Event event) {
        // 當Activity生命週期發生變化時,通過 CallbackInfo 來觸發 LifecycleObserver 各方法
        // 因此重點就在 ClassesInfoCache 類生成的 CallbackInfo 中
        mInfo.invokeCallbacks(source, event, mWrapped);
    }
}
複製程式碼
// package android.arch.lifecycle;
// ClassesInfoCache.java
class ClassesInfoCache {
    CallbackInfo getInfo(Class klass) {
        // 由於執行時反射成本大, 因此先查快取,若不存在,則反射提取各方法
        CallbackInfo existing = mCallbackMap.get(klass);
        if (existing != null) {
            return existing;
        }
        existing = createInfo(klass, null);
        return existing;
    }

    private CallbackInfo createInfo(Class klass, @Nullable Method[] declaredMethods) {
        // 檢視父類是否也有生命週期事件註解,若有,一併新增到快取中
        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);
            }
        }

        // 遍歷我們定義的 LifecycleObserver 實現類方法, 若帶有 OnLifecycleEvent 註解,則快取
        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;

            // 自定義的方法允許帶有引數,並且第一個引數型別只能是 LifecycleOwner
            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();

            // 若註解事件是 Lifecycle.Event.ON_ANY, 則還允許有第二個引數,但引數型別必須是 Lifecycle.Event
            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");
                }
            }

            // 引數個數不允許超過2個
            if (params.length > 2) {
                throw new IllegalArgumentException("cannot have more than 2 params");
            }

            // 若handlerToEvent中無該方法的快取,則新增進去
            MethodReference methodReference = new MethodReference(callType, method);
            verifyAndPutHandler(handlerToEvent, methodReference, event, klass);
        }

        // 將搜尋到的帶註解事件方法列表快取到CallbackInfo中,並返回
        CallbackInfo info = new CallbackInfo(handlerToEvent);
        // 把相關的 LifecycleObserver 類及相應註解方法都快取到 mCallbackMap 中
        mCallbackMap.put(klass, info);
        mHasLifecycleMethods.put(klass, hasLifecycleMethods);
        return info;
    }

    static class CallbackInfo {
        final Map<Lifecycle.Event, List<MethodReference>> mEventToHandlers;
        final Map<MethodReference, Lifecycle.Event> mHandlerToEvent;

        CallbackInfo(Map<MethodReference, Lifecycle.Event> handlerToEvent) {
            mHandlerToEvent = handlerToEvent;
            mEventToHandlers = new HashMap<>();
            for (Map.Entry<MethodReference, Lifecycle.Event> entry : handlerToEvent.entrySet()) {
                Lifecycle.Event event = entry.getValue();
                List<MethodReference> methodReferences = mEventToHandlers.get(event);
                if (methodReferences == null) {
                    methodReferences = new ArrayList<>();
                    mEventToHandlers.put(event, methodReferences);
                }
                methodReferences.add(entry.getKey());
            }
        }

        @SuppressWarnings("ConstantConditions")
        void invokeCallbacks(LifecycleOwner source, Lifecycle.Event event, Object target) {
            // 呼叫一次對應 event 事件的註解方法,同一個event事件可能存在多個註解方法,需要遍歷
            invokeMethodsForEvent(mEventToHandlers.get(event), source, event, target);
            // 任意事件都會觸發一次 ON_ANY 註解方法
            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) {
                // 遍歷指定 event 事件對應的方法列表, 觸發 MethodReference 的 invokeCallback(*) 方法
                for (int i = handlers.size() - 1; i >= 0; i--) {
                    handlers.get(i).invokeCallback(source, event, mWrapped);
                }
            }
        }
    }

    static class MethodReference {
        final int mCallType;
        final Method mMethod;

        MethodReference(int callType, Method method) {
            mCallType = callType;
            mMethod = method;
            mMethod.setAccessible(true);
        }

        void invokeCallback(LifecycleOwner source, Lifecycle.Event event, Object target) {
            // 關於方法引數個數問題,上面已經有說過
            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);
            }
        }
    }
}
複製程式碼

至此我們就知曉了 LifecycleRegistry 處理生命週期變化的邏輯及如何回撥通知被各註解標記的方法的, 但它是如何知道 Activity 生命週期的? 這個我們還沒有看到,下面探究下;

LifecycleRegistry 如何獲知 Activity 的生命週期變化

偶然看了眼 SupportActivity 類的導包列表,發現 android.arch.lifecycle 包下除了 ReportFragment 類外都有分析過, 我們來看看它的作用:

package android.support.v4.app;

import android.arch.lifecycle.Lifecycle;
import android.arch.lifecycle.LifecycleOwner;
import android.arch.lifecycle.LifecycleRegistry;
import android.arch.lifecycle.ReportFragment;
import android.arch.lifecycle.Lifecycle.State;

@RestrictTo({Scope.LIBRARY_GROUP})
public class SupportActivity extends Activity implements LifecycleOwner, Component {

    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ReportFragment.injectIfNeededIn(this);
    }
}
複製程式碼
// package android.arch.lifecycle;
// ReportFragment.java
public class ReportFragment extends Fragment {
    private static final String REPORT_FRAGMENT_TAG = "android.arch.lifecycle"
            + ".LifecycleDispatcher.report_fragment_tag";

    /**
     * 搜尋當前activity中是否已有 ReportFragment, 若無,則建立並注入
     */
    public static void injectIfNeededIn(Activity activity) {
        android.app.FragmentManager manager = activity.getFragmentManager();
        if (manager.findFragmentByTag(REPORT_FRAGMENT_TAG) == null) {
            manager.beginTransaction().add(new ReportFragment(), REPORT_FRAGMENT_TAG).commit();
            manager.executePendingTransactions();
        }
    }

    /**
     * 通過fragment的生命週期來獲知activity的生命週期
     * 然後通過 dispatch(event) 來通知各 LifecycleObserver
     */
    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        dispatch(Lifecycle.Event.ON_CREATE);
    }

    @Override
    public void onStart() {
        super.onStart();
        dispatch(Lifecycle.Event.ON_START);
    }

    @Override
    public void onResume() {
        super.onResume();
        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);
    }

    private void dispatch(Lifecycle.Event event) {
        Activity activity = getActivity();
        if (activity instanceof LifecycleRegistryOwner) {
            ((LifecycleRegistryOwner) activity).getLifecycle().handleLifecycleEvent(event);
            return;
        }

        // 此處就把activity的生命週期事件傳送到 LifecycleRegistry 中了
        if (activity instanceof LifecycleOwner) {
            Lifecycle lifecycle = ((LifecycleOwner) activity).getLifecycle();
            if (lifecycle instanceof LifecycleRegistry) {
                ((LifecycleRegistry) lifecycle).handleLifecycleEvent(event);
            }
        }
    }
}
複製程式碼

至此,整體流程就通了,不過我還是有點疑問,知道的童鞋可以幫忙解惑下:

  1. 為何要通過注入 Fragment 的方式來獲取 Activity 的生命週期, 通過 ActivityLifecycleCallbacks 也可以吧?

  2. 為何 ReportFragment 是繼承自已被Deprecated的 android.app.Fragment?

    整套lifecycle的實現是基於 SupportActivity 的, support-fragment 庫已被匯入, injectIfNeededIn(Activity) 引數型別不需要非得是 Activity 吧?

小結

  1. ReportFragmentSupportActivity 建立後被注入到Activity中,作為"中介",監聽 Activity 的生命週期變化,並把事件傳遞給 LifecycleRegistry;
  2. LifecycleRegistry 會弱引用其所在的 SupportActivity, 並管理各 LifecycleObserver;
  3. 我們自定義的 LifecycleObserver 實現類, 預設會在執行時通過反射查詢並快取帶有 OnLifecycleEvent 註解的方法;
  4. 若使用 lifeCycleCompiler 庫(kapt("android.arch.lifecycle:compiler:1.1.1")),則自定義的 LifecycleObserver 類會在編譯時生成 *_LifecycleAdapter 類, 避免執行時反射;
  5. LifecycleObserver 實現類中的相關注解方法允許帶有最多2個引數;

相關文章