Android Lifecycle源码解析(一)
Android Lifecycle源碼解析(一)
首先我們看HomeActivity中我們添加到一行代碼
public class HomeActivity extends AppCompatActivity {@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);//heregetLifecycle().addObserver(new HomeObserver());} }先看下類的繼承關系
public class AppCompatActivity extends FragmentActivity public class FragmentActivity extends SupportActivity我們看下getLifecycle()是個什么東西?點擊去看發現getLifecycle()方法是定義在SupportActivity,下面是其部分源碼
SupportActivity
public class SupportActivity extends Activity implements LifecycleOwner, Component {...private LifecycleRegistry mLifecycleRegistry = new LifecycleRegistry(this);public SupportActivity() {}protected void onCreate(@Nullable Bundle savedInstanceState) {super.onCreate(savedInstanceState);ReportFragment.injectIfNeededIn(this);}@CallSuperprotected void onSaveInstanceState(Bundle outState) {this.mLifecycleRegistry.markState(State.CREATED);super.onSaveInstanceState(outState);}public Lifecycle getLifecycle() {return this.mLifecycleRegistry;}... }可以看到getLifecycle返回的其實是個LifecycleRegistry對象;該類繼承了Lifecycle抽象類;
Lifecycle類可以理解為具備獲取生命周期狀態的抽象類,為什么?看下面代碼
Lifecycle聲明了添加觀察者,移除觀察者,獲取當前生命周期狀態三個抽象方法
而LifecycleRegistry則是其子類,他是觀察者和被觀察者(HomeActivity)的紐帶,能夠管理多個觀察者;HomeActivity的生命周期事件都是通過該類handleLifecycleEvent方法進行下發的,那么是誰將Activity的生命周期的事件轉給LifecycleRegistry類中呢?答案是ReportFragment
這里有點像Glide框架中到設計一樣使用一個空Fragment來感知Activity生命周期,避免圖片加載出現內存泄漏
ReportFragment這家伙是在哪出現的?我們在SupportActivity類中的onCreate找到答案
ReportFragment
@RestrictTo(RestrictTo.Scope.LIBRARY_GROUP) public class ReportFragment extends Fragment {private static final String REPORT_FRAGMENT_TAG = "android.arch.lifecycle"+ ".LifecycleDispatcher.report_fragment_tag";/****在Activity上附上一個空視圖的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 activitiesandroid.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();}}private ActivityInitializationListener mProcessListener;private void dispatchCreate(ActivityInitializationListener listener) {if (listener != null) {listener.onCreate();}}...@Overridepublic void onActivityCreated(Bundle savedInstanceState) {super.onActivityCreated(savedInstanceState);dispatchCreate(mProcessListener);dispatch(Lifecycle.Event.ON_CREATE);}@Overridepublic void onStart() {super.onStart();dispatchStart(mProcessListener);dispatch(Lifecycle.Event.ON_START);}...@Overridepublic void onDestroy() {super.onDestroy();dispatch(Lifecycle.Event.ON_DESTROY);// just want to be sure that we won't leak reference to an activitymProcessListener = null;}//可以看到Activtity的onCreate方法,以及ResportFragment中的onStart等各種生命周期方法都調用該方法,private void dispatch(Lifecycle.Event event) {Activity activity = getActivity();//v7中LifecycleRegistryOwner類不建議使用if (activity instanceof LifecycleRegistryOwner) {((LifecycleRegistryOwner) activity).getLifecycle().handleLifecycleEvent(event);return;}//因為SupportActivity實現了LifecycleOwner接口,所以會走此處分支if (activity instanceof LifecycleOwner) {Lifecycle lifecycle = ((LifecycleOwner) activity).getLifecycle();if (lifecycle instanceof LifecycleRegistry) {//關鍵點:生命周期事件轉發給了LifecycleRegistry中了((LifecycleRegistry) lifecycle).handleLifecycleEvent(event);}}}... }至此我們明白了Activity的生命周期事件是如何被轉發到LifecycleRegistry中了,以一張流程圖總結下
ActivityReportFragmentLifecycleRegistryonCreateinjectIfNeededIn(activity)onActivityCreatedispatch(state)handleLifecycleEventActivityReportFragmentLifecycleRegistry接下來我們看下LifecycleRegistry類是如何處理事件的
LifecycleRegistry
我理解的是LifecycleRegistry類和java中的Observable類有點像;因為Lifecycle的設計思想有部分就是使用了觀察者模式,LifecycleRegistry類中可以注冊或反注冊多個觀察者,一旦生命周期發生變更LifecycleRegistry會及時通知所有的觀察者,這樣就達到了觀察者能夠感知帶生命周期組件的變化了。
/*** An implementation of {@link Lifecycle} that can handle multiple observers.* <p>* It is used by Fragments and Support Library Activities. You can also directly use it if you have* a custom LifecycleOwner.*/ public class LifecycleRegistry extends Lifecycle {private static final String LOG_TAG = "LifecycleRegistry";/*** Custom list that keeps observers and can handle removals / additions during traversal.** Invariant: at any moment of time for observer1 & observer2:* if addition_order(observer1) < addition_order(observer2), then* state(observer1) >= state(observer2),*/private FastSafeIterableMap<LifecycleObserver, ObserverWithState> mObserverMap =new FastSafeIterableMap<>();/*** Current state*/private State mState;/*** The provider that owns this Lifecycle.* Only WeakReference on LifecycleOwner is kept, so if somebody leaks Lifecycle, they won't leak* the whole Fragment / Activity. However, to leak Lifecycle object isn't great idea neither,* because it keeps strong references on all other listeners, so you'll leak all of them as* well.*///使用弱引用避免Activity/Fragment內存泄漏private final WeakReference<LifecycleOwner> mLifecycleOwner;private int mAddingObserverCounter = 0;private boolean mHandlingEvent = false;private boolean mNewEventOccurred = false;// we have to keep it for cases:// void onStart() {// mRegistry.removeObserver(this);// mRegistry.add(newObserver);// }// newObserver should be brought only to CREATED state during the execution of// this onStart method. our invariant with mObserverMap doesn't help, because parent observer// is no longer in the map.private ArrayList<State> mParentStates = new ArrayList<>();/*** Creates a new LifecycleRegistry for the given provider.* <p>* You should usually create this inside your LifecycleOwner class's constructor and hold* onto the same instance.** @param provider The owner LifecycleOwner*/public LifecycleRegistry(@NonNull LifecycleOwner provider) {mLifecycleOwner = new WeakReference<>(provider);mState = INITIALIZED;}/*** Moves the Lifecycle to the given state and dispatches necessary events to the observers.** @param state new state*/@SuppressWarnings("WeakerAccess")@MainThreadpublic void markState(@NonNull State state) {moveToState(state);}/*** 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) {State next = getStateAfter(event);moveToState(next);}private void moveToState(State next) {//1. 如果狀態和當前狀態一樣,則不需要下發事件通知if (mState == next) {return;}//2. 更新最新生命周期事件狀態mState = next;if (mHandlingEvent || mAddingObserverCounter != 0) {mNewEventOccurred = true;// we will figure out what to do on upper level.return;}//3. 表示當前正在處理事件mHandlingEvent = true;//4. 同步事件到各Observersync();//5. 同步結束,重置標志mHandlingEvent = false;}// happens only on the top of stack (never in reentrance),// so it doesn't have to take in account parentsprivate 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;}//判斷最新的和最舊的觀察者狀態是否一致,如果一致說明同步狀態成功;如果無觀察者默認已同步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;}private void forwardPass(LifecycleOwner lifecycleOwner) {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&& mObserverMap.contains(entry.getKey()))) {pushParentState(observer.mState);//可以看到最終事件是在這里分發給了observerobserver.dispatchEvent(lifecycleOwner, upEvent(observer.mState));popParentState();}}}private void backwardPass(LifecycleOwner lifecycleOwner) {Iterator<Entry<LifecycleObserver, ObserverWithState>> descendingIterator =mObserverMap.descendingIterator();while (descendingIterator.hasNext() && !mNewEventOccurred) {Entry<LifecycleObserver, ObserverWithState> entry = descendingIterator.next();ObserverWithState observer = entry.getValue();while ((observer.mState.compareTo(mState) > 0 && !mNewEventOccurred&& mObserverMap.contains(entry.getKey()))) {Event event = downEvent(observer.mState);pushParentState(getStateAfter(event));observer.dispatchEvent(lifecycleOwner, event);popParentState();}}}... }通過上面代碼我們知道handleLifecycleEvent事件最后傳遞給observer的dispatchEvent方法中了;那么這個observer是什么?
首先看下它的類型是ObserverWithState,它是在什么時候被創建的呢?答案是addObserver方法
可以看到在ObserverWithState的dispatchEvent方法最終將事件委托給mLifecycleObserver,
運行demo可以看到這個mLifecycleObserver類型其實是ReflectiveGenericLifecycleObserver類型;其實也好蠻理解,因為我們的觀察者的方法標注了注解,而要想調用它,其實此處是通過反射來查找觀察者的帶生命周期注解的方法,一旦狀態改變時,通過反射直接調用就行;
因為反射代價較大,所以不太建議此種寫法,建議通過注解處理器,動態生成輔助類來提高性能,這個后面再說
GenericLifecycleObserver的實現類有五種,感興趣可以看看
推薦寫法
上面一開始寫法涉及到反射,為提高性能我們使用注解處理器方式來實現,google已經為我們想好了
1. 集成
annotationProcessor "android.arch.lifecycle:compiler:1.1.1" //java kapt "android.arch.lifecycle:compiler:1.1.1" //如果用kotlin重新clean,rebuild下可以看到,注解處理器幫我創建了輔助類,通過調用輔助類來提高運行期性能
輔助類代碼
public class HomeObserver_LifecycleAdapter implements GeneratedAdapter {final HomeObserver mReceiver;HomeObserver_LifecycleAdapter(HomeObserver receiver) {this.mReceiver = receiver;}@Overridepublic void callMethods(LifecycleOwner owner, Lifecycle.Event event, boolean onAny,MethodCallsLogger logger) {boolean hasLogger = logger != null;if (onAny) {return;}if (event == Lifecycle.Event.ON_CREATE) {if (!hasLogger || logger.approveCall("onCreate", 1)) {mReceiver.onCreate();}return;}if (event == Lifecycle.Event.ON_RESUME) {if (!hasLogger || logger.approveCall("onResume", 1)) {mReceiver.onResume();}return;}if (event == Lifecycle.Event.ON_DESTROY) {if (!hasLogger || logger.approveCall("onDestroy", 1)) {mReceiver.onDestroy();}return;}} }給大家的問題
總結
以上是生活随笔為你收集整理的Android Lifecycle源码解析(一)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Android Lifecycle组件使
- 下一篇: 谈谈数字签名