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
- 通過單例創(chuàng)建 Glide 對象
- 當(dāng)參數(shù)類型為 Application 時鼎兽, Glide 生命周期與 Application 一致答姥;當(dāng)參數(shù)類型為非 Application 時,會創(chuàng)建一個透明的 Fragment谚咬,Glide 生命周期與 Fragment 一致
- 最終返回一個 RequestManager 對象
- load
- 創(chuàng)建一個 RequestBuilder 對象
- 將傳入的資源賦值給 RequestBuilder 對象中的 model 并返回
- into
- 執(zhí)行 request
- 根據(jù)生命周期處理 request