前言
系列文章
android.arch.lifecycle 包提供了類和接口允許你構(gòu)建生命周期感知(lifecycle-aware)的組件——可以基于當(dāng)前activity或fragment生命周期自動調(diào)節(jié)它們的行為的組件。
注意:將 android.arch.lifecycle 導(dǎo)入Android工程祸憋,請參見將Architecture Components引入工程会宪。
大部分定義在Android框架中的組件都包含附加到其上的生命周期。這些生命周期由操作系統(tǒng)或運行在你的進程中的框架代碼管理蚯窥。它們是Android如何工作的核心掸鹅,你的應(yīng)用程序必須尊重它們塞帐。不這樣做可能會觸發(fā)內(nèi)存泄漏甚至應(yīng)用程序崩潰。
常用場景
- 位置獲取精細度的切換巍沙,在程序可見啟用精度高定位葵姥,程序進入后臺切換低精度定位
- 視頻緩沖,在生命周期組件啟動啟動視頻緩沖句携,延遲緩沖直到應(yīng)用程序完全啟動榔幸,在終止應(yīng)用的時候銷毀。
- 啟動停止網(wǎng)絡(luò)連接矮嫉,程序在前臺的時候更新網(wǎng)絡(luò)數(shù)據(jù)削咆,后臺的時候取消或暫停
- 暫停或者回復(fù)動畫繪制敞临。使用生命周期組件的時候在后臺的時候暫停動畫繪制态辛,前臺的時候恢復(fù)繪制。
用法
-
觀察者模式: 觀察者模式面向的需求是:A對象(觀察者)對B對象(被觀察者)的某種變化高度敏感挺尿,需要在B變化的一瞬間做出反應(yīng)奏黑。舉個例子,新聞里喜聞樂見的警察抓小偷编矾,警察需要在小偷伸手作案的時候?qū)嵤┳ゲ妒焓贰T谶@個例子里,警察是觀察者窄俏、小偷是被觀察者蹂匹,警察需要時刻盯著小偷的一舉一動,才能保證不會錯過任何瞬間凹蜈。程序里的觀察者和這種真正的【觀察】略有不同限寞,觀察者不需要時刻盯著被觀察者(例如A不需要每隔1ms就檢查一次B的狀態(tài)),二是采用注冊(Register)或者成為訂閱(Subscribe)的方式告訴被觀察者:我需要你的某某狀態(tài)仰坦,你要在它變化時通知我履植。采取這樣被動的觀察方式,既省去了反復(fù)檢索狀態(tài)的資源消耗悄晃,也能夠得到最高的反饋速度
在lifecycle中玫霎,LifecycleObserver 是觀察者都需要到被觀察者Lifecycle中去注冊,在生命周期有變化的時候告知所有的observer
- 自定義觀察者
eg:
public class MyLifecycle implements LifecycleObserver { @OnLifecycleEvent(Lifecycle.Event.ON_ANY) void onAny(LifecycleOwner owner, Lifecycle.Event event) { System.out.println("onAny:" + event.name()); } @OnLifecycleEvent(Lifecycle.Event.ON_CREATE) void onCreate() { System.out.println("onCreate"); } @OnLifecycleEvent(Lifecycle.Event.ON_DESTROY) void onDestroy() { System.out.println("onDestroy"); } }
- 在activity或者fragmetn中注冊
getLifecycle().addObserver(new MyLifecycle());
- 在service中注冊繼承LifecycleService
public class MyService extends LifecycleService { @Override public void onCreate() { super.onCreate(); getLifecycle().addObserver(new MyLifecycle()); } }
- 監(jiān)測app進入前后臺的寫法
public class App extends Application { @Override public void onCreate() { super.onCreate(); ProcessLifecycleOwner.get().getLifecycle().addObserver(new MyLifecycle()); } }
- 自定義觀察者
代碼分析
- 先不看官方代碼妈橄,手寫代碼實現(xiàn)lifecycle功能
-
觀察者
public interface LifecycleObserver { public abstract void onStateChanged(Lifecycle.Event mEvent); }
-
被觀察者lifecycle
package com.delta.androiddagger; /** * description : * * @author : Wenju.Tian * @version date : 2017/11/6 14:58 */ public abstract class Lifecycle { public abstract void addObserver(LifecycleObserver observer); public abstract void removeObserver(LifecycleObserver observer); public abstract void handleLifecycleEvent( Event event); @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; } }
在官方的libary中l(wèi)ifecycle扮演者被觀察者(小偷)的角色庶近,所有的觀察者(警察)都要在這里注冊,移除眷蚓,notify.
-
被觀察者實現(xiàn)類LifecycleRegistry
public class LifecycleRegistry extends Lifecycle { private State mState; private List<LifecycleObserver> mObservers = new ArrayList<>(); @Override public void addObserver(LifecycleObserver observer) { if (mObservers.contains(observer)) { return; } mObservers.add(observer); } @Override public void removeObserver(LifecycleObserver observer) { if (mObservers.contains(observer)) { mObservers.remove(observer); } } @Override public void handleLifecycleEvent(Event event) { for (LifecycleObserver mObserver : mObservers) { if (sync(event)) //判斷event狀態(tài)執(zhí)行change方法 mObserver.onStateChanged(event); } } private boolean sync(Event event) { State mStateAfter = getStateAfter(event); if (mState==mStateAfter) return false; return true; }; 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); } }
其中我們需要關(guān)心的有三點
- addObserver 添加觀察者
- handleLifecycleEvent(Event event) 通知觀察者
- 怎么獲取Event從而調(diào)用handleLifecycleEvent鼻种。
在官方libary中LifecycleRegistry時lifecycle的實現(xiàn)類,這里我們是模擬其實現(xiàn)沙热,handleLifecycleEvent是真正處理事件的方法普舆,在這里可以遍歷observer,根據(jù)相應(yīng)的狀態(tài)變更恬口,notify相應(yīng)的observer.
-
自定義Activity(這里不是Android四大組件)
public class MyActivity { private LifecycleRegistry mLifecycleRegistry = new LifecycleRegistry(); public LifecycleRegistry getLifecycleRegistry() { return mLifecycleRegistry; } public static void main(String[] args) { new MyActivity().getLifecycleRegistry().addObserver(new LifecycleObserver() { @Override public void onStateChanged(Lifecycle.Event mEvent) { } }); lifecycleRegistry.handleLifecycleEvent(Lifecycle.Event.ON_START); } }
這個類是我們模擬的activity,activity中擁有一個被觀察者叫LifecycleRegistry。在官方源碼中對應(yīng)的activity中也會有這樣一個LifecycleRegistry沼侣。我們總結(jié)一下就是==LifecycleRegistry在獲取Event事件之后用handleLifecycleEvent方法通知所有的觀察者做出相應(yīng)的改變祖能。==
-
官方源代碼分析
我們主要從三點進行分析
- addObserver 添加觀察者
- handleLifecycleEvent(Event event) 通知觀察者
- 怎么獲取Event從而調(diào)用handleLifecycleEvent。
-
首先看下被觀察者LifecycleRegistry,我們看下他的addObserver
@Override public void addObserver(@NonNull LifecycleObserver observer) { State initialState = mState == DESTROYED ? DESTROYED : INITIALIZED; ObserverWithState statefulObserver = new ObserverWithState(observer, initialState); ObserverWithState previous = mObserverMap.putIfAbsent(observer, statefulObserver); if (previous != null) { return; } LifecycleOwner lifecycleOwner = mLifecycleOwner.get(); if (lifecycleOwner == null) { // it is null we should be destroyed. Fallback quickly return; } boolean isReentrance = mAddingObserverCounter != 0 || mHandlingEvent; State targetState = calculateTargetState(observer); mAddingObserverCounter++; while ((statefulObserver.mState.compareTo(targetState) < 0 && mObserverMap.contains(observer))) { pushParentState(statefulObserver.mState); statefulObserver.dispatchEvent(lifecycleOwner, upEvent(statefulObserver.mState)); popParentState(); // mState / subling may have been changed recalculate targetState = calculateTargetState(observer); } if (!isReentrance) { // we do sync only on the top level. sync(); } mAddingObserverCounter--; }
我們的被觀察著傳入進來之后蛾洛,首先被封裝成ObserverWithState养铸,意思是帶狀態(tài)的Observer,初始化的是INITIALIZED或者DESTROYED轧膘,然后放入我們的mObserverMap,管理起來钞螟。我們看下ObserverWithState源碼
static class ObserverWithState { State mState; GenericLifecycleObserver mLifecycleObserver; ObserverWithState(LifecycleObserver observer, State initialState) { mLifecycleObserver = Lifecycling.getCallback(observer); mState = initialState; } void dispatchEvent(LifecycleOwner owner, Event event) { State newState = getStateAfter(event); mState = min(mState, newState); mLifecycleObserver.onStateChanged(owner, event); mState = newState; } }
里面有兩個變量,mState存放的是這個observer的狀態(tài)谎碍,傳入進來的observer通過Lifecycling.getCallback(observer)返回了一個GenericLifecycleObserver對象鳞滨,我們先看下getCallback方法做了什么
@NonNull static GenericLifecycleObserver getCallback(Object object) { if (object instanceof FullLifecycleObserver) { return new FullLifecycleObserverAdapter((FullLifecycleObserver) object); } if (object instanceof GenericLifecycleObserver) { return (GenericLifecycleObserver) object; } 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); } return new ReflectiveGenericLifecycleObserver(object); }
當(dāng)調(diào)用 getCallback 時,Lifecycling 會根據(jù)傳入的 Object(LifecycleObserver)調(diào)用 getGeneratedAdapterConstructor蟆淀。接著看源碼
@Nullable private static Constructor<? extends GenericLifecycleObserver> getGeneratedAdapterConstructor( Class<?> klass) { final String fullPackage = klass.getPackage().getName(); String name = klass.getCanonicalName(); // anonymous class bug:35073837 if (name == null) { return null; } final String adapterName = getAdapterName(fullPackage.isEmpty() ? name : name.substring(fullPackage.length() + 1)); try { @SuppressWarnings("unchecked") final Class<? extends GenericLifecycleObserver> aClass = (Class<? extends GenericLifecycleObserver>) Class.forName( fullPackage.isEmpty() ? adapterName : fullPackage + "." + adapterName); return aClass.getDeclaredConstructor(klass); } catch (ClassNotFoundException e) { final Class<?> superclass = klass.getSuperclass(); if (superclass != null) { // 找不到 LifecycleAdapter 時獲取父類的 LifecycleAdapter return getGeneratedAdapterConstructor(superclass); } } catch (NoSuchMethodException e) { // this should not happen throw new RuntimeException(e); } return null; } static String getAdapterName(String className) { return className.replace(".", "_") + "_LifecycleAdapter"; }
不難看出拯啦,getGeneratedAdapterConstructor 主要是獲取 annotationProcessor 生成的 xxx_LifecycleAdapter(eg:我們定義了MyLifecycle,就會自動生成MyLifecycle_LifecycleAdapter,存放在build/generated/source/apt文件夾下,感興趣的同學(xué)請看怎么編譯器生成注解的文章)的構(gòu)造函數(shù)熔任,并通過反射實例化返回到 getCallback 中褒链。
需注意的是,如果找不到 LifecycleAdapter 且 object(LifecycleObserver) 存在父類時會試圖獲取父類的LifecycleAdapter(估計是為了應(yīng)對混淆時只混淆了子類的情況)疑苔。
LifecycleAdapter的主要作用就是把我們寫的MyLifecycle轉(zhuǎn)化為我們的GenericLifecycleObserver甫匹。
apt(編譯期)自動生成的MyLifecycle_LifecycleAdapter源碼如下:
public class MyLifecycle_LifecycleAdapter implements GeneratedAdapter { final MyLifecycle mReceiver; MyLifecycle_LifecycleAdapter(MyLifecycle receiver) { this.mReceiver = receiver; } @Override public void callMethods(LifecycleOwner owner, Lifecycle.Event event, boolean onAny, MethodCallsLogger logger) { boolean hasLogger = logger != null; if (onAny) { if (!hasLogger || logger.approveCall("onAny", 4)) { mReceiver.onAny(owner,event); } return; } if (event == Lifecycle.Event.ON_CREATE) { if (!hasLogger || logger.approveCall("onCreate", 1)) { mReceiver.onCreate(); } return; } if (event == Lifecycle.Event.ON_DESTROY) { if (!hasLogger || logger.approveCall("onDestroy", 1)) { mReceiver.onDestroy(); } return; } } }
通過callMethods根據(jù)不同得到event執(zhí)行不同的方法回調(diào),調(diào)用我們自己定義的MyLifecycle的各個方法惦费。
回到getCallback方法兵迅,首先我們獲取MyLifecycle_LifecycleAdapter構(gòu)造方法方法,然后反射生產(chǎn)GeneratedAdapter對象.
如果只有一個構(gòu)造的話返回SingleGeneratedAdapterObserver薪贫,多個的話返回CompositeGeneratedAdaptersObserver都失敗的話返回ReflectiveGenericLifecycleObserver喷兼,估計是為了應(yīng)對代碼混淆的情況。這里我們只有一個這樣的構(gòu)造方法后雷,所以
我們看下SingleGeneratedAdapterObserver的源碼public class SingleGeneratedAdapterObserver implements GenericLifecycleObserver { private final GeneratedAdapter mGeneratedAdapter; SingleGeneratedAdapterObserver(GeneratedAdapter generatedAdapter) { mGeneratedAdapter = generatedAdapter; } @Override public void onStateChanged(LifecycleOwner source, Lifecycle.Event event) { mGeneratedAdapter.callMethods(source, event, false, null); mGeneratedAdapter.callMethods(source, event, true, null); } }
GeneratedAdapter就是MyLifecycle_LifecycleAdapter,我們在SingleGeneratedAdapterObserver的源碼中看到有個onStateChanged方法吠各,在調(diào)用onStateChanged的時候會調(diào)用GeneratedAdapter的callMethods臀突,從而會調(diào)用MyLifecycle的方法。那么onStateChanged是誰調(diào)用的贾漏?
我們回到ObserverWithState候学,發(fā)現(xiàn)了它的dispatchEvent方法里面有個onStateChanged,而這個mLifecycleObserver就是我們上面講的SingleGeneratedAdapterObserver,它是通過我們上面講的Lifecycling.getCallback(observer)生成的。
void dispatchEvent(LifecycleOwner owner, Event event) { State newState = getStateAfter(event); mState = min(mState, newState); mLifecycleObserver.onStateChanged(owner, event); mState = newState; }
后面會講到怎么通知所有的觀察者處理事件纵散,我們先總結(jié)下添加及調(diào)用的過程梳码。
- acitivty中調(diào)用LifecycleRegistry的ddObserver(LifecycleObserver observer)
- LifecycleObserver 被封裝成了ObserverWithState并存入我們集合中
- ObserverWithState 在構(gòu)造的時候隐圾,調(diào)用了Lifecycling.getCallback(observer)
- getCallback(observer)調(diào)用了createGeneratedAdapter()
- createGeneratedAdapter通過反射生了MyLifecycle_LifecycleAdapter對象
- MyLifecycle_LifecycleAdapter是在編譯器有apt幫我們生成的
- 最后返回一個SingleGeneratedAdapterObserver對象
- 在ObserverWithState的dispatchEvent()方法調(diào)用了SingleGeneratedAdapterObserver對象的onStateChanged方法,
- 它又調(diào)用了MyLifecycle_LifecycleAdapter的callMethods掰茶,然后再調(diào)用了我們自定義的MyLifecycle方法
-
被觀察者LifecycleRegister的handleLifecycleEvent()暇藏,源碼分析
public void handleLifecycleEvent(@NonNull Lifecycle.Event event) { State next = getStateAfter(event); moveToState(next); }
其中有個event和state是我們需要關(guān)注的,看下源碼
@SuppressWarnings("WeakerAccess") public enum Event { /** * Constant for onCreate event of the {@link LifecycleOwner}. */ ON_CREATE, /** * Constant for onStart event of the {@link LifecycleOwner}. */ ON_START, /** * Constant for onResume event of the {@link LifecycleOwner}. */ ON_RESUME, /** * Constant for onPause event of the {@link LifecycleOwner}. */ ON_PAUSE, /** * Constant for onStop event of the {@link LifecycleOwner}. */ ON_STOP, /** * Constant for onDestroy event of the {@link LifecycleOwner}. */ ON_DESTROY, /** * An {@link Event Event} constant that can be used to match all events. */ ON_ANY } /** * Lifecycle states. You can consider the states as the nodes in a graph and * {@link Event}s as the edges between these nodes. */ @SuppressWarnings("WeakerAccess") public enum State { /** * Destroyed state for a LifecycleOwner. After this event, this Lifecycle will not dispatch * any more events. For instance, for an {@link android.app.Activity}, this state is reached * <b>right before</b> Activity's {@link android.app.Activity#onDestroy() onDestroy} call. */ DESTROYED, /** * Initialized state for a LifecycleOwner. For an {@link android.app.Activity}, this is * the state when it is constructed but has not received * {@link android.app.Activity#onCreate(android.os.Bundle) onCreate} yet. */ INITIALIZED, /** * Created state for a LifecycleOwner. For an {@link android.app.Activity}, this state * is reached in two cases: * <ul> * <li>after {@link android.app.Activity#onCreate(android.os.Bundle) onCreate} call; * <li><b>right before</b> {@link android.app.Activity#onStop() onStop} call. * </ul> */ CREATED, /** * Started state for a LifecycleOwner. For an {@link android.app.Activity}, this state * is reached in two cases: * <ul> * <li>after {@link android.app.Activity#onStart() onStart} call; * <li><b>right before</b> {@link android.app.Activity#onPause() onPause} call. * </ul> */ STARTED, /** * Resumed state for a LifecycleOwner. For an {@link android.app.Activity}, this state * is reached after {@link android.app.Activity#onResume() onResume} is called. */ RESUMED; /** * Compares if this State is greater or equal to the given {@code state}. * * @param state State to compare with * @return true if this State is greater or equal to the given {@code state} */ public boolean isAtLeast(@NonNull State state) { return compareTo(state) >= 0; } }
他們是怎樣的一個對應(yīng)關(guān)系呢濒蒋,我們看下官方圖解
舉個列子盐碱,假如傳入的event是onstart那么我們就可以知道它現(xiàn)在的狀態(tài)是create,經(jīng)過onstart他要去Started狀態(tài).我們再回到handleLifecycleEvent
其中g(shù)etStateAfter方法就是獲得的是next狀態(tài)就是Started.那么MovetoNext方法是干啥的呢沪伙?
看下源碼private void moveToState(State next) { if (mState == next) { return; } mState = next; if (mHandlingEvent || mAddingObserverCounter != 0) { mNewEventOccurred = true; // we will figure out what to do on upper level. return; } mHandlingEvent = true; sync(); mHandlingEvent = false; }
里面有個mstate變量這個變量存放的是LifecycleRegister的當(dāng)前的state瓮顽,以上面例子,假如我們當(dāng)前的是Started围橡,那么我們就不需要sync()了;如果不是Started暖混,我們先當(dāng)前的mState狀態(tài)重新賦值,然后同步翁授,怎么同步策略呢拣播?看 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; // no need to check eldest for nullability, because isSynced does it for us. 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; }
它是比較當(dāng)前的狀態(tài)和我們存我們存放觀察者的集合最早或最新放入的觀察者的狀態(tài),我們知道集合存放的是ObserverWithState里面有我們注冊觀察者的狀態(tài)黔漂,假如mState是STARTED,如果觀察者的狀態(tài)是CREATED诫尽,那么我們需要通過forwardPass()告訴觀察者狀態(tài)變了你要到STARTED,看官方圖就可以知道這個event就為ON_START炬守,看下forwardPass()源碼
Iterator<Entry<LifecycleObserver, ObserverWithState>> ascendingIterator = mObserverMap.iteratorWithAdditions(); while (ascendingIterator.hasNext() && !mNewEventOccurred) { Entry<LifecycleObserver, ObserverWithState> entry = ascendingIterator.next(); ObserverWithState observer = entry.getValue(); while ((observer.mState.compareTo(mState) < 0 && !mNewEventOccurred pushParentState(observer.mState); observer.dispatchEvent(lifecycleOwner, upEvent(observer.mState)); popParentState(); } }
第一個while循壞遍歷我們存儲觀察者的集合牧嫉,第二個是要處理各個狀態(tài)經(jīng)過的event,eg:msate是RESUMED而ObserverWithState中的state是INITIALIZED减途,那么他要分發(fā)ON_CREATE,ON_RESUME,調(diào)用ObserverWithState的dispatchEvent方法酣藻,其中upEvent就是返回所要經(jīng)歷的event,那么dispatchEvent什么時候調(diào)用的鳍置?
-
被觀察者LifecycleRegister的handleLifecycleEvent()調(diào)用
我們先猜測一下辽剧,引文這個方法需要傳入一個event事件,那么這個event肯定和生命周期關(guān)聯(lián)起來税产,那怎么關(guān)聯(lián)的呢怕轿?還有這個官方的框架怎么沒有看到初始化的地方?
其實官方用了一個很好的方法辟拷,它是在provider中進行初始化的撞羽,我們找到xml文件,在as3.0中在xml中我們能找到merge的manifest文件看下
<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="android.arch.lifecycle.extensions" > <uses-sdk android:minSdkVersion="14" android:targetSdkVersion="26" /> <application> <provider android:name="android.arch.lifecycle.ProcessLifecycleOwnerInitializer" android:authorities="${applicationId}.lifecycle-trojan" android:exported="false" android:multiprocess="true" /> </application> </manifest>
有個provider這個清單文件是在lifecycle:extensions下的也就是說merge之后這個provider就加到我們的manifest衫冻,我們看下ProcessLifecycleOwnerInitializer诀紊,源碼
@RestrictTo(RestrictTo.Scope.LIBRARY_GROUP) public class ProcessLifecycleOwnerInitializer extends ContentProvider { @Override public boolean onCreate() { LifecycleDispatcher.init(getContext()); ProcessLifecycleOwner.init(getContext()); return true; } @Nullable @Override public Cursor query(@NonNull Uri uri, String[] strings, String s, String[] strings1, String s1) { return null; } @Nullable @Override public String getType(@NonNull Uri uri) { return null; } @Nullable @Override public Uri insert(@NonNull Uri uri, ContentValues contentValues) { return null; } @Override public int delete(@NonNull Uri uri, String s, String[] strings) { return 0; } @Override public int update(@NonNull Uri uri, ContentValues contentValues, String s, String[] strings) { return 0; } }
我們可以看到onCreate()方法里面有init方法,我們重點關(guān)注 LifecycleDispatcher.init(getContext());
看下他的源碼static void init(Context context) { if (sInitialized.getAndSet(true)) { return; } ((Application) context.getApplicationContext()) .registerActivityLifecycleCallbacks(new DispatcherActivityCallback()); }
在這里注冊了ActivityLifecycleCallbacks叫做new DispatcherActivityCallback()隅俘,看下他的源碼
static class DispatcherActivityCallback extends EmptyActivityLifecycleCallbacks { private final FragmentCallback mFragmentCallback; DispatcherActivityCallback() { mFragmentCallback = new FragmentCallback(); } @Override public void onActivityCreated(Activity activity, Bundle savedInstanceState) { if (activity instanceof FragmentActivity) { ((FragmentActivity) activity).getSupportFragmentManager() .registerFragmentLifecycleCallbacks(mFragmentCallback, true); } ReportFragment.injectIfNeededIn(activity); } @Override public void onActivityStopped(Activity activity) { if (activity instanceof FragmentActivity) { markState((FragmentActivity) activity, CREATED); } } @Override public void onActivitySaveInstanceState(Activity activity, Bundle outState) { if (activity instanceof FragmentActivity) { markState((FragmentActivity) activity, CREATED); } } }
我們看到onActivityCreated中注冊了一個FragmentLifecycleCallbacks邻奠,這個是監(jiān)控fragment的生命周期回調(diào)笤喳,我們看下面那句injectIfNeededIn,看下他的源碼
public class ReportFragment extends Fragment { private static final String REPORT_FRAGMENT_TAG = "android.arch.lifecycle" + ".LifecycleDispatcher.report_fragment_tag"; public static void injectIfNeededIn(Activity activity) { // ProcessLifecycleOwner should always correctly work and some activities may not extend // FragmentActivity from support lib, so we use framework fragments for activities android.app.FragmentManager manager = activity.getFragmentManager(); if (manager.findFragmentByTag(REPORT_FRAGMENT_TAG) == null) { manager.beginTransaction().add(new ReportFragment(), REPORT_FRAGMENT_TAG).commit(); // Hopefully, we are the first to make a transaction. manager.executePendingTransactions(); } } static ReportFragment get(Activity activity) { return (ReportFragment) activity.getFragmentManager().findFragmentByTag( REPORT_FRAGMENT_TAG); } private ActivityInitializationListener mProcessListener; private void dispatchCreate(ActivityInitializationListener listener) { if (listener != null) { listener.onCreate(); } } private void dispatchStart(ActivityInitializationListener listener) { if (listener != null) { listener.onStart(); } } private void dispatchResume(ActivityInitializationListener listener) { if (listener != null) { listener.onResume(); } } @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); } @Override public void onResume() { super.onResume(); dispatchResume(mProcessListener); 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); // just want to be sure that we won't leak reference to an activity mProcessListener = null; } private void dispatch(Lifecycle.Event event) { Activity activity = getActivity(); if (activity instanceof LifecycleRegistryOwner) { ((LifecycleRegistryOwner) activity).getLifecycle().handleLifecycleEvent(event); return; } if (activity instanceof LifecycleOwner) { Lifecycle lifecycle = ((LifecycleOwner) activity).getLifecycle(); if (lifecycle instanceof LifecycleRegistry) { ((LifecycleRegistry) lifecycle).handleLifecycleEvent(event); } } } void setProcessListener(ActivityInitializationListener processListener) { mProcessListener = processListener; } interface ActivityInitializationListener { void onCreate(); void onStart(); void onResume(); }
在injectIfNeededIn中我們把reportFragment加入到我們的activity中然后在其各個生命周期中都會調(diào)用dispatch()碌宴,最后調(diào)用了被觀察者的handleLifecycleEvent杀狡,這就回答了我們的問題,但是還有一個疑問唧喉,就是為什么要用fragment而不用ActivityCallBack呢捣卤,其實很簡單,ActivityCallBacks生命周期比我們的activity的生命周期要早八孝,也就是說ActivityCallBacks的oncreate比activity的要早董朝,所以我們用了fragment的生命周期和我們handleLifecycleEvent相綁定。這設(shè)計的很巧妙干跛。
總結(jié)一下調(diào)用過程
- 清單文件注冊的ProcessLifecycleOwnerInitializer這個provider在oncreate中調(diào)用了 LifecycleDispatcher.init(getContext());
- LifecycleDispatcher中的init方法調(diào)用了((Application) context.getApplicationContext())
.registerActivityLifecycleCallbacks(new DispatcherActivityCallback()); - DispatcherActivityCallback中的onActivityCreated中調(diào)用了
ReportFragment.injectIfNeededIn 把(activity); - injectIfNeededIn 把ReportFragment的各個生命周期中調(diào)用了加入到我們activity中
- 在ReportFragment的各個生命周期中調(diào)用了它的dispatch()調(diào)用了子姜。
- dispatch()調(diào)用了LifecycleRegister的handleLifecycleEvent()。