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 方法是一個重載方法诲泌,但最終都會調(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 對象透典。

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 方法也是一個重載方法晴楔,這里就不全部羅列了∏椭洌看起來處理比較多税弃,而實際上只處理了兩種情況的參數(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ù)時,會創(chuàng)建一個 ApplicationLifecycle 對象,此時 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)建一個 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ù)時西壮,會創(chuàng)建一個 ActivityFragmentLifecycle 對象,此時 Glide 的生命周期就和 Fragment 生命周期一致。

最終 Glide.with() 方法會返回一個 RequestManager 對象才菠。

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 方法其實是創(chuàng)建一個 RequestBuilder 對象

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 方法流程比較簡單茸时,首先會創(chuàng)建一個 RequestBuilder 對象,然后將傳入的資源賦值給 RequestBuilder 對象中的 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í)行隊列
    requests.add(request);
    //判斷當(dāng)前狀態(tài)是否是暫停
    if (!isPaused) {
      //不是暫停則執(zhí)行請求
      request.begin();
    } else {
      //暫停則清楚
      request.clear();
      if (Log.isLoggable(TAG, Log.VERBOSE)) {
        Log.v(TAG, "Paused, delaying request");
      }
      //加入等待隊列
      pendingRequests.add(request);
    }
}

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

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

根據(jù)方法倒推

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

所以我們重點看 RequestManager 對象

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 方法時會觸發(fā) lifecycle.onStart 方法步悠,lifecycle.onStart 則會出發(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 顯示時會便利 request 執(zhí)行隊列,當(dāng) Activity 不可見時會將 request 加入到 pendingRequests 等待隊列

總結(jié)

  • with
  1. 通過單例創(chuàng)建 Glide 對象
  2. 當(dāng)參數(shù)類型為 Application 時鼎兽, Glide 生命周期與 Application 一致答姥;當(dāng)參數(shù)類型為非 Application 時,會創(chuàng)建一個透明的 Fragment谚咬,Glide 生命周期與 Fragment 一致
  3. 最終返回一個 RequestManager 對象
  • load
  1. 創(chuàng)建一個 RequestBuilder 對象
  2. 將傳入的資源賦值給 RequestBuilder 對象中的 model 并返回
  • into
  1. 執(zhí)行 request
  2. 根據(jù)生命周期處理 request
Glide 源碼分析生命周期和基本流程大致就介紹到這里了鹦付,如果有什么寫得不對的,可以在下方評論留言择卦,我會第一時間改正敲长。
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末郎嫁,一起剝皮案震驚了整個濱河市,隨后出現(xiàn)的幾起案子祈噪,更是在濱河造成了極大的恐慌泽铛,老刑警劉巖,帶你破解...
    沈念sama閱讀 206,311評論 6 481
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件辑鲤,死亡現(xiàn)場離奇詭異盔腔,居然都是意外死亡,警方通過查閱死者的電腦和手機(jī)遂填,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 88,339評論 2 382
  • 文/潘曉璐 我一進(jìn)店門铲觉,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人吓坚,你說我怎么就攤上這事〉朴” “怎么了礁击?”我有些...
    開封第一講書人閱讀 152,671評論 0 342
  • 文/不壞的土叔 我叫張陵,是天一觀的道長逗载。 經(jīng)常有香客問我哆窿,道長,這世上最難降的妖魔是什么厉斟? 我笑而不...
    開封第一講書人閱讀 55,252評論 1 279
  • 正文 為了忘掉前任挚躯,我火速辦了婚禮,結(jié)果婚禮上擦秽,老公的妹妹穿的比我還像新娘码荔。我一直安慰自己,他們只是感情好感挥,可當(dāng)我...
    茶點故事閱讀 64,253評論 5 371
  • 文/花漫 我一把揭開白布缩搅。 她就那樣靜靜地躺著,像睡著了一般触幼。 火紅的嫁衣襯著肌膚如雪硼瓣。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 49,031評論 1 285
  • 那天置谦,我揣著相機(jī)與錄音堂鲤,去河邊找鬼。 笑死媒峡,一個胖子當(dāng)著我的面吹牛瘟栖,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播丝蹭,決...
    沈念sama閱讀 38,340評論 3 399
  • 文/蒼蘭香墨 我猛地睜開眼慢宗,長吁一口氣:“原來是場噩夢啊……” “哼坪蚁!你這毒婦竟也來了?” 一聲冷哼從身側(cè)響起镜沽,我...
    開封第一講書人閱讀 36,973評論 0 259
  • 序言:老撾萬榮一對情侶失蹤敏晤,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后缅茉,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體嘴脾,經(jīng)...
    沈念sama閱讀 43,466評論 1 300
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 35,937評論 2 323
  • 正文 我和宋清朗相戀三年蔬墩,在試婚紗的時候發(fā)現(xiàn)自己被綠了译打。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 38,039評論 1 333
  • 序言:一個原本活蹦亂跳的男人離奇死亡拇颅,死狀恐怖奏司,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情樟插,我是刑警寧澤韵洋,帶...
    沈念sama閱讀 33,701評論 4 323
  • 正文 年R本政府宣布,位于F島的核電站黄锤,受9級特大地震影響搪缨,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜鸵熟,卻給世界環(huán)境...
    茶點故事閱讀 39,254評論 3 307
  • 文/蒙蒙 一副编、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧流强,春花似錦痹届、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 30,259評論 0 19
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至僵控,卻和暖如春香到,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背报破。 一陣腳步聲響...
    開封第一講書人閱讀 31,485評論 1 262
  • 我被黑心中介騙來泰國打工悠就, 沒想到剛下飛機(jī)就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人充易。 一個月前我還...
    沈念sama閱讀 45,497評論 2 354
  • 正文 我出身青樓梗脾,卻偏偏與公主長得像,于是被迫代替她去往敵國和親盹靴。 傳聞我的和親對象是個殘疾皇子炸茧,可洞房花燭夜當(dāng)晚...
    茶點故事閱讀 42,786評論 2 345

推薦閱讀更多精彩內(nèi)容