編輯:關於 Android 開發
本文以 GitHub 上 Glide 4.0.0 版本的程式碼為基礎進行解析。最基本的使用方式如下:
Glide.with(this)
.asDrawable()
.load("https://i6.topit.me/6/5d/45/1131907198420455d6o.jpg")
.apply(fitCenterTransform(this))
.apply(placeholderOf(R.drawable.skyblue_logo_wechatfavorite_checked))
.into(imageView);
Glide 採用現在相當流行的流式(fluent)編碼風格,讓呼叫鏈讀起來簡潔直觀。以下就沿著這條鏈條逐段拆解。
RequestOptions 中收攏了大量常用選項,光看命名就能理解用途:
public final class RequestOptions extends BaseRequestOptions<RequestOptions> {
private static RequestOptions skipMemoryCacheTrueOptions;
private static RequestOptions skipMemoryCacheFalseOptions;
private static RequestOptions fitCenterOptions;
private static RequestOptions centerCropOptions;
private static RequestOptions circleCropOptions;
private static RequestOptions noTransformOptions;
private static RequestOptions noAnimationOptions;
// ...其餘省略
}
RequestBuilder 上幾個關鍵方法:
transition(TransitionOptions):設定從佔位圖或縮圖過渡到最終圖的轉場動畫。load(...):可載入 String、Uri、File、resourceId、byte[] 等多種型別,各對應不同的編碼路徑。into(...):真正觸發請求的地方。特別值得一提的是 registry 這個域,它掛載了 ModelLoader(模型載入器)、Encoder(編碼器)、ResourceDecoder(資源解碼器)、ResourceEncoder(資源編碼器)、DataRewinder(資料回捲器)與 Transcoder(轉碼器)。這些元件是 Glide 資源編解碼機制中既基礎又核心的組成。
把重要元件的類別結構列出來,便於快速定位自己需要的能力:
ModelLoader
DataFetcher
Target
Resource
ResourceTransformation
Pool
Cache
Decoder
Encoder
Glide 會依 Fragment 版本建立 RequestManagerFragment 或 SupportRequestManagerFragment 並加入對應的 FragmentManager。這兩種 Fragment 不帶任何畫面,唯一目的是同步生命週期。
public static RequestManager with(Context context) {
RequestManagerRetriever retriever = RequestManagerRetriever.get();
return retriever.get(context);
}
// RequestManagerRetriever.get(...)
@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);
android.app.FragmentManager fm = activity.getFragmentManager();
return fragmentGet(activity, fm, null);
}
}
public RequestBuilder<Drawable> asDrawable() {
return as(Drawable.class).transition(new DrawableTransitionOptions());
}
public RequestBuilder load(@Nullable Object model) {
return loadGeneric(model);
}
private RequestBuilder loadGeneric(@Nullable Object model) {
this.model = model;
isModelSet = true;
return this;
}
public <Y extends TargetTranscodeType> Y into(@NonNull Y target) {
Util.assertMainThread();
Preconditions.checkNotNull(target);
if (!isModelSet) {
throw new IllegalArgumentException(
"You must call #load() before calling #into()");
}
Request previous = target.getRequest();
if (previous != null) {
requestManager.clear(target);
}
requestOptions.lock();
Request request = buildRequest(target);
target.setRequest(request);
requestManager.track(target, request);
return target;
}
絕大多數情境下載入的是圖片,因此實際會走到這個多載:
public Target into(ImageView view) {
Util.assertMainThread();
Preconditions.checkNotNull(view);
if (!requestOptions.isTransformationSet()
&& requestOptions.isTransformationAllowed()
&& view.getScaleType() != null) {
if (requestOptions.isLocked()) {
requestOptions = requestOptions.clone();
}
switch (view.getScaleType()) {
case CENTER_CROP:
requestOptions.optionalCenterCrop(context);
break;
case FIT_CENTER:
case FIT_START:
case FIT_END:
requestOptions.optionalFitCenter(context);
break;
default:
// 其餘縮放模式不做處理
}
}
return into(context.buildImageViewTarget(view, transcodeClass));
}
這裡會依 ImageView 的 scaleType 自動套用對應的 transformation,再由 ImageView 與轉碼型別組出不同的 Target(例如 Bitmap 對應 BitmapImageViewTarget、Drawable 對應 DrawableImageViewTarget)。
Request 一律使用 SingleRequest;若有縮圖,則由 ThumbnailRequestCoordinator 負責協調:
private Request obtainRequest(Target target,
BaseRequestOptions<?> requestOptions,
RequestCoordinator requestCoordinator,
TransitionOptions<?, ? super TranscodeType> transitionOptions,
Priority priority,
int overrideWidth,
int overrideHeight) {
requestOptions.lock();
return SingleRequest.obtain(
context, model, transcodeClass, requestOptions,
overrideWidth, overrideHeight, priority, target,
requestListener, requestCoordinator,
context.getEngine(), transitionOptions.getTransitionFactory());
}
值得留意的是 SingleRequest.obtain(...) 這種寫法,比直接 new 更簡潔。
另外 target.setRequest(request) 也是個關鍵:若 target 是 ViewTarget,request 會被塞進 View 的 tag 中。這樣每個 View 都持有自己的 Request,同一個 View 上若發生重複請求,會先取回上一個 Request 並從 RequestManager 中回收,達到去重的效果。
這個方法相當複雜,涵蓋了觸發請求、編解碼、載入與快取等全部環節。
4.2.1 快取 target 並啟動 Request
void track(Target<?> target, Request request) {
targetTracker.track(target);
requestTracker.runRequest(request);
}
public void runRequest(Request request) {
requests.add(request);
if (!isPaused) {
request.begin(); // 直接開始
} else {
pendingRequests.add(request); // 先掛起
}
}
接著看 SingleRequest.begin():
@Override
public void begin() {
stateVerifier.throwIfRecycled();
startTime = LogTime.getLogTime();
// model 為空則無法執行
if (model == null) {
if (Util.isValidDimensions(overrideWidth, overrideHeight)) {
width = overrideWidth;
height = overrideHeight;
}
onLoadFailed(new GlideException("Received null model"), Log.WARN);
return;
}
status = Status.WAITING_FOR_SIZE;
// 尺寸已知,直接进入加载流程
if (Util.isValidDimensions(overrideWidth, overrideHeight)) {
onSizeReady(overrideWidth, overrideHeight);
} else {
// 尺寸未知:View 尚未绘制,交由 ViewTreeObserver 等待
target.getSize(this);
}
// 等待或執行中,先顯示佔位圖
if ((status == Status.RUNNING || status == Status.WAITING_FOR_SIZE)
&& canNotifyStatusChanged()) {
target.onLoadStarted(getPlaceholderDrawable());
}
}
接著是 ViewTarget.getSize()。這裡只看尺寸尚未取得的情況:
void getSize(SizeReadyCallback cb) {
int currentWidth = getViewWidthOrParam();
int currentHeight = getViewHeightOrParam();
if (isSizeValid(currentWidth) && isSizeValid(currentHeight)) {
cb.onSizeReady(currentWidth, currentHeight);
} else {
if (!cbs.contains(cb)) {
cbs.add(cb);
}
if (layoutListener == null) {
final ViewTreeObserver observer = view.getViewTreeObserver();
layoutListener = new SizeDeterminerLayoutListener(this);
// 在繪製之前掛上尺寸監聽
observer.addOnPreDrawListener(layoutListener);
}
}
}
private static class SizeDeterminerLayoutListener
implements ViewTreeObserver.OnPreDrawListener {
// 使用弱引用,避免 observer 持有 SizeDeterminer 造成記憶體洩漏
private final WeakReference<SizeDeterminer> sizeDeterminerRef;
public SizeDeterminerLayoutListener(SizeDeterminer sizeDeterminer) {
sizeDeterminerRef = new WeakReference<>(sizeDeterminer);
}
@Override
public boolean onPreDraw() {
SizeDeterminer sizeDeterminer = sizeDeterminerRef.get();
if (sizeDeterminer != null) {
// 重新檢查尺寸,並觸發後續流程
sizeDeterminer.checkCurrentDimens();
}
return true;
}
}
尺寸就緒後回到 SingleRequest.onSizeReady(),由 Engine 接手:
public void onSizeReady(int width, int height) {
stateVerifier.throwIfRecycled();
if (status != Status.WAITING_FOR_SIZE) {
return;
}
status = Status.RUNNING;
float sizeMultiplier = requestOptions.getSizeMultiplier();
this.width = Math.round(sizeMultiplier * width);
this.height = Math.round(sizeMultiplier * height);
loadStatus = engine.load(
glideContext, model, requestOptions.getSignature(),
this.width, this.height,
requestOptions.getResourceClass(), transcodeClass,
priority, requestOptions.getDiskCacheStrategy(),
requestOptions.getTransformations(),
requestOptions.isTransformationRequired(),
requestOptions.getOptions(),
requestOptions.isMemoryCacheable(), this);
}
所有操作都來自唯一的 Engine 實例,它在 Glide 初始化時建立。若需要自訂快取行為,可以從這裡往下看:
if (engine == null) {
engine = new Engine(memoryCache, diskCacheFactory,
diskCacheExecutor, sourceExecutor);
}
Engine.load 的詳細過程:
public <R> LoadStatus load(GlideContext glideContext, Object model,
Key signature, int width, int height,
Class<?> resourceClass, Class<R> transcodeClass,
Priority priority, DiskCacheStrategy diskCacheStrategy,
Map<Class<?>, Transformation<?>> transformations,
boolean isTransformationRequired, Options options,
boolean isMemoryCacheable, ResourceCallback cb) {
Util.assertMainThread();
long startTime = LogTime.getLogTime();
// 為這次載入建立唯一識別鍵
EngineKey key = keyFactory.buildKey(model, signature, width, height,
transformations, resourceClass, transcodeClass, options);
// 一級記憶體快取(LRU)
EngineResource<?> cached = loadFromCache(key, isMemoryCacheable);
if (cached != null) {
cb.onResourceReady(cached, DataSource.MEMORY_CACHE);
return null;
}
// 二級記憶體快取(正在使用中的資源引用)
EngineResource<?> active = loadFromActiveResources(key, isMemoryCacheable);
if (active != null) {
cb.onResourceReady(active, DataSource.MEMORY_CACHE);
return null;
}
// 已有相同 key 的 job 在跑,直接掛上 callback 共用結果
EngineJob current = jobs.get(key);
if (current != null) {
current.addCallback(cb);
return new LoadStatus(cb, current);
}
// 建立新 job 並丟入執行緒池
EngineJob<R> engineJob = engineJobFactory.build(key, isMemoryCacheable);
DecodeJob<R> decodeJob = decodeJobFactory.build(
glideContext, model, key, signature, width, height,
resourceClass, transcodeClass, priority, diskCacheStrategy,
transformations, isTransformationRequired, options, engineJob);
jobs.put(key, engineJob);
engineJob.addCallback(cb);
engineJob.start(decodeJob);
return new LoadStatus(cb, engineJob);
}
這段程式碼有幾個值得留意的設計:
內建快取預設是 LruResourceCache,也可以自訂。
之所以要兩級記憶體快取,是因為 LRU 快取無法保證百分之百命中,加上「進行中資源」這一層可以明顯提高命中率。
EngineJob 與 DecodeJob 分工明確:EngineJob 是管理者與調度者,負責載入與各類回呼通知;DecodeJob 是實作 Runnable 的實際工作者。
private void runWrapped() {
switch (runReason) {
case INITIALIZE:
stage = getNextStage(Stage.INITIALIZE);
currentGenerator = getNextGenerator();
runGenerators();
break;
case SWITCH_TO_SOURCE_SERVICE:
runGenerators();
break;
case DECODE_DATA:
decodeFromRetrievedData();
break;
default:
throw new IllegalStateException("Unrecognized run reason: " + runReason);
}
}
// 階段策略:先找資源快取,再找資料快取,最後才是來源
private Stage getNextStage(Stage current) {
switch (current) {
case INITIALIZE:
// 由 diskCacheStrategy 決定下一階段
return diskCacheStrategy.decodeCachedResource()
? Stage.RESOURCE_CACHE : getNextStage(Stage.RESOURCE_CACHE);
case RESOURCE_CACHE:
return diskCacheStrategy.decodeCachedData()
? Stage.DATA_CACHE : getNextStage(Stage.DATA_CACHE);
case DATA_CACHE:
return Stage.SOURCE;
case SOURCE:
case FINISHED:
return Stage.FINISHED;
default:
throw new IllegalArgumentException("Unrecognized stage: " + current);
}
}
private DataFetcherGenerator getNextGenerator() {
switch (stage) {
case RESOURCE_CACHE:
// 讀取含降採樣/轉換後資源的快取檔
return new ResourceCacheGenerator(decodeHelper, this);
case DATA_CACHE:
// 讀取原始未修改的來源資料快取檔
return new DataCacheGenerator(decodeHelper, this);
case SOURCE:
// 透過 ModelLoader 取得來源資料
return new SourceGenerator(decodeHelper, this);
case FINISHED:
return null;
default:
throw new IllegalStateException("Unrecognized stage: " + stage);
}
}
最後真正發出請求的地方是 SourceGenerator.startNext():
public boolean startNext() {
if (dataToCache != null) {
Object data = dataToCache;
dataToCache = null;
cacheData(data);
}
if (sourceCacheGenerator != null && sourceCacheGenerator.startNext()) {
return true;
}
sourceCacheGenerator = null;
loadData = null;
boolean started = false;
// 依序嘗試各個 ModelLoader
while (!started && hasNextModelLoader()) {
loadData = helper.getLoadData().get(loadDataListIndex++);
if (loadData != null
&& (helper.getDiskCacheStrategy()
.isDataCacheable(loadData.fetcher.getDataSource())
|| helper.hasLoadPath(loadData.fetcher.getDataClass()))) {
started = true;
loadData.fetcher.loadData(helper.getPriority(), this);
}
}
return started;
}
這裡的 Model 必須實作 GlideModule,fetcher 則實作 DataFetcher。有興趣可以往下看 integration 模組中的 okhttp 與 volley 專案——Glide 主要透過這兩個網路庫下載圖片。
public void onDataReady(Object data) {
DiskCacheStrategy diskCacheStrategy = helper.getDiskCacheStrategy();
if (data != null
&& diskCacheStrategy.isDataCacheable(loadData.fetcher.getDataSource())) {
dataToCache = data;
// 可能被回呼到其他執行緒,先切回 Glide 的執行緒再處理
cb.reschedule();
} else {
cb.onDataFetcherReady(loadData.sourceKey, data, loadData.fetcher,
loadData.fetcher.getDataSource(), originalKey);
}
}
只看 dataToCache = data 確實會讓人困惑,關鍵在 cb.reschedule()。這裡的 cb 就是 DecodeJob:
public void reschedule() {
runReason = RunReason.SWITCH_TO_SOURCE_SERVICE;
callback.reschedule(this);
}
這個 Callback 定義在 DecodeJob 內部,實作則在外部的 Engine 中。之所以要切換執行緒池,是因為下載借用第三方網路庫的執行緒,而實際編解碼在 Glide 自有的執行緒池中進行:
public void reschedule(DecodeJob<?> job) {
if (isCancelled) {
MAIN_THREAD_HANDLER.obtainMessage(MSG_CANCELLED, this).sendToTarget();
} else {
sourceExecutor.execute(job);
}
}
再次進入 DecodeJob.runWrapped(),這次 runReason 是 SWITCH_TO_SOURCE_SERVICE,因此直接執行 runGenerators() → SourceGenerator.startNext()。此時 dataToCache 已有值,於是走 cacheData(data),依註冊的 Encoder 把原始資料寫入磁碟快取。之後 sourceCacheGenerator 已存在,改由 DataCacheGenerator 接手,從快取檔讀回資料:
public boolean startNext() {
while (modelLoaders == null || !hasNextModelLoader()) {
sourceIdIndex++;
if (sourceIdIndex >= cacheKeys.size()) {
return false;
}
Key sourceId = cacheKeys.get(sourceIdIndex);
Key originalKey = new DataCacheKey(sourceId, helper.getSignature());
cacheFile = helper.getDiskCache().get(originalKey);
if (cacheFile != null) {
this.sourceKey = sourceId;
modelLoaders = helper.getModelLoaders(cacheFile);
modelLoaderIndex = 0;
}
}
loadData = null;
boolean started = false;
while (!started && hasNextModelLoader()) {
ModelLoader<File, ?> modelLoader = modelLoaders.get(modelLoaderIndex++);
loadData = modelLoader.buildLoadData(cacheFile,
helper.getWidth(), helper.getHeight(), helper.getOptions());
if (loadData != null && helper.hasLoadPath(loadData.fetcher.getDataClass())) {
started = true;
loadData.fetcher.loadData(helper.getPriority(), this);
}
}
return started;
}
這裡的 ModelLoader 對應 registry 中的 modelLoaderRegistry,實際由 Registry.getModelLoaders(...) 取得:
public <Model> List<ModelLoader<Model, ?>> getModelLoaders(Model model) {
List<ModelLoader<Model, ?>> result = modelLoaderRegistry.getModelLoaders(model);
if (result.isEmpty()) {
throw new NoModelLoaderAvailableException(model);
}
return result;
}
一路追下來,最終落到 FileLoader 的 FileFetcher:
public void loadData(Priority priority, DataCallback<? super Data> callback) {
try {
data = opener.open(file);
} catch (FileNotFoundException e) {
callback.onLoadFailed(e);
return;
}
callback.onDataReady(data);
}
回呼鏈路如下(細節從略):
DataCacheGenerator.onDataReady → SourceGenerator.onDataFetcherReady → DecodeJob.onDataFetcherReady → DecodeJob.decodeFromRetrievedData → DecodeJob.notifyEncodeAndRelease → DecodeJob.notifyComplete → EngineJob.onResourceReady
Debug 流程圖:

