您好,登錄后才能下訂單哦!
本文小編為大家詳細介紹“Android中Lifecycle的原理是什么”,內容詳細,步驟清晰,細節處理妥當,希望這篇“Android中Lifecycle的原理是什么”文章能幫助大家解決疑惑,下面跟著小編的思路慢慢深入,一起來學習新知識吧。
Lifecycle是Android Architecture Components的成員,是一個生命周期感知組件,能夠感知Activity、Fragment等組件的生命周期變化,并將變化通知到已注冊的觀察者。正確的使用有助于更好地組織代碼,減少內存泄漏,增強穩定。下面分析他的實現原理,看看到底只怎么感知生命周期的。
1、引入依賴庫
dependencies { def lifecycle_version = "2.5.0-alpha01" def arch_version = "2.1.0" implementation "androidx.lifecycle:lifecycle-viewmodel:$lifecycle_version" implementation "androidx.lifecycle:lifecycle-livedata:$lifecycle_version" implementation "androidx.lifecycle:lifecycle-runtime:$lifecycle_version" //非java8使用 annotationProcessor "androidx.lifecycle:lifecycle-compiler:$lifecycle_version" //java8使用 implementation "androidx.lifecycle:lifecycle-common-java8:$lifecycle_version" }
2、自定義一個類實現LifecycleObserver,在類中監聽生命周期回調
public class BaseJsApi implements LifecycleObserver { @OnLifecycleEvent(Lifecycle.Event.ON_CREATE) void create() { onCreate(); } @OnLifecycleEvent(Lifecycle.Event.ON_DESTROY) void destroy() { onDestroy(); } @OnLifecycleEvent(Lifecycle.Event.ON_RESUME) void resume() { onResume(); } @OnLifecycleEvent(Lifecycle.Event.ON_PAUSE) void pause() { onPause(); } …………………………………… }
3、在Activity或者fragment中注冊。
getLifecycle().addObserver(getJsBridge());
通過以上兩步就可以感知當前Activity的生命周期了,非常的簡便實用。
public interface LifecycleObserver { } public interface LifecycleOwner { @NonNull Lifecycle getLifecycle(); }
LifecycleObserver是一個空接口,LifecycleOwner提供getLifecycle返回Lifecycle,該接口由ComponentActivity實現,提供了getLifecycle的實現。
getLifecycle方法實際上是調用的ComponentActivity的getLifecycle方法,通過查看,Activity確實也是繼承的ComponentActivity,該方法返回mLifecycleRegistry對象,該對象繼承自Lifecycle,具體實現了添加觀察者,移出觀察者的方法,還定義了一個生命周期的枚舉。
public class LifecycleRegistry extends Lifecycle { } 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(); public enum Event { ON_CREATE, ON_START, ON_RESUME, ON_PAUSE, ON_STOP, ON_DESTROY, ON_ANY; ………………………………………… } ……………………………… }
也就可以看出getLifecycle().addObserver實際上就是執行LifecycleRegistry的addObserver的方法添加觀察者,做一個小總結如下:
觀察者實現LifecycleObserver,實現需要的生命周期。在Activity、Fragment中添通過getLifecycle().addObserver加觀察者。實際上調用的是ComponentActivity的getLifecycle方法返回mLifecycleRegistry。調用LifecycleRegistry的addObserver加觀察者。三、添加觀察者的流程
詳情看注釋:
@Override public void addObserver(@NonNull LifecycleObserver observer) { //檢查是否在主線程 enforceMainThreadIfNeeded("addObserver"); //設置狀態值 State initialState = mState == DESTROYED ? DESTROYED : INITIALIZED; //將觀察者和初始化的值封裝到ObserverWithState中 ObserverWithState statefulObserver = new ObserverWithState(observer, initialState); //以觀察者為key,statefulObserver為value放到hashMap集合中 ObserverWithState previous = mObserverMap.putIfAbsent(observer, statefulObserver); //不為null表示之前已經放進去了,否則沒放進去,放進去了就添加結束 if (previous != null) { return; } //獲取被觀察者對象,即Activity,如果被銷毀了,則結束 LifecycleOwner lifecycleOwner = mLifecycleOwner.get(); if (lifecycleOwner == null) { // it is null we should be destroyed. Fallback quickly return; } //mAddingObserverCounter 表示正在添加的觀察者的數量, //開始添加新的observe之前,對該變量進行++操作,添加完成后,進行--操作。 //mHandlingEvent表示是否正在處理 boolean isReentrance = mAddingObserverCounter != 0 || mHandlingEvent; //計算狀態,進行while循環 State targetState = calculateTargetState(observer); mAddingObserverCounter++; //新添加的LifecycleObserver ,會不斷更新自己的生命周期到指定的targetState while ((statefulObserver.mState.compareTo(targetState) < 0 && mObserverMap.contains(observer))) { //添加狀態到list,計算當前狀態,用于計算狀態calculateTargetState pushParentState(statefulObserver.mState); // final Event event = Event.upFrom(statefulObserver.mState); if (event == null) { throw new IllegalStateException("no event up from " + statefulObserver.mState); } //生命周期分發:分發到mLifecycleObserver里面 statefulObserver.dispatchEvent(lifecycleOwner, event); //移除狀態到list popParentState(); // mState / subling may have been changed recalculate //重新計算狀態 targetState = calculateTargetState(observer); } //沒有事件正在處理,或者是添加了observe,就需要重新同步一次狀態,下面詳細介紹 if (!isReentrance) { // we do sync only on the top level. sync(); } mAddingObserverCounter--; }
//計算狀態規則 private State calculateTargetState(LifecycleObserver observer) { //在map中獲取到當前observer的前一個observer Map.Entry<LifecycleObserver, ObserverWithState> previous = mObserverMap.ceil(observer); //前一個observer的state State siblingState = previous != null ? previous.getValue().mState : null; //如果是嵌套添加observer,獲取父級observer的狀態 State parentState = !mParentStates.isEmpty() ? mParentStates.get(mParentStates.size() - 1) : null; //獲取最小狀態,DESTROYED < INITIALIZED < CREATED < STARTED < RESUMED return min(min(mState, siblingState), parentState); }
上面介紹了addObserver的流程,在ComponentActivity的onCreate方法中:
ReportFragment.injectIfNeededIn(this);
ReportFragment是一個Fragment,它負責分派生命周期的事件,injectIfNeededIn()就是在當前的Activity里添加一個ReportFragment,和glide的綁定生命周期比較類似。
public static void injectIfNeededIn(Activity activity) { //當API>=29注冊registerIn綁定生命周期 if (Build.VERSION.SDK_INT >= 29) { // On API 29+, we can register for the correct Lifecycle callbacks directly LifecycleCallbacks.registerIn(activity); } 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(); } }
當API>=29是通過Application.ActivityLifecycleCallbacks的方式注冊生命周期, 以onStart為例,其他onResume、onPause等類似:
@Override public void onStart() { super.onStart(); dispatchStart(mProcessListener); dispatch(Lifecycle.Event.ON_START); }
重點看看dispatch:
private void dispatch(@NonNull Lifecycle.Event event) { //當API<29分發dispatch綁定生命周期 if (Build.VERSION.SDK_INT < 29) { // Only dispatch events from ReportFragment on API levels prior // to API 29. On API 29+, this is handled by the ActivityLifecycleCallbacks // added in ReportFragment.injectIfNeededIn dispatch(getActivity(), event); } }
不管是pplication.ActivityLifecycleCallbacks還是當前fragment的生命周期方式都會執行如下dispatch:
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); } } }
調用LifecycleRegistry的handleLifecycleEvent將生命周期分發出去,LifecycleRegistry上面已經介紹過了addObserve邏輯了,代碼比較長,只顯示關鍵代碼:
handleLifecycleEvent -> moveToState -> sync
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) { //如果ObserverWithState的state小于當前state,那么就調用forwardPass方法, backwardPass(lifecycleOwner); } Map.Entry<LifecycleObserver, ObserverWithState> newest = mObserverMap.newest(); if (!mNewEventOccurred && newest != null && mState.compareTo(newest.getValue().mState) > 0) { //如果大于當前state,那么就調用backwardPass方法。 forwardPass(lifecycleOwner); } } mNewEventOccurred = false; }
backwardPass和forwardPass的代碼都會調用:
observer.dispatchEvent(lifecycleOwner, event)
static class ObserverWithState { State mState; LifecycleEventObserver mLifecycleObserver; ObserverWithState(LifecycleObserver observer, State initialState) { mLifecycleObserver = Lifecycling.lifecycleEventObserver(observer); mState = initialState; } void dispatchEvent(LifecycleOwner owner, Event event) { State newState = event.getTargetState(); mState = min(mState, newState); mLifecycleObserver.onStateChanged(owner, event); mState = newState; } }
調用了Lifecycling.getCallback方法來獲得mLifecycleObserver的實例,通過這個實例調用onStateChanged:
static LifecycleEventObserver lifecycleEventObserver(Object object) { boolean isLifecycleEventObserver = object instanceof LifecycleEventObserver; boolean isFullLifecycleObserver = object instanceof FullLifecycleObserver; if (isLifecycleEventObserver && isFullLifecycleObserver) { return new FullLifecycleObserverAdapter((FullLifecycleObserver) object, (LifecycleEventObserver) object); } if (isFullLifecycleObserver) { return new FullLifecycleObserverAdapter((FullLifecycleObserver) object, null); } if (isLifecycleEventObserver) { return (LifecycleEventObserver) object; } //通過反射,找到Lifecycle 自動生成的類 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); 最終使用生成的Adapter,創建SingleGeneratedAdapterObserver 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); }
class SingleGeneratedAdapterObserver implements LifecycleEventObserver { private final GeneratedAdapter mGeneratedAdapter; SingleGeneratedAdapterObserver(GeneratedAdapter generatedAdapter) { mGeneratedAdapter = generatedAdapter; } @Override public void onStateChanged(@NonNull LifecycleOwner source, @NonNull Lifecycle.Event event) { mGeneratedAdapter.callMethods(source, event, false, null); mGeneratedAdapter.callMethods(source, event, true, null); } }
到這里會根據依賴中添加的annotationProcessor "androidx.lifecycle:lifecycle-compiler:2.2.0"根據不同生命周期注解生成不同的類,整個過程還是比較復雜的。整體過程如下圖:
讀到這里,這篇“Android中Lifecycle的原理是什么”文章已經介紹完畢,想要掌握這篇文章的知識點還需要大家自己動手實踐使用過才能領會,如果想了解更多相關內容的文章,歡迎關注億速云行業資訊頻道。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。