Android-Universal-Image-Loader

官方使用介绍,参考
wiki

默认值

ImageLoaderConfiguration

全局显示选项

/* ImageLoader Configuration (ImageLoaderConfiguration) is global for application. You should set it once.
All options in Configuration builder are optional. Use only those you really want to customize.
See default values for config options in Java docs for every option.*/
// DON'T COPY THIS CODE TO YOUR PROJECT! This is just example of ALL options using.
// See the sample project how to use ImageLoader correctly.
File cacheDir = StorageUtils.getCacheDirectory(context);
ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(context).memoryCacheExtraOptions(480, 800) // default = device screen dimensions 图片内存缓存最大宽高,默认屏幕宽高.diskCacheExtraOptions(480, 800, null) //图片硬盘缓存最大宽高,默认屏幕宽高.taskExecutor(...).taskExecutorForCachedImages(...).threadPoolSize(3) // default.threadPriority(Thread.NORM_PRIORITY - 2) // default.tasksProcessingOrder(QueueProcessingType.FIFO) // default.denyCacheImageMultipleSizesInMemory() //默认可以内存缓存会缓存不同尺寸的同一个图片,此时使用的是FuzzyKeyMemoryCache,会使memoryCache设置无效.memoryCache(new LruMemoryCache(2 * 1024 * 1024)).memoryCacheSize(2 * 1024 * 1024).memoryCacheSizePercentage(13) // default:1/8 设置内存缓存占总内存的百分比,memoryCacheSize效果一样,使用一个就行.diskCache(new LruDiskCache(cacheDir)) // default.diskCacheSize(50 * 1024 * 1024).diskCacheFileCount(100) //硬盘缓存目录最大文件个数,默认无限制.diskCacheFileNameGenerator(new HashCodeFileNameGenerator()) // default.imageDownloader(new BaseImageDownloader(context)) // default.imageDecoder(new BaseImageDecoder()) // default.defaultDisplayImageOptions(DisplayImageOptions.createSimple()) // default.writeDebugLogs().build();

DisplayImageOptions

为每个任务设置显示选项,如果DisplayImageOptions为null,那么会使用ImageLoaderConfiguration.defaultDisplayImageOptions

/*Display Options (DisplayImageOptions) are local for every display task (ImageLoader.displayImage(...)).
Display Options can be applied to every display task (ImageLoader.displayImage(...) call).
Note: If Display Options wasn't passed to ImageLoader.displayImage(...)method then default Display Options from configuration (ImageLoaderConfiguration.defaultDisplayImageOptions(...)) will be used. */// DON'T COPY THIS CODE TO YOUR PROJECT! This is just example of ALL options using.
// See the sample project how to use ImageLoader correctly.
DisplayImageOptions options = new DisplayImageOptions.Builder().showImageOnLoading(R.drawable.ic_stub) // resource or drawable.showImageForEmptyUri(R.drawable.ic_empty) // resource or drawable.showImageOnFail(R.drawable.ic_error) // resource or drawable.resetViewBeforeLoading(false)  // default.delayBeforeLoading(1000).cacheInMemory(false) // default.cacheOnDisk(false) // default.preProcessor(...).postProcessor(...).extraForDownloader(...).considerExifParams(false) // default.imageScaleType(ImageScaleType.IN_SAMPLE_POWER_OF_2) // default 压缩图片选项Options.inSampleSize是否用2的倍数,默认2的倍数.bitmapConfig(Bitmap.Config.ARGB_8888) // default.decodingOptions(...).displayer(new SimpleBitmapDisplayer()) // default.handler(new Handler()) // default.build();

