Android Glide 源碼分析(一)生命周期和基本流程

Glide 依賴

implementation 'com.github.bumptech.glide:glide:4.9.0'

Glide 使用方式

Glide.with(context)
     .load(url)
     .into(view);                  

Glide -> with

//Context
public static RequestManager with(@NonNull Context context) {
    return getRetriever(context).get(context);
}

//Activity
public static RequestManager with(@NonNull Activity activity) {
    return getRetriever(activity).get(activity);
}

//FragmentActivity
public static RequestManager with(@NonNull FragmentActivity activity) {
    return getRetriever(activity).get(activity);
}

//Fragment
public static RequestManager with(@NonNull Fragment fragment) {
    return getRetriever(fragment.getActivity()).get(fragment);
}

//android.app.Fragment
public static RequestManager with(@NonNull android.app.Fragment fragment) {
    return getRetriever(fragment.getActivity()).get(fragment);
}

//View
public static RequestManager with(@NonNull View view) {
    return getRetriever(view.getContext()).get(view);
}

with 方法是一個(gè)重載方法,但最終都會(huì)調(diào)用 getRetriever 方法。

getRetriever

private static RequestManagerRetriever getRetriever(@Nullable Context context) {
    // Context could be null for other reasons (ie the user passes in null), but in practice it will
    // only occur due to errors with the Fragment lifecycle.
    Preconditions.checkNotNull(
        context,
        "You cannot start a load on a not yet attached View or a Fragment where getActivity() "
            + "returns null (which usually occurs when getActivity() is called before the Fragment "
            + "is attached or after the Fragment is destroyed).");
    return Glide.get(context).getRequestManagerRetriever();
}

public static Glide get(@NonNull Context context) {
    if (glide == null) {
        synchronized (Glide.class) {
            if (glide == null) {
                checkAndInitializeGlide(context);
            }
        }
    }
    return glide;
}

Glide 的創(chuàng)建使用的是雙重檢索( DCL )單例,然后通過 getRequestManagerRetriever 方法獲取 RequestManagerRetriever 對(duì)象。

RequestManagerRetriever.get

//Context
public RequestManager get(@NonNull Context context) {
    if (context == null) {
      throw new IllegalArgumentException("You cannot start a load on a null Context");
    } else if (Util.isOnMainThread() && !(context instanceof Application)) {
      if (context instanceof FragmentActivity) {
        return get((FragmentActivity) context);
      } else if (context instanceof Activity) {
        return get((Activity) context);
      } else if (context instanceof ContextWrapper) {
        return get(((ContextWrapper) context).getBaseContext());
      }
    }

    return getApplicationManager(context);
}

get 方法也是一個(gè)重載方法,這里就不全部羅列了。看起來處理比較多,而實(shí)際上只處理了兩種情況的參數(shù)。
一種為「 非 Application 」類型的參數(shù),一種為「 Application 」類型的參數(shù)。

getApplicationManager

private RequestManager getApplicationManager(@NonNull Context context) {
    if (applicationManager == null) {
      synchronized (this) {
        if (applicationManager == null) {
          // Normally pause/resume is taken care of by the fragment we add to the fragment or
          // activity. However, in this case since the manager attached to the application will not
          // receive lifecycle events, we must force the manager to start resumed using
          // ApplicationLifecycle.

          // TODO(b/27524013): Factor out this Glide.get() call.
          Glide glide = Glide.get(context.getApplicationContext());
          applicationManager =
              factory.build(
                  glide,
                  new ApplicationLifecycle(),
                  new EmptyRequestManagerTreeNode(),
                  context.getApplicationContext());
        }
      }
    }
    return applicationManager;
}

ApplicationLifecycle

class ApplicationLifecycle implements Lifecycle {
  @Override
  public void addListener(@NonNull LifecycleListener listener) {
    listener.onStart();
  }

  @Override
  public void removeListener(@NonNull LifecycleListener listener) {
    // Do nothing.
  }
}

當(dāng)參數(shù)為 Application 類型的參數(shù)時(shí),會(huì)創(chuàng)建一個(gè) ApplicationLifecycle 對(duì)象,此時(shí) Glide 的生命周期就和 Application 生命周期一致。

RequestManagerRetriever.get

public RequestManager get(@NonNull FragmentActivity activity) {
    if (Util.isOnBackgroundThread()) {
      return get(activity.getApplicationContext());
    } else {
      assertNotDestroyed(activity);
      //通過當(dāng)前 activity 獲取 FragmentManager
      //用于創(chuàng)建透明 fragment
      FragmentManager fm = activity.getSupportFragmentManager();
      return supportFragmentGet(
          activity, fm, /*parentHint=*/ null, isActivityVisible(activity));
    }
}

supportFragmentGet

