lifecycle
Lifecycle是個(gè)抽象類,拋去里面的枚舉Event和State,只有三個(gè)方法,分別是addObserver、removeObserver和getCurrentState
LifecycleEventObserver
觀察者,LifecycleObserver的子接口,與Lifecycle配合使用,觀察Lifecycle的生命狀態(tài),通過里面的onStateChanged方法收到通知
注冊(cè)觀察者
@MainThread
public abstract void addObserver(@NonNull LifecycleObserver observer);
移除觀察者
@MainThread
public abstract void removeObserver(@NonNull LifecycleObserver observer);
獲取當(dāng)前的狀態(tài)
@MainThread
@NonNull
public abstract State getCurrentState();
那么它是怎么監(jiān)聽activity的生命周期的呢,在開始一直以為是在activity的某一級(jí)子類中,每個(gè)生命周期的方法中更改Lifecycle中記錄的狀態(tài),但是一路查看下去發(fā)現(xiàn)并沒有這個(gè)行為。
直到在ComponentActivity才發(fā)現(xiàn)跟Lifecycle相關(guān)的東西
public class ComponentActivity extends androidx.core.app.ComponentActivity implements
LifecycleOwner,
ViewModelStoreOwner,
HasDefaultViewModelProviderFactory,
SavedStateRegistryOwner,
OnBackPressedDispatcherOwner {
對(duì),就是這個(gè)LifecycleOwner,LifecycleOwner是個(gè)接口,里面只定義一個(gè)行為,獲取Lifecycle
public interface LifecycleOwner {
/**
* Returns the Lifecycle of the provider.
*
* @return The lifecycle of the provider.
*/
@NonNull
Lifecycle getLifecycle();
}
這種面向接口和單一職責(zé)的設(shè)計(jì)方式,深得我心...
回去看ComponentActivity 中的實(shí)現(xiàn),getLifecycle方法返回一個(gè)LifecycleRegistry類型的對(duì)象,不用想了,這個(gè)LifecycleRegistry肯定是Lifecycle的實(shí)現(xiàn)類,
這個(gè)實(shí)現(xiàn)類除了實(shí)現(xiàn)了Lifecycle的三個(gè)方法,另外多了好幾個(gè)方法,其中最令人欣喜的就是終于有了設(shè)置生命狀態(tài)和通知觀察者的方法
@Deprecated
@MainThread
public void markState(@NonNull State state) {
setCurrentState(state);
}
@MainThread
public void setCurrentState(@NonNull State state) {
moveToState(state);
}
public void handleLifecycleEvent(@NonNull Lifecycle.Event event) {
State next = getStateAfter(event);
moveToState(next);
}
private void moveToState(State next) {
if (mState == next) {
return;
}
//在這里更改了lifecycle當(dāng)前的狀態(tài)
mState = next;
if (mHandlingEvent || mAddingObserverCounter != 0) {
mNewEventOccurred = true;
// we will figure out what to do on upper level.
return;
}
mHandlingEvent = true;
//在這里同步出去,可以想象的到,這里面應(yīng)該就是通知注冊(cè)過來的觀察者們
sync();
mHandlingEvent = false;
}
private void sync() {
//...省略部分代碼
if (mState.compareTo(mObserverMap.eldest().getValue().mState) < 0) {
//通知lifecycleOwner
backwardPass(lifecycleOwner);
}
Entry<LifecycleObserver, ObserverWithState> newest = mObserverMap.newest();
if (!mNewEventOccurred && newest != null
&& mState.compareTo(newest.getValue().mState) > 0) {
//通知lifecycleOwner
forwardPass(lifecycleOwner);
}
}
其中有兩個(gè)主要邏輯方法,都是分發(fā)狀態(tài)事件(dispatchEvent)的
在里面會(huì)遍歷觀察者們(注意:此觀察者是并非直接注冊(cè)的LifecycleObserver,而是經(jīng)過包裝的ObserverWithState)
再調(diào)用觀察者們的onStateChanged方法,那直接看分發(fā)事件的邏輯就好了
void dispatchEvent(LifecycleOwner owner, Event event) {
State newState = getStateAfter(event);
mState = min(mState, newState);
mLifecycleObserver.onStateChanged(owner, event);
mState = newState;
}
到這里,就完成了lifecycle的注冊(cè)觀察者、狀態(tài)更改、通知觀察者的流程
接下來只需要把a(bǔ)ctivity的生命周期通知給lifecycle,那么就相當(dāng)于完成activity的生命周期管理。
可是ComponentActivity 類中并沒有在生命周期方法中調(diào)用LifecycleRegistry中更改的方法...
如果全交給LifecycleRegistry處理的話,肯定要再activity的初始化時(shí)做工作(才能及時(shí)管理到各個(gè)生命周期)
@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);
//只有這里看起來合適和可疑(其實(shí)就是它了……)
ReportFragment.injectIfNeededIn(this);
if (mContentLayoutId != 0) {
setContentView(mContentLayoutId);
}
}
進(jìn)去看看
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();
}
}
看到是添加了個(gè)空fragment...
然后是再fragment中的生命周期方法中更新Lifecycle的狀態(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);
}
@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;
}
static void dispatch(@NonNull Activity activity, @NonNull Lifecycle.Event event) {
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);
}
}
}
這個(gè)內(nèi)容不是很多,也談不上難,只是做個(gè)給自己解惑的記錄好了