3. Jetpack源碼解析---用Lifecycles管理生命週期

1. 背景

上一篇我門對Jetpack組件中的Navigation作了介紹,而且對其作了源碼分析,相信看過以後已經對此有了必定的瞭解,本篇文章咱們會對Lifecycles進行使用及源碼的介紹,還沒看上篇的能夠看一下:php

系列文章java

1. Jetpack源碼解析---看完你就知道Navigation是什麼了?android

2. Jetpack源碼解析---Navigation爲何切換Fragment會重繪?bash

2. 基礎

2.1 簡介

Lifecycles是一個持有組件生命週期狀態(如Activity、Fragment)信息的類,並容許其餘對象觀察此狀態。能夠幫助咱們方便的管理ActivityFragment的生命週期。app

Lifecycle組件中經過兩個枚舉類來跟蹤其關聯組件的生命週期:
ide

2.2 基本使用

在咱們的平常開發中,常常須要咱們在Activity或者Fragment的生命週期方法中手動去管理一下資源的釋放等行爲。舉個簡單的例子,當咱們作自定義相機掃描的時候,camera相關的資源就須要咱們手動的去釋放及開啓預覽;或者咱們在使用MVP模式去開發的時候,P的建立和銷燬也須要咱們在生命週期方法中去操做。源碼分析

經過Lifecycles組件咱們能夠這樣使用:
咱們能夠定義一個Observer實現LifecycleObserver,而且在Activity或者Fragment中進行觀察:post

/** * created by ${Hankkin} * on 2019-06-10 */

class MyObserver : LifecycleObserver {

    @OnLifecycleEvent(Lifecycle.Event.ON_START)
    fun onStart() {
        Log.e(javaClass.name, "-------onStart")
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_CREATE)
    fun onCreate() {
        Log.e(javaClass.name, "-------onCreate")
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_RESUME)
    fun onResume() {
        Log.e(javaClass.name, "-------onResume")
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_PAUSE)
    fun onPause() {
        Log.e(javaClass.name, "-------onPause")
    }


    @OnLifecycleEvent(Lifecycle.Event.ON_STOP)
    fun onStop() {
        Log.e(javaClass.name, "-------onStop")
    }


    @OnLifecycleEvent(Lifecycle.Event.ON_DESTROY)
    fun onDestroy() {
        Log.e(javaClass.name, "-------onDestroy")
    }

}
複製代碼

下面是Activity:優化

class MainActivity : AppCompatActivity() {
    
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)


        lifecycle.addObserver(MyObserver())
        Log.e(javaClass.name, "-------onCreate")

    }

    override fun onStart() {
        super.onStart()
        Log.e(javaClass.name, "-------onStart")
    }

    override fun onResume() {
        super.onResume()
        Log.e(javaClass.name, "-------onResume")
    }

    override fun onPause() {
        super.onPause()
        Log.e(javaClass.name, "-------onPause")
    }

    override fun onStop() {
        super.onStop()
        Log.e(javaClass.name, "-------onStop")
    }

    override fun onDestroy() {
        super.onDestroy()
        Log.e(javaClass.name, "-------onDestroy")
    }
}
複製代碼

啓動Activity,咱們能夠看到控制檯中的打印日誌:ui

MainActivity: -------onCreate
MyObserver: -------onCreate
MainActivity: -------onStart
MyObserver: -------onStart
MainActivity: -------onResume
MyObserver: -------onResume
......
複製代碼

經過控制檯打印咱們能夠看到咱們的觀察者Activity和被觀察者的日誌均被打印了。具體是怎麼實現的呢?

3. 源碼分析

經過代碼咱們大概能看出來Lifecycles組件是經過觀察者模式來實現的,接下來咱們具體分析實現原理,咱們發如今ActivityFragment中能夠直接經過getLifecycle()方法獲取到Lifecycle,那麼咱們就從這裏入手:

3.1 getLifecycle()

咱們點擊進去發現ComponentActivity中實現了LifecycleOwner接口,LifecycleOwner接口中則聲明瞭getLifecycle()方法,而ComponentActivity中直接返回了mLifecycleRegistry

