以前用過一些android架構組件,但也僅限於api調用,知其然也該知其因此然,因此嘗試瞭解下其源碼實現;java
本文主要想簡單探究下如下問題:android
- Lifecycle 如何知曉 Activity 的生命週期變化;
- LifecycleObserver 的註解如何生效;
本文基於: macOS 10.13/AS 3.4/support-v7 28.0.0git
demo項目github
之前拆分業務邏輯到獨立的 presenter
中時,須要重寫 Activity
/Fragment
各生命週期,而後告知 presenter
, 寫起來麻煩, 有沒有比較簡單的方式能把這些"髒活"給處理掉呢?api
咱們看看 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
各生命週期的監聽;markdown
P.S. 因爲
Android Studio
建立項目時默認導入了 support 的appcompat-v7
包,已經把Lifecycle
相關代碼導入進來了, 所以咱們能夠直接使用,不須要額外添加依賴;架構
如下就從 lifecycle.addObserver(MainActObserver())
展開:app
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
只是個抽象類,也沒有對生命週期的變化作出響應的方法,只是簡單定義了生命週期事件及狀態, 所以應該有個實現類對生命週期事件做出處理;ide
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()
// 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; } } 複製代碼
從上圖可知, 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); } } } } 複製代碼
至此,總體流程就通了,不過我仍是有點疑問,知道的童鞋能夠幫忙解惑下:
爲什麼要經過注入 Fragment
的方式來獲取 Activity
的生命週期, 經過 ActivityLifecycleCallbacks
也能夠吧?
爲什麼 ReportFragment
是繼承自已被Deprecated的 android.app.Fragment
?
整套lifecycle的實現是基於 SupportActivity
的, support-fragment
庫已被導入, injectIfNeededIn(Activity)
參數類型不須要非得是 Activity
吧?
ReportFragment
在 SupportActivity
建立後被注入到Activity中,做爲"中介",監聽 Activity
的生命週期變化,並把事件傳遞給 LifecycleRegistry
;LifecycleRegistry
會弱引用其所在的 SupportActivity
, 並管理各 LifecycleObserver
;LifecycleObserver
實現類, 默認會在運行時經過反射查找並緩存帶有 OnLifecycleEvent
註解的方法;lifeCycleCompiler
庫(kapt("android.arch.lifecycle:compiler:1.1.1")
),則自定義的 LifecycleObserver
類會在編譯時生成 *_LifecycleAdapter
類, 避免運行時反射;LifecycleObserver
實現類中的相關注解方法容許帶有最多2個參數;