本文首發於微信公衆號「後廠村碼農」前端
在上一篇文章中,咱們學習瞭如何去使用Lifecycle,固然之會使用是不夠的,還須要瞭解它的原理,這是成爲優秀工程師必備的。這篇文章就來學習Lifecycle的基本原理。java
Lifecycle使用兩個枚舉來跟蹤其關聯組件的生命週期狀態,這兩個枚舉分別是Event和State。 State指的是Lifecycle的生命週期所處的狀態。 Event表明Lifecycle生命週期對應的事件,這些事件會映射到Activity和Fragment中的回調事件中。android
Android 9.0的Lifecycle的源碼以下所示。 frameworks/support/lifecycle/common/src/main/java/androidx/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();
@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,它可用於匹配全部事件。設計模式
State與Event的關係入下面的時序圖所示。 微信
在Android Support Library 26.1.0 及其以後的版本,Activity和Fragment已經默認實現了LifecycleOwner接口,LifecycleOwner能夠理解爲被觀察者,那麼Lifecycle是如何觀察Activity和Fragment的生命週期的呢?app
在上一篇文章舉的例子中,MainActivity繼承了AppCompatActivity,而AppCompatActivity繼承了FragmentActivity。在Android 8.0時,FragmentActivity繼承自SupportActivity,而在Android 9.0,FragmentActivity繼承自ComponentActivity 。SupportActivity和ComponentActivity的代碼區別不大,這裏以ComponentActivity舉例,以下所示。ide
frameworks/support/compat/src/main/java/androidx/core/app/ComponentActivity.java學習
@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中。this
frameworks/support/lifecycle/runtime/src/main/java/androidx/lifecycle/ReportFragment.java
@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方法。 frameworks/support/lifecycle/runtime/src/main/java/androidx/lifecycle/LifecycleRegistry.java
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方法以下所示。
frameworks/support/lifecycle/runtime/src/main/java/androidx/lifecycle/LifecycleRegistry.java
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方法是如何實現的。 frameworks/support/lifecycle/common/src/main/java/androidx/lifecycle/ReflectiveGenericLifecycleObserver.java
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方法,代碼以下所示。 frameworks/support/lifecycle/common/src/main/java/androidx/lifecycle/ClassesInfoCache.java
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方法。
frameworks/support/lifecycle/common/src/main/java/androidx/lifecycle/ClassesInfoCache.java
@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接口的類中,註解修飾的方法和事件會被保存起來,經過反射對事件的對應方法進行調用。 這個調用鏈的時序圖以下所示。
第2節是以一個調用鏈的形式來介紹Lifecycle,調用鏈中涉及的類具體都是什麼關係很難總體去把握,所以這裏再以UML圖的形式給出Lifecycle關聯類,版本爲Android 9.0。
AppCompatActivity繼承自FragmentActivity,這兩個類都不算是Lifecycle關聯類。FragmentActivity實現了LifecycleOwner接口,LifecycleOwner和Lifecycle有一個"弱擁有的關係",LifecycleRegistry繼承自Lifecycle,剩下的就很少介紹了,看圖一目瞭然。若是看不懂UML類圖,能夠閱讀《大話設計模式》這本書。
更多的內容請關注個人獨立博客的知識體系:
liuwangshu.cn/system/
這裏不只分享大前端、Android、Java等技術,還有程序員成長類文章。