依赖库
implementation 'com.github.bumptech.glide:glide:4.9.0'
基本用法
Glide.with(this)
.load(url)
.into(imageView);
过程
- 创建request
- 执行加载
- 回调刷新UI
源码分析
Glide#with
获得RequestManager:请求管理类,创建RequestBuilder。控制整个界面的生命周期监听。
传入不同的Context处理
- applicationContext
不做任何特殊处理,通过RequestManagerFactory来build出一个RequestManager。Application对象的生命周期即应用程序的生命周期,因此Glide并不需要做什么特殊的处理,它自动就是和应用程序的生命周期是同步的,如果应用程序关闭的话,Glide的加载也会同时终止。 - Activity
public RequestManager get(@NonNull Activity activity) {
if (Util.isOnBackgroundThread()) {
return get(activity.getApplicationContext());
} else {
assertNotDestroyed(activity);
android.app.FragmentManager fm = activity.getFragmentManager();
return fragmentGet(
activity, fm, /*parentHint=*/ null, isActivityVisible(activity));
}
}
RequestManagerRetriever#fragmentGet
@Deprecated
@NonNull
private RequestManager fragmentGet(@NonNull Context context,
@NonNull android.app.FragmentManager fm,
@Nullable android.app.Fragment parentHint,
boolean isParentVisible) {
RequestManagerFragment current = getRequestManagerFragment(fm, parentHint, isParentVisible);
RequestManager requestManager = current.getRequestManager();
if (requestManager == null) {
Glide glide = Glide.get(context);
requestManager =
factory.build(
glide, current.getGlideLifecycle(), current.getRequestManagerTreeNode(), context);
// RequestManagerFragment和RequestManager绑定起来
//监听Activity的生命周期来管理图片加载
current.setRequestManager(requestManager);
}
return requestManager;
}
Activity中添加没有UI的Fragment。需要这个Fragment来监听Activity的生命周期。Fragment的生命周期和Activity是同步的,如果Activity被销毁了,Fragment是可以监听到的,这样Glide就可以捕获这个事件并停止图片加载了。
3.非主线程使用Glide
如果我们是在非主线程当中使用的Glide,那么不管你是传入的Activity还是Fragment,都会被强制当成Application来处理。
如何进行生命周期绑定的
RequestManagerFragment中ActivityFragmentLifecycle
管理生命周期,注册了一些回调接口,当Activity,Fragment调用回调方法,去处理图片加载请求。当图片加载到一半,Activity切走,就会停止加载。
@Override
public void onStop() {
super.onStop();
lifecycle.onStop();
}
Glide#load
public RequestBuilder<Drawable> load(@Nullable String string) {
return asDrawable().load(string);
}
RequestManager#asDrawable
@NonNull
@CheckResult
public RequestBuilder<Drawable> asDrawable() {
return as(Drawable.class);
}
return new RequestBuilder<>(glide, this, resourceClass, context);
RequestBuilder#load
@NonNull
private RequestBuilder<TranscodeType> loadGeneric(@Nullable Object model) {
this.model = model;
isModelSet = true;
return this;
}
Glide#into
RequestBuilder#into
@NonNull
public ViewTarget<ImageView, TranscodeType> into(@NonNull ImageView view) {
// into要在主线程中调用
Util.assertMainThread();
// 对传进来的ImageView做是否为空的判断
Preconditions.checkNotNull(view);
// 配置图片加载设置
BaseRequestOptions<?> requestOptions = this;
if (!requestOptions.isTransformationSet()
&& requestOptions.isTransformationAllowed()
&& view.getScaleType() != null) {
// options保存四种scaleType规格
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:
}
}
// 这个transcodeClass是指的drawable或bitmap
// glideContext#buildImageViewTarget,这个方法会构建出一个Target对象,Target对象则是用来最终展示图片用的
return into(
glideContext.buildImageViewTarget(view, transcodeClass),
/*targetListener=*/ null,
requestOptions,
Executors.mainThreadExecutor());
}
GlideContext#buildImageViewTarget
实际里面调用了ImageViewTargetFactory#buildTarget
public class ImageViewTargetFactory {
@NonNull
@SuppressWarnings("unchecked")
// 返回展示Bimtap/Drawable资源的目标对象
// 这个Class是之前load方法,调用as(Class class)传入的
public <Z> ViewTarget<ImageView, Z> buildTarget(@NonNull ImageView view,
@NonNull Class<Z> clazz) {
if (Bitmap.class.equals(clazz)) {
return (ViewTarget<ImageView, Z>) new BitmapImageViewTarget(view);
} else if (Drawable.class.isAssignableFrom(clazz)) {
return (ViewTarget<ImageView, Z>) new DrawableImageViewTarget(view);
} else {
throw new IllegalArgumentException(
"Unhandled class: " + clazz + ", try .as*(Class).transcode(ResourceTranscoder)");
}
}
}
RequestBuilder#into
/**
* 将资源加载到传入的target
*/
private <Y extends Target<TranscodeType>> Y into(
@NonNull Y target,
@Nullable RequestListener<TranscodeType> targetListener,
BaseRequestOptions<?> options,
Executor callbackExecutor) {
Preconditions.checkNotNull(target);
// 这个变量load时置
if (!isModelSet) {
throw new IllegalArgumentException("You must call #load() before calling #into()");
}
// 创建Request,request是用来发出加载图片请求的
// 实例化对象是SingleRequest
Request request = buildRequest(target, targetListener, options, callbackExecutor);
// 获取当前target所绑定的request对象,旧的request
Request previous = target.getRequest();
// 当前请求和上次请求一致的话就返回相应的target对象
// isSkipMemoryCacheWithCompletePreviousRequest看options中是否设置不支持内存缓存以及之前的请求是否以及完成。
if (request.isEquivalentTo(previous)
&& !isSkipMemoryCacheWithCompletePreviousRequest(options, previous)) {
request.recycle();
if (!Preconditions.checkNotNull(previous).isRunning()) {
previous.begin();
}
return target;
}
// 清除旧的Target
requestManager.clear(target);
// target绑定新的request对象
target.setRequest(request);
// 执行request
requestManager.track(target, request);
return target;
}
1.创建加载图片的Request
2.对旧的Target绑定进行删除
3.交给requestManager进行相应的request处理
RequestBuilder#buildRequest
最终执行到buildThumbnailRequestRecursive
方法。
buildRequest - buildRequestRecursive - buildThumbnailRequestRecursive
buildThumbnailRequestRecursive有多个分支前面都是和缩略图有关,实际创建Request请求是最后一行调用obtainRequest
方法。
private Request obtainRequest(
Target<TranscodeType> target,
RequestListener<TranscodeType> targetListener,
BaseRequestOptions<?> requestOptions,
RequestCoordinator requestCoordinator,
TransitionOptions<?, ? super TranscodeType> transitionOptions,
Priority priority,
int overrideWidth,
int overrideHeight,
Executor callbackExecutor) {
// 进行初始化,返回Request对象
return SingleRequest.obtain(
context,
glideContext,
model,
transcodeClass,
requestOptions,
overrideWidth,
overrideHeight,
priority,
target,
targetListener,
requestListeners,
requestCoordinator,
glideContext.getEngine(),
transitionOptions.getTransitionFactory(),
callbackExecutor);
}
RequestManager#track
synchronized void track(@NonNull Target<?> target, @NonNull Request request) {
// 添加target进目标集合
targetTracker.track(target);
requestTracker.runRequest(request);
}
RequestTraker#runRequest
public void runRequest(@NonNull Request request) {
requests.add(request);
// 是否有正在进行的request请求
if (!isPaused) {
request.begin();
} else {
// 加入待执行队列
request.clear();
pendingRequests.add(request);
}
}
SingleRequest#begin
@Override
public synchronized void begin() {
assertNotCallingCallbacks();
stateVerifier.throwIfRecycled();
startTime = LogTime.getLogTime();
// model就是我们在load()方法中传入的资源
// 会先去获取一个error的占位图,如果获取不到的话会再去获取一个loading占位图,然后调用target.onLoadFailed(error)方法并将占位图传入
if (model == null) {
if (Util.isValidDimensions(overrideWidth, overrideHeight)) {
width = overrideWidth;
height = overrideHeight;
}
int logLevel = getFallbackDrawable() == null ? Log.WARN : Log.DEBUG;
onLoadFailed(new GlideException("Received null model"), logLevel);
return;
}
...
status = Status.WAITING_FOR_SIZE;
// 是否使用了override() API为图片指定了一个固定的宽高
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));
}
}
SingleRequest#onSizeReady
public synchronized void onSizeReady(int width, int height) {
...
/**
* 当前图片需要裁剪的倍数,得出需要加载图片的宽,高
*/
float sizeMultiplier = requestOptions.getSizeMultiplier();
this.width = maybeApplySizeMultiplier(width, sizeMultiplier);
this.height = maybeApplySizeMultiplier(height, sizeMultiplier);
// 根据给定的配置进行加载,engine是一个负责加载、管理活跃和缓存资源的引擎类
loadStatus =
engine.load(...);
...
}
Engine#load
/**
* 该方法负责管理活动和缓存资源
*/
public synchronized <R> LoadStatus load(...) {
// 生成缓存key
EngineKey key = keyFactory.buildKey(model, signature, width, height, transformations,
resourceClass, transcodeClass, options);
// 内存采用了一个HashMap进行内存的缓存,使用了弱引用ResourceWeakReference持有了Resource
// 从Map<Key, ResourceWeakReference> activeEngineResources这个缓存中取EngineResource里面主要维护了acquire int,资源被使用加1,被释放-1,资源没有被使用时,则会调用onResourceReleased,将资源存储到MemoryCache中。
EngineResource<?> active = loadFromActiveResources(key, isMemoryCacheable);
if (active != null) {
cb.onResourceReady(active, DataSource.MEMORY_CACHE);
if (VERBOSE_IS_LOGGABLE) {
logWithTimeAndKey("Loaded resource from active resources", startTime, key);
}
return null;
}
// 没有再从磁盘内存中查找,有的话会取出并放到ActiveResources(内部维护的弱引用缓存map)里面
EngineResource<?> cached = loadFromCache(key, isMemoryCacheable);
if (cached != null) {
cb.onResourceReady(cached, DataSource.MEMORY_CACHE);
if (VERBOSE_IS_LOGGABLE) {
logWithTimeAndKey("Loaded resource from cache", startTime, key);
}
return null;
}
// 当前Request是否正在执行
EngineJob<?> current = jobs.get(key, onlyRetrieveFromCache);
if (current != null) {
current.addCallback(cb, callbackExecutor);
if (VERBOSE_IS_LOGGABLE) {
logWithTimeAndKey("Added to existing load", startTime, key);
}
return new LoadStatus(cb, current);
}
// 创建engineJob,创建后台任务执行
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内部维护的HashMap中
jobs.put(key, engineJob);
engineJob.addCallback(cb, callbackExecutor);
// 内部开启线程去执行decodeJob的run方法
engineJob.start(decodeJob);
if (VERBOSE_IS_LOGGABLE) {
logWithTimeAndKey("Started new load", startTime, key);
}
// 开始一个新加载
return new LoadStatus(cb, engineJob);
}
EngineJob#start
public synchronized void start(DecodeJob<R> decodeJob) {
this.decodeJob = decodeJob;
// //这里根据缓存策略,决定使用哪个Executor。默认情况返回diskCacheExecutor。
//共三种执行器:diskCacheExecutor、sourceExecutor、sourceUnlimitedExecutor
GlideExecutor executor = decodeJob.willDecodeFromCache()
? diskCacheExecutor
: getActiveSourceExecutor();
// 正式开启子线程进行资源加载,线程也从主线程切换到子线程
executor.execute(decodeJob);
}
DecodeJob#run
里面执行到runWrapped方法
private void runWrapped() {
switch (runReason) {
// 第一次加载,DecodeJob调用init方法就会置成这个状态
case INITIALIZE:
// 获取下一阶段状态
stage = getNextStage(Stage.INITIALIZE);
// 获取下一阶段的Generator对象
currentGenerator = getNextGenerator();
// 内部会调用相应Generator的startNext()
// 真正的去加载网络资源
runGenerators();
break;
case SWITCH_TO_SOURCE_SERVICE:
runGenerators();
break;
case DECODE_DATA:
// 将获取的数据解码成对应的资源
decodeFromRetrievedData();
break;
default:
throw new IllegalStateException("Unrecognized run reason: " + runReason);
}
}
DecodeJob#getNextStage
INITIALIZE:初始化、RESOURCE_CACHE:读取转换后的缓存、DATA_CACHE:读取原文件缓存、SOURCE:原文件加载、FINISHED:结束状态。
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:
return onlyRetrieveFromCache ? Stage.FINISHED : Stage.SOURCE;
case SOURCE:
case FINISHED:
return Stage.FINISHED;
default:
throw new IllegalArgumentException("Unrecognized stage: " + current);
}
}
DecodeJob#getNextGenerator
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);
}
}
SourceGenerator#startNext
@Override
public boolean startNext() {
...
while (!started && hasNextModelLoader()) {
// getLoadData()方法内部会在modelLoaders里面找到ModelLoder对象
// 并使用modelLoader.buildLoadData方法返回一个loadData列表
loadData = helper.getLoadData().get(loadDataListIndex++);
if (loadData != null
&& (helper.getDiskCacheStrategy().isDataCacheable(loadData.fetcher.getDataSource())
|| helper.hasLoadPath(loadData.fetcher.getDataClass()))) {
started = true;
// 通过loadData对象的fetcher对象的loadData方法来获取图片数据
// 最终是通过HttpUrlFetcher调用loadData方法获取数据
// 内部是通过HttpURLConnection网络请求数据
loadData.fetcher.loadData(helper.getPriority(), this);
}
}
return started;
}
DecodeHelper#getLoadData
List<LoadData<?>> getLoadData() {
if (!isLoadDataSet) {
isLoadDataSet = true;
loadData.clear();
// Registry类是一个组件管理类,它的主要用途是扩展和替换Glide组件,这些组件包括加载,编码,解码等逻辑。
// Registry并不是承当所有模块的注册工作,而是把各个模块分配的不同的Registry当中。
// ModelLoader主要工作是将复杂数据模型转通过DataFetcher转换成需要的Data
List<ModelLoader<Object, ?>> modelLoaders = glideContext.getRegistry().getModelLoaders(model);
//noinspection ForLoopReplaceableByForEach to improve perf
for (int i = 0, size = modelLoaders.size(); i < size; i++) {
ModelLoader<Object, ?> modelLoader = modelLoaders.get(i);
// 注意:这里最终是通过HttpGlideUrlLoader的buildLoadData获取到实际的loadData对象
LoadData<?> current =
modelLoader.buildLoadData(model, width, height, options);
if (current != null) {
loadData.add(current);
}
}
}
return loadData;
}
HttpGlideUrlLoader#buildLoadData
@Override
public LoadData<InputStream> buildLoadData(@NonNull GlideUrl model, int width, int height,
@NonNull Options options) {
// GlideUrls memoize parsed URLs so caching them saves a few object instantiations and time
// spent parsing urls.
GlideUrl url = model;
if (modelCache != null) {
url = modelCache.get(model, 0, 0);
if (url == null) {
// 使用LruCache来对解析后的url来进行缓存,以便后续可以省去解析url的时间
modelCache.put(model, 0, 0, model);
url = model;
}
}
int timeout = options.get(TIMEOUT);
// HttpUrlFetcher实际上就是最终的请求执行者
return new LoadData<>(url, new HttpUrlFetcher(url, timeout));
}
HttpUrlFetcher#load
@Override
public void loadData(@NonNull Priority priority,@NonNull DataCallback<? super InputStream> callback) {
long startTime = LogTime.getLogTime();
try {
// loadDataWithRedirects内部是通过HttpURLConnection网络请求数据
// 当code是2xx,会调用getStreamForSuccessfulRequest()方法获取到了最终的图片流
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));
}
}
}
DecodeJob#runWrapped
得到数据流需要将其变成我们想要的资源。最终调用到decodeFromRetrievedData
。
private void decodeFromRetrievedData() {
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();
}
}
解码得到资源
DecodeJob#decodeFromData方法 - DecodeJob#decodeFromFetcher方法 - DecodeJob#runLoadPath方法 - LoadPath#load方法 - LoadPath#loadWithExceptionList方法 - DecodePath#decode方法 - DecodePath#decodeResource方法 - DecodePath#decodeResourceWithList方法
public Resource<Transcode> decode(DataRewinder<DataType> rewinder, int width, int height,
@NonNull Options options, DecodeCallback<ResourceType> callback) throws GlideException {
//获取到Resource<Bitmap>对象
Resource<ResourceType> decoded = decodeResource(rewinder, width, height, options);
//将资源转化为目标效果,如在构建request时设置的CenterCrop
Resource<ResourceType> transformed = callback.onResourceDecoded(decoded);
//将数据转化为目标格式,将Resource<Bitmap>转换为LazyBitmapDrawableResource对象
//可通过LazyBitmapDrawableResource的get获取到BitmapDrawable对象
//该transcoder为BitmapDrawableTranscoder
return transcoder.transcode(transformed, options);
}
将结果设置到对应的ImageView
DecodeJob#notifyEncodeAndRelease
private void notifyEncodeAndRelease(Resource<R> resource, DataSource dataSource) {
...
notifyComplete(result, dataSource);
...
}
EngineJob#onResourceReady -> EngineJob#notifyCallbacksOfResult
void notifyCallbacksOfResult() {
ResourceCallbacksAndExecutors copy;
Key localKey;
EngineResource<?> localResource;
synchronized (this) {
...
copy = cbs.copy();
...
}
//通知上层Engine的任务完成了
listener.onEngineJobComplete(this, localKey, localResource);
for (final ResourceCallbackAndExecutor entry : copy) {
// //回调给ImageViewTarget来展示资源
entry.executor.execute(new CallResourceReady(entry.cb));
}
decrementPendingCallbacks();
}
EngineJob#CallResourceReady#run
@Override
public void run() {
synchronized (EngineJob.this) {
if (cbs.contains(cb)) {
// Acquire for this particular callback.
engineResource.acquire();
callCallbackOnResourceReady(cb);
removeCallback(cb);
}
decrementPendingCallbacks();
}
}
EngineJob#callCallbackOnResourceReady -> SingleRequest#onResourceReady
private synchronized void onResourceReady(Resource<R> resource, R result, DataSource dataSource) {
// 第一次加载
boolean isFirstResource = isFirstReadyResource();
status = Status.COMPLETE;
this.resource = resource;
isCallingCallbacks = true;
try {
boolean anyListenerHandledUpdatingTarget = false;
if (requestListeners != null) {
for (RequestListener<R> listener : requestListeners) {
anyListenerHandledUpdatingTarget |=
listener.onResourceReady(result, model, target, dataSource, isFirstResource);
}
}
anyListenerHandledUpdatingTarget |=
targetListener != null
&& targetListener.onResourceReady(result, model, target, dataSource, isFirstResource);
if (!anyListenerHandledUpdatingTarget) {
Transition<? super R> animation =
animationFactory.build(dataSource, isFirstResource);
//展示照片
//此时的target为DrawableImageViewTarget
target.onResourceReady(result, animation);
}
} finally {
isCallingCallbacks = false;
}
//通知加载成功
notifyLoadSuccess();
}
ImageViewTarget#onResourceReady
@Override
public void onResourceReady(@NonNull Z resource, @Nullable Transition<? super Z> transition) {
//是否有动画效果
if (transition == null || !transition.transition(resource, this)) {
// 静态图
// 内部调用setResource来展示照片
setResourceInternal(resource);
} else {
// gif
maybeUpdateAnimatable(resource);
}
}
总结
with:
1.获取RequestManager用来管理请求
2.Gradle绑定组件生命周期,通过不同生命周期来进行相应处理
load:
在RequestBuilder中设置要请求的url,并置状态。返回RequestBuilder对象
into:
1.创建加载图片请求Request,ViewTarget对象
2.生成唯一的缓存key,在内存缓存,磁盘缓存中按顺序查找,查找到哪一步有缓存就直接返回图片,否则继续检查下一步。如果都没有缓存,则 Glide会从原始资源(File、Uri、远程图片 url 等)中解码,变换,缓存,加载图片。
参考
Glide4.0源码全解析
Android图片加载框架最全解析(二),从源码的角度理解Glide的执行流程
Glide 4.0源码解析
Android主流三方库源码分析(三、深入理解Glide源码)