private RequestManager supportFragmentGet(
      @NonNull Context context,
      @NonNull FragmentManager fm,
      @Nullable Fragment parentHint,
      boolean isParentVisible) {
    //創(chuàng)建透明的 fragment
    SupportRequestManagerFragment current =
        getSupportRequestManagerFragment(fm, parentHint, isParentVisible);
    RequestManager requestManager = current.getRequestManager();
    if (requestManager == null) {
      // TODO(b/27524013): Factor out this Glide.get() call.
      Glide glide = Glide.get(context);
      //將 Glide 生命周期與 fragment 綁定
      requestManager =
          factory.build(
              glide, current.getGlideLifecycle(), current.getRequestManagerTreeNode(), context);
      current.setRequestManager(requestManager);
    }
    return requestManager;
}

getSupportRequestManagerFragment

private SupportRequestManagerFragment getSupportRequestManagerFragment(
      @NonNull final FragmentManager fm, @Nullable Fragment parentHint, boolean isParentVisible) {
    //通過 TAG 查找 fragment
    SupportRequestManagerFragment current =
        (SupportRequestManagerFragment) fm.findFragmentByTag(FRAGMENT_TAG);
    if (current == null) {
      //通過 FragmentManager 查找 fragment
      current = pendingSupportRequestManagerFragments.get(fm);
      //如果為空則創(chuàng)建一個(gè) fragment 并加入緩存
      if (current == null) {
        current = new SupportRequestManagerFragment();
        current.setParentFragmentHint(parentHint);
        if (isParentVisible) {
          current.getGlideLifecycle().onStart();
        }
        pendingSupportRequestManagerFragments.put(fm, current);
        fm.beginTransaction().add(current, FRAGMENT_TAG).commitAllowingStateLoss();
        handler.obtainMessage(ID_REMOVE_SUPPORT_FRAGMENT_MANAGER, fm).sendToTarget();
      }
    }
    return current;
}

SupportRequestManagerFragment

public class SupportRequestManagerFragment extends Fragment {  
    ...
    @Override
    public void onStart() {
        super.onStart();
        lifecycle.onStart();
    }

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

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

當(dāng)參數(shù)為非 Application 類型的參數(shù)時(shí),會(huì)創(chuàng)建一個(gè) ActivityFragmentLifecycle 對(duì)象,此時(shí) Glide 的生命周期就和 Fragment 生命周期一致。

最終 Glide.with() 方法會(huì)返回一個(gè) RequestManager 對(duì)象。

RequestManager -> load

public RequestBuilder<Drawable> load(@Nullable Bitmap bitmap) {
    return asDrawable().load(bitmap);
}

public RequestBuilder<Drawable> load(@Nullable Drawable drawable) {
    return asDrawable().load(drawable);
}

public RequestBuilder<Drawable> load(@Nullable String string) {
    return asDrawable().load(string);
}

public RequestBuilder<Drawable> load(@Nullable Uri uri) {
    return asDrawable().load(uri);
}

public RequestBuilder<Drawable> load(@Nullable File file) {
    return asDrawable().load(file);
}

public RequestBuilder<Drawable> load(@RawRes @DrawableRes @Nullable Integer resourceId) {
    return asDrawable().load(resourceId);
}

public RequestBuilder<Drawable> load(@Nullable URL url) {
    return asDrawable().load(url);
}

public RequestBuilder<Drawable> load(@Nullable byte[] model) {
    return asDrawable().load(model);
}

public RequestBuilder<Drawable> load(@Nullable Object model) {
    return asDrawable().load(model);
}

asDrawable

public RequestBuilder<Drawable> asDrawable() {
    return as(Drawable.class);
}

public <ResourceType> RequestBuilder<ResourceType> as(
      @NonNull Class<ResourceType> resourceClass) {
    return new RequestBuilder<>(glide, this, resourceClass, context);
}

asDrawable 方法其實(shí)是創(chuàng)建一個(gè) RequestBuilder 對(duì)象

load

public RequestBuilder<TranscodeType> load(@Nullable URL url) {
    return loadGeneric(url);
}

loadGeneric

private RequestBuilder<TranscodeType> loadGeneric(@Nullable Object model) {
    this.model = model;
    isModelSet = true;
    return this;
}

load 方法流程比較簡(jiǎn)單,首先會(huì)創(chuàng)建一個(gè) RequestBuilder 對(duì)象,然后將傳入的資源賦值給 RequestBuilder 對(duì)象中的 model。

RequestBuilder -> into

public ViewTarget<ImageView, TranscodeType> into(@NonNull ImageView view) {
    ...
    return into(
        glideContext.buildImageViewTarget(view, transcodeClass),
        /*targetListener=*/ null,
        requestOptions,
        Executors.mainThreadExecutor());
}

into

private <Y extends Target<TranscodeType>> Y into(
      @NonNull Y target,
      @Nullable RequestListener<TranscodeType> targetListener,
      BaseRequestOptions<?> options,
      Executor callbackExecutor) {
    ...
    requestManager.track(target, request);
    ...
}

track

synchronized void track(@NonNull Target<?> target, @NonNull Request request) {
    targetTracker.track(target);
    requestTracker.runRequest(request);
}

runRequest

public void runRequest(@NonNull Request request) {
    //將當(dāng)前 request 加入執(zhí)行隊(duì)列
    requests.add(request);
    //判斷當(dāng)前狀態(tài)是否是暫停
    if (!isPaused) {
      //不是暫停則執(zhí)行請(qǐng)求
      request.begin();
    } else {
      //暫停則清楚
      request.clear();
      if (Log.isLoggable(TAG, Log.VERBOSE)) {
        Log.v(TAG, "Paused, delaying request");
      }
      //加入等待隊(duì)列
      pendingRequests.add(request);
    }
}

在 RequestTracker 中維護(hù)了兩種隊(duì)列 : requests 執(zhí)行隊(duì)列、pendingRequests 等待隊(duì)列。( Okhttp 中也有類似的隊(duì)列,同步異步的執(zhí)行就緒隊(duì)列 )

所以我們知道 into 方法最終會(huì)執(zhí)行 request,那么是誰去維護(hù)處理這 2 個(gè)隊(duì)列呢?

根據(jù)方法倒推

