这篇文章将会为大家梳理一下Glide3.5版本的基本流程,为了方便阅读,文章中的源码部分将省略部分有关异常捕获与日志相关代码。
使用示例
首先依照惯例,先来一个最简单的例子:
Glide.with(context).load(path).into(imageView);
非常简洁的一句代码,下面我们按照这个调用的流程一步步的来进行分析。
1.Glide.with(Context context)
public static RequestManager with(Context context) {
RequestManagerRetriever retriever = RequestManagerRetriever.get();
return retriever.get(context);
}
这个方法很好理解,其中RequestManagerRetriever.get()方法的作用为获得RequestManagerRetriever的单例对象,然后调用其中的get方法获得RequestManager对象。
其中RequestManager类实现了LifecycleListener接口,主要作用是根据Fragment或Activity的生命周期来调用onStart,onStop,onDestroy方法,以此控制请求的开启,停止与重启。
RequestManagerRetriever.get(Context context)
RequestManagerRetriever中,get方法的数量很多但是逻辑上都是大同小异,先放上代码:
//下面会省略部分异常判断的代码
public RequestManager get(Context context) {
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) {
//获取ContextWrapper中的mBase并作为参数重新调用该方法
return get(((ContextWrapper) context).getBaseContext());
}
}
return getApplicationManager(context);
}
public RequestManager get(FragmentActivity activity) {
if (Util.isOnBackgroundThread()) {
return get(activity.getApplicationContext());
} else {
FragmentManager fm = activity.getSupportFragmentManager();
return supportFragmentGet(activity, fm);
}
}
//该方法会在Glide.with(Fragment)方法中调用
public RequestManager get(Fragment fragment) {
if (Util.isOnBackgroundThread()) {
return get(fragment.getActivity().getApplicationContext());
} else {
FragmentManager fm = fragment.getChildFragmentManager();
return supportFragmentGet(fragment.getActivity(), fm);
}
}
@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 {
android.app.FragmentManager fm = activity.getFragmentManager();
return fragmentGet(activity, fm);
}
}
@TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR1)
public RequestManager get(android.app.Fragment fragment) {
if (Util.isOnBackgroundThread() || Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN_MR1) {
return get(fragment.getActivity().getApplicationContext());
} else {
android.app.FragmentManager fm = fragment.getChildFragmentManager();
return fragmentGet(fragment.getActivity(), fm);
}
}
在上述方法中可以看到,这些方法的作用为根据传入的Context类型的不同调用不同方法构造不同的RequestManager对象。
需要注意的是:其中如果传入的Context为Application或该方法不在主线程中执行,则会返回Application级别的RequestManager单例对象,也就是说图片的加载不会与Activity或Fragment的生命周期绑定。
RequestManagerRetriever.supportFragmentGet(Context context, FragmentManager fm)
RequestManagerRetriever.fragmentGet(Context context, android.app.FragmentManager fm)
RequestManagerRetriever.getApplicationManager(Context context)
由于这三个方法可以归到一类里,所以就在这里一起分析
private RequestManager getApplicationManager(Context context) {
//返回applicationManager的单例对象
if (applicationManager == null) {
synchronized (this) {
if (applicationManager == null) {
applicationManager = new RequestManager(context.getApplicationContext(),
new ApplicationLifecycle(), new EmptyRequestManagerTreeNode());
}
}
}
return applicationManager;
}
RequestManager fragmentGet(Context context, android.app.FragmentManager fm) {
//RequestManagerFragment这个类与下面的SupportRequestManagerFragment类似,都是一个包含了ActivityFragmentLifecycle的对象且不可见的Fragment
RequestManagerFragment current = getRequestManagerFragment(fm);
RequestManager requestManager = current.getRequestManager();
if (requestManager == null) {
requestManager = new RequestManager(context, current.getLifecycle(), current.getRequestManagerTreeNode());
current.setRequestManager(requestManager);
}
return requestManager;
}
RequestManager supportFragmentGet(Context context, FragmentManager fm) {
SupportRequestManagerFragment current = getSupportRequestManagerFragment(fm);
RequestManager requestManager = current.getRequestManager();
if (requestManager == null) {
requestManager = new RequestManager(context, current.getLifecycle(), current.getRequestManagerTreeNode());
current.setRequestManager(requestManager);
}
return requestManager;
}
上面这部分就是Glide能够绑定生命周期的关键代码了,通过上述代码可以发现,Glide中会在Activity或Fragment中添加一个不可见的Fragment,这个Fragment对象中会持有Lifecycle的对象。因为Activity与其内部的Fragment的生命周期是绑定的,所以在Activity执行生命周期的方法时,Glide中对应的Fragment也会进行相应的生命周期,这样就相当于实现了对Activity生命周期的监听。
还有其中的RequestManagerTreeNode类,可以通过这个类获取到RequestManagerFragment对象下属的所有子RequestManagerFragment以达到统一控制其生命周期的效果。
2.RequestManager.load(T model)
public <T> DrawableTypeRequest<T> load(T model) {
return (DrawableTypeRequest<T>) loadGeneric(getSafeClass(model)).load(model);
}
这个方法也只有短短的一行,其中getSafeClass(T model)方法作用是返回传入参数的Class对象,下文就不再赘述了
RequestManager.loadGeneric(Class<T> modelClass)
private <T> DrawableTypeRequest<T> loadGeneric(Class<T> modelClass) {
//获取ModelLoader对象,用于将传入的数据转换为可以解码的另一种类型
ModelLoader<T, InputStream> streamModelLoader = Glide.buildStreamModelLoader(modelClass, context);
ModelLoader<T, ParcelFileDescriptor> fileDescriptorModelLoader =
Glide.buildFileDescriptorModelLoader(modelClass, context);
//apply方法为使用类型为DefaultOptions的options对DrawableTypeRequest对象进行预处理
//在默认设置下,options为null,即该方法不做任何处理
return optionsApplier.apply(
//DrawableTypeRequest为图片加载的请求类,与图片的加载相关的配置都是由这个类来完成的
//如图片的显示位置,占位图,图片加载的优先级等等
new DrawableTypeRequest<T>(modelClass, streamModelLoader, fileDescriptorModelLoader, context,
glide, requestTracker, lifecycle, optionsApplier));
}
DrawableTypeRequest.load(T model)
//DrawableTypeRequest.load(T model)
public DrawableRequestBuilder<T> load(ModelType model) {
super.load(model);
return this;
}
//GenericRequestBuilder.load(T model)
public DrawableRequestBuilder<T> load(T model) {
super.load(model);
return this;
}
//GenericRequestBuilder.load(T model)
public GenericRequestBuilder<ModelType, DataType, ResourceType, TranscodeType> load(ModelType model) {
this.model = model;
isModelSet = true;
return this;
}
通过代码可以看到,虽然该方法名字叫做load,但是方法中只是将传入的model保存了下来,而真正的加载,则是在into()方法中进行的。
3.DrawableRequestBuilder.into(ImageView view)
//DrawableRequestBuilder.into(ImageView view)
public Target<GlideDrawable> into(ImageView view) {
return super.into(view);
}
//GenericRequestBuilder.into(ImageView view)
//下面将省略部分异常捕获代码
public Target<TranscodeType> into(ImageView view) {
if (!isTransformationSet && view.getScaleType() != null) {
//针对不同的图片展示方式进行处理,由子类DrawableRequestBuilder进行具体实现
switch (view.getScaleType()) {
case CENTER_CROP:
applyCenterCrop();
break;
case FIT_CENTER:
case FIT_START:
case FIT_END:
applyFitCenter();
break;
}
}
return into(glide.buildImageViewTarget(view, transcodeClass));
}
Glide.buildImageViewTarget(ImageView imageView, Class<R> transcodedClass)
//Glide.buildImageViewTarget(ImageView imageView, Class<R> transcodedClass)
<R> Target<R> buildImageViewTarget(ImageView imageView, Class<R> transcodedClass) {
return imageViewTargetFactory.buildTarget(imageView, transcodedClass);
}
//ImageViewTargetFactory.buildTarget(ImageView view, Class<Z> clazz)
public <Z> Target<Z> buildTarget(ImageView view, Class<Z> clazz) {
//根据传入的class对象决定Target的类型,默认情况下为GlideDrawable
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);
}
}
上述代码中出现的三个Target类负责将加载出的图片在ImageView中展示出来,并且由于Target类继承LifecycleListener接口,可以看出也正是Target类负责执行对于其所绑定的Activity或Fragment的生命周期的监听。
GenericRequestBuilder.into(T target)
//省略部分异常捕获代码
public <Y extends Target<TranscodeType>> Y into(Y target) {
Request previous = target.getRequest();
//如果Taget中已存在Request请求,将其清除
if (previous != null) {
previous.clear();
requestTracker.removeRequest(previous);
previous.recycle();
}
//构建新的Request对象并放入Target中
Request request = buildRequest(target);
target.setRequest(request);
//添加生命周期监听
lifecycle.addListener(target);
//开始请求
//requestTracker负责追踪并控制Request的状态,如cancel,restart
requestTracker.runRequest(request);
return target;
}
经过前面漫长的准备工作,终于在这个方法中正式开始了图片的请求。
RequestTracker.runRequest(Request request)
//RequestTracker.runRequest(Request request)
public void runRequest(Request request) {
//将request加入队列
requests.add(request);
if (!isPaused) {
//开始执行请求
request.begin();
} else {
//如果RequestTracker为暂停状态,将request加入等待队列
pendingRequests.add(request);
}
}
GenericRequest.begin()
public void begin() {
startTime = LogTime.getLogTime();
status = Status.WAITING_FOR_SIZE;
//如果没有为图片设置尺寸,则使用控件尺寸作为图片尺寸
if (Util.isValidDimensions(overrideWidth, overrideHeight)) {
onSizeReady(overrideWidth, overrideHeight);
} else {
//在获取到控件的宽高时,调用onSizeReady方法回调
target.getSize(this);
}
if (!isComplete() && !isFailed() && canNotifyStatusChanged()) {
//在控件中放入占位图
target.onLoadStarted(getPlaceholderDrawable());
}
}
在target.getSize(this)这句语句中传入的回调方法,将在控件的ViewTreeObserver.OnPreDrawListener方法中,也就是控件即将绘制时调用。
GenericRequest.onSizeReady(int width, int height)
public void onSizeReady(int width, int height) {
if (status != Status.WAITING_FOR_SIZE) {
return;
}
status = Status.RUNNING;
//设置图片的缩放尺寸
width = Math.round(sizeMultiplier * width);
height = Math.round(sizeMultiplier * height);
ModelLoader<A, T> modelLoader = loadProvider.getModelLoader();
final DataFetcher<T> dataFetcher = modelLoader.getResourceFetcher(model, width, height);
//获取GifBitmapWrapperDrawableTranscoder,用于将加载出的Bitmap转换为Drawable
ResourceTranscoder<Z, R> transcoder = loadProvider.getTranscoder();
loadedFromMemoryCache = true;
//调用引擎加载图片
loadStatus = engine.load(signature, width, height, dataFetcher, loadProvider, transformation, transcoder,
priority, isMemoryCacheable, diskCacheStrategy, this);
loadedFromMemoryCache = resource != null;
}
Engine.load(Key signature, int width, int height, DataFetcher<T> fetcher,DataLoadProvider<T, Z> loadProvider, Transformation<Z> transformation, ResourceTranscoder<Z, R> transcoder,Priority priority, boolean isMemoryCacheable, DiskCacheStrategy diskCacheStrategy, ResourceCallback cb)
public <T, Z, R> LoadStatus load(Key signature, int width, int height, DataFetcher<T> fetcher,
DataLoadProvider<T, Z> loadProvider, Transformation<Z> transformation, ResourceTranscoder<Z, R> transcoder,
Priority priority, boolean isMemoryCacheable, DiskCacheStrategy diskCacheStrategy, ResourceCallback cb) {
final String id = fetcher.getId();
//获取图片所对应的key
EngineKey key = keyFactory.buildKey(id, signature, width, height, loadProvider.getCacheDecoder(),
loadProvider.getSourceDecoder(), transformation, loadProvider.getEncoder(),
transcoder, loadProvider.getSourceEncoder());
//判断图片是否已存在于一级Lru缓存中
EngineResource<?> cached = loadFromCache(key, isMemoryCacheable);
if (cached != null) {
cb.onResourceReady(cached);
return null;
}
//判断图片是否存在于Active缓存中
EngineResource<?> active = loadFromActiveResources(key, isMemoryCacheable);
if (active != null) {
cb.onResourceReady(active);
return null;
}
//判断是否有相同的图片正在加载
//jobs为一个Map,用以记录有哪些图片加载的请求正在进行
EngineJob current = jobs.get(key);
if (current != null) {
current.addCallback(cb);
return new LoadStatus(cb, current);
}
//EngineJob对象负责图片的加载与在加载请求完成或被取消时执行相应的回调
EngineJob engineJob = engineJobFactory.build(key, isMemoryCacheable);
//DecodeJob负责对请求返回的数据进行解码
DecodeJob<T, Z, R> decodeJob = new DecodeJob<T, Z, R>(key, width, height, fetcher, loadProvider, transformation,
transcoder, diskCacheProvider, diskCacheStrategy, priority);
EngineRunnable runnable = new EngineRunnable(engineJob, decodeJob, priority);
jobs.put(key, engineJob);
engineJob.addCallback(cb);
//将会开启新线程来执行runnable中的run方法开始加载图片
engineJob.start(runnable);
return new LoadStatus(cb, engineJob);
}
其中可以发现Glide中使用了二级的内存缓存,其中第一级为LRU缓存(最近最少使用),第二级为Active缓存,如果一张图片在LRU缓存中已经不存在了,但是依然在其他地方被使用着,那么就会去直接使用那一张图片。
EngineRunnable.run()
public void run() {
if (isCancelled) {
return;
}
Exception exception = null;
Resource<?> resource = null;
try {
//该方法执行加载任务
resource = decode();
} catch (Exception e) {
exception = e;
}
if (isCancelled) {
if (resource != null) {
resource.recycle();
}
return;
}
//根据加载返回的结果调用相应回调方法
if (resource == null) {
//如果从DISK缓存中加载数据失败,则修改缓存标记并重新执行,如果由数据源加载失败,则执行onException回调
onLoadFailed(exception);
} else {
onLoadComplete(resource);
}
}
EngineRunnable.decode()
private Resource<?> decode() throws Exception {
if (isDecodingFromCache()) {
//由缓存加载数据
return decodeFromCache();
} else {
//由数据源加载数据
return decodeFromSource();
}
}
private Resource<?> decodeFromCache() throws Exception {
Resource<?> result = null;
try {
//判断转换后的图片缓存是否存在
result = decodeJob.decodeResultFromCache();
} catch (Exception e) {
if (Log.isLoggable(TAG, Log.DEBUG)) {
Log.d(TAG, "Exception decoding result from cache: " + e);
}
}
if (result == null) {
//判断原图缓存是否存在
result = decodeJob.decodeSourceFromCache();
}
return result;
}
private Resource<?> decodeFromSource() throws Exception {
return decodeJob.decodeFromSource();
}
在上面的decodeFromCache方法中,就是Glide缓存策略的第二层,也就是磁盘缓存,而磁盘缓存又分为两种,一是由源地址所获取的图片原文件,二是经过转换后的图片文件。Glide一大特点即为能够根据控件大小的不同对图片尺寸进行处理后再加载,而这处理后的图片文件也会被保存入缓存中,而且在图片加载时优先级会更高于原图。
而且由上面的代码能看出,不论是由缓存加载,还是由数据源加载,实际都是交由DecodeJob来进行处理的。
DecodeJob.decodeFromSource()
public Resource<Z> decodeFromSource() throws Exception {
//由数据源获取源数据并进行解码
Resource<T> decoded = decodeSource();
return transformEncodeAndTranscode(decoded);
}
DecodeJob.decodeSource()
private Resource<T> decodeSource() throws Exception {
Resource<T> decoded = null;
try {
//从数据源加载图片
final A data = fetcher.loadData(priority);
if (isCancelled) {
return null;
}
//将由数据源加载的数据进行解码
decoded = decodeFromSourceData(data);
} finally {
fetcher.cleanup();
}
return decoded;
}
DecodeJob.decodeFromSourceData(A data)
//如果缓存策略为磁盘缓存,则会先将图片加载至磁盘缓存中,再由磁盘缓存中取出使用
private Resource<T> decodeFromSourceData(A data) throws IOException {
final Resource<T> decoded;
if (diskCacheStrategy.cacheSource()) {
decoded = cacheAndDecodeSourceData(data);
} else {
//使用loadProvider对源数据进行解码
decoded = loadProvider.getSourceDecoder().decode(data, width, height);
}
return decoded;
}
DecodeJob.transformEncodeAndTranscode(Resource<T> decoded)
private Resource<Z> transformEncodeAndTranscode(Resource<T> decoded) {
//对获取的图片进行尺寸等转换,如生成适配控件的尺寸的图片等
Resource<T> transformed = transform(decoded);
//将转换后的图片写入缓存
writeTransformedToCache(transformed);
//对图片进行类型转换,如将Bitmap转换为Drawable
Resource<Z> result = transcode(transformed);
return result;
}
在该方法在返回成功后,会将其作为参数调用onLoadComplete方法。
EngineRunnable.onLoadComplete(Resource resource)
//EngineRunnable.onLoadComplete
private void onLoadComplete(Resource resource) {
manager.onResourceReady(resource);
}
//EngineJob.onResourceReady
public void onResourceReady(final Resource<?> resource) {
this.resource = resource;
//通过handler将加载出的resource发送给主线程的MAIN_THREAD_HANDLER处理
MAIN_THREAD_HANDLER.obtainMessage(MSG_COMPLETE, this).sendToTarget();
}
//EngineJob.MAIN_THREAD_HANDLER
private static final Handler MAIN_THREAD_HANDLER = new Handler(Looper.getMainLooper(), new MainThreadCallback());
//EngineJob.MainThreadCallback
private static class MainThreadCallback implements Handler.Callback {
@Override
public boolean handleMessage(Message message) {
if (MSG_COMPLETE == message.what || MSG_EXCEPTION == message.what) {
EngineJob job = (EngineJob) message.obj;
if (MSG_COMPLETE == message.what) {
job.handleResultOnMainThread();
} else {
job.handleExceptionOnMainThread();
}
return true;
}
return false;
}
}
//EngineJob.handleResultOnMainThread
private void handleResultOnMainThread() {
if (isCancelled) {
resource.recycle();
return;
}
//EngineResource为Resource的包装类,添加了查看这个对象被引用次数的功能
engineResource = engineResourceFactory.build(resource, isCacheable);
hasResource = true;
engineResource.acquire();
//将图片存入active缓存
listener.onEngineJobComplete(key, engineResource);
for (ResourceCallback cb : cbs) {
if (!isInIgnoredCallbacks(cb)) {
engineResource.acquire();
//调用资源加载完成的回调方法
cb.onResourceReady(engineResource);
}
}
engineResource.release();
}
由于上面这几个方法的调用逻辑很清晰,所以就姑且写在一起了,上面的流程为onLoadComplete作为回调方法被调用,随后将传入的Resource参数使用Handler传给主线程处理,主线程根据message来调用加载成功或失败的方法。
GenericRequest.onResourceReady(Resource<?> resource, R result)
private void onResourceReady(Resource<?> resource, R result) {
boolean isFirstResource = isFirstReadyResource();
status = Status.COMPLETE;
this.resource = resource;
if (requestListener == null || !requestListener.onResourceReady(result, model, target, loadedFromMemoryCache,
isFirstResource)) {
GlideAnimation<R> animation = animationFactory.build(loadedFromMemoryCache, isFirstResource);
//开始加载动画并将图片放入控件中
target.onResourceReady(result, animation);
}
notifyLoadSuccess();
}
至这个方法为止,一个最简单的图片加载流程就算是基本结束了。
小结
本篇文章简单的梳理了Glide加载图片的基本流程,没有想到Glide如此简单易用的外表下,内部的逻辑竟然如此的复杂与庞大,不得不说,Glide源代码的复杂程度超出了我的预期,其中引入的抽象概念与泛型的大量使用也给阅读也带来了不小的困难,碍于本人水平有限,文章中难免有错误与疏漏之处,欢迎大家来批评指正。