您的位置:首页 > 移动开发 > Android开发

胖虎谈ImageLoader框架(二)

2015-11-26 11:21 465 查看

前言

从学校出来的这半年时间,发现很少有时间可以静下来学习和写博文了,为了保持着学习和分享的习惯,我准备之后每周抽出一部分时间为大家带来一个优秀的Android框架源码阅读后的理解系列博文。

期许:希望可以和大家一起学习好此框架,也希望大家看博文前最好是先了解下框架的基本使用场景和使用方法,有什么问题可以留言给我,交流学习。

当然,再好的博文,也不如自己看一遍源码!

这周为大家带来的是《胖虎谈ImageLoader框架》系列,分析优秀的框架源码能让我们更迅速地提升,大家共勉!!

源码包下载地址:http://download.csdn.net/detail/u011133213/9210765

希望我们尊重每个人的成果,转载请注明出处。

转载于:CSDN 胖虎 , http://blog.csdn.net/ljphhj

正文

继上篇博文《胖虎谈ImageLoader框架(一)》 带来这篇《胖虎谈ImageLoader框架(二)》,上篇我们简单梳理了一下ImageLoader的3个步骤来异步加载图片,今天我们来详细看一下ImageLoader中加载图片的函数displayImage(…)和其中涉及到的一些ImageLoader框架带给我们的知识点。

(ps:读此博文前,希望网友已经阅读并理解了《胖虎谈ImageLoader框架(一)》 再阅读此博文。)

public void displayImage(String uri, ImageAware imageAware,
DisplayImageOptions options, ImageLoadingListener listener,
ImageLoadingProgressListener progressListener) {
checkConfiguration();
if (imageAware == null) {
throw new IllegalArgumentException(ERROR_WRONG_ARGUMENTS);
}
if (listener == null) {
listener = defaultListener;
}
if (options == null) {
options = configuration.defaultDisplayImageOptions;
}

if (TextUtils.isEmpty(uri)) {
engine.cancelDisplayTaskFor(imageAware);
listener.onLoadingStarted(uri, imageAware.getWrappedView());
if (options.shouldShowImageForEmptyUri()) {
imageAware.setImageDrawable(options
.getImageForEmptyUri(configuration.resources));
} else {
imageAware.setImageDrawable(null);
}
listener.onLoadingComplete(uri, imageAware.getWrappedView(), null);
return;
}

ImageSize targetSize = ImageSizeUtils.defineTargetSizeForView(
imageAware, configuration.getMaxImageSize());
String memoryCacheKey = MemoryCacheUtils.generateKey(uri, targetSize);
engine.prepareDisplayTaskFor(imageAware, memoryCacheKey);

listener.onLoadingStarted(uri, imageAware.getWrappedView());

Bitmap bmp = configuration.memoryCache.get(memoryCacheKey);
if (bmp != null && !bmp.isRecycled()) {
L.d(LOG_LOAD_IMAGE_FROM_MEMORY_CACHE, memoryCacheKey);

if (options.shouldPostProcess()) {
ImageLoadingInfo imageLoadingInfo = new ImageLoadingInfo(uri,
imageAware, targetSize, memoryCacheKey, options,
listener, progressListener, engine.getLockForUri(uri));
ProcessAndDisplayImageTask displayTask = new ProcessAndDisplayImageTask(
engine, bmp, imageLoadingInfo, defineHandler(options));
if (options.isSyncLoading()) {
displayTask.run();
} else {
engine.submit(displayTask);
}
} else {
options.getDisplayer().display(bmp, imageAware,
LoadedFrom.MEMORY_CACHE);
listener.onLoadingComplete(uri, imageAware.getWrappedView(),
bmp);
}
} else {
if (options.shouldShowImageOnLoading()) {
imageAware.setImageDrawable(options
.getImageOnLoading(configuration.resources));
} else if (options.isResetViewBeforeLoading()) {
imageAware.setImageDrawable(null);
}

ImageLoadingInfo imageLoadingInfo = new ImageLoadingInfo(uri,
imageAware, targetSize, memoryCacheKey, options, listener,
progressListener, engine.getLockForUri(uri));
LoadAndDisplayImageTask displayTask = new LoadAndDisplayImageTask(
engine, imageLoadingInfo, defineHandler(options));
if (options.isSyncLoading()) {
displayTask.run();
} else {
engine.submit(displayTask);
}
}
}


1、我们分析下函数的这几个参数:

