- 介面LifecycleOwner:生命週期持有者,程式碼如下:
其中google提供了介面LifecycleRegistryOwner繼承了LifecycleOwner
具有生命週期的Activity、Fragment應該實現LifecycleRegistry並重寫getLifecycle()方法。
抽象類Lifecycle主要具有新增觀察者addObserver()、移除觀察者removeObserver()功能
抽象類LifecycleRegister繼承Lifecycle,重寫了addObserver()、removeObserver(),除此之外實現將Lifecycle.Event和State之間的轉換,並且狀態發生變化時,通知觀察者。
一般使用Activity、Fragment繼承LifecycleRegistryOwner重寫getLifecyle(),方法示例如下:
需要針對生命週期做出變化的類實現LifecycleObserver也就是觀察者,並通過LifecycleRegistry的addObserver()方法將觀察者新增到LifecycleRegistry中,其中紅框部分稍後分析,這裡僅以Activity為例來分析Lifecycle的運作過程。啟動Activity呼叫棧如下所示:
可以看到Activity啟動時,在ActivityThread類中installProvider方法中呼叫了ContentProvider的attchInfo方法,進而呼叫了LifecycleRuntimeTrojanProvider類的onCreate()方法,該方法如下所示
跟進LifecycleDispatcher
private static final String REPORT_FRAGMENT_TAG = "android.arch.lifecycle"
+ ".LifecycleDispatcher.report_fragment_tag";
private static AtomicBoolean sInitialized = new AtomicBoolean(false);
static void init(Context context) {
if (sInitialized.getAndSet(true)) {
return;
}
((Application) context.getApplicationContext())
.registerActivityLifecycleCallbacks(new DispatcherActivityCallback());
}複製程式碼
init方法只是將DispatherActivityCallback新增到Application儲存的map中去,繼續檢視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);
}
}
}複製程式碼
經過斷點試驗發現當ThreadActivity執行performCreate方法時會呼叫DispatcherActivityCallback的onActivityCreated方法,該方法中會呼叫ReportFragment.injectIfNeedIn(activity),其中該activity即為實現了LifecycleRegistryOwner的物件,繼續更近ReportFragment程式碼如下:
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();
}
}複製程式碼
從程式碼可以看出相當於在activity中新增了一個沒有任何內容的Fragment,該Fragment用來監聽activity生命週期的變化並通知觀察者,利用Fragment應該是是因為Fragment的onCreate()、onStart()、onResume()方法均在其所在的Activity的相應的onCreate()、onStart()、onResume()方法之後執行,但是Fragment的onPause()、onStop()、onDestroy()均在所在Activit相應的onPause()、onStop()、onDestroy()之前執行,這一點兒很重要!
當執行完畢Activity中的onCreate方法後,會執行ReportFragment方法中的onAcitivityCreate方法
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
dispatchCreate(mProcessListener);
dispatch(Lifecycle.Event.ON_CREATE);
}複製程式碼
其中dispatch方法如下所示
private void dispatch(Lifecycle.Event event) {
if (getActivity() instanceof LifecycleRegistryOwner) {
((LifecycleRegistryOwner) getActivity()).getLifecycle().handleLifecycleEvent(event);
}
}複製程式碼
這裡個getActivity就是實現了第三張圖中實現LifecycleRegistryOwner的Activity,此處也應該注意被監聽生命週期變化的Activity應該繼承的是LifecycleRegisterOwner類,而不應該是LifecycleOwner。繼續跟進handleLifecycleEvent方法
public void handleLifecycleEvent(Lifecycle.Event event) {
if (mLastEvent == event) {
return;
}
mLastEvent = event;
mState = getStateAfter(event);
for (Map.Entry<LifecycleObserver, ObserverWithState> entry : mObserverSet) {
entry.getValue().sync();
}
}複製程式碼
只要mLastEvent!=event就會執行for迴圈,其中mObserverSet中的元素是在addObserver的時候新增的,如下所示
@Override
public void addObserver(LifecycleObserver observer) {
ObserverWithState observerWithState = new ObserverWithState(observer);
mObserverSet.putIfAbsent(observer, observerWithState);
observerWithState.sync();
}複製程式碼
其中ObserverWithState物件對observer進行了封裝,
ObserverWithState(LifecycleObserver observer) {
mCallback = Lifecycling.getCallback(observer);
}複製程式碼
ObserverWithState建構函式中呼叫了Lifecycleing.getCallback(observer)檢視該方法(這裡不再貼程式碼)只是根據observer所在包名和類名通過反射構建出了一個“className”+"_LifecycleAdapter的類並呼叫該類的建構函式將observer作為引數傳遞給該類的例項,例如自己的demo中名為CustomLifecycleObser_LifeAdapter,該類在app/build/generated/source/apt/debug下,檢視該類如下
public class CustomLifecycleObserver_LifecycleAdapter implements GenericLifecycleObserver {
final CustomLifecycleObserver mReceiver;
CustomLifecycleObserver_LifecycleAdapter(CustomLifecycleObserver receiver) {
this.mReceiver = receiver;
}
@Override
public void onStateChanged(LifecycleOwner owner, Lifecycle.Event event) {
if (event == Lifecycle.Event.ON_CREATE) {
mReceiver.onCreate(owner);
}
if (event == Lifecycle.Event.ON_START) {
mReceiver.onStart(owner);
}
if (event == Lifecycle.Event.ON_RESUME) {
mReceiver.onResume(owner);
}
if (event == Lifecycle.Event.ON_STOP) {
mReceiver.onStop(owner);
}
if (event == Lifecycle.Event.ON_PAUSE) {
mReceiver.onPause(owner);
}
if (event == Lifecycle.Event.ON_DESTROY) {
mReceiver.onDestroy(owner);
}
mReceiver.onAny(owner,event);
}
public Object getReceiver() {
return mReceiver;
}
}複製程式碼
註解處理器apt生成該類時會生成一個onStateChanged方法,並根據event呼叫observer中相應的方法,這些方法是observer中被onLifecycleEvent註解的方法,那onStateChanged方法在哪裡被呼叫呢,例如上面的Activity的onCreate方法執行後會呼叫onActivityCreated方法,然後呼叫handleLifecycleEvent方法,該方法遍歷mObserverSet後呼叫sync方法,該方法如下所示
void sync() {
if (mState == DESTROYED && mObserverCurrentState == INITIALIZED) {
mObserverCurrentState = DESTROYED;
}
while (mObserverCurrentState != mState) {
Event event = mObserverCurrentState.isAtLeast(mState)
? downEvent(mObserverCurrentState) : upEvent(mObserverCurrentState);
mObserverCurrentState = getStateAfter(event);
mCallback.onStateChanged(mLifecycleOwner, event);
}
}複製程式碼
當mState不等於mObserverCurrentState的時候就會進行兩種狀態的比較,其中返回的Event其實就是mObserverCurrentState過渡到mState時所需的Event詳見頭圖,例如mObserverCurrentState是INITIALIZED,而mState是CREATED的時候,這個時候然需要經過ON_CREATE事件後,mObserverCurrentState才可以過度到mState的狀態,進而更新mObserverState對應的狀態為mState,然後呼叫“className”+"_LifecycleAdapter的onStateChange方法,進而呼叫到觀察者中相應的方法。
再說紅色方框中為啥要呼叫markState方法,因為Activity的onCreate方法要比Fragment的早,如果不手動呼叫的話mObserverCurrentState和mState都是INITIALIZED,進而不會執行
mCallBack.onStateChanged方法。