前言
閱讀源碼應(yīng)該認(rèn)準(zhǔn)一個(gè)功能點(diǎn)(主線),然后去分析這個(gè)功能點(diǎn)是如何實(shí)現(xiàn)的。千萬不要試圖去搞懂每一行代碼都是什么意思,那樣很容易會(huì)陷入到源碼中,而且越陷越深。
Glide 使用簡明的流式語法API,在大部分情況下一行代碼即可搞定需求:
Glide.with(fragment)
.load(url)
.into(imageView);
取消加載同樣很簡單:
Glide.with(fragment).clear(imageView);
盡管及時(shí)取消不必要的加載是很好的習(xí)慣,但這并不是必須的操作。實(shí)際上,當(dāng) Glide.with() 中傳入的 Activity 或 Fragment 實(shí)例銷毀時(shí),Glide 會(huì)自動(dòng)取消加載并回收資源。Glide的使用非常簡單,但是簡單的背后,隱藏了復(fù)雜的實(shí)現(xiàn),源碼內(nèi)容非常多。

Glide.with
Glide類是單例模式,其中重載了多個(gè)with方法,允許我們傳遞上下文(Context)以及能夠獲得上下文的Fragment與View。
所有的with方法中的實(shí)現(xiàn)均為:
//Glide
public static RequestManager with(@NonNull Context context) {
return getRetriever(context).get(context);
}
private static RequestManagerRetriever getRetriever(@Nullable Context context) {
return Glide.get(context).getRequestManagerRetriever();
}
主要做了兩件事情:
- 通過
get方法獲得Glide單例對(duì)象并獲取其成員屬性:RequestManagerRetriever; - 通過RequestManagerRetriever的
get方法獲得RequestManager。
RequestManagerRetriever
RequestManagerRetriever的功能就是獲得RequestManager請(qǐng)求管理者。Glide中所有加載圖片的請(qǐng)求都是由請(qǐng)求管理器進(jìn)行管理。為了進(jìn)行自動(dòng)生命周期的管理,請(qǐng)求管理器與Glide.with方法傳遞的不同參數(shù)相對(duì)應(yīng)。
Glide.with參數(shù):
- 傳遞Activity,則此次加載圖片會(huì)在退出Activity后自動(dòng)取消;
- 傳遞Fragment,則加載圖片會(huì)在Fragment銷毀時(shí)取消;
- 傳遞Application,那么Glide將無法管理圖片請(qǐng)求生命周期。
換句話說,每一個(gè)Activity存在一個(gè)對(duì)應(yīng)的RequestManager,每一個(gè)不同的Fragment也有其對(duì)應(yīng)的RequestManager,而整個(gè)應(yīng)用運(yùn)行階段同樣會(huì)有一個(gè)RequestManager。這些不同的RequestManager通過RequestManagerRetriever.get獲取。RequestManagerRetriever同樣重載了多個(gè)get方法,以get(FragmentActivity)為例:
//RequestManagerRetriever
public RequestManager get(@NonNull FragmentActivity activity) {
if (Util.isOnBackgroundThread()) {
return get(activity.getApplicationContext());
} else {
assertNotDestroyed(activity);
FragmentManager fm = activity.getSupportFragmentManager();
return supportFragmentGet(activity, fm, /*parentHint=*/ null, isActivityVisible(activity));
}
}
- 若非主線程,則使用Application上下文調(diào)用get重載方法
get(Context),直接返回自己的成員屬性RequestManager類型的applicationManager; - 若在主線程,則獲得Activity對(duì)應(yīng)的FragmentManager來獲得RequestManager。
對(duì)于主線程的情況,Glide為了進(jìn)行生命周期管理,在Activity#onDestory時(shí)取消圖片加載。那么如何監(jiān)聽到Activity的onDestory回調(diào)?如果向此Activity中添加一個(gè)Fragment,當(dāng)Activity銷毀時(shí),Activity中附加的Fragment同樣也會(huì)銷毀。事實(shí)上實(shí)現(xiàn)也確實(shí)如此,在獲得了Activity對(duì)應(yīng)的FragmentManager之后,supportFragmentGet的實(shí)現(xiàn)為:
//RequestManagerRetriever
private RequestManager supportFragmentGet(@NonNull Context context,@NonNull FragmentManager fm, @Nullable Fragment parentHint, boolean isParentVisible) {
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);
requestManager =
factory.build(
glide, current.getGlideLifecycle(), current.getRequestManagerTreeNode(), context);
current.setRequestManager(requestManager);
}
return requestManager;
}
其中getSupportRequestManagerFragment(fm, parentHint, isParentVisible)就是獲得附加在對(duì)應(yīng)Activity的Fragment,而此Fragment中存在成員RequestManager。如果此成員不為null,則直接返回,否則創(chuàng)建并設(shè)置進(jìn)入Fragment之后再返回。
小結(jié)