1.1 String uri : URI,如果是网络图片(http://、https:// ),本地图片(file:// ),ContentProvider访问的(content:// ),app的Assets目录下(assets:// ),app的Drawable目录下(drawable:// )

1.2 ImageAware imageAware :

ImageView的包装类接口,实现该接口的类有:ViewAware、NonViewAware[这个为了防止加载同样的URI只回调一次而设计]

主要这边涉及到的都是ViewAware这个类:该类中中将ImageView包装放入一个WeakReference对象中,(插播一下弱引用的知识:当一个对象仅仅被WeakReference指向, 而没有任何其他StrongReference指向的时候, 如果GC运行, 那么这个对象就会被回收., 所以这样设计,ImageView就有可能会被GC回收),因此如果弱引用viewRef.get() == null, 就可以表示这个ImageView已经被GC回收了(对应的函数: ViewAware.isCollected())

ImageLoader框架的设计者考虑到了当用户要加载图片前,加载图片完成到要显示前,可能这两个时间点ImageView都已经被GC回收了,如果被回收了,这两个动作就没有必要进行了。

1.3 DisplayImageOptions options :

此类中包括的一些重要参数,系列博文第一篇中已经讲过,这边如果指定了该参数,会调用指定的来显示,或者调用之前init(…)进来的配置。

1.4ImageLoadingListener listener:

此类为加载图片的各种情况的回调监听类:onLoadingStarted, onLoadingFailed, onLoadingComplete, onLoadingCancelled

1.5 ImageLoadingProgressListener progressListener

此类为加载图片进度回调监听类:onProgressUpdate(String imageUri, View view, int current, int total) 可以用来显示某个图片加载的进度情况

2、我们分析对应代码行:

2.1 第4行 checkConfiguration() , 判断了ImageLoaderConfiguration成员变量是否被赋值,没被赋值即没调用init(….),抛异常出去,不允许继续往下执行。

private void checkConfiguration() {
if (configuration == null) {
throw new IllegalStateException(ERROR_NOT_INIT);
}
}


2.2 第5-14行,都是为了保证参数有被正常赋值。

if (imageAware == null) {
throw new IllegalArgumentException(ERROR_WRONG_ARGUMENTS);
}
if (listener == null) {
listener = defaultListener;
}
if (options == null) {
options = configuration.defaultDisplayImageOptions;
}


2.3 第15-27行,实际上只做了两件事,第一件事:如果是imageview的重用,现在imageview对应的uri已经为空了,那么之前未重用前的那个加载图片task,便可以从ImageLoaderEngine中取消掉了(如果还存在该task的话), 第二件事:如果开发者有设定Uri为空时要显示某张图片的话,将该图片显示到ImageView上。

if (TextUtils.isEmpty(uri)) {
engine.cancelDisplayTaskFor(imageAware);
listener.onLoadingStarted(uri, imageAware.getWrappedView());
if (options.shouldShowImageForEmptyUri()) {
imageAware.setImageDrawable(
options.getImageForEmptyUri(configuration.resources));
} else {
imageAware.setImageDrawable(null);
}
listener.onLoadingComplete(uri, imageAware.getWrappedView(), null);
return;
}


// 一个线程安全的Map, 用于控制ImageView和Uri对应上.
// key: ImageView的id,
// value: 图片Uri_WxH)
private final Map<Integer, String> cacheKeysForImageAwares
= Collections.synchronizedMap(new HashMap<Integer, String>());

void cancelDisplayTaskFor(ImageAware imageAware) {
cacheKeysForImageAwares.remove(imageAware.getId());
}


2.4 第28-30行,获取了图片的大小(就是控件大小,如果控件大小小于屏幕大小,或者以屏幕大小为该ImageSize的大小),之后通过Uri和ImageSize,生成对应的Key值 (图片Uri_WxH),以便下面在内存缓存中查询此Key对应的Bitmap是否存在。

ImageSize targetSize = ImageSizeUtils.defineTargetSizeForView(
imageAware, configuration.getMaxImageSize());
String memoryCacheKey = MemoryCacheUtils.generateKey(uri, targetSize);


public static ImageSize defineTargetSizeForView(ImageAware imageAware, ImageSize maxImageSize) {
int width = imageAware.getWidth();
if (width <= 0) width = maxImageSize.getWidth();

int height = imageAware.getHeight();
if (height <= 0) height = maxImageSize.getHeight();

return new ImageSize(width, height);
}


public static String generateKey(String imageUri, ImageSize targetSize) {
return new StringBuilder(imageUri).append("_").
append(targetSize.getWidth()).append("x").
append(targetSize.getHeight()).toString();
}


2.5 第31行,engine.prepareDisplayTaskFor(imageAware, memoryCacheKey); 这行代码看似不重要,其实很重要,大家都像ListView或者GridView等这些控件加载Adapter的,滑动时很重要的一个知识就是View重用,那么有可能当你这个ImageView要被另一张图片(另一个Uri)使用时,前面那个加载任务还没开始执行,那么那个任务怎么知道是否被重用了呢?

ImageLoader维护了一个cacheKeysForImageAwares的线程安全的HashMap,当加载图片任务要做一些加载时会去调用checkViewReused()方法去看当前要加载图片的那个ImageView匹配的是否是当前的这张图片Uri,如果不是,那么便不需要再继续往下执行这个任务了。

void prepareDisplayTaskFor(ImageAware imageAware, String memoryCacheKey) {
cacheKeysForImageAwares.put(imageAware.getId(), memoryCacheKey);
}


/** @throws TaskCancelledException if target ImageAware is collected by GC */
private void checkViewReused() throws TaskCancelledException {
if (isViewReused()) {
throw new TaskCancelledException();
}
}

/** @return <b>true</b> - if current ImageAware is reused for displaying another image; <b>false</b> - otherwise */
private boolean isViewReused() {
String currentCacheKey = engine.getLoadingUriForView(imageAware);
// Check whether memory cache key (image URI) for current ImageAware is actual.
// If ImageAware is reused for another task then current task should be cancelled.
boolean imageAwareWasReused = !memoryCacheKey.equals(currentCacheKey);
if (imageAwareWasReused) {
L.d(LOG_TASK_CANCELLED_IMAGEAWARE_REUSED, memoryCacheKey);
return true;
}
return false;
}


2.6 第35-56行,主要是从内存缓存里面获取该Key值(图片Uri_WxH) 对应的Bitmap, 判断Bitmap是否存在, 如果options.shouldPostProcess(), 即上篇博文说到的,开发者设置了该值为true,表示需要在图片加载入内存中(已存在于内存中的也算这种情况),做一些额外的Process操作,这样就要开一个Task任务来执行了,执行完了再显示出图片来【ProcessAndDisplayImageTask(看源码)】。否则就直接调用开发者设置的BitmapDisplayer的对象(默认为SimpleBitmapDisplayer)显示出图片。

2.6提到的这个处理任务,看源码:ProcessAndDisplayImageTask

if (bmp != null && !bmp.isRecycled()) {
L.d(LOG_LOAD_IMAGE_FROM_MEMORY_CACHE, memoryCacheKey);

if (options.shouldPostProcess()) {
ImageLoadingInfo imageLoadingInfo = new ImageLoadingInfo(uri,
imageAware, targetSize, memoryCacheKey, options,
listener, progressListener, engine.getLockForUri(uri));
ProcessAndDisplayImageTask displayTask = new ProcessAndDisplayImageTask(
engine, bmp, imageLoadingInfo, defineHandler(options));
if (options.isSyncLoading()) {
displayTask.run();
} else {
engine.submit(displayTask);
}
} else {
options.getDisplayer().display(bmp, imageAware,
LoadedFrom.MEMORY_CACHE);
listener.onLoadingComplete(uri, imageAware.getWrappedView(),
bmp);
}
}


2.7 第57-73行,整个ImageLoader真正调用的入口,大部分都在这几行代码中体现了。前面几行是看是否需要为加载中的图片设置一个加载中的图片,和是否需要重置ImageView。接着是一个实体类(ImageLoadingInfo),把之后LoadAndDisplayImageTask需要用到的一些信息封装进去,接着将LoadAndDisplayImageTask任务submit到ImageLoaderEngine中(这边提的只考虑异步的情况,如果Sync同步的情况就执行执行这个Task)[PS: 具体的Task类,下一篇博文会介绍]

if (options.shouldShowImageOnLoading()) {
imageAware.setImageDrawable(options
.getImageOnLoading(configuration.resources));
} else if (options.isResetViewBeforeLoading()) {
imageAware.setImageDrawable(null);
}

ImageLoadingInfo imageLoadingInfo = new ImageLoadingInfo(uri,imageAware, targetSize,
memoryCacheKey, options, listener,progressListener, engine.getLockForUri(uri));
LoadAndDisplayImageTask displayTask = new LoadAndDisplayImageTask(
engine, imageLoadingInfo, defineHandler(options));
if (options.isSyncLoading()) {
displayTask.run();
} else {
engine.submit(displayTask);
}


总结

其实这篇博文旨在将ImageLoader的主干入口displayImage中的一些代码行做一些解析,我不太擅于通过文字将这些东西讲得很透彻,还是那句话“要想学会框架,最终还是要自己去看看源码”,此博文中提到了几个类,我觉得都需要大家自己去看看。

(LoadAndDisplayImageTask (这个类非常重要,你需要了解该类中waitIfPaused函数,checkTaskNotActual函数,checkTaskInterrupted函数,和整个run函数是怎么运作的),

ImageLoaderEngine(你需要了解该类中包含的3个线程池各自的作用),

ProcessAndDisplayImageTask,

BitmapDisplayer,[3个子类: FadeInBitmapDisplayer、RoundedBitmapDisplayer、SimpleBitmapDisplayer]

ImageSizeUtils,[这个工具类还不错]

MemoryCacheUtils,

ImageSize)

[类的先后顺序为优先级高低,高->低]
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息