Android開發Jetpack組件Lifecycle原理篇
前言
在上一篇文章中,我們學習瞭如何去使用Lifecycle; 當然之會使用是不夠的,還需要瞭解它的原理,這是成為優秀工程師必備的;這篇文章就來學習Lifecycle的基本原理
1.Lifecycle的生命周期狀態事件和狀態
**Lifecycle使用兩個枚舉來跟蹤其關聯組件的生命周期狀態,這兩個枚舉分別是Event和State;**State指的是Lifecycle的生命周期所處的狀態;Event代表Lifecycle生命周期對應的事件,這些事件會映射到Activity和Fragment中的回調事件中
Android 9.0的Lifecycle的源碼如下所示
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(); @SuppressWarnings("WeakerAccess") public enum Event { ON_CREATE, ON_START, ON_RESUME, ON_PAUSE, ON_STOP, ON_DESTROY, ON_ANY } @SuppressWarnings("WeakerAccess") public enum State { DESTROYED, INITIALIZED, CREATED, STARTED, RESUMED; public boolean isAtLeast(@NonNull State state) { return compareTo(state) >= 0; } } }
Lifecycle是一個抽象類; 其內部不僅包括瞭添加和移除觀察者的方法,還包括瞭此前說到的Event和State枚舉。可以看到Event中的事件和Activity的生命周期幾乎是對應的,除瞭ON_ANY,它可用於匹配所有事件
2.Lifecycle如何觀察Activity和Fragment的生命周期
在Android Support Library 26.1.0 及其之後的版本,Activity和Fragment已經默認實現瞭LifecycleOwner接口,LifecycleOwner可以理解為被觀察者,那麼Lifecycle是如何觀察Activity和Fragment的生命周期的呢?
在上一篇文章舉的例子中,MainActivity繼承瞭AppCompatActivity,而AppCompatActivity繼承瞭FragmentActivity。在Android 8.0時,FragmentActivity繼承自SupportActivity,而在Android 9.0,FragmentActivity繼承自ComponentActivity 。SupportActivity和ComponentActivity的代碼區別不大,這裡以ComponentActivity舉例,如下所示
@RestrictTo(LIBRARY_GROUP) public class ComponentActivity extends Activity implements LifecycleOwner { private SimpleArrayMap<Class<? extends ExtraData>, ExtraData> mExtraDataMap = new SimpleArrayMap<>(); private LifecycleRegistry mLifecycleRegistry = new LifecycleRegistry(this);//1 @RestrictTo(LIBRARY_GROUP) public void putExtraData(ExtraData extraData) { mExtraDataMap.put(extraData.getClass(), extraData); } @Override @SuppressWarnings("RestrictedApi") protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); ReportFragment.injectIfNeededIn(this);//2 } @CallSuper @Override protected void onSaveInstanceState(Bundle outState) { mLifecycleRegistry.markState(Lifecycle.State.CREATED);//3 super.onSaveInstanceState(outState); } @RestrictTo(LIBRARY_GROUP) public <T extends ExtraData> T getExtraData(Class<T> extraDataClass) { return (T) mExtraDataMap.get(extraDataClass); } @Override public Lifecycle getLifecycle() { return mLifecycleRegistry;//4 } @RestrictTo(LIBRARY_GROUP) public static class ExtraData { } }
註釋1處創建瞭LifecycleRegistry,它是Lifecycle的實現類;註釋4處實現瞭LifecycleOwner接口定義的getLifecycle方法,返回瞭LifecycleRegistry。在註釋3處,將Lifecycle的State設置為CREATED;
正常來說應該在ComponentActivity的各個生命周期方法中改變Lifecycle的State,顯然在ComponentActivity中沒有做這些,而是將這個任務交給瞭ReportFragment,註釋2處的將ComponentActivity註入到ReportFragment中
@RestrictTo(RestrictTo.Scope.LIBRARY_GROUP) public class ReportFragment extends Fragment { private static final String REPORT_FRAGMENT_TAG = "androidx.lifecycle" + ".LifecycleDispatcher.report_fragment_tag"; 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(); } } static ReportFragment get(Activity activity) { return (ReportFragment) activity.getFragmentManager().findFragmentByTag( REPORT_FRAGMENT_TAG); } ... @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);//1 } @Override public void onResume() { super.onResume(); dispatchResume(mProcessListener); dispatch(Lifecycle.Event.ON_RESUME); } ... private void dispatch(Lifecycle.Event event) { Activity activity = getActivity(); if (activity instanceof LifecycleRegistryOwner) {//2 ((LifecycleRegistryOwner) activity).getLifecycle().handleLifecycleEvent(event); return; } if (activity instanceof LifecycleOwner) {//3 Lifecycle lifecycle = ((LifecycleOwner) activity).getLifecycle(); if (lifecycle instanceof LifecycleRegistry) { ((LifecycleRegistry) lifecycle).handleLifecycleEvent(event); } } } ... }
ReportFragment的onStart方法中會調用註釋1處的dispatch方法; 在dispatch方法的註釋2處,判斷Activity是否實現瞭LifecycleRegistryOwner接口,LifecycleRegistryOwner繼承瞭LifecycleOwner接口
這兩個接口不同的是: LifecycleRegistryOwner定義的getLifecycle方法返回的是LifecycleRegistry類型,而LifecycleOwner定義的getLifecycle方法返回的是Lifecycle類型。註釋3處如果Activity實現瞭LifecycleOwner接口,會調用LifecycleRegistry的handleLifecycleEvent方法
public void handleLifecycleEvent(@NonNull Lifecycle.Event event) { State next = getStateAfter(event); moveToState(next); }
getStateAfter方法會獲取“即將的事件” :當前事件執行後,即將會處於什麼事件,代碼如下所示
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); }
這個和文章開頭給出的State與Event關系的時序圖對照看會比較好理解; 比如當前執行瞭ON_CREATE事件或者ON_STOP事件,那麼狀態就會處於CREATED;回到handleLifecycleEvent方法,其內部還會調用moveToState方法
private void moveToState(State next) { if (mState == next) { return; } mState = next; if (mHandlingEvent || mAddingObserverCounter != 0) { mNewEventOccurred = true; return; } mHandlingEvent = true; sync(); mHandlingEvent = false; }
如果當前所處的狀態和即將要處於的狀態一樣就不做任何操作,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; 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; }
sync方法中會根據當前狀態和mObserverMap中的eldest和newest的狀態做對比 ,判斷當前狀態是向前還是向後; 比如由STARTED到RESUMED是狀態向前,反過來就是狀態向後,這個不要和Activity的生命周期搞混;向前還是向後的代碼大同小異,這裡以向後為例
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();//1 while ((observer.mState.compareTo(mState) < 0 && !mNewEventOccurred && mObserverMap.contains(entry.getKey()))) { pushParentState(observer.mState); observer.dispatchEvent(lifecycleOwner, upEvent(observer.mState));//2 popParentState(); } } }
註釋1處的用於獲取ObserverWithState,後面會在提到它。 註釋2處的upEvent方法會得到當前狀態的向前狀態
ObserverWithState的dispatchEvent方法如下所示
static class ObserverWithState { State mState; GenericLifecycleObserver mLifecycleObserver; ObserverWithState(LifecycleObserver observer, State initialState) { mLifecycleObserver = Lifecycling.getCallback(observer);//1 mState = initialState; } void dispatchEvent(LifecycleOwner owner, Event event) { State newState = getStateAfter(event); mState = min(mState, newState); mLifecycleObserver.onStateChanged(owner, event); mState = newState; } }
從名稱就可以看出來,它內部包括瞭State和GenericLifecycleObserver,GenericLifecycleObserver是一個接口,它繼承瞭LifecycleObserver接口; ReflectiveGenericLifecycleObserver和CompositeGeneratedAdaptersObserver是GenericLifecycleObserver的實現類,這裡主要查看ReflectiveGenericLifecycleObserver的onStateChanged方法是如何實現的
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 } }
註釋1處會調用CallbackInfo的invokeCallbacks方法,在講這個方法前,需要先瞭解CallbackInfo是怎麼創建的,是由createInfo方法創建的,如下所示
private CallbackInfo createInfo(Class klass, @Nullable Method[] declaredMethods) { Class superclass = klass.getSuperclass(); Map<MethodReference, Lifecycle.Event> handlerToEvent = new HashMap<>(); ... Method[] methods = declaredMethods != null ? declaredMethods : getDeclaredMethods(klass); boolean hasLifecycleMethods = false; for (Method method : methods) { OnLifecycleEvent annotation = method.getAnnotation(OnLifecycleEvent.class);//1 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 event = annotation.value();//2 ... MethodReference methodReference = new MethodReference(callType, method);//3 verifyAndPutHandler(handlerToEvent, methodReference, event, klass);//4 } CallbackInfo info = new CallbackInfo(handlerToEvent);//5 mCallbackMap.put(klass, info); mHasLifecycleMethods.put(klass, hasLifecycleMethods); return info; }
關鍵點在註釋1處; 不斷的遍歷各個方法,獲取方法上的名為OnLifecycleEvent的註解,這個註解正是實現LifecycleObserver接口時用到的。
註釋2處獲取該註解的值; 也就是在@OnLifecycleEvent中定義的事件
註釋3處新建瞭一個MethodReference; 其內部包括瞭使用瞭該註解的方法
註釋4處的verifyAndPutHandler方法用於將MethodReference和對應的Event存在類型為Map<MethodReference, Lifecycle.Event>
的handlerToEvent中
註釋5處新建CallbackInfo,並將handlerToEvent傳進去
接著回頭看CallbackInfo的invokeCallbacks方法,代碼如下所示
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()) {//1 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) { invokeMethodsForEvent(mEventToHandlers.get(event), source, event, target);//2 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);//1 } } }
註釋1處的循環的意義在於將handlerToEvent進行數據類型轉換,轉化為一個HashMap,key的值為事件,value的值為MethodReference。註釋2處的invokeMethodsForEvent方法會傳入mEventToHandlers.get(event),也就是事件對應的MethodReference的集合。invokeMethodsForEvent方法中會遍歷MethodReference的集合,調用MethodReference的invokeCallback方法
@SuppressWarnings("WeakerAccess") 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); } } ... }
MethodReference類中有兩個變量,一個是callType,它代表調用方法的類型,另一個是Method; 它代表方法,不管是哪種callType都會通過invoke對方法進行反射。 簡單來說,實現LifecycleObserver接口的類中,註解修飾的方法和事件會被保存起來,通過反射對事件的對應方法進行調用
到此這篇關於Android開發Jetpack組件Lifecycle使用原理篇的文章就介紹到這瞭,更多相關Android Jetpack組件Lifecycle內容請搜索WalkonNet以前的文章或繼續瀏覽下面的相關文章希望大傢以後多多支持WalkonNet!
推薦閱讀:
- Android mvvm之LiveData原理案例詳解
- Android開發Jetpack組件Lifecycle使用篇
- Android Jetpack 組件LiveData源碼解析
- Android開發Viewbinding委托實例詳解
- Android內存泄漏的原因及解決技巧