UIL在listview, gridview, viewpager中的用法

        //Application中定义全局的配置属性ImageLoaderConfiguration configuration = new ImageLoaderConfiguration.Builder(this).threadPriority(Thread.NORM_PRIORITY - 2) //设置线程优先级.denyCacheImageMultipleSizesInMemory() //拒绝内存缓存中缓存不同size的图片.diskCacheFileNameGenerator(new Md5FileNameGenerator()) //硬盘缓存图片文件名生成器-md5加密,默认HashCodeFileNameGenerator-hashcode.diskCacheSize(50 * 1024 * 1024) //硬盘缓存大小50MiB,默认LruDiskCache.tasksProcessingOrder(QueueProcessingType.LIFO) //任务后进先出,后面添加的任务先执行,多用于listview等控件,默认FIFO.imageDownloader(new BaseImageDownloader(context,10000,20000)) //自定义图片下载器,设置10s(默认5s)连接超时,20s(默认20s)读取超时,默认5次重连.writeDebugLogs() //打印log信息.build(); //其它默认值看ImageLoaderConfiguration的initEmptyFieldsWithDefaultValues方法// Initialize ImageLoader with configuration.ImageLoader.getInstance().init(configuration);private static class ImageAdapter extends BaseAdapter {private static final String[] IMAGE_URLS = Constants.IMAGES;private LayoutInflater inflater;private DisplayImageOptions options;ImageAdapter(Context context) {inflater = LayoutInflater.from(context);options = new DisplayImageOptions.Builder().showImageOnLoading(R.drawable.ic_stub) //加载中的图片显示.showImageForEmptyUri(R.drawable.ic_empty) //url为null的图片显示.showImageOnFail(R.drawable.ic_error) //请求失败图片显示.cacheInMemory(true) //默认false,同时使用LruMemoryCache.cacheOnDisk(true) //默认false,同时使用LruDiskCache.considerExifParams(true) //解码图片的时候需要考虑图片的Exif参数,有些图片自带了旋转缩放等参数.displayer(new CircleBitmapDisplayer(Color.WHITE, 5)) //显示为圆形图片,还有其他形状的图片.build();}@Overridepublic int getCount() {return IMAGE_URLS.length;}@Overridepublic Object getItem(int position) {return position;}@Overridepublic long getItemId(int position) {return position;}@Overridepublic View getView(final int position, View convertView, ViewGroup parent) {View view = convertView;final ViewHolder holder;if (convertView == null) {view = inflater.inflate(R.layout.item_list_image, parent, false);holder = new ViewHolder();holder.text = (TextView) view.findViewById(R.id.text);holder.image = (ImageView) view.findViewById(R.id.image);view.setTag(holder);} else {holder = (ViewHolder) view.getTag();}holder.text.setText("Item " + (position + 1));ImageLoader.getInstance().displayImage(IMAGE_URLS[position], holder.image, options);return view;}}static class ViewHolder {TextView text;ImageView image;}//同时注意在activity中,如果被销毁了,必须手动停止线程池,否则会造成资源的浪费@Overridepublic void onDestroy() {super.onDestroy();ImageLoader.getInstance().stop();}

不需要setTag,内部实现已经实现了,不会出现错乱。
pauseOnScroll:Scroll的时候是否加载图片 pauseOnFling:Fling是否加载图片

//onMyScrollListener如果需要自己的滚动监视器则这样使用
listView.setOnScrollListener(new PauseOnScrollListener(ImageLoader.getInstance(), pauseOnScroll, pauseOnFling),onMyScrollListener);

ImageLoader是单例的,listView的滚动事件首先交给OnScrollListener来处理,onScrollStateChanged其中分别调用imageLoader.resume()恢复下载/imageLoader.pause()暂停下载来实现,如果定义了externalListener,那么就调用externalListener的onScroll/onScrollStateChanged方法.

优点

  1. 多线程下载图片,图片可以来源于网络,文件系统,项目文件夹assets中以及drawable中等
  2. 支持随意的配置ImageLoader,例如线程池,图片下载器,内存缓存策略,硬盘缓存策略,图片显示选项以及其他的一些配置
  3. 支持图片的内存缓存,文件系统缓存或者SD卡缓存
  4. 支持图片下载过程的监听
  5. 根据控件(ImageView)的大小对Bitmap进行裁剪,减少Bitmap占用过多的内存
  6. 较好的控制图片的加载过程,例如暂停图片加载,重新开始加载图片,一般使用在ListView,GridView中,滑动过程中暂停加载图片,停止滑动的时候去加载图片
  7. 提供在较慢的网络下对图片进行加载

Volley并没有对imageview的大小进行匹配,而是需要自己去定义图片的显示大小好麻烦

OutOfMemoryError

