開(kāi)發(fā)中掸刊,在Activity或者fragment的各個(gè)生命周期階段琢蛤,可能未對(duì)資源進(jìn)行正確操作導(dǎo)致一些問(wèn)題害捕,從而導(dǎo)致內(nèi)存泄露甚至引發(fā)Crash鹰晨。
在mvp時(shí)代墨叛,我們會(huì)在P層定義一些接口止毕,在組件回調(diào)生命周期函數(shù)時(shí)調(diào)用接口方法,在這些方法中進(jìn)行資源釋放或者取消一些操作的處理漠趁。lifecycle就是為了解決這個(gè)問(wèn)題出現(xiàn)的扁凛,可以讓一些組件擁有生命周期感知的能力。lifecycle已經(jīng)成為android的基礎(chǔ)組件闯传。
在Activity的父類ComponentActivity中谨朝,做了這些操作。
在該父類Activity的onCreate中甥绿,谷歌使用了一個(gè)空布局的Fragment依附于Activity字币,而后這個(gè)fragment組件是可以感知到activity的一些生命周期的,為什么要用fragment呢妹窖?是因?yàn)閘ifecycle是從api29開(kāi)始增加的,28以及之前都是使用的support庫(kù)收叶,也沒(méi)有ComponentActivity骄呼。因此為了兼容低版本,谷歌想到了這么一個(gè)合適的方法判没。從源碼中可以看出相關(guān)的版本判斷蜓萄。大于28的版本,直接使用LifecycleCallbacks注冊(cè)接口澄峰。
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
// Restore the Saved State first so that it is available to
// OnContextAvailableListener instances
mSavedStateRegistryController.performRestore(savedInstanceState);
mContextAwareHelper.dispatchOnContextAvailable(this);
super.onCreate(savedInstanceState);
mActivityResultRegistry.onRestoreInstanceState(savedInstanceState);
ReportFragment.injectIfNeededIn(this);
if (mContentLayoutId != 0) {
setContentView(mContentLayoutId);
}
}
public static void injectIfNeededIn(Activity activity) {
if (Build.VERSION.SDK_INT >= 29) {
// On API 29+, we can register for the correct Lifecycle callbacks directly
LifecycleCallbacks.registerIn(activity);
}
// Prior to API 29 and to maintain compatibility with older versions of
// ProcessLifecycleOwner (which may not be updated when lifecycle-runtime is updated and
// need to support activities that don't extend from FragmentActivity from support lib),
// use a framework fragment to get the correct timing of Lifecycle events
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();
}
}
在ComponentActivity中會(huì)創(chuàng)建一個(gè)mLifecycleRegistry對(duì)象嫉沽,會(huì)在getLifecycle()方法中返回該對(duì)象。在依附的空布局fragment的生命周期函數(shù)中俏竞,會(huì)調(diào)用dispatch(@NonNull Activity activity, @NonNull Lifecycle.Event event)绸硕,event即為生命周期的狀態(tài)。
@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);
}
該函數(shù)會(huì)判斷Activity的類型魂毁,如果為lifecycleowner玻佩,則會(huì)調(diào)用到一個(gè)getLifecycle(),其實(shí)就是上面說(shuō)的mLifecycleRegistry,LifecycleRegistry.handleLifecycleEvent(event)席楚,由于ComponentActivity實(shí)現(xiàn)了lifecycleOwner接口咬崔,則肯定滿足該條件,另外一個(gè)判斷是為了兼容其他情況烦秩。
@SuppressWarnings("deprecation")
static void dispatch(@NonNull Activity activity, @NonNull Lifecycle.Event event) {
if (activity instanceof LifecycleRegistryOwner) {
((LifecycleRegistryOwner) activity).getLifecycle().handleLifecycleEvent(event);
return;
}
if (activity instanceof LifecycleOwner) {
//getLifecycle()返回的就是在ComponentActivity中的
Lifecycle lifecycle = ((LifecycleOwner) activity).getLifecycle();
if (lifecycle instanceof LifecycleRegistry) {
((LifecycleRegistry) lifecycle).handleLifecycleEvent(event);
}
}
}
/**
* Sets the current state and notifies the observers.
* <p>
* Note that if the {@code currentState} is the same state as the last call to this method,
* calling this method has no effect.
*
* @param event The event that was received
*/
public void handleLifecycleEvent(@NonNull Lifecycle.Event event) {
enforceMainThreadIfNeeded("handleLifecycleEvent");
moveToState(event.getTargetState());
}
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;
}
private boolean isSynced() {
if (mObserverMap.size() == 0) {
return true;
}
State eldestObserverState = mObserverMap.eldest().getValue().mState;
State newestObserverState = mObserverMap.newest().getValue().mState;
return eldestObserverState == newestObserverState && mState == newestObserverState;
}
/**
* Returns the new {@link Lifecycle.State} of a {@link Lifecycle} that just reported
* this {@link Lifecycle.Event}.
*
* Throws {@link IllegalArgumentException} if called on {@link #ON_ANY}, as it is a special
* value used by {@link OnLifecycleEvent} and not a real lifecycle event.
*
* @return the state that will result from this event
*/
@NonNull
public State getTargetState() {
switch (this) {
case ON_CREATE:
case ON_STOP:
return State.CREATED;
case ON_START:
case ON_PAUSE:
return State.STARTED;
case ON_RESUME:
return State.RESUMED;
case ON_DESTROY:
return State.DESTROYED;
case ON_ANY:
break;
}
throw new IllegalArgumentException(this + " has no target state");
}
該函數(shù)里面有一個(gè)比較有趣的狀態(tài)機(jī)制垮斯。event.getTargetState(),我們平時(shí)開(kāi)發(fā)能接觸到的基本都是onCreate onStart這種回調(diào)函數(shù)只祠,在谷歌的設(shè)計(jì)里兜蠕,這些回調(diào)函數(shù)是屬于事件,相對(duì)應(yīng)的 組件還會(huì)有一些狀態(tài)抛寝。這些狀態(tài)我們實(shí)際開(kāi)發(fā)中不太能接觸到牺氨。說(shuō)回這個(gè)狀態(tài)機(jī)制狡耻,核心是事件驅(qū)動(dòng)狀態(tài)。當(dāng)調(diào)用了onCreate之后猴凹,組件狀態(tài)就由INITALIZED走向Created夷狰,當(dāng)調(diào)用了onStart之后,組件就從created走向started郊霎,當(dāng)調(diào)用onResume沼头,就從started變?yōu)閞esumed。這是事件的正向流動(dòng)书劝,如果用戶返回關(guān)閉頁(yè)面或者將app放到后臺(tái)进倍,事件就會(huì)回流,先調(diào)用onPause购对,resumed狀態(tài)會(huì)變?yōu)閟tarted猾昆,調(diào)用onStop,就從started更改為created骡苞,然后調(diào)用onDestory垂蜗,就從created更改為Destoryed。下圖概括了一下事件的流向以及狀態(tài)的變化解幽。
狀態(tài)變更之后贴见,需要根據(jù)組件的狀態(tài)同步LifecycleRegistry中保存的mState狀態(tài),通過(guò)調(diào)用moveToState函數(shù)來(lái)進(jìn)行同步躲株,函數(shù)中有一個(gè)sysnc(),其中開(kāi)啟了一個(gè)死循環(huán)片部,條件為 當(dāng)前狀態(tài)與保存起來(lái)的狀態(tài)是否一致,如果不一致霜定,則同步档悠。
這里注意,不論事件是前進(jìn)或者回流望浩,都是根據(jù)State的枚舉類型進(jìn)行compareTo站粟,如果被觀察者比觀察者新,同步時(shí)狀態(tài)正向更新,前進(jìn)曾雕,就會(huì)調(diào)用Event.upFrom(observer.mState)更新?tīng)顟B(tài)奴烙,若為回流,會(huì)調(diào)用Event.downFrom(observer.mState)更新?tīng)顟B(tài)剖张,隨即調(diào)用observer的dispatchEvent(lifecycleOwner, event)切诀,這里的observer實(shí)際上就是lifecycle.addObserver( LifecycleObserver observer)傳進(jìn)來(lái)的這個(gè)observer,只不過(guò)這個(gè)需要我們自己手動(dòng)去傳入搔弄,而后調(diào)用mLifecycleRegistry的addObserver幅虑,源碼中會(huì)將這些保存在一個(gè)observerMap中,源碼如下:
// happens only on the top of stack (never in reentrance),
// so it doesn't have to take in account parents
private void sync() {
LifecycleOwner lifecycleOwner = mLifecycleOwner.get();
if (lifecycleOwner == null) {
throw new IllegalStateException("LifecycleOwner of this LifecycleRegistry is already"
+ "garbage collected. It is too late to change lifecycle state.");
}
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);
}
Map.Entry<LifecycleObserver, ObserverWithState> newest = mObserverMap.newest();
if (!mNewEventOccurred && newest != null
&& mState.compareTo(newest.getValue().mState) > 0) {
forwardPass(lifecycleOwner);
}
}
mNewEventOccurred = false;
}
private void backwardPass(LifecycleOwner lifecycleOwner) {
Iterator<Map.Entry<LifecycleObserver, ObserverWithState>> descendingIterator =
mObserverMap.descendingIterator();
while (descendingIterator.hasNext() && !mNewEventOccurred) {
Map.Entry<LifecycleObserver, ObserverWithState> entry = descendingIterator.next();
ObserverWithState observer = entry.getValue();
while ((observer.mState.compareTo(mState) > 0 && !mNewEventOccurred
&& mObserverMap.contains(entry.getKey()))) {
Event event = Event.downFrom(observer.mState);
if (event == null) {
throw new IllegalStateException("no event down from " + observer.mState);
}
pushParentState(event.getTargetState());
observer.dispatchEvent(lifecycleOwner, event);
popParentState();
}
}
}
private void forwardPass(LifecycleOwner lifecycleOwner) {
Iterator<Map.Entry<LifecycleObserver, ObserverWithState>> ascendingIterator =
mObserverMap.iteratorWithAdditions();
while (ascendingIterator.hasNext() && !mNewEventOccurred) {
Map.Entry<LifecycleObserver, ObserverWithState> entry = ascendingIterator.next();
ObserverWithState observer = entry.getValue();
while ((observer.mState.compareTo(mState) < 0 && !mNewEventOccurred
&& mObserverMap.contains(entry.getKey()))) {
pushParentState(observer.mState);
final Event event = Event.upFrom(observer.mState);
if (event == null) {
throw new IllegalStateException("no event up from " + observer.mState);
}
observer.dispatchEvent(lifecycleOwner, event);
popParentState();
}
}
}
那最后還有一個(gè)問(wèn)題顾犹,Activity觸發(fā)生命周期之后倒庵,是如何調(diào)用相應(yīng)的observer中的同名方法的呢褒墨,其實(shí)在backwardPass()或者forwardPass()中,最后有一個(gè)遍歷map集合擎宝,取出其中的statefulObserver郁妈,調(diào)用dispatchEvent,這個(gè)statefulObserver實(shí)際上里面包裝了咱們傳進(jìn)去的那個(gè)Observer绍申,也就是lifecycle.addObserver( LifecycleObserver observer)這里的observer噩咪,只不過(guò)api30之前可能是使用了反射的方式調(diào)用method,api30這里是用map里的對(duì)象調(diào)用的极阅。
lifecycle為liveData+ViewModel功能提供了擴(kuò)展胃碾,所以這兩個(gè)庫(kù)可以感知到生命周期,在合適的時(shí)候發(fā)送數(shù)據(jù)筋搏,這是后話仆百。