如何綁定頁面生命週期(一)-Glide實現

Glide中一個重要的特性,就是Request能夠隨着Activity或Fragment的onStart而resume,onStop而pause,onDestroy而clear。從而節約流量和內存,而且防止內存泄露,這一切都由Glide在內部實現了。用戶惟一要注意的是,Glide.with()方法中儘可能傳入Activity或Fragment,而不是Application,否則沒辦法進行生命週期管理。android

由於對Glide綁定生命週期的原理很感興趣,因此看了一些源碼解析的文章,也讀了Glide的相關源碼。發現大多數對於Glide生命週期綁定原理的介紹,是直接經過源碼一步步的介紹。我的感受這樣沒有重點,容易迷失在代碼流程細節中。git

因此這篇文章經過另一種方式介紹Glide生命週期管理的原理,即經過提問解答的方式,帶着問題閱讀,更加具備針對性。介紹完了原理以後,咱們經過基於Glide生命週期感知的原理,實現了一個仿Glide生命週期管理框架的demo,進一步加深鞏固以前所學知識點。因此,本文介紹主要分爲兩個部分:github

  • Glide生命週期管理原理
  • 仿Glide自定義生命週期管理框架實踐

Glide生命週期管理原理

這裏的話,我主要提了三個問題:bash

  • 整體實現原理
  • 如何綁定生命週期
  • 如何傳遞生命週期

下面經過解答這三個問題,讓咱們一塊兒來探究下Glide綁定生命週期的實現原理。本文以Activity爲例進行講解。app

整體實現原理

基於當前Activity添加無UI的Fragment,經過Fragment接收Activity傳遞的生命週期。Fragment和RequestManager基於Lifecycle創建聯繫,並傳遞生命週期事件,實現生命週期感知。分析上述的原理,能夠概括爲兩個方面:框架

  1. 如何基於當前傳入Activity生成無UI的Fragment,即如何實現對頁面的週期綁定。
  2. 無UI的fragment如何將生命週期傳遞給RequestManager,即如何實現生命週期傳遞。

如何綁定生命週期

使用Glide時,咱們經過Glide.with(Activity activity)的方式傳入頁面引用,讓咱們看下with(Activity activity)方法的實現:ide

public static RequestManager with(Activity activity) {
    RequestManagerRetriever retriever = RequestManagerRetriever.get();
    return retriever.get(activity);
}
複製代碼

with(Activity activity)在方法體內先獲取了RequestManagerRetriever實例retriever,而後經過retriever去調用成員函數get(activity)。接下來咱們看下get(activity)的實現:函數

@TargetApi(Build.VERSION_CODES.HONEYCOMB)
public RequestManager get(Activity activity) {
    if (Util.isOnBackgroundThread() || Build.VERSION.SDK_INT < Build.VERSION_CODES.HONEYCOMB) {
        return get(activity.getApplicationContext());
    } else {
        assertNotDestroyed(activity);
        // 獲取當前Activity的FragmentManager
        android.app.FragmentManager fm = activity.getFragmentManager();
        return fragmentGet(activity, fm);
    }
}
複製代碼

咱們看上面函數方法體代碼,當應用在後臺或系統低於HONEYCOMB版本,則直接綁定應用的生命週期,這裏咱們主要看else部分的代碼。oop

首先,經過傳入的activity引用,獲取當前頁面的FragmentManager,而後將當前頁面的引用和剛生成的FragmentManager對象引用,做爲參數一塊兒傳入fragmentGet(activity, fm)方法。下面看下fragmentGet(activity, fm)的具體實現:源碼分析

@TargetApi(Build.VERSION_CODES.HONEYCOMB)
RequestManager fragmentGet(Context context, android.app.FragmentManager fm) {
	// 基於當前activity註冊無UI的RequestManagerFragment
    RequestManagerFragment current = getRequestManagerFragment(fm);
    // 生成RequestManager
    RequestManager requestManager = current.getRequestManager();
    if (requestManager == null) {
    	// 經過current.getLifecycle()獲取fragment的lifecycle,傳入requestManager,將fragment和requestManager創建聯繫
        requestManager = new RequestManager(context, current.getLifecycle(), current.getRequestManagerTreeNode());
        current.setRequestManager(requestManager);
    }
    return requestManager;
}
複製代碼

上述方法具體執行的步驟,如上註釋所示:

  1. 基於當前activity註冊無UI的RequestManagerFragment
  2. 生成RequestManager,經過current.getLifecycle()獲取fragment的lifecycle,傳入requestManager,將fragment和requestManager創建聯繫

這裏有兩點須要咱們關注下:

  1. 經過getRequestManagerFragment(fm)生成無UI的fragment

生成fragment時,最終會調用到RequestManagerFragment的構造方法,實現形式以下:

public RequestManagerFragment() {
    this(new ActivityFragmentLifecycle());
}

// For testing only.
@SuppressLint("ValidFragment")
RequestManagerFragment(ActivityFragmentLifecycle lifecycle) {
    this.lifecycle = lifecycle;
}
複製代碼