虽然这个框架有很好的缓存机制,有效的避免了OOM的产生,一般的情况下产生OOM的概率比较小,但是并不能保证OutOfMemoryError永远不发生,这个框架对于OutOfMemoryError做了简单的catch,保证我们的程序遇到OOM而不被crash掉,但是如果我们使用该框架经常发生OOM,我们应该怎么去改善呢?

  1. 减少线程池中线程的个数,在ImageLoaderConfiguration中的(threadPoolSize)中配置,推荐配置1-5
  2. 在DisplayImageOptions选项中配置bitmapConfig为Bitmap.Config.RGB_565,因为默认是ARGB_8888, 使用RGB_565会比使用ARGB_8888少消耗2倍的内存
  3. 在ImageLoaderConfiguration中配置图片的内存缓存为memoryCache(new WeakMemoryCache()) 或者不使用内存缓存
  4. 在DisplayImageOptions选项中设置.imageScaleType(ImageScaleType.IN_SAMPLE_INT)或者imageScaleType(ImageScaleType.EXACTLY)

通过上面这些,相信大家对Universal-Image-Loader框架的使用已经非常的了解了,我们在使用该框架的时候尽量的使用displayImage()方法去加载图片,loadImage()是将图片对象回调到ImageLoadingListener接口的onLoadingComplete()方法中,需要我们手动去设置到ImageView上面,displayImage()方法中,对ImageView对象使用的是Weak references,方便垃圾回收器回收ImageView对象,如果我们要加载固定大小的图片的时候,使用loadImage()方法需要传递一个ImageSize对象,而displayImage()方法会根据ImageView对象的测量值,或者android:layout_width and android:layout_height设定的值,或者android:maxWidth/android:maxHeight设定的值来裁剪图片

new ImageViewAware(imageView).ImageViewAware内部弱引用指向imageView,这样就防止了OOM了,如果activity退出,那么发生GC,那么会回收该imageview,那么也就会回收该activity,view内部持有context引用。

简单流程

简单的讲就是ImageLoader收到加载及显示图片的任务,如果是同步的直接运行LoadAndDisplayImageTask任务,如果是异步的,那么将它交给ImageLoaderEngine线程池管理,ImageLoaderEngine分发任务到具体的线程去执行,任务实际上是通过Cache及ImageDownloader获取图片,中间可能经过BitmapProcessor和ImageDecoder处理,最终转换为Bitmap交给BitmapDisplayer在ImageAware中显示。
ImageLoaderEngine:任务分发器,负责分发LoadAndDisplayImageTask和ProcessAndDisplayImageTask给具体的线程池去执行,本文中也称其为engine

ImageAware:显示图片的对象,可以是ImageView等
ImageDownloader:图片下载器,负责从图片的各个来源获取输入流
MemoryCache:内存图片缓存,可向内存缓存缓存图片或从内存缓存读取图片
DiskCache:本地图片缓存,可向本地磁盘缓存保存图片或从本地磁盘读取图片
ImageDecoder:图片解码器,负责将图片输入流InputStream转换为Bitmap对象
BitmapProcessor:图片处理器,负责从缓存读取或写入前对图片进行处理,默认是null,如果有需求将图片设置成圆形的,可以实现该类
BitmapDisplayer:将Bitmap对象显示在相应的控件ImageAware上
LoadAndDisplayImageTask:用于加载并显示图片的任务
ProcessAndDisplayImageTask:用于处理并显示图片的任务,跟BitmapProcessor对应,必须定义了BitmapProcessor,但是内部实现其实还是使用LoadAndDisplayImageTask的
DisplayBitmapTask:用于显示图片的任务

参考
Android 开源框架Universal-Image-Loader完全解析(一)— 基本介绍及使用
Android Universal Image Loader 源码分析

