随着Android开发的愈渐火热,各种Android的图片加载库也曾出不穷,比较有名的有:Fresco 、Picasso 、Universal Image Loader 等等。在这篇文章中,我会通过源码来简单地分析一下Glide 使用时所发生的事情。
###使用方法 对于Glide 的使用方法不是本文的重点,在这里就不多说了,这里贴出Glide 的Github地址 ,如果对使用方法有什么疑问的就上官方去看看吧。这里我们从Glide最简单的三行使用方法入手进行分析:1
2
3
Glide.with(...)
.load(...)
.into(...);
###流程分析 首先我们进入Glide 类看看with() 方法:1
2
3
4
public static RequestManager with (Context context) {
RequestManagerRetriever retriever = RequestManagerRetriever.get();
return retriever.get(context);
}
我们可以看到with() 方法是Glide 类中的一个静态方法,它会创建一个RequestManagerRetriever 对象,在这里我们先不看这个类在创建过程中发生的事情,先看看它通过传入的Context 对象所返回的这个RequestManager 对象。
对于RequestManager 这个类,官方文档是这样描述的:A class for managing and starting requests for Glide. Can use activity, fragment and connectivity lifecycle events to intelligently stop, start, and restart requests. Retrieve either by instantiating a new object, or to take advantage built in Activity and Fragment lifecycle handling, use the static Glide.load methods with your Fragment or Activity. 本人英文一般,就不逐字逐句地翻译了。总之,对于RequestManager 这个类的定位就是对图片加载请求进行管理的类,并且它会根据与其产生联系的Context 对象的生命周期来管理图片加载的过程。因此,图片资源加载进ImageView 的过程事实上是由它来一手掌管的。
知道了这些,我们接下来来看看它的load() 方法,也就是我们将资源路径传入的这个方法,这里我们以传入一个Uri 为例:1
2
3
public DrawableTypeRequest<Uri> load (Uri uri) {
return (DrawableTypeRequest<Uri>) fromUri().load(uri);
}
在这个方法中使用了DrawableTypeRequest 中的load() 方法去加载这个uri:1
2
3
4
public DrawableRequestBuilder<ModelType> load (ModelType model) {
super .load(model);
return this ;
}
这个方法的泛型参数ModelType 在这里所对应的实际类型就是我们传入的资源类型Uri ,并且调用了DrawableRequestBuilder 的父类方法load() 来处理。
GenericRequestBuilder 就是DrawableRequestBuilder 的父类,这个类及其子类的作用就是用于请求加载的。我们来看看里面刚刚提到的load() 方法:1
2
3
4
5
public GenericRequestBuilder<ModelType, DataType, ResourceType, TranscodeType> load (ModelType model) {
this .model = model;
isModelSet = true ;
return this ;
}
这里我们发现,load() 方法仅仅是将资源——这里就是我们的图片资源Uri赋值给了一个变量model ,至于图片资源究竟是怎么加载进ImageView 的,我们回到这里实际进行加载请求的类DrawableRequestBuilder 去看看它当中被我们最后调用的into() 方法:1
2
3
public Target<GlideDrawable> into (ImageView view) {
return super .into(view);
}
和load() 方法相同,这里也调用了父类GenericRequestBuilder 的into() 方法:1
2
3
4
public Target<TranscodeType> into (ImageView view) {
......
return into(glide.buildImageViewTarget(view, transcodeClass));
}
对于这个方法我们只看最后一句代码。在这里又再次回到一开始的Glide ,并调用了其中的buildImageViewTarget() 方法,而在这个方法中传入了一个GlideDrawable 对象transcodedClass :1
2
3
<R> Target<R> buildImageViewTarget (ImageView imageView, Class<R> transcodedClass) {
return imageViewTargetFactory.buildTarget(imageView, transcodedClass);
}
我们继续跟踪下去:1
2
3
4
5
6
7
8
9
10
11
public <Z> Target<Z> buildTarget (ImageView view, Class<Z> clazz) {
if (GlideDrawable.class.isAssignableFrom(clazz)) {
return (Target<Z>) new GlideDrawableImageViewTarget(view);
} else if (Bitmap.class.equals(clazz)) {
return (Target<Z>) new BitmapImageViewTarget(view);
} else if (Drawable.class.isAssignableFrom(clazz)) {
return (Target<Z>) new DrawableImageViewTarget(view);
} else {
throw new IllegalArgumentException("Unhandled class: " + clazz + ", try .as*(Class).transcode(ResourceTranscoder)" );
}
}
经过反复地辗转我们终于发现了上面我们传入into() 方法中的是一个和我们所要将图片加载进的ImageView 相关的GlideDrawableImageViewTarget 对象。我们先记住这一点,不继续深究下去,先回头看看那个GenericRequestBuilder 中的into() 方法:1
2
3
4
5
6
7
8
9
public <Y extends Target<TranscodeType>> Y into (Y target) {
......
Request request = buildRequest(target);
target.setRequest(request);
......
requestTracker.runRequest(request);
return target;
}
这段代码所做的事情根据方法名很容易就能猜到,它先根据传入的一个Target 对象创建一个Request ,并将两者建立关联,最后执行加载请求。
这里我们反过来会发现,这个Target 的实际对象就是我们刚刚所说的那个GlideDrawable ,另外谈到请求,是不是想到我们前面load() 进去的那个Uri 对象了呢?一阵云里雾里,整个内容终于联系了起来,那么我们就先来看看这个Request 对象究竟是怎么创建的:1
2
3
4
private Request buildRequest (Target<TranscodeType> target) {
......
return buildRequestRecursive(target, null );
}
这里又将那个Target 对象传进一个buildRequestRecursive() 方法中:1
2
3
4
private Request buildRequestRecursive (Target<TranscodeType> target, ThumbnailRequestCoordinator parentCoordinator) {
......
return obtainRequest(target, sizeMultiplier, priority, parentCoordinator);
}
对于这个方法,我们重点来关注一下其中的一行代码,其中涉及了obtainRequest() 方法,这个方法有四个参数,其中最重要的就是第一个,这里将刚刚的Target 对象给传了进去,我们接下来看一下这个方法:1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
private Request obtainRequest (Target<TranscodeType> target,
float sizeMultiplier, Priority priority,
RequestCoordinator requestCoordinator) {
return GenericRequest.obtain(
loadProvider,
model,
signature,
context,
priority,
target,
sizeMultiplier,
placeholderDrawable,
placeholderId,
errorPlaceholder,
errorId,
fallbackDrawable,
fallbackResource,
requestListener,
requestCoordinator,
glide.getEngine(),
transformation,
transcodeClass,
isCacheable,
animationFactory,
overrideWidth,
overrideHeight,
diskCacheStrategy);
}
这个方法中只做了一件事,调用了GenericRequest 类的静态方法obtain() ,并且传入了很多的参数,这里注意其中的参数target ,即上面的GlideDrawableImageViewTarget 对象,另外还有就是这里执行了Glide 中的getEngine() 方法,还有资源模型model 。然后继续往下看:1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
public static <A, T, Z, R> GenericRequest<A, T, Z, R> obtain (
LoadProvider<A, T, Z, R> loadProvider,
A model,
Key signature,
Context context,
Priority priority,
Target<R> target,
float sizeMultiplier,
Drawable placeholderDrawable,
int placeholderResourceId,
Drawable errorDrawable,
int errorResourceId,
Drawable fallbackDrawable,
int fallbackResourceId,
RequestListener<? super A, R> requestListener,
RequestCoordinator requestCoordinator,
Engine engine,
Transformation<Z> transformation,
Class<R> transcodeClass,
boolean isMemoryCacheable,
GlideAnimationFactory<R> animationFactory,
int overrideWidth,
int overrideHeight,
DiskCacheStrategy diskCacheStrategy) {
@SuppressWarnings ("unchecked" )
GenericRequest<A, T, Z, R> request = (GenericRequest<A, T, Z, R>) REQUEST_POOL.poll();
if (request == null ) {
request = new GenericRequest<A, T, Z, R>();
}
request.init(loadProvider,
model,
signature,
context,
priority,
target,
sizeMultiplier,
placeholderDrawable,
placeholderResourceId,
errorDrawable,
errorResourceId,
fallbackDrawable,
fallbackResourceId,
requestListener,
requestCoordinator,
engine,
transformation,
transcodeClass,
isMemoryCacheable,
animationFactory,
overrideWidth,
overrideHeight,
diskCacheStrategy);
return request;
}
这一段看上去有点长,但是其实也只涉及到了一个方法init() ,这个方法同样接受了很多参数,并且在这个方法中,做的也只有一件事,就是将这些传入的参数一一赋值给GenericRequest 的成员变量:1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
private void init (
LoadProvider<A, T, Z, R> loadProvider,
A model,
Key signature,
Context context,
Priority priority,
Target<R> target,
float sizeMultiplier,
Drawable placeholderDrawable,
int placeholderResourceId,
Drawable errorDrawable,
int errorResourceId,
Drawable fallbackDrawable,
int fallbackResourceId,
RequestListener<? super A, R> requestListener,
RequestCoordinator requestCoordinator,
Engine engine,
Transformation<Z> transformation,
Class<R> transcodeClass,
boolean isMemoryCacheable,
GlideAnimationFactory<R> animationFactory,
int overrideWidth,
int overrideHeight,
DiskCacheStrategy diskCacheStrategy) {
this .loadProvider = loadProvider;
this .model = model;
this .signature = signature;
this .fallbackDrawable = fallbackDrawable;
this .fallbackResourceId = fallbackResourceId;
this .context = context.getApplicationContext();
this .priority = priority;
this .target = target;
this .sizeMultiplier = sizeMultiplier;
this .placeholderDrawable = placeholderDrawable;
this .placeholderResourceId = placeholderResourceId;
this .errorDrawable = errorDrawable;
this .errorResourceId = errorResourceId;
this .requestListener = requestListener;
this .requestCoordinator = requestCoordinator;
this .engine = engine;
this .transformation = transformation;
this .transcodeClass = transcodeClass;
this .isMemoryCacheable = isMemoryCacheable;
this .animationFactory = animationFactory;
this .overrideWidth = overrideWidth;
this .overrideHeight = overrideHeight;
this .diskCacheStrategy = diskCacheStrategy;
status = Status.PENDING;
......
}
到这里对于加载请求的设置几本完成,我们再回去看看那句运行加载的代码requestTracker.runRequest(request); 所做的具体的事情:1
2
3
4
5
6
7
8
public void runRequest (Request request) {
......
if (!isPaused) {
request.begin();
} else {
......
}
}
这里调用了刚刚设置好的Request 对象的begin() 方法,而这里的Request 对象的实际类型就是上面我们所看到的GenericRequest 对象。于是,我们来看看它的begin() 方法:1
2
3
4
5
6
7
public void begin () {
......
if (!isComplete() && !isFailed() && canNotifyStatusChanged()) {
target.onLoadStarted(getPlaceholderDrawable());
}
......
}
这里我们需要关注的就是一个Target 对象的onLoadStarted() 方法,在这里我们记起这个Target 对象的实际类型就是上面的init() 方法中所设置的GlideDrawableImageViewTarget 对象。也许你会认为这个begin() 方法就是资源加载进ImageView 的关键,但是当我们点进去查看它的begin() 方法时却发现并不如我们所想,它只是为我们的ImageView 设置了一个占位图,并没有做其他的事情。但是我们在查看GlideDrawableImageViewTarget 的源码的时候,我们发现了这么一个方法onResourceReady() ,在这个方法中有这么一句代码:
接着看看setResource() :1
2
3
public void setResource (GlideDrawable resource) {
view.setImageDrawable(resource);
}
这里的resource我们猜应该就是图片资源了,也会是说这里所做的事情就是最后将图片呈现在ImageView 上,但程序究竟是怎么到这里的呢,我们想到了上面的getEngine() 方法,于是我们来看看这里所做的事情:1
2
3
Engine getEngine () {
return engine;
}
这个Engine 又是一个非常重要的类,我们来看看这个类的官方介绍:Responsible for starting loads and managing active and cached resources. 我们发现这个类就是真正用来管理加载的类。但是这个不是我这篇文章的重点,关于它所作的事情我会在后面的文章中对它进行简析。既然这个Engine 对象是用来加载资源的,那么我们就想到了一开始的那个上面另外一个要记住的model ,看看它们是怎么运用的。要想知道这到底是怎么使用的,我在这里贴出最重要的一段:1
2
3
private void onLoadComplete (Resource resource) {
manager.onResourceReady(resource);
}
这个方法是EngineRunnable 类中的,这个类从名字就可以看出来它的作用就是响应Engine 的。而这里的onResourceReady() 则是触发了GenericRequest 中的一个回调onResourceReady() :1
2
3
4
public void onResourceReady (Resource<?> resource) {
......
onResourceReady(resource, (R) received);
}
这里又调用了该类中的一个重载方法:1
2
3
4
5
6
7
8
9
private void onResourceReady (Resource<?> resource, R result) {
......
if (requestListener == null || !requestListener.onResourceReady(result, model, target, loadedFromMemoryCache,
isFirstResource)) {
......
}
notifyLoadSuccess();
......
}
这里我们看到了,这个方法使用到了model ,而这个方法则属于一个RequestListener 回调接口,这个回调接口究竟会在哪里被调用呢,其实就是我们上面提到的GlideDrawableImageViewTarget 的onResourceReady() ,而在这个方法中,另一个参数target 在这里的实际类型就是GlideDrawableImageViewTarget 。到这里我们终于是弄明白整个图片资源的加载过程了。
至此Glide加载图片的调用链大致是搞明白了,里面涉及了大量的设计模式,因此十分复杂,但是原理很简单易懂,理清楚之后便十分清晰明了。