您好,登錄后才能下訂單哦!
這篇文章主要介紹“Android如何開發Jetpack組件Lifecycle”的相關知識,小編通過實際案例向大家展示操作過程,操作方法簡單快捷,實用性強,希望這篇“Android如何開發Jetpack組件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,它可用于匹配所有事件
在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”的內容就介紹到這里了,感謝大家的閱讀。如果想了解更多行業相關的知識,可以關注億速云行業資訊頻道,小編每天都會為大家更新不同的知識點。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。