EngineJob 中有一個 MAIN_THREAD_HANDLER,負責把結果切回主執行緒,最終完成顯示:
EngineJob.handleResultOnMainThread → SingleRequest.onResourceReady → ImageViewTarget.onResourceReady → ImageViewTarget.setResource → ImageView.setImageDrawable / ImageView.setImageBitmap
Debug 流程圖二:

而 decode 發生在 DecodeJob.decodeFromRetrievedData:
private void decodeFromRetrievedData() {
Resource<R> resource = null;
try {
resource = decodeFromData(currentFetcher, currentData, currentDataSource);
} catch (GlideException e) {
e.setLoggingDetails(currentAttemptingKey, currentDataSource);
exceptions.add(e);
}
if (resource != null) {
notifyEncodeAndRelease(resource, currentDataSource);
} else {
runGenerators();
}
}
中間經歷一連串轉換:
DecodeJob.decodeFromData → DecodeJob.decodeFromFetcher → DecodeJob.runLoadPath → LoadPath.load → LoadPath.loadWithExceptionList → LoadPath.decode → LoadPath.decodeResource → LoadPath.decodeResourceWithList → ResourceDecoder.handles → ResourceDecoder.decode
至於 encode,它發生在資料寫入快取的階段,實際呼叫點在 DiskLruCacheWrapper 與 DataCacheWriter 中。BitmapEncoder 對 Bitmap 的壓縮處理是一個值得參考的例子。
整體程式碼寫得相當漂亮,單從使用者角度切入很容易。
原始碼大量使用靜態工廠方法建立物件,類似String.valueOf(...)的風格,體現了編碼上的優雅。
但想深度改造並不容易:程式碼中 Callback 介面層層相扣,來回追蹤幾次很容易迷失方向。
另一個不舒服的地方是建構子參數過多,SingleRequest 就有 12 個。
單例的使用也略顯模糊:GlideContext 有時透過Glide.get(context).getGlideContext()取得,有時又靠建構注入。既然 Glide 本身已是單例,這樣的傳遞顯得多餘。程式碼寫作總要折衷,但如果專案能事先擬定並貫徹一套規則,可讀性會好很多。
本文只把最重要的載入主線走了一遍,一些細節沒有展開。如果你有特定疑問,沿著這條主線 debug 一遍,答案通常都能找到。歸納起來,Glide 的載入流程可以濃縮為:掛生命週期 → 建 Request → 等尺寸 → 查兩級記憶體快取 → 依快取策略逐級降级到來源 → 執行緒切換後下載並寫入磁碟快取 → 解碼轉換 → 切回主執行緒顯示。
QQ 風格註冊頁實作:Spinner 下拉選單與 CheckBox 控制按鈕啟用
延續登入頁,再做一個註冊頁 還不到睡覺時間,於是又加做了一個註冊畫面。延續上一篇登入頁的視覺風格,這次的新課題是下拉選單、標題欄處理,以及用 CheckBox 控制按鈕的
Android 圖標設計全攻略:各分辨率下的尺寸規範
Android 圖標設計全攻略:各分辨率下的尺寸規範 圖標是應用給使用者的第一印象,尺寸是否得當直接影響視覺觀感。本文整理了一份完整的圖標尺寸參考,方便設計與開發時對照。
Android 狀態列適配:Toolbar 與全版本 SystemBar 處理方案
狀態列為什麼需要適配 自 Material Design 推出後,狀態列不再只是系統預設的黑色區域,而是可以與 App 的視覺風格整合。Android 5.0 之後可自訂
Android 與 3G 行動通訊時代的前言
Android 與 3G 行動通訊時代的前言 本章節作為 Android 學習的開場,先從 3G 行動通訊、智能手機軟體平台與 Android 系統的基本背景開始,幫助讀