public class ComponentActivity extends androidx.core.app.ComponentActivity implements
        LifecycleOwner,
        ViewModelStoreOwner,
        SavedStateRegistryOwner,
        OnBackPressedDispatcherOwner {

    private final LifecycleRegistry mLifecycleRegistry = new LifecycleRegistry(this);
    ......
    @NonNull
    @Override
    public Lifecycle getLifecycle() {
        return mLifecycleRegistry;
    }
複製代碼

LifecycleRegistry是個什麼東西呢?原來它繼承了Lifecycle

public class LifecycleRegistry extends Lifecycle
複製代碼

3.2 Lifecycle和LifecycleRegistry

咱們看一下Lifecycle類:

public abstract class Lifecycle {

        //註冊LifecycleObserver (好比Presenter)
        public abstract void addObserver(@NonNull LifecycleObserver observer);
        //移除LifecycleObserver 
        public abstract void removeObserver(@NonNull LifecycleObserver observer);
        //獲取當前狀態
        public abstract State getCurrentState();

        public enum Event {
            ON_CREATE,
            ON_START,
            ON_RESUME,
            ON_PAUSE,
            ON_STOP,
            ON_DESTROY,
            ON_ANY
        }
        
       public enum State {
            DESTROYED,
            INITIALIZED,
            CREATED,
            STARTED,
            RESUMED;

            public boolean isAtLeast(@NonNull State state) {
                return compareTo(state) >= 0;
            }
       }
}
複製代碼

Lifecycle中就是聲明瞭一些抽象方法和兩個狀態的枚舉類,具體的實現看LifecycleRegistry

public class LifecycleRegistry extends Lifecycle {

// LifecycleObserver Map,每個Observer都有一個State
    private FastSafeIterableMap<LifecycleObserver, ObserverWithState> mObserverMap = new FastSafeIterableMap<>();
    // 當前的狀態
    private State mState;
    // 生命週期擁有者,ComponentActivity繼承了LifecycleOwner
    private final WeakReference<LifecycleOwner> mLifecycleOwner;

    //修改State值
    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;
    }

    /** * 添加LifecycleObserver觀察者,並將以前的狀態分發給這個Observer,例如咱們在onResume以後註冊這個Observer, * 該Observer依然能收到ON_CREATE事件 */
    @Override
    public void addObserver(@NonNull LifecycleObserver observer) {
        State initialState = mState == DESTROYED ? DESTROYED : INITIALIZED;
        //新建帶有狀態的觀察者
        ObserverWithState statefulObserver = new ObserverWithState(observer, initialState);
        ObserverWithState previous = mObserverMap.putIfAbsent(observer, statefulObserver);
        ......
        // 例如:Observer初始狀態是INITIALIZED,當前狀態是RESUMED,須要將INITIALIZED到RESUMED之間的
        // 全部事件分發給Observer
        while ((statefulObserver.mState.compareTo(targetState) < 0
                && mObserverMap.contains(observer))) {
            pushParentState(statefulObserver.mState);
            statefulObserver.dispatchEvent(lifecycleOwner, upEvent(statefulObserver.mState));
            popParentState();
            targetState = calculateTargetState(observer);
        }
        ......
}

/** * 同步Observer狀態,並分發事件 */
    private void sync() {
        LifecycleOwner lfecycleOwner = 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;
            // State中,狀態值是從DESTROYED-INITIALIZED-CREATED-STARTED-RESUMED增大
            // 若是當前狀態值 < Observer狀態值,須要通知Observer減少狀態值,直到等於當前狀態值
            if (mState.compareTo(mObserverMap.eldest().getValue().mState) < 0) {
                backwardPass(lifecycleOwner);
            }
            Entry<LifecycleObserver, ObserverWithState> newest = mObserverMap.newest();
            // 若是當前狀態值 > Observer狀態值,須要通知Observer增大狀態值,直到等於當前狀態值
            if (!mNewEventOccurred && newest != null
                    && mState.compareTo(newest.getValue().mState) > 0) {
                forwardPass(lifecycleOwner);
            }
        }
        mNewEventOccurred = false;
    }

    /** * 向前傳遞事件,對應圖中的INITIALIZED -> RESUMED * 增長Observer的狀態值,直到狀態值等於當前狀態值 */
    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);
                // 分發狀態改變事件
                observer.dispatchEvent(lifecycleOwner, upEvent(observer.mState));
                popParentState();
            }
        }
    }

    /** * 向後傳遞事件,對應圖中的RESUMED -> DESTROYED * 減少Observer的狀態值,直到狀態值等於當前狀態值 */
    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();
            }
        }
    }
複製代碼

LifecycleRegistry代碼我門看完了,註釋也已經很清楚了,基本做用就是添加觀察者,響應生命週期事件,分發生命週期事件的做用。

3.3 ReportFragment

接下來咱們繼續分析ComponentActivity,咱們在onCreate()聲明週期中發現一個比較熟悉ReportFragment,這個fragment我之前在作內存泄漏優化的時候常常碰到,在leakcanary中常常會報出這個類,因此這裏面看看ReportFragment.injectIfNeededIn(this);到底作了什麼?