- 構(gòu)建 Glide 實(shí)例;
- 獲取 RequestManagerRetriever 對(duì)象;
- 構(gòu)建 RequestManager 對(duì)象。
- 若傳遞Activity/Fragment并為主線程調(diào)用, 則為 Activity/Fragment 添加一個(gè) RequestManagerFragment, 其內(nèi)部含有 ReqeustManager 對(duì)象;
- 否則, 獲取一個(gè)相當(dāng)于單例的
applicationManager專門用于處理這類請(qǐng)求。
RequestManager.load
Glide.with獲得RequestManager之后,執(zhí)行l(wèi)oad方法設(shè)置圖片源。圖片源可以是:圖片數(shù)據(jù)字節(jié)數(shù)組、File文件,網(wǎng)絡(luò)圖片地址等。以load(String)為例:
//RequestManager
public RequestBuilder<Drawable> load(@Nullable String string) {
return asDrawable().load(string);
}
public RequestBuilder<Drawable> asDrawable() {
return as(Drawable.class);
}
public <ResourceType> RequestBuilder<ResourceType> as(
@NonNull Class<ResourceType> resourceClass) {
return new RequestBuilder<>(glide, this, resourceClass, context);
}
load方法默認(rèn)設(shè)置目標(biāo)資源為 Drawable,獲得一個(gè)RequestBuilder。緊接著調(diào)用RequestBuilder.load方法記錄加載的model(圖片源)。
//RequestBuilder
public RequestBuilder<TranscodeType> load(@Nullable String string) {
return loadGeneric(string);
}
@NonNull
private RequestBuilder<TranscodeType> loadGeneric(@Nullable Object model) {
this.model = model;
isModelSet = true;
return this;
}
RequestBuilder是請(qǐng)求構(gòu)建者,用戶可以使用它設(shè)置如:單獨(dú)的緩存策略、加載成功前占位圖、加載失敗后顯示圖片等等加載圖片的各種配置。當(dāng)RequestBuilder 構(gòu)建完成之后,接下來就等待執(zhí)行這個(gè)請(qǐng)求。
RequestBuilder.into
使用Glide最簡單的方式加載圖片最后一個(gè)階段就是執(zhí)行into方法。從into方法為入口開始執(zhí)行圖片加載,邏輯也開始復(fù)雜起來。
//RequestBuilder
@NonNull
public ViewTarget<ImageView, TranscodeType> into(@NonNull ImageView view) {
Util.assertMainThread();
Preconditions.checkNotNull(view);
BaseRequestOptions<?> requestOptions = this;
if (!requestOptions.isTransformationSet()
&& requestOptions.isTransformationAllowed()
&& view.getScaleType() != null) {
// Clone in this method so that if we use this RequestBuilder to load into a View and then
// into a different target, we don't retain the transformation applied based on the previous
// View's scale type.
switch (view.getScaleType()) {
case CENTER_CROP:
requestOptions = requestOptions.clone().optionalCenterCrop();
break;
case CENTER_INSIDE:
requestOptions = requestOptions.clone().optionalCenterInside();
break;
case FIT_CENTER:
case FIT_START:
case FIT_END:
requestOptions = requestOptions.clone().optionalFitCenter();
break;
case FIT_XY:
requestOptions = requestOptions.clone().optionalCenterInside();
break;
case CENTER:
case MATRIX:
default:
// Do nothing.
}
}
return into(
glideContext.buildImageViewTarget(view, transcodeClass),
/*targetListener=*/ null,
requestOptions,
Executors.mainThreadExecutor());
}
一般來說,我們?cè)趫?zhí)行into時(shí)傳入一個(gè)ImageView用于顯示。在這個(gè)into方法中,先確定本次加載的BaseRequestOptions,然后執(zhí)行重載的另一個(gè)into方法。其中BaseRequestOptions就是上面我們提到的RequestBuilder可以設(shè)置圖片加載的各種配置,這些配置選項(xiàng)就被封裝在BaseRequestOptions中(RequestBuilder extends BaseRequestOptions)。而重載的into方法實(shí)現(xiàn)為:
//RequestBuilder
private <Y extends Target<TranscodeType>> Y into(
@NonNull Y target,
@Nullable RequestListener<TranscodeType> targetListener,
BaseRequestOptions<?> options,
Executor callbackExecutor) {
Preconditions.checkNotNull(target);
if (!isModelSet) {
throw new IllegalArgumentException("You must call #load() before calling #into()");
}
Request request = buildRequest(target, targetListener, options, callbackExecutor);
Request previous = target.getRequest();
if (request.isEquivalentTo(previous)
&& !isSkipMemoryCacheWithCompletePreviousRequest(options, previous)) {
// If the request is completed, beginning again will ensure the result is re-delivered,
// triggering RequestListeners and Targets. If the request is failed, beginning again will
// restart the request, giving it another chance to complete. If the request is already
// running, we can let it continue running without interruption.
if (!Preconditions.checkNotNull(previous).isRunning()) {
// Use the previous request rather than the new one to allow for optimizations like skipping
// setting placeholders, tracking and un-tracking Targets, and obtaining View dimensions
// that are done in the individual Request.
previous.begin();
}
return target;
}
requestManager.clear(target);
target.setRequest(request);
requestManager.track(target, request);
return target;
}
這個(gè)into方法中首先調(diào)用 buildRequest 構(gòu)建了一個(gè)請(qǐng)求Request,然后把Request交給RequestManager跟蹤(生命周期)并啟動(dòng)請(qǐng)求。