構造fragment時,會同時初始化成員變量lifecycle

  1. 生成RequestManager對象時,經過current.getLifecycle()獲取fragment的成員lifecycle,做爲參數傳入RequestManager構造函數。
public RequestManager(Context context, Lifecycle lifecycle, RequestManagerTreeNode treeNode) {
    this(context, lifecycle, treeNode, new RequestTracker(), new ConnectivityMonitorFactory());
}

RequestManager(Context context, final Lifecycle lifecycle, RequestManagerTreeNode treeNode,
        RequestTracker requestTracker, ConnectivityMonitorFactory factory) {
    this.context = context.getApplicationContext();
    this.lifecycle = lifecycle;
    this.treeNode = treeNode;
    this.requestTracker = requestTracker;
    this.glide = Glide.get(context);
    this.optionsApplier = new OptionsApplier();

    ConnectivityMonitor connectivityMonitor = factory.build(context,
            new RequestManagerConnectivityListener(requestTracker));

    // If we're the application level request manager, we may be created on a background thread. In that case we // cannot risk synchronously pausing or resuming requests, so we hack around the issue by delaying adding // ourselves as a lifecycle listener by posting to the main thread. This should be entirely safe. if (Util.isOnBackgroundThread()) { new Handler(Looper.getMainLooper()).post(new Runnable() { @Override public void run() { lifecycle.addListener(RequestManager.this); } }); } else { lifecycle.addListener(this); } lifecycle.addListener(connectivityMonitor); } 複製代碼

可見在RequestManager初始化時,調用了lifecycle.addListener(this),將本身的引用存入lifecycle,從而實現與fragment關聯。

創建了聯繫,下面咱們看下生命週期是如何傳遞的。

如何傳遞生命週期

經過上面生命週期綁定的流程,咱們已經知道經過ActivityFragmentLifecycle,將空白Fragment和RequestManager創建了聯繫。由於空白fragment註冊在頁面上,其能夠感知頁面的生命週期。下面咱們來看下如何從空白fragment,將生命週期傳遞給RequestManager,從而對Request進行管理。

首先,咱們來看空白RequestManagerFragment生命週期回調方法:

...
@Override
public void onStart() {
    super.onStart();
    lifecycle.onStart();
}

@Override
public void onStop() {
    super.onStop();
    lifecycle.onStop();
}

@Override
public void onDestroy() {
    super.onDestroy();
    lifecycle.onDestroy();
}
...

複製代碼

咱們看到會調用其成員對象lifecycle相關對應生命週期的回調方法,這裏咱們以onStart()爲例,看一下ActivityFragmentLifecycle中的方法實現:

void onStart() {
    isStarted = true;
    for (LifecycleListener lifecycleListener : Util.getSnapshot(lifecycleListeners)) {
        lifecycleListener.onStart();
    }
}
複製代碼

可見回調lifeCycleListener中的相關方法,由於RequestManager實現了lifeCycleListener接口。且在綁定階段,在RequestManager的構造方法中,將RequestManager加入到了lifeCycle中。故回調lifeCycleListener中的相關方法,能夠調用到它裏面的對request生命週期進行管理的方法。由此,實現了Request對生命週期的感知。

/**
 * Lifecycle callback that registers for connectivity events (if the android.permission.ACCESS_NETWORK_STATE
 * permission is present) and restarts failed or paused requests.
 */
@Override
public void onStart() {
    // onStart might not be called because this object may be created after the fragment/activity's onStart method. resumeRequests(); } /** * Lifecycle callback that unregisters for connectivity events (if the android.permission.ACCESS_NETWORK_STATE * permission is present) and pauses in progress loads. */ @Override public void onStop() { pauseRequests(); } /** * Lifecycle callback that cancels all in progress requests and clears and recycles resources for all completed * requests. */ @Override public void onDestroy() { requestTracker.clearRequests(); } 複製代碼

基於生命週期傳遞的過程,畫了下生命週期傳遞的示意圖,以下所示:

Glide中生命週期傳遞

幾個核心類介紹

經過對Glide生命週期綁定和傳遞整個流程過了一遍以後,你們應該對總體實現的框架有必定的瞭解。如今再來看下面一些核心類的介紹,應該更加有感觸。

  • Glide:庫提供對外調用方法的類,傳入頁面引用。
  • RequestManagerRetriever:一個處理中間類,獲取RequestManager和RequestManagerFragment,並將二者綁定
  • RequestManagerFragment:無UI的fragment,與RequestManager綁定,感知並傳遞頁面的生命週期
  • RequestManager:實現了LifeCycleListener,主要做用爲結合Activity或Fragment生命週期,對Request進行管理,如pauseRequests(), resumeRequests(), clearRequests()。
  • LifecycleListener:接口,定義生命週期管理方法,onStart(), onStop(), onDestroy(). RequestManager實現了它。
  • ActivityFragmentLifecycle:保存fragment和Requestmanager映射關係的類,管理LifecycleListener, 空白Fragment會回調它的onStart(), onStop(), onDestroy()。

生命週期管理框架實踐

理解了Glide的生命週期管理框架的實現原理,下面咱們來本身實現一個簡單的綁定頁面Activity的生命週期管理框架。

  • 定義對外調用類LifecycleDetector,單例模式獲取類實例。
public class LifecycleDetector {

    static final String FRAGMENT_TAG = "com.bumptech.glide.manager";

    private static volatile LifecycleDetector sInstance;

    public static LifecycleDetector getInstance() {
        if (sInstance == null) {
            synchronized (LifecycleDetector.class) {
                if (sInstance == null) {
                    sInstance = new LifecycleDetector();
                }
            }
        }

        return sInstance;
    }

    public void observer(Activity activity, LifecycleListener lifecycleListener) {
        // 獲取當前activity的FragmentManager
        android.app.FragmentManager fm = activity.getFragmentManager();
        // 註冊無UI的fragment
        LifecycleManagerFragment current = getRequestManagerFragment(fm);

        current.getLifecycle().addListener(lifecycleListener);
    }


    @TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR1)
    LifecycleManagerFragment getRequestManagerFragment(final android.app.FragmentManager fm) {
        LifecycleManagerFragment current = (LifecycleManagerFragment) fm.findFragmentByTag(FRAGMENT_TAG);
        if (current == null) {
            if (current == null) {
                current = new LifecycleManagerFragment();
                fm.beginTransaction().add(current, FRAGMENT_TAG).commitAllowingStateLoss();
            }
        }
        return current;
    }
}
複製代碼
  • 定義接口Lifecycle和其實現類ActivityFragmentLifecycle
// 接口
public interface Lifecycle {
    void addListener(LifecycleListener listener);
}

// 實現類,保存fragment和Requestmanager映射關係的類,管理LifecycleListener
public class ActivityFragmentLifecycle implements Lifecycle {
    private final Set<LifecycleListener> lifecycleListeners =
            Collections.newSetFromMap(new WeakHashMap<LifecycleListener, Boolean>());
    private boolean isStarted;
    private boolean isDestroyed;


    @Override
    public void addListener(LifecycleListener listener) {
        lifecycleListeners.add(listener);

        if (isDestroyed) {
            listener.onDestroy();
        } else if (isStarted) {
            listener.onStart();
        } else {
            listener.onStop();
        }
    }

    void onStart() {
        isStarted = true;
        for (LifecycleListener lifecycleListener : Util.getSnapshot(lifecycleListeners)) {
            lifecycleListener.onStart();
        }
    }

    void onStop() {
        isStarted = false;
        for (LifecycleListener lifecycleListener : Util.getSnapshot(lifecycleListeners)) {
            lifecycleListener.onStop();
        }
    }

    void onDestroy() {
        isDestroyed = true;
        for (LifecycleListener lifecycleListener : Util.getSnapshot(lifecycleListeners)) {
            lifecycleListener.onDestroy();
        }
    }
}
複製代碼
  • 定義空白Fragment(LifecycleManagerFragment)
public class LifecycleManagerFragment extends Fragment {

    private final ActivityFragmentLifecycle lifecycle;


    public LifecycleManagerFragment() {
        this(new ActivityFragmentLifecycle());
    }

    // For testing only.
    @SuppressLint("ValidFragment")
    LifecycleManagerFragment(ActivityFragmentLifecycle lifecycle) {
        this.lifecycle = lifecycle;
    }

    public ActivityFragmentLifecycle getLifecycle() {
        return lifecycle;
    }

    @Override
    public void onStart() {
        super.onStart();
        lifecycle.onStart();
    }

    @Override
    public void onStop() {
        super.onStop();
        lifecycle.onStop();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        lifecycle.onDestroy();
    }

}
複製代碼
  • 定義LifecycleListener
public interface LifecycleListener {

    /**
     * Callback for when {@link android.app.Fragment#onStart()}} or {@link android.app.Activity#onStart()} is called.
     */
    void onStart();

    /**
     * Callback for when {@link android.app.Fragment#onStop()}} or {@link android.app.Activity#onStop()}} is called.
     */
    void onStop();

    /**
     * Callback for when {@link android.app.Fragment#onDestroy()}} or {@link android.app.Activity#onDestroy()} is
     * called.
     */
    void onDestroy();
}
複製代碼

當以上框架所需的類定義好了以後,咱們定義一個Test類實現LifecycleListener接口。而後在Activity頁面中,好比onCreate方法中實現以下代碼:

@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        Test test = new Test();
        LifecycleDetector.getInstance().observer(this, test);
    }
複製代碼

以後,咱們就能夠在Test監聽Activity頁面的生命週期變化了。具體框架的一個類圖以下所示:

仿Glide生命週期框架

具體工程代碼能夠從這裏獲取:CustomGlideLifecycleDemo

結束

至此,關於Glide如何綁定頁面生命週期的原理講解結束。在下一篇文章如何綁定頁面生命週期(二)-基於Android Architecture Components的Lifecycle實現,將會介紹綁定頁面生命週期的另外一種方式,即基於Android Architecture Components框架的Lifecycle實現生命週期綁定。

參考

  1. Glide源碼分析3 -- 綁定Activity生命週期
相關文章
相關標籤/搜索