目錄
專案中經常用到Glide、面試也有被問到,是時候系統的深入瞭解一下Glide了。
做Android開發的,對上述圖片載入框架,應該比較熟悉了,我簡單的介紹一下,對比分析一下。
Picasso是Square公司開源的專案,功能強大、呼叫簡單:
Picasso
.with(context)
.load(Url)
.into(targetImageView);
Glide是谷歌員工開源的一個專案,呼叫方式如下:
Glide
.with(context)
.load(Url)
.into(targetImageView);
從上面可以看出,二者的呼叫方式幾乎相同,有著近乎一樣的API風格,但Glide在快取策略和載入GIF方面略勝一籌。主要區別如下:
1.呼叫方式上:Glide with接收的引數不僅僅是context,還可以是Activity、Fragment,並且和Activity、Fragment生命週期保持一致,在Pasuse,暫停載入圖片,Resume的時候,恢復載入(後面重點介紹)。
2.磁碟快取和圖片格式:Picasso使用的是全尺寸快取,Glide和使用的ImageView大小相同,相比來說,Glide載入圖片較Picasso要快,Picasso載入前需要重新調整大小,Picasso預設使用的圖片格式是ARGB8888,Glide預設使用的圖片格式是RGB565,後者要比前者相同情況下,少一半記憶體。
3.支援GIF:Glide支援載入GIF動圖、Picasso不支援。
4.包大小:Glide要比Picasso大一些。
Fresco是Facebook開源的圖片庫,和Glide具備相同的功能(支援載入gif)。
Fresco最大的亮點在於它的記憶體管理,Android 解壓後的圖片即Android中的Bitmap,佔用大量的記憶體,Android 5.0以下系統,會顯著的引發介面卡頓,Freco很好的解決了這個問題。Fresco和Glide主要區別如下:
1.Glide載入速度快(快取的圖片規格多),記憶體開銷小(rgb565)。
2.Fresco最大的優勢在於5.0(Android 2.3)以下bitmap的載入,5.0以下系統,Fresco將圖片放在一個特別的記憶體區域,大大減少OOM。
3.Fresco包比較大,使用麻煩,適合高效能載入大量圖片。
1.Picasso所能實現的功能,Glide都能實現,只是設定不同,二者區別是Picasso包體積比Glide小且圖片品質比Glide高,但Glide載入速度比Picasso快,Glide支援gif,適合處理大型圖片流,如果視訊類應用,首選Glide。
2.Fresco綜合之前圖片載入庫的優點,在5.0以下記憶體優化比較好,但包體積比較大,Fresco>Glide>Picasso,Fresco在圖片較多的應用凸顯其價值,但如果應用對圖片需求較少的,不推薦使用。
這裡我只分析Glide的快取原理和生命週期處理。不知道大家怎麼學習的,在使用了大量的框架的時候,我發現要學習一個東西,大概一個步驟就是,這個東西是什麼,用來幹什麼,使用、熟練使用,瞭解原理,最後融會貫通。其實分析原始碼的過程,最簡單的就是從呼叫方式出發,一步一步往下看,基本就能瞭解個大概,剛開始看的時候,有點吃力,多看幾遍就ok了。話不多說,接下來分兩個部分介紹:
1.快取原理
2.生命週期處理
以下原始碼基於:glide:4.6.1
溫馨提示:原理程式碼分析過程較長,如果不想看的話,可直接跳轉到小結1、小結2。
在前面Glide和Picasso對比介紹的時候,我們已經描述了Glide最基本呼叫過程:
Glide
.with(context)
.load(Url)
.into(targetImageView);
從上述程式碼可以看出,with傳人的是context上下文,load載入圖片資源resouce,into是設定到具體的Imageview處理顯示,根據以往經驗,into應該是載入圖片的起點,我們先看裡面的原始碼。
點進去發現有幾個構造過載方法,隨便點選去一個,我們會發現最終呼叫的方法是下面這個方法:
private <Y extends Target<TranscodeType>> Y into(
@NonNull Y target,
@Nullable RequestListener<TranscodeType> targetListener,
@NonNull RequestOptions options) {
// 是否在主執行緒
Util.assertMainThread();
// 判斷載入圖片target是否為空
Preconditions.checkNotNull(target);
// 沒有設定圖片資源報錯
if (!isModelSet) {
throw new IllegalArgumentException("You must call #load() before calling #into()");
}
// 圖片資源格式clone
options = options.autoClone();
// 構造圖片請求request
Request request = buildRequest(target, targetListener, options);
// 獲取當前request
Request previous = target.getRequest();
// 新建立的request和當前相同,將新構造的request回收並複用當前request
if (request.isEquivalentTo(previous)
&& !isSkipMemoryCacheWithCompletePreviousRequest(options, previous)) {
request.recycle();
// 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.
// 如果當前request正在執行,直接開始載入圖片
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;
}
// 清除當前request
requestManager.clear(target);
// 將新構造的請求和當前target繫結起來
target.setRequest(request);
// 開始處理新構造的request
requestManager.track(target, request);
return target;
}
從上面的原始碼可以看出,當我們into載入圖片首先會構造一個新的圖片request,我們看下buildRequest(target, targetListener, options)這個方法做了那些處理,我們跟進去會發現,最終呼叫的是buildRequestRecursive()方法。
private Request buildRequestRecursive(
Target<TranscodeType> target,
@Nullable RequestListener<TranscodeType> targetListener,
@Nullable RequestCoordinator parentCoordinator,
TransitionOptions<?, ? super TranscodeType> transitionOptions,
Priority priority,
int overrideWidth,
int overrideHeight,
RequestOptions requestOptions) {
// Build the ErrorRequestCoordinator first if necessary so we can update parentCoordinator.
// 建立一個錯誤處理器,以便後面可以更新原來的parentCoordinator
ErrorRequestCoordinator errorRequestCoordinator = null;
if (errorBuilder != null) {
errorRequestCoordinator = new ErrorRequestCoordinator(parentCoordinator);
parentCoordinator = errorRequestCoordinator;
}
// 構造一個mainRequest
Request mainRequest =
buildThumbnailRequestRecursive(
target,
targetListener,
parentCoordinator,
transitionOptions,
priority,
overrideWidth,
overrideHeight,
requestOptions);
// 之前傳入的parentCoordinator == null 直接返回構造的request
if (errorRequestCoordinator == null) {
return mainRequest;
}
// 為errorRequest圖片寬、高賦值,為後續請求準備
int errorOverrideWidth = errorBuilder.requestOptions.getOverrideWidth();
int errorOverrideHeight = errorBuilder.requestOptions.getOverrideHeight();
if (Util.isValidDimensions(overrideWidth, overrideHeight)
&& !errorBuilder.requestOptions.isValidOverride()) {
errorOverrideWidth = requestOptions.getOverrideWidth();
errorOverrideHeight = requestOptions.getOverrideHeight();
}
// 構造一個errorRequest,並返回
Request errorRequest = errorBuilder.buildRequestRecursive(
target,
targetListener,
errorRequestCoordinator,
errorBuilder.transitionOptions,
errorBuilder.requestOptions.getPriority(),
errorOverrideWidth,
errorOverrideHeight,
errorBuilder.requestOptions);
errorRequestCoordinator.setRequests(mainRequest, errorRequest);
return errorRequestCoordinator;
}
從上面程式碼可以看出,他首先會建立一個ErrorRequestCoordinator排程器,來更新之前傳入的parentCoordinator,之前傳入的程式碼如下:
return buildRequestRecursive(
target,
targetListener,
/*parentCoordinator=*/ null,
transitionOptions,
requestOptions.getPriority(),
requestOptions.getOverrideWidth(),
requestOptions.getOverrideHeight(),
requestOptions);
可以看出直接傳入了一個null,所以errorRequestCoordinator = null,直接返回mainRequest;我們再一下mainRequest如何建立的:
private Request buildThumbnailRequestRecursive(
Target<TranscodeType> target,
RequestListener<TranscodeType> targetListener,
@Nullable RequestCoordinator parentCoordinator,
TransitionOptions<?, ? super TranscodeType> transitionOptions,
Priority priority,
int overrideWidth,
int overrideHeight,
RequestOptions requestOptions) {
if (thumbnailBuilder != null) {
// Recursive case: contains a potentially recursive thumbnail request builder.
...
ThumbnailRequestCoordinator coordinator = new ThumbnailRequestCoordinator(parentCoordinator);
Request fullRequest =
obtainRequest(
target,
targetListener,
requestOptions,
coordinator,
transitionOptions,
priority,
overrideWidth,
overrideHeight);
isThumbnailBuilt = true;
// Recursively generate thumbnail requests.
Request thumbRequest =
thumbnailBuilder.buildRequestRecursive(
target,
targetListener,
coordinator,
thumbTransitionOptions,
thumbPriority,
thumbOverrideWidth,
thumbOverrideHeight,
thumbnailBuilder.requestOptions);
isThumbnailBuilt = false;
coordinator.setRequests(fullRequest, thumbRequest);
return coordinator;
} else if (thumbSizeMultiplier != null) {
// Base case: thumbnail multiplier generates a thumbnail request, but cannot recurse.
ThumbnailRequestCoordinator coordinator = new ThumbnailRequestCoordinator(parentCoordinator);
Request fullRequest =
obtainRequest(
target,
targetListener,
requestOptions,
coordinator,
transitionOptions,
priority,
overrideWidth,
overrideHeight);
RequestOptions thumbnailOptions = requestOptions.clone()
.sizeMultiplier(thumbSizeMultiplier);
Request thumbnailRequest =
obtainRequest(
target,
targetListener,
thumbnailOptions,
coordinator,
transitionOptions,
getThumbnailPriority(priority),
overrideWidth,
overrideHeight);
coordinator.setRequests(fullRequest, thumbnailRequest);
return coordinator;
} else {
// Base case: no thumbnail.
return obtainRequest(
target,
targetListener,
requestOptions,
parentCoordinator,
transitionOptions,
priority,
overrideWidth,
overrideHeight);
}
}
從上面程式碼可以看出,它分為三種請求,一種包含縮圖的請求但是遞迴呼叫的,一種包含縮圖請求直接請求的,一種不含縮圖的請求,但是他們三個最終呼叫了SingleRequest.obtain()方法:
return SingleRequest.obtain(
context,
glideContext,
model,
transcodeClass,
requestOptions,
overrideWidth,
overrideHeight,
priority,
target,
targetListener,
requestListener,
requestCoordinator,
glideContext.getEngine(),
transitionOptions.getTransitionFactory());
}
再往裡看就是一個init方法,對請求各種引數的初始化:
private void init(
Context context,
GlideContext glideContext,
Object model,
Class<R> transcodeClass,
RequestOptions requestOptions,
int overrideWidth,
int overrideHeight,
Priority priority,
Target<R> target,
RequestListener<R> targetListener,
RequestListener<R> requestListener,
RequestCoordinator requestCoordinator,
Engine engine,
TransitionFactory<? super R> animationFactory) {
this.context = context;
this.glideContext = glideContext;
this.model = model;
this.transcodeClass = transcodeClass;
this.requestOptions = requestOptions;
this.overrideWidth = overrideWidth;
this.overrideHeight = overrideHeight;
this.priority = priority;
this.target = target;
this.targetListener = targetListener;
this.requestListener = requestListener;
this.requestCoordinator = requestCoordinator;
this.engine = engine;
this.animationFactory = animationFactory;
status = Status.PENDING;
}
分析到這裡我們發現,request請求構造完畢,接下來何時開始請求的呢?
我們回到最前面的into()方法裡面,接著往下看,我們會發現,有兩處地方,一處是previous.begin(),一處是requestManager.track(target, request),前者是複用上一個請求直接開始請求,後者是呼叫了RequestTracker.runRequest()方法:
public void runRequest(@NonNull Request request) {
requests.add(request);
if (!isPaused) {
request.begin();
} else {
pendingRequests.add(request);
}
}
首先將request新增到一個佇列裡面,如果當前不是pause狀態,開始請求,否則加入待請求佇列。(這裡的佇列不是說儲存結構是佇列)。
請求開始的地方找到了,我們之前構造請求分析到最終呼叫SingleRequest.init()方法,SingleRequest是request介面實現類,request.begin(),其實最終會回撥SingleRequest.begin()方法:
public void begin() {
...
// 圖片資源為空拋異常
if (model == null) {
if (Util.isValidDimensions(overrideWidth, overrideHeight)) {
width = overrideWidth;
height = overrideHeight;
}
// Only log at more verbose log levels if the user has set a fallback drawable, because
// fallback Drawables indicate the user expects null models occasionally.
int logLevel = getFallbackDrawable() == null ? Log.WARN : Log.DEBUG;
onLoadFailed(new GlideException("Received null model"), logLevel);
return;
}
if (status == Status.RUNNING) {
throw new IllegalArgumentException("Cannot restart a running request");
}
// If we're restarted after we're complete (usually via something like a notifyDataSetChanged
// that starts an identical request into the same Target or View), we can simply use the
// resource and size we retrieved the last time around and skip obtaining a new size, starting a
// new load etc. This does mean that users who want to restart a load because they expect that
// the view size has changed will need to explicitly clear the View or Target before starting
// the new load.
// 圖片載入完成,釋放資源
if (status == Status.COMPLETE) {
onResourceReady(resource, DataSource.MEMORY_CACHE);
return;
}
// Restarts for requests that are neither complete nor running can be treated as new requests
// and can run again from the beginning.
// 新的請求從獲取圖片size開始
status = Status.WAITING_FOR_SIZE;
if (Util.isValidDimensions(overrideWidth, overrideHeight)) {
onSizeReady(overrideWidth, overrideHeight);
} else {
target.getSize(this);
}
// 通知載入圖片開始
if ((status == Status.RUNNING || status == Status.WAITING_FOR_SIZE)
&& canNotifyStatusChanged()) {
target.onLoadStarted(getPlaceholderDrawable());
}
if (IS_VERBOSE_LOGGABLE) {
logV("finished run method in " + LogTime.getElapsedMillis(startTime));
}
}
我們看上面程式碼會發現,一個新的請求是從onSizeReady()開始的:
public void onSizeReady(int width, int height) {
...
loadStatus = engine.load(
glideContext,
model,
requestOptions.getSignature(),
this.width,
this.height,
requestOptions.getResourceClass(),
transcodeClass,
priority,
requestOptions.getDiskCacheStrategy(),
requestOptions.getTransformations(),
requestOptions.isTransformationRequired(),
requestOptions.isScaleOnlyOrNoTransform(),
requestOptions.getOptions(),
requestOptions.isMemoryCacheable(),
requestOptions.getUseUnlimitedSourceGeneratorsPool(),
requestOptions.getUseAnimationPool(),
requestOptions.getOnlyRetrieveFromCache(),
this);
// This is a hack that's only useful for testing right now where loads complete synchronously
// even though under any executor running on any thread but the main thread, the load would
// have completed asynchronously.
if (status != Status.RUNNING) {
loadStatus = null;
}
if (IS_VERBOSE_LOGGABLE) {
logV("finished onSizeReady in " + LogTime.getElapsedMillis(startTime));
}
}
我們看裡面會呼叫一個engine.load()方法,engine幹嘛的呢,我們進入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,
boolean isScaleOnlyOrNoTransform,
Options options,
boolean isMemoryCacheable,
boolean useUnlimitedSourceExecutorPool,
boolean useAnimationPool,
boolean onlyRetrieveFromCache,
ResourceCallback cb) {
Util.assertMainThread();
long startTime = LogTime.getLogTime();
// 生成快取的key
EngineKey key = keyFactory.buildKey(model, signature, width, height, transformations,
resourceClass, transcodeClass, options);
// 從活動快取獲取
EngineResource<?> active = loadFromActiveResources(key, isMemoryCacheable);
if (active != null) {
cb.onResourceReady(active, DataSource.MEMORY_CACHE);
if (Log.isLoggable(TAG, Log.VERBOSE)) {
logWithTimeAndKey("Loaded resource from active resources", startTime, key);
}
return null;
}
// 從記憶體快取LruCache獲取
EngineResource<?> cached = loadFromCache(key, isMemoryCacheable);
if (cached != null) {
cb.onResourceReady(cached, DataSource.MEMORY_CACHE);
if (Log.isLoggable(TAG, Log.VERBOSE)) {
logWithTimeAndKey("Loaded resource from cache", startTime, key);
}
return null;
}
// 開啟執行緒從磁碟獲取快取
EngineJob<?> current = jobs.get(key, onlyRetrieveFromCache);
if (current != null) {
current.addCallback(cb);
if (Log.isLoggable(TAG, Log.VERBOSE)) {
logWithTimeAndKey("Added to existing load", startTime, key);
}
return new LoadStatus(cb, current);
}
EngineJob<R> engineJob =
engineJobFactory.build(
key,
isMemoryCacheable,
useUnlimitedSourceExecutorPool,
useAnimationPool,
onlyRetrieveFromCache);
DecodeJob<R> decodeJob =
decodeJobFactory.build(
glideContext,
model,
key,
signature,
width,
height,
resourceClass,
transcodeClass,
priority,
diskCacheStrategy,
transformations,
isTransformationRequired,
isScaleOnlyOrNoTransform,
onlyRetrieveFromCache,
options,
engineJob);
jobs.put(key, engineJob);
// 新增載入失敗、完成的回撥
engineJob.addCallback(cb);
// 通過執行緒池開啟一個執行緒
engineJob.start(decodeJob);
if (Log.isLoggable(TAG, Log.VERBOSE)) {
logWithTimeAndKey("Started new load", startTime, key);
}
return new LoadStatus(cb, engineJob);
}
看到這裡我們會驚喜的發現有兩個方法loadFromActiveResources()、loadFromCache(),這不就是我們想要獲取快取的方法嗎。我們先看loadFromActiveResources()方法:
private EngineResource<?> loadFromActiveResources(Key key, boolean isMemoryCacheable) {
// 不使用記憶體快取直接返回null
if (!isMemoryCacheable) {
return null;
}
// 通過key取出快取
EngineResource<?> active = activeResources.get(key);
if (active != null) {
// 參照計數+1
active.acquire();
}
return active;
}
我們從上面可以看到兩個方法一個獲取快取的get()方法,一個是acquire()方法,分別看下實現:
EngineResource<?> get(Key key) {
ResourceWeakReference activeRef = activeEngineResources.get(key);
if (activeRef == null) {
return null;
}
EngineResource<?> active = activeRef.get();
if (active == null) {
cleanupActiveReference(activeRef);
}
return active;
}
void acquire() {
if (isRecycled) {
throw new IllegalStateException("Cannot acquire a recycled resource");
}
if (!Looper.getMainLooper().equals(Looper.myLooper())) {
throw new IllegalThreadStateException("Must call acquire on the main thread");
}
++acquired;
}
我們從上面程式碼可以看出我們使用一個弱參照儲存我們的活動快取,然後用一個計數器來標記是否正在使用,每參照一次+1,相反release時候-1,最後acquired=0時,回收我們的活動快取。
void release() {
if (acquired <= 0) {
throw new IllegalStateException("Cannot release a recycled or not yet acquired resource");
}
if (!Looper.getMainLooper().equals(Looper.myLooper())) {
throw new IllegalThreadStateException("Must call release on the main thread");
}
if (--acquired == 0) {
listener.onResourceReleased(key, this);
}
}
接下來我們看一下loadFromCache()方法,如下:
private EngineResource<?> loadFromCache(Key key, boolean isMemoryCacheable) {
if (!isMemoryCacheable) {
return null;
}
// 從Lrucahe取出快取,並從中移除
EngineResource<?> cached = getEngineResourceFromCache(key);
// 將快取存入弱參照中
if (cached != null) {
cached.acquire();
activeResources.activate(key, cached);
}
return cached;
}
private EngineResource<?> getEngineResourceFromCache(Key key) {
Resource<?> cached = cache.remove(key);
final EngineResource<?> result;
if (cached == null) {
result = null;
} else if (cached instanceof EngineResource) {
// Save an object allocation if we've cached an EngineResource (the typical case).
result = (EngineResource<?>) cached;
} else {
result = new EngineResource<>(cached, true /*isMemoryCacheable*/, true /*isRecyclable*/);
}
return result;
}
void activate(Key key, EngineResource<?> resource) {
ResourceWeakReference toPut =
new ResourceWeakReference(
key,
resource,
getReferenceQueue(),
isActiveResourceRetentionAllowed);
ResourceWeakReference removed = activeEngineResources.put(key, toPut);
if (removed != null) {
removed.reset();
}
}
我們可以看到他是先從LruCache獲取快取並從Lrucache中移除,然後在放入弱參照中儲存,完成快取從LruCache到弱參照的轉移。
接著engine.load()方法往下看,我們可以看到分別建立了一個EngineJob、DecodeJob,EngineJob是負責管理載入成功、失敗的回撥,DecodeJob是一個執行緒,負責獲取磁碟快取。
Engine#load方法: engineJob.addCallback(cb);
engineJob.start(decodeJob);
// 新增載入完成的回撥
void addCallback(ResourceCallback cb) {
Util.assertMainThread();
stateVerifier.throwIfRecycled();
if (hasResource) {
cb.onResourceReady(engineResource, dataSource);
} else if (hasLoadFailed) {
cb.onLoadFailed(exception);
} else {
cbs.add(cb);
}
}
// 開啟一個執行緒
public void start(DecodeJob<R> decodeJob) {
this.decodeJob = decodeJob;
GlideExecutor executor = decodeJob.willDecodeFromCache()
? diskCacheExecutor
: getActiveSourceExecutor();
executor.execute(decodeJob);
}
我們知道一個執行緒開啟後,執行的方法是run(),so我們看看DecodeJob的run()方法
public void run() {
DataFetcher<?> localFetcher = currentFetcher;
try {
// 如果取消了,直接通知錯誤
if (isCancelled) {
notifyFailed();
return;
}
// 根據策略載入不同的快取
runWrapped();
} catch (Throwable t) {
if (Log.isLoggable(TAG, Log.DEBUG)) {
Log.d(TAG, "DecodeJob threw unexpectedly"
+ ", isCancelled: " + isCancelled
+ ", stage: " + stage, t);
}
// When we're encoding we've already notified our callback and it isn't safe to do so again.
if (stage != Stage.ENCODE) {
throwables.add(t);
notifyFailed();
}
if (!isCancelled) {
throw t;
}
} finally {
// 最後呼叫clean方法
if (localFetcher != null) {
localFetcher.cleanup();
}
TraceCompat.endSection();
}
}
從上面的程式碼可以看出主要是呼叫了runWrapped()方法,這個方法主要是根據不同的策略載入不同型別的磁碟快取,在分析程式碼之前我們先回顧一下Glide支援哪幾種磁碟快取?
Glide5大磁碟快取策略
DiskCacheStrategy.DATA
: 只快取原始圖片;DiskCacheStrategy.RESOURCE
:只快取轉換過後的圖片;DiskCacheStrategy.ALL
:既快取原始圖片,也快取轉換過後的圖片;對於遠端圖片,快取DATA
和RESOURCE
;對於本地圖片,只快取RESOURCE
;DiskCacheStrategy.NONE
:不快取任何內容;DiskCacheStrategy.AUTOMATIC
:預設策略,嘗試對本地和遠端圖片使用最佳的策略。當下載網路圖片時,使用DATA
;對於本地圖片,使用RESOURCE
;
從上面可以知道,Glide支援5種磁碟快取策略,接著看runWrapped()方法實現:
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);
}
}
我們從上面程式碼可以看出主要呼叫了3個方法 getNextStage()、getNextGenerator()、runGenerators():
private Stage getNextStage(Stage current) {
switch (current) {
case INITIALIZE:
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:
// Skip loading from source if the user opted to only retrieve the resource from cache.
return onlyRetrieveFromCache ? Stage.FINISHED : 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:
return new SourceGenerator(decodeHelper, this);
case FINISHED:
return null;
default:
throw new IllegalStateException("Unrecognized stage: " + stage);
}
}
private void runGenerators() {
currentThread = Thread.currentThread();
startFetchTime = LogTime.getLogTime();
boolean isStarted = false;
while (!isCancelled && currentGenerator != null
&& !(isStarted = currentGenerator.startNext())) {
stage = getNextStage(stage);
currentGenerator = getNextGenerator();
if (stage == Stage.SOURCE) {
reschedule();
return;
}
}
// We've run out of stages and generators, give up.
if ((stage == Stage.FINISHED || isCancelled) && !isStarted) {
notifyFailed();
}
}
依次往下看getNextStage()方法會根據當前Stage的狀態返回下一個Stage狀態,然後getNextGenerator()會根據當前的Stage狀態返回對應的快取生成器,然後執行runGenerators()方法,裡面呼叫了快取生成器的startNext()方法,迴圈執行getNextStage()、getNextGenerator()方法,最後當前stage是Stage.SOURCE跳出當前迴圈。如果我們第一次從網路載入圖片,由於Stage最開始狀態是INITIALIZE,最終呼叫的是SouceGenerator,如果有磁碟快取時,呼叫DataCacheGenerator、ResouceCacheGenerator。
我們在SouceGenerator的StartNext()可以看到:
public boolean startNext() {
// 如果有快取,從快取中獲取
if (dataToCache != null) {
Object data = dataToCache;
dataToCache = null;
cacheData(data);
}
// 呼叫DataCacheGenerator startNext()方法
if (sourceCacheGenerator != null && sourceCacheGenerator.startNext()) {
return true;
}
sourceCacheGenerator = null;
loadData = null;
boolean started = false;
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;
}
從上面程式碼可以看出SouceGenerator.StartNext()方法先會判斷當前是否有快取,由於第一次從網路載入圖片是沒有快取的,最終呼叫的是fetcher.loadData()方法,通過HttpUrlFetcher實現的,程式碼如下:
@Override
public void loadData(@NonNull Priority priority,
@NonNull DataCallback<? super InputStream> callback) {
long startTime = LogTime.getLogTime();
try {
InputStream result = loadDataWithRedirects(glideUrl.toURL(), 0, null, glideUrl.getHeaders());
// 請求完成回撥
callback.onDataReady(result);
} catch (IOException e) {
if (Log.isLoggable(TAG, Log.DEBUG)) {
Log.d(TAG, "Failed to load data for url", e);
}
callback.onLoadFailed(e);
} finally {
if (Log.isLoggable(TAG, Log.VERBOSE)) {
Log.v(TAG, "Finished http url fetcher fetch in " + LogTime.getElapsedMillis(startTime));
}
}
}
請求完成通過onDataReady()回撥-->到SourceGenerator.onDataFetcherReady()方法先儲存資料:
@Override
public void onDataReady(Object data) {
DiskCacheStrategy diskCacheStrategy = helper.getDiskCacheStrategy();
if (data != null && diskCacheStrategy.isDataCacheable(loadData.fetcher.getDataSource())) {
// 儲存資料
dataToCache = data;
// We might be being called back on someone else's thread. Before doing anything, we should
// reschedule to get back onto Glide's thread.
// 回撥
cb.reschedule();
} else {
cb.onDataFetcherReady(loadData.sourceKey, data, loadData.fetcher,
loadData.fetcher.getDataSource(), originalKey);
}
}
通過回撥,最終通過DecodeJob#run()方法通過decodeFromRetrievedData()方法呼叫notifyEncodeAndRelease()方法
private void decodeFromRetrievedData() {
if (Log.isLoggable(TAG, Log.VERBOSE)) {
logWithTimeAndKey("Retrieved data", startFetchTime,
"data: " + currentData
+ ", cache key: " + currentSourceKey
+ ", fetcher: " + currentFetcher);
}
Resource<R> resource = null;
try {
resource = decodeFromData(currentFetcher, currentData, currentDataSource);
} catch (GlideException e) {
e.setLoggingDetails(currentAttemptingKey, currentDataSource);
throwables.add(e);
}
if (resource != null) {
// 載入資料
notifyEncodeAndRelease(resource, currentDataSource);
} else {
runGenerators();
}
}
最後到handleResultOnMainThread()方法完成載入圖片,並通過弱參照寫入快取:
@Synthetic
void handleResultOnMainThread() {
stateVerifier.throwIfRecycled();
if (isCancelled) {
resource.recycle();
release(false /*isRemovedFromQueue*/);
return;
} else if (cbs.isEmpty()) {
throw new IllegalStateException("Received a resource without any callbacks to notify");
} else if (hasResource) {
throw new IllegalStateException("Already have resource");
}
engineResource = engineResourceFactory.build(resource, isCacheable);
hasResource = true;
// Hold on to resource for duration of request so we don't recycle it in the middle of
// notifying if it synchronously released by one of the callbacks.
engineResource.acquire();
// 圖片請求完成,並寫入快取
listener.onEngineJobComplete(this, key, engineResource);
//noinspection ForLoopReplaceableByForEach to improve perf
for (int i = 0, size = cbs.size(); i < size; i++) {
ResourceCallback cb = cbs.get(i);
if (!isInIgnoredCallbacks(cb)) {
engineResource.acquire();
cb.onResourceReady(engineResource, dataSource);
}
}
// Our request is complete, so we can release the resource.
engineResource.release();
release(false /*isRemovedFromQueue*/);
}
public void onEngineJobComplete(EngineJob<?> engineJob, Key key, EngineResource<?> resource) {
Util.assertMainThread();
// A null resource indicates that the load failed, usually due to an exception.
if (resource != null) {
resource.setResourceListener(key, this);
if (resource.isCacheable()) {
activeResources.activate(key, resource);
}
}
jobs.removeIfCurrent(key, engineJob);
}
我們第一次從網路載入圖片是通過SouceGenerator從網路獲取顯示並寫入快取,我們再看看DataCacheGenerator、ResouceCacheGenerator快取獲取。
public boolean startNext() {
List<Key> sourceIds = helper.getCacheKeys();
if (sourceIds.isEmpty()) {
return false;
}
List<Class<?>> resourceClasses = helper.getRegisteredResourceClasses();
if (resourceClasses.isEmpty()) {
if (File.class.equals(helper.getTranscodeClass())) {
return false;
}
throw new IllegalStateException(
"Failed to find any load path from " + helper.getModelClass() + " to "
+ helper.getTranscodeClass());
}
while (modelLoaders == null || !hasNextModelLoader()) {
resourceClassIndex++;
if (resourceClassIndex >= resourceClasses.size()) {
sourceIdIndex++;
if (sourceIdIndex >= sourceIds.size()) {
return false;
}
resourceClassIndex = 0;
}
Key sourceId = sourceIds.get(sourceIdIndex);
Class<?> resourceClass = resourceClasses.get(resourceClassIndex);
Transformation<?> transformation = helper.getTransformation(resourceClass);
// 獲取快取Key
currentKey =
new ResourceCacheKey(// NOPMD AvoidInstantiatingObjectsInLoops
helper.getArrayPool(),
sourceId,
helper.getSignature(),
helper.getWidth(),
helper.getHeight(),
transformation,
resourceClass,
helper.getOptions());
// 讀取快取
cacheFile = helper.getDiskCache().get(currentKey);
if (cacheFile != null) {
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;
}
大概流程:先獲取快取key,然後取出快取,如果快取不存在,通過網路重新獲取。
至此,終於將Glide快取原理全部分析完畢,總結一下。
Glide總共有2級快取,一級記憶體快取包括弱參照活動快取、LruCache快取,二級DiskLruCache,第一次從網路載入圖片時,會開啟執行緒從網路下載圖片,下載完成後儲存到磁碟,然後再加入弱參照快取,下次載入圖片會先從弱參照獲取,弱參照維護一個acquired引數,判斷當前圖片是否正在使用,每load一次+1,每release一次-1,如果acquired == 0時,代表圖片不在使用,回收弱參照物件並把快取寫入LruCache,如果從弱參照獲取不到快取,就會從LruCache獲取快取,並將從當前佇列移除,放入弱參照儲存,最後如果LruCache也獲取不到快取,從磁碟獲取快取,如果磁碟快取不存在,就會重新從網路載入圖片。
Glide生命週期相比快取處理,要簡單不少,下面通過原始碼簡單介紹一下。
熟悉Glide的同學應該知道,Glide是通過Glide.With("xxx")傳入生命週期:
大概有5個構造方法,和之前一樣隨便點進去一個去看:
@NonNull
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);
}
我們發現其實你傳入無論是fragment還是activity還是view context主要分為兩種一種是Application、一種非Application,我們先看下Application的,返回的是getApplicationManager(context):
@NonNull
private RequestManager getApplicationManager(@NonNull Context context) {
// Either an application context or we're on a background thread.
if (applicationManager == null) {
synchronized (this) {
if (applicationManager == null) {
// 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;
}
從上面程式碼可以看出關聯的是app生命週期,和應用的生命週期一致。我們再看非Application,根據是否support包下區分為
fragmentGet()、supportFragmentGet()方法:
private RequestManager supportFragmentGet(@NonNull Context context, @NonNull FragmentManager fm,
@Nullable Fragment parentHint) {
// 建立一個空白fragment
SupportRequestManagerFragment current = getSupportRequestManagerFragment(fm, parentHint);
RequestManager requestManager = current.getRequestManager();
if (requestManager == null) {
// glide關聯fragment的生命週期
Glide glide = Glide.get(context);
requestManager =
factory.build(
glide, current.getGlideLifecycle(), current.getRequestManagerTreeNode(), context);
current.setRequestManager(requestManager);
}
return requestManager;
}
@NonNull
private RequestManager fragmentGet(@NonNull Context context,
@NonNull android.app.FragmentManager fm,
@Nullable android.app.Fragment parentHint) {
// 建立一個空白fragment
RequestManagerFragment current = getRequestManagerFragment(fm, parentHint);
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;
}
我們可以看到他們首先都會建立一個空白fragment,然後和Glide關聯起來。
RequestManagerFragment getRequestManagerFragment(
@NonNull final android.app.FragmentManager fm, @Nullable android.app.Fragment parentHint) {
// 先根據tag查詢是否存在
RequestManagerFragment current = (RequestManagerFragment) fm.findFragmentByTag(FRAGMENT_TAG);
if (current == null) {
如果為空從map中取出
current = pendingRequestManagerFragments.get(fm);
if (current == null) {
// 建立一個空白fragment
current = new RequestManagerFragment();
current.setParentFragmentHint(parentHint);
// 放入map裡面
pendingRequestManagerFragments.put(fm, current);
// 新增之前建立的空白fragment
fm.beginTransaction().add(current, FRAGMENT_TAG).commitAllowingStateLoss();
// 通知map移除剛新增的fragment
handler.obtainMessage(ID_REMOVE_FRAGMENT_MANAGER, fm).sendToTarget();
}
}
return current;
}
我們進入RequestManagerFragment會發現,建立的時候,會預設構造一個ActivityFragmentLifecycle:
public RequestManagerFragment() {
this(new ActivityFragmentLifecycle());
}
class ActivityFragmentLifecycle implements Lifecycle {
// 省略程式碼...
@Override
public void addListener(@NonNull LifecycleListener listener) {
lifecycleListeners.add(listener);
if (isDestroyed) {
listener.onDestroy();
} else if (isStarted) {
listener.onStart();
} else {
listener.onStop();
}
}
@Override
public void removeListener(@NonNull LifecycleListener listener) {
lifecycleListeners.remove(listener);
}
void onStart() {
isStarted = true;
for (LifecycleListener lifecycleListener : Util.getSnapshot(lifecycleListeners)) {
lifecycleListener.onStart();
}
}
void onStop() {
isStarted = false;
for (LifecycleListener lifecycleListener : Util.getSnapshot(lifecycleListeners)) {
lifecycleListener.onStop();
}
}
void onDestroy() {
isDestroyed = true;
for (LifecycleListener lifecycleListener : Util.getSnapshot(lifecycleListeners)) {
lifecycleListener.onDestroy();
}
}
}
其中宣告了onStart()、onStop()、onDestroy()方法,我們再看RequestManagerFragment裡面對應的onStart()、onStop()、onDestroy()方法:
#RequestManagerFragment
@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();
}
會發現fragment週期方法回撥的時候會回撥ActivityFragmentLifecycle的方法,然後遍歷所有LifecycleListener,LifecycleListener是什麼呢?
public interface LifecycleListener {
/**
* Callback for when {@link android.app.Fragment#onStart()}} or {@link
* android.app.Activity#onStart()} is called.
*/
void onStart();
/**
* Callback for when {@link android.app.Fragment#onStop()}} or {@link
* android.app.Activity#onStop()}} is called.
*/
void onStop();
/**
* Callback for when {@link android.app.Fragment#onDestroy()}} or {@link
* android.app.Activity#onDestroy()} is called.
*/
void onDestroy();
}
其實就是Glide定義生命週期相關介面,通過介面回撥,來控制暫停、恢復載入、移除相關操作。
總結一下,Glide生命週期和Activity、Fragment關聯,是通過with方法傳入引數,如果是Application context就與app的生命週期關聯起來,如果非Application context 先判斷是否是後臺執行緒,會轉為Application context方法,繼續執行,如果不是就會通過建立一個空白fragment,並構造一個ActivityFragmentLifecycle介面,fragment生命週期方法呼叫時,ActivityFragmentLifecycle中的介面方法會呼叫並回撥到Glide LifecycleListener介面,從而實現了和fragment生命週期管理起來。
至此,終於全部分析完了,本文描述了Glide、Fresco、Picasso對比,著重從原始碼分析了一下Glide快取和生命週期原理,由於個人水平有限,有誤的地方敬請指出,謝謝。
Thanks:
創作不易,如果覺得有用的話,麻煩點個贊。