Universal-Image-Loader系列1-配置使用相关推荐

  1. (universal Image Loader)UIL 使用 (2)

    系列(universal Image Loader)UIL 使用 (1)   UIL 使用 3 简单介绍了UIL的最基本的使用方法,这次继续老学习UIL的使用 这次只是分析学习一个方法 <spa ...

  2. android universal image loader 缓冲原理详解

    1. 功能介绍 1.1 Android Universal Image Loader Android Universal Image Loader 是一个强大的.可高度定制的图片缓存,本文简称为UIL ...

  3. 【Android应用开发】 Universal Image Loader ( 使用简介 | 示例代码解析 )

    作者 : 韩曙亮 转载请注明出处 : http://blog.csdn.net/shulianghan/article/details/50824912 相关地址介绍 : -- Universal I ...

  4. 【译】UNIVERSAL IMAGE LOADER. PART 3---ImageLoader详解

    在之前的文章,我们重点讲了Android-Universal-Image-Loader的三个主要组件,现在我们终于可以开始使用它了. Android-Universal-Image-Loader有四个 ...

  5. (universal Image Loader)UIL 使用 (1)

    UIL Github 网址 系类文章:(universal Image Loader)UIL使用(2),UIL使用3 universal image loader 的功能就是加载图片 在as 中 ap ...

  6. universal image loader在listview/gridview中滚动时重复加载图片的问题及解决方法

    universal image loader在listview/gridview中滚动时重复加载图片的问题及解决方法 参考文章: (1)universal image loader在listview/ ...

  7. LOAM系列——LeGO-LOAM配置、安装、问题解决及VLP16测试效果(完结版)

    LOAM系列--LeGO-LOAM配置.安装.问题解决及VLP16测试效果 安装依赖 安装 VLP16 bag测试 问题解决 问题1 解决1 安装依赖 ros gtsam wget -O ~/Down ...

  8. iOS微信授权登录中Universal Link(通用链接)的配置 ,解决ios13,ios14微信支付不走回调问题

    这里写自定义目录标题 简介 Unuversal Links介绍 配置Unuversal Links 1.苹果开发者账号打开配置 2.XCode工程配置 3.配置JSON文件 4.后台服务器配置 5.微 ...

  9. LOAM系列——FLOAM配置、安装、问题解决及VLP16测试效果(完结版)

    LOAM系列--FLOAM配置.安装.问题解决及VLP16测试效果 安装依赖 安装 KITTI sequence 07 VLP16 bag测试 问题解决 问题1 安装依赖 Ubuntu and ROS ...

  10. RS485modbus转Profinet网关协议连接富凌DZB300系列变频器配置方法

    RS485modbus转Profinet网关协议连接富凌DZB300系列变频器配置方法 案例介绍:改造项目原系统的1200plc连接了多台富凌DXB300系列变频器,出现干扰导致间断性变频器报警,重启 ...

最新文章

  1. (完全解决)Precision and F-score are ill-defined for being 0.0 in labels with no predicted samples.
  2. mybatis-plus 多列映射成数组_JavaScript 为什么需要类数组
  3. android百度地图sdk定位权限,Android:使用百度地图SDK实现定位:下载SDK、申请密钥、动态获得Android权限...
  4. jquery3和layui冲突导,致使用layui.layer.full弹出全屏iframe窗口时高度152px问题
  5. 新版Elemen Plus 国际化 1.0.2-beta.59(包含59)
  6. php实现微信公众号半匹配,半全局块匹配(Semi-Global Block Matching)算法
  7. 美国OCC代理署长Brian Brooks将于今日离任,由首席运营官接任
  8. mysql导出excel出乱码_Mysql中文乱码以及导出为sql语句和Excel问题解决方法[图文]...
  9. 【Spring Cloud】网关-gateway(2.x)
  10. 【追光者系列】Hikari连接池大小多大合适?(第一弹)
  11. 玩转树莓派-2.配置你的树莓派
  12. WinSCP(Windows与Linux文件同步工具)使用总结
  13. Hacking Box Droopy: v0.2
  14. IDEA社区版tomcat配置教程
  15. 腾讯云与本地主机socket通信网络问题
  16. 浅析SkipList跳跃表原理及代码实现
  17. 青春饭碗——程序员,年纪大了怎么办?
  18. 关于上海四金计算和工资对照表(转载)
  19. 今日头条搜索排名seo怎么做?今天头条网站优化规则揭秘!
  20. linux根目录硬盘空间不足的扩容与报错信息解决

热门文章

  1. 探索在原生网页中使用自定义数据属性
  2. 我的物联网项目初建团队
  3. 网络营销推广实战宝典 2.3 软文推广
  4. HTML5七夕情人节表白网页制作【JS烟花表白】HTML+CSS+JavaScript 烟花表白代码 html烟花告白源码
  5. 输入两个自然数min,max,计算、输出[min,max]中的超级素数的个数#C语言
  6. Ubuntu下使用gcc和makefile编写c语言程序
  7. 在下列用户中什么管理计算机的权限最小,计算机网络管理员考试试题和答案
  8. C#毕业设计——基于C#+asp.net+sqlserver的网络在线考试系统设计与实现(毕业论文+程序源码)——网络在线考试系统
  9. img标签加载src图片,图片逆时针旋转了90度,解决方案
  10. OSD的主要实现方法和类型