  • runRequest 方法在 RequestTracker 類中
    RequestTracker -> runRequest
  • track 方法執(zhí)行了 runRequest 方法
    RequestManager -> track
  • RequestManager 對(duì)象中持有 RequestTracker 對(duì)象
    RequestManager

所以我們重點(diǎn)看 RequestManager 對(duì)象

RequestManager

public class RequestManager implements LifecycleListener,
    ModelTypes<RequestBuilder<Drawable>> {
    ...
    
    public synchronized void onStart() {
        resumeRequests();
        targetTracker.onStart();
    }
     
    public synchronized void onStop() {
        pauseRequests();
        targetTracker.onStop();
    }
    
    public synchronized void onDestroy() {
        targetTracker.onDestroy();
        for (Target<?> target : targetTracker.getAll()) {
            clear(target);
        }
        targetTracker.clear();
        requestTracker.clearRequests();
        lifecycle.removeListener(this);
        lifecycle.removeListener(connectivityMonitor);
        mainHandler.removeCallbacks(addSelfToLifecycle);
        glide.unregisterRequestManager(this);
    }
    ...
}

回到之前 with 方法中添加的透明 Fragment

SupportRequestManagerFragment

public class SupportRequestManagerFragment extends Fragment {  
    ...
    @Override
    public void onStart() {
        super.onStart();
        lifecycle.onStart();
    }

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

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

在頁面執(zhí)行 onStart 方法時(shí)會(huì)觸發(fā) lifecycle.onStart 方法,lifecycle.onStart 則會(huì)出發(fā) RequestManager 的 onStart 方法

RequestManager -> onStart

public synchronized void onStart() {
    resumeRequests();
    targetTracker.onStart();
}

resumeRequests

public synchronized void resumeRequests() {
    requestTracker.resumeRequests();
}

resumeRequests

public void resumeRequests() {
    isPaused = false;
    for (Request request : Util.getSnapshot(requests)) {
      // We don't need to check for cleared here. Any explicit clear by a user will remove the
      // Request from the tracker, so the only way we'd find a cleared request here is if we cleared
      // it. As a result it should be safe for us to resume cleared requests.
      if (!request.isComplete() && !request.isRunning()) {
        request.begin();
      }
    }
    pendingRequests.clear();
}

所以可以想到,當(dāng) Activity 顯示時(shí)會(huì)便利 request 執(zhí)行隊(duì)列,當(dāng) Activity 不可見時(shí)會(huì)將 request 加入到 pendingRequests 等待隊(duì)列

總結(jié)

  • with
  1. 通過單例創(chuàng)建 Glide 對(duì)象
  2. 當(dāng)參數(shù)類型為 Application 時(shí), Glide 生命周期與 Application 一致;當(dāng)參數(shù)類型為非 Application 時(shí),會(huì)創(chuàng)建一個(gè)透明的 Fragment,Glide 生命周期與 Fragment 一致
  3. 最終返回一個(gè) RequestManager 對(duì)象
  • load
  1. 創(chuàng)建一個(gè) RequestBuilder 對(duì)象
  2. 將傳入的資源賦值給 RequestBuilder 對(duì)象中的 model 并返回
  • into
  1. 執(zhí)行 request
  2. 根據(jù)生命周期處理 request
Glide 源碼分析生命周期和基本流程大致就介紹到這里了,如果有什么寫得不對(duì)的,可以在下方評(píng)論留言,我會(huì)第一時(shí)間改正。
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容