@RestrictTo(RestrictTo.Scope.LIBRARY_GROUP_PREFIX)
public class ReportFragment extends Fragment {
    private static final String REPORT_FRAGMENT_TAG = "androidx.lifecycle"
            + ".LifecycleDispatcher.report_fragment_tag";

    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();
        }
    }
    private void dispatchCreate(ActivityInitializationListener listener) {
        if (listener != null) {
            listener.onCreate();
        }
    }

    private void dispatchStart(ActivityInitializationListener listener) {
        if (listener != null) {
            listener.onStart();
        }
    }

    private void dispatchResume(ActivityInitializationListener listener) {
        if (listener != null) {
            listener.onResume();
        }
    }

    @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;
    }

    private void dispatch(Lifecycle.Event event) {
        Activity activity = getActivity();
        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);
            }
        }
    }
複製代碼

查看源碼咱們發現,ReportFragment在每一個生命週期中都作了分發事件的處理,經過調用getLifecycle().handleLifecycleEvent(event)來作生命週期的分發。意思也就是在ComponentActivity中添加了一個沒有頁面的ReportFragment,當Activity生命週期變化的時候,經過調用LifecycleRegistry.handleLifecycleEvent()方法通知LifecycleRegistry改變狀態,LifecycleRegistry內部調用moveToState()改變狀態,並調用每一個LifecycleObserver.onStateChange()方法通知生命週期變化。

咱們經過查看ReportFragment調用,發現還有兩個類也調用了它,一個是LifecycleDispatcher,一個是ProcessLifecycleOwner,這兩個到底是作什麼的呢?

3.4 LifecycleDispatcher

class LifecycleDispatcher {

    private static AtomicBoolean sInitialized = new AtomicBoolean(false);

    static void init(Context context) {
        if (sInitialized.getAndSet(true)) {
            return;
        }
        ((Application) context.getApplicationContext())
                .registerActivityLifecycleCallbacks(new DispatcherActivityCallback());
    }

    @SuppressWarnings("WeakerAccess")
    @VisibleForTesting
    static class DispatcherActivityCallback extends EmptyActivityLifecycleCallbacks {

        @Override
        public void onActivityCreated(Activity activity, Bundle savedInstanceState) {
            ReportFragment.injectIfNeededIn(activity);
        }

        @Override
        public void onActivityStopped(Activity activity) {
        }

        @Override
        public void onActivitySaveInstanceState(Activity activity, Bundle outState) {
        }
    }

    private LifecycleDispatcher() {
    }
}
複製代碼

咱們查看源碼,發如今init()方法中,經過Application註冊了DispatcherActivityCallback,而且在onActivityCreated中將ReportFragment注入到Activity中。

3.5 ProcessLifecycleOwner

public class ProcessLifecycleOwner implements LifecycleOwner {

       private final LifecycleRegistry mRegistry = new LifecycleRegistry(this);

    private Runnable mDelayedPauseRunnable = new Runnable() {
        @Override
        public void run() {
            dispatchPauseIfNeeded();
            dispatchStopIfNeeded();
        }
    };

    private ActivityInitializationListener mInitializationListener =
            new ActivityInitializationListener() {
                @Override
                public void onCreate() {
                }

                @Override
                public void onStart() {
                    activityStarted();
                }

                @Override
                public void onResume() {
                    activityResumed();
                }
            };

    private static final ProcessLifecycleOwner sInstance = new ProcessLifecycleOwner();

   
    public static LifecycleOwner get() {
        return sInstance;
    }

    static void init(Context context) {
        sInstance.attach(context);
    }

    void activityStarted() {
        mStartedCounter++;
        if (mStartedCounter == 1 && mStopSent) {
            mRegistry.handleLifecycleEvent(Lifecycle.Event.ON_START);
            mStopSent = false;
        }
    }

    void activityResumed() {
        mResumedCounter++;
        if (mResumedCounter == 1) {
            if (mPauseSent) {
                mRegistry.handleLifecycleEvent(Lifecycle.Event.ON_RESUME);
                mPauseSent = false;
            } else {
                mHandler.removeCallbacks(mDelayedPauseRunnable);
            }
        }
    }

   ......
    private void dispatchStopIfNeeded() {
        if (mStartedCounter == 0 && mPauseSent) {
            mRegistry.handleLifecycleEvent(Lifecycle.Event.ON_STOP);
            mStopSent = true;
        }
    }

    private ProcessLifecycleOwner() {
    }
    //監聽Application生命週期,並分發給Activity
    void attach(Context context) {
        mHandler = new Handler();
        mRegistry.handleLifecycleEvent(Lifecycle.Event.ON_CREATE);
        Application app = (Application) context.getApplicationContext();
        app.registerActivityLifecycleCallbacks(new EmptyActivityLifecycleCallbacks() {
            @Override
            public void onActivityCreated(Activity activity, Bundle savedInstanceState) {
                ReportFragment.get(activity).setProcessListener(mInitializationListener);
            }

            @Override
            public void onActivityPaused(Activity activity) {
                activityPaused();
            }

            @Override
            public void onActivityStopped(Activity activity) {
                activityStopped();
            }
        });
    }
}
複製代碼

根據官方註釋,咱們能夠了解到:

  • ProcessLifecycleOwner是用來監聽Application生命週期的,所以它只會分發一次ON_CREATE事件,而且不會分發ON_DESTROY事件。
  • ProcessLifecycleOwner在Activity的onResume和onStop方法中都採用了Handle.postDelayed()方法,是爲了處理Activity重建時好比橫豎屏幕切換時,不會發送事件。
  • ProcessLifecycleOwner通常用來判斷應用是在前臺仍是後臺。但因爲使用了Handle.postDelayed(),所以這個判斷不是即時的,有默認700ms的延遲。
  • ProcessLifecycleOwner與LifecycleDispatcher同樣,都是經過註冊Application.registerActivityLifecycleCallbacks來監聽Activity的生命週期回調,來給每一個Activity添加ReportFragment的。

看了着兩個類咱們發現它們的入口均爲init(),因此看一下誰調用了?

3.6 ProcessLifecycleOwnerInitializer

public class ProcessLifecycleOwnerInitializer extends ContentProvider {
    @Override
    public boolean onCreate() {
        LifecycleDispatcher.init(getContext());
        ProcessLifecycleOwner.init(getContext());
        return true;
    }

    @Nullable
    @Override
    public Cursor query(@NonNull Uri uri, String[] strings, String s, String[] strings1, String s1) {
        return null;
    }

    @Nullable
    @Override
    public String getType(@NonNull Uri uri) {
        return null;
    }

    @Nullable
    @Override
    public Uri insert(@NonNull Uri uri, ContentValues contentValues) {
        return null;
    }

    @Override
    public int delete(@NonNull Uri uri, String s, String[] strings) {
        return 0;
    }

    @Override
    public int update(@NonNull Uri uri, ContentValues contentValues, String s, String[] strings) {
        return 0;
    }
}
複製代碼

果然,在ProcessLifecycleOwnerInitializeronCreate()中對這兩個進行了初始化,看類名能夠翻譯成_進程生命週期初始化_,到這裏咱們對該類就找不到調用者或者使用者了,因此不得不百度一下,發現有人說這個類是在AndroidManifest.xml中聲明的,在構建APK過程當中,AS會將多個模塊的AndroidManifest.xml合併到一塊兒,因此查看build目錄,具體路徑爲build/intermediates/bundle_manifest/debug/processDebugManifest/bundle-manifest/AndroidManifest.xml,果然在裏面:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.hankkin.reading_aac" android:versionCode="1" android:versionName="1.0" >

    <uses-sdk android:minSdkVersion="19" android:targetSdkVersion="28" />

    <application android:appComponentFactory="androidx.core.app.CoreComponentFactory" android:debuggable="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:roundIcon="@mipmap/ic_launcher_round" android:supportsRtl="true" android:testOnly="true" android:theme="@style/AppTheme" >
        <activity android:name="com.hankkin.reading_aac.ui.LoginActivity" >
        </activity>
        <activity android:name="com.hankkin.reading_aac.MainActivity" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

        <provider android:name="androidx.lifecycle.ProcessLifecycleOwnerInitializer" android:authorities="com.hankkin.reading_aac.lifecycle-process" android:exported="false" android:multiprocess="true" />
    </application>

</manifest>
複製代碼

到這裏整個Lifecycle初始化的過程就結束了。

4. 總結

通過上面的源碼分析,咱們能夠大概給整個Lifecycle組件分爲三部分:

4.1 Lifecycle的初始化

經過在manifest中聲明provider,`ProcessLifecycleOwnerInitializer`註冊Activity和fragment.的聲明週期回調並作監聽,同時向Activity中添加一個空白的`ReportFragment`,使用它做爲生命週期的事件分發。而當Activity和Fragment生命週期狀態發生改變時,都經過LifecycleRegistryOwner來處理生命週期狀態的改變。
複製代碼

4.2 Lifecycle的狀態改變及狀態分發

在`ReportFragment`中調用`LifecycleRegister.handleLifecycleEvent(Lifecycle.Event)`,經過**獲取事件對應的下一個狀態**以及**改變當前狀態到下一個狀態**,同步分發事件;最後將各個觀察者的生命週期狀態依次移動到正確狀態。
複製代碼

能夠查看下面的時序圖:

4.3 Lifecycle解析生命週期

咱們聲明的MyObserver中的方法都是帶有註解的,查看OnLifecycleEvent

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface OnLifecycleEvent {
    Lifecycle.Event value();
}
複製代碼

註解修飾的方法會經過反射的方式獲取,而且保存在ClassesInfoCache中,而後在生命週期發生改變的時候再找到對應 Event 的方法,經過反射來調用方法。

5. 參考連接:

juejin.im/post/5cd816…

yuqirong.me/2018/07/15/…

相關文章
相關標籤/搜索