Android_开源框架_AndroidUniversalImageLoader网络图片加载

1.功能概要

Android-Universal-Image-Loader是一个开源的UI组件程序,该项目的目的是提供一个可重复使用的仪器为异步图像加载,缓存和显示。

(1).使用多线程加载图片
(2).灵活配置ImageLoader的基本参数,包括线程数、缓存方式、图片显示选项等;
(3).图片异步加载缓存机制,包括内存缓存及SDCard缓存;
(4).采用监听器监听图片加载过程及相应事件的处理;
(5).配置加载的图片显示选项,比如图片的圆角处理及渐变动画。

2.简单实现

ImageLoader采用单例设计模式,ImageLoader imageLoader = ImageLoader.getInstance();得到该对象,每个ImageLoader采用单例设计模式,ImageLoader必须调用init()方法完成初始化。

  1. //  1.完成ImageLoaderConfiguration的配置
  2. ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(this)
  3. .memoryCacheExtraOptions(480, 800)          // default = device screen dimensions
  4. .discCacheExtraOptions(480, 800, CompressFormat.JPEG, 75, null)
  5. .taskExecutor(...)
  6. .taskExecutorForCachedImages(...)
  7. .threadPoolSize(3)                          // default
  8. .threadPriority(Thread.NORM_PRIORITY - 1)   // default
  9. .tasksProcessingOrder(QueueProcessingType.FIFO) // default
  10. .denyCacheImageMultipleSizesInMemory()
  11. .memoryCache(new LruMemoryCache(2 * 1024 * 1024))
  12. .memoryCacheSize(2 * 1024 * 1024)
  13. .memoryCacheSizePercentage(13)              // default
  14. .discCache(new UnlimitedDiscCache(cacheDir))// default
  15. .discCacheSize(50 * 1024 * 1024)        // 缓冲大小
  16. .discCacheFileCount(100)                // 缓冲文件数目
  17. .discCacheFileNameGenerator(new HashCodeFileNameGenerator()) // default
  18. .imageDownloader(new BaseImageDownloader(context)) // default
  19. .imageDecoder(new BaseImageDecoder()) // default
  20. .defaultDisplayImageOptions(DisplayImageOptions.createSimple()) // default
  21. .writeDebugLogs()
  22. .build();
  23. //  2.单例ImageLoader类的初始化
  24. ImageLoader imageLoader = ImageLoader.getInstance();
  25. imageLoader.init(config);
  26. //  3.DisplayImageOptions实例对象的配置
  27. //      以下的设置再调用displayImage()有效,使用loadImage()无效
  28. DisplayImageOptions options = new DisplayImageOptions.Builder()
  29. .showStubImage(R.drawable.ic_stub)          // image在加载过程中,显示的图片
  30. .showImageForEmptyUri(R.drawable.ic_empty)  // empty URI时显示的图片
  31. .showImageOnFail(R.drawable.ic_error)       // 不是图片文件 显示图片
  32. .resetViewBeforeLoading(false)  // default
  33. .delayBeforeLoading(1000)
  34. .cacheInMemory(false)           // default 不缓存至内存
  35. .cacheOnDisc(false)             // default 不缓存至手机SDCard
  36. .preProcessor(...)
  37. .postProcessor(...)
  38. .extraForDownloader(...)
  39. .imageScaleType(ImageScaleType.IN_SAMPLE_POWER_OF_2)// default
  40. .bitmapConfig(Bitmap.Config.ARGB_8888)              // default
  41. .decodingOptions(...)
  42. .displayer(new SimpleBitmapDisplayer()) // default 可以设置动画,比如圆角或者渐变
  43. .handler(new Handler())                             // default
  44. .build();
  45. //  4图片加载
  46. //  4.1 调用displayImage
  47. imageLoader.displayImage(
  48. uri,        /*
  49. String imageUri = "http://site.com/image.png";      // from Web
  50. String imageUri = "file:///mnt/sdcard/image.png";   // from SD card
  51. String imageUri = "content://media/external/audio/albumart/13"; // from content provider
  52. String imageUri = "assets://image.png";             // from assets
  53. */
  54. imageView,      // 对应的imageView控件
  55. options);       // 与之对应的image显示方式选项
  56. //  4.2 调用loadImage
  57. //      对于部分DisplayImageOptions对象的设置不起作用
  58. imageLoader.loadImage(
  59. uri,
  60. options,
  61. new MyImageListener()); //ImageLoadingListener
  62. class MyImageListener extends SimpleImageLoadingListener{
  63. @Override
  64. public void onLoadingStarted(String imageUri, View view) {
  65. imageView.setImageResource(R.drawable.loading);
  66. super.onLoadingStarted(imageUri, view);
  67. }
  68. @Override
  69. public void onLoadingFailed(String imageUri, View view,
  70. FailReason failReason) {
  71. imageView.setImageResource(R.drawable.no_pic);
  72. super.onLoadingFailed(imageUri, view, failReason);
  73. }
  74. @Override
  75. public void onLoadingComplete(String imageUri, View view,
  76. Bitmap loadedImage) {
  77. imageView.setImageBitmap(loadedImage);
  78. super.onLoadingComplete(imageUri, view, loadedImage);
  79. }
  80. @Override
  81. public void onLoadingCancelled(String imageUri, View view) {
  82. imageView.setImageResource(R.drawable.cancel);
  83. super.onLoadingCancelled(imageUri, view);
  84. }
  85. }

3.支持的Uri

  1. String imageUri = "http://site.com/image.png";      // from Web
  2. String imageUri = "file:///mnt/sdcard/image.png";   // from SD card
  3. String imageUri = "content://media/external/audio/albumart/13"; // from content provider
  4. String imageUri = "assets://image.png";             // from assets
  5. String imageUri = "drawable://" + R.drawable.image; // from drawables (only images, non-9patch)
  6. 加载drawables下图片,可以通过ImageView.setImageResource(...) 而不是通过上面的ImageLoader.

4.缓冲至手机

默认不能保存缓存,必须通过下面的方式指定

  1. DisplayImageOptions options = new DisplayImageOptions.Builder()
  2. ...
  3. .cacheInMemory(true)
  4. .cacheOnDisc(true)
  5. ...
  6. .build();
  7. ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(getApplicationContext())
  8. ...
  9. .defaultDisplayImageOptions(options)
  10. ...
  11. .build();
  12. ImageLoader.getInstance().init(config); // Do it on Application start
  13. ImageLoader.getInstance().displayImage(imageUrl, imageView);    /*
  14. 默认为defaultDisplayImageOptions设定的options对象,此处不用指定options对象 */

或者通过下面这种方式

  1. DisplayImageOptions options = new DisplayImageOptions.Builder()
  2. ...
  3. .cacheInMemory(true)
  4. .cacheOnDisc(true)
  5. ...
  6. .build();
  7. ImageLoader.getInstance().displayImage(imageUrl, imageView, options); //此处指定options对象

由于缓存需要在外设中写入数据,故需要添加下面的权限

  1. <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>

5.OutOfMemoryError

如果OutOfMemoryError错误很常见,可以通过下面的方式设置
(1).减少configuration中线程池的线程数目(.threadPoolSize(...)) 推荐为1 - 5
(2).display options通过.bitmapConfig(Bitmap.Config.RGB_565)设置. Bitmaps in RGB_565 consume 2 times less memory than in ARGB_8888.
(3).使用configuration的memoryCache(new WeakMemoryCache())方法 或者不调用.cacheInMemory()方法
(4).display options通过.imageScaleType(ImageScaleType.IN_SAMPLE_INT) 或者 .imageScaleType(ImageScaleType.EXACTLY)方法
(4).避免使用RoundedBitmapDisplayer,它创建了一个新的ARGB_8888 Bitmap对象

6.内存缓存管理

通过imageLoaderConfiguration.memoryCache([new LruMemoryCache(1)]))对手机内存缓存进行管理


LruMemoryCache


API >= 9默认.it is moved to the head of a queue.


FreqLimitedMemoryCache


当超过缓存大小后,删除最近频繁使用的bitmap


LRULimitedMemoryCache


API < 9 默认.当超过缓存大小后,删除最近使用的bitmap


FIFOLimitedMemoryCache


FIFO rule is used for deletion when cache size limit is exceeded


LargestLimitedMemoryCache


The largest bitmap is deleted when cache size limit is exceeded


WeakMemoryCache


Unlimited cache

7.SDcard缓存管理

通过imageLoaderConfiguration.discCache([new TotalSizeLimitedDiscCache()]))对SD卡缓存进行管理


UnlimitedDiscCache


default The fastest cache, doesn‘t limit cache size


TotalSizeLimitedDiscCache


Cache limited by total cache size. If cache size exceeds specified limit then file with themost oldest lastusage date will be deleted


FileCountLimitedDiscCache


Cache limited by file count. If file count in cache directory exceeds specified limit then file with the most oldest last usage date will be deleted.


LimitedAgeDiscCache


Size-unlimited cache with limited files‘ lifetime. If age of cached file exceeds defined limit then it will be deleted from cache.

UnlimitedDiscCache is 30%-faster than other limited disc cache implementations.

时间: 2024-08-27 03:46:02

Android_开源框架_AndroidUniversalImageLoader网络图片加载的相关文章

[转]Android_开源框架_AndroidUniversalImageLoader网络图片加载

1.功能概要 Android-Universal-Image-Loader是一个开源的UI组件程序,该项目的目的是提供一个可重复使用的仪器为异步图像加载,缓存和显示. (1).使用多线程加载图片(2).灵活配置ImageLoader的基本参数,包括线程数.缓存方式.图片显示选项等:(3).图片异步加载缓存机制,包括内存缓存及SDCard缓存:(4).采用监听器监听图片加载过程及相应事件的处理:(5).配置加载的图片显示选项,比如图片的圆角处理及渐变动画. 2.简单实现 ImageLoader采用

Android开源框架ImageLoader:加载图片的三级缓存机制

前言:可从  https://github.com/nostra13/Android-Universal-Image-Loader 下载三级缓存机制的开源框架.下文简单介绍该框架中主要的常用方法,掌握这些方法,基本就可应对多数图片下载的需求. 注意:以下代码为示意代码片断,仔细读一下应能知道怎么用.蓝色表示为开源框架中的类. 1.初始化ImageLoader类对象: ImageLoader imageLoader = ImageLoader.getInstance(); imageLoader.

Android 开源框架 ( 九 ) 图片加载框架---ImageLoader

一.引言 Android的每一个App通常只拥有有限的系统资源,Android设备为每个App分配的内存大小是也是有上限的,并且,针对不同的设备配置所分配的内存大小也是不一样的,最小为16MB.图片会占用大量的内存,尤其是那些超清照片.所以图片加载时做容易造成安卓内存溢出的原因,而要解决这些问题还需要很多相关知识: 1.多线程下载,线程管理. 2.多级缓存架构设计和策略,内存缓存,磁盘缓存,缓存有效性处理. 3.图片压缩,特效处理,动画处理. 4.复杂网络情况下下载图片策略,例如弱网络等. 5.

iOS网络开发(6)网络图片加载开源框架SDWebImage

SDWebImage是一个第三方框架,用以实现网络图像的缓存,及处理等功能. Github的托管下载地址: https://github.com/rs/SDWebImage SDWebImage默认使用磁盘缓存, 在 沙盒/Library/Cache中可以找到带WebImageCache字眼的目录,可以找到缓存的图片 SDWebImage以分类的形式,对UIKit中的控件扩展了网络图片加载接口,使用起来非常方便. 介绍SDWebImage中的几个分类: UIImageView加载网络图片 UIB

网络图片加载框架Universal-ImageLoader和Picasso优缺点对比

网络图片加载库的特点及优势 Android 中图片处理的难点: oom内存溢出 图片尺寸和缩略图处理的平衡 网络图片的加载与缓存机制 今天学习两款比较优秀的开源图片处理库框架: Universal-ImageLoader的简介和特点: android 主流的图片处理框架之一,作者是白俄罗斯的Sergey Tarasevich 1.支持本地图片和网络图片的多线程异步加载和缓存处理(另外对大图片进行压缩等处理防止内存溢出) 2.个性化的配置自己项目的ImageLoader (配置线程数,缓存空间的大

优化ListView中的网络图片加载 及 Volley库源码分析

使用适当的开源库,如Volley或者Universal ImageLoader 以Volley库为例.Volley使用了线程池来作为基础结构,主要分为主线程,cache线程和network线程. 主线程和cache线程都只有一个,而NetworkDispatcher线程可以有多个,这样能解决比并行问题.如下图: 其中左下角是NetworkDispatcher线程,大致步骤是: 1.不断从请求队列中取出请求 request = mQueue.take(); 2.发起网络请求 NetworkResp

Android 网络图片加载缓存处理库ImageLoader和Picasso

在Android图片处理中需要考虑的问题很多,例如OOM.图片缓存和网络图片加载.多线程问题及图片压缩处理等等复杂的问题.网上也有一些很优秀的开源库帮我们处理这些问题,下面介绍两款开源图片处理库框架:Universal-ImageLoader和Picasso. Universal-ImageLoader: 优点: 支持本地图片和网络图片的多线程异步加载和缓存处理: 个性化的配置自己项目的ImageLoader: 图片加载过程的监听回调: 自动对加载的图片针对当前剩余内存进行裁剪优化,防止OOM:

网络图片加载优化

网络图片加载优化 比如使用淘宝浏览产品的时候(大部分应用也是如此),就会发现每次下拉产品目录进行更新的时候,都会出现对应的Item的时候,才开始从网络下载并加载图片. taobao加载 可以看到宝贝图片下拉刷新的时候,图片加载是实时从网络下载的.即使在Wifi的网络环境下,加载图片也是有比较大的延迟. 假设我们浏览每屏宝贝需要2s的时间(人眼对于淘宝搜索的宝贝其实过滤速度非常快).如果每一屏页面需要1s才可以完全加载完图片,则如果浏览10屏的宝贝,就会需要30s.如果加载图片几乎不需要时间,则只

Viewpager图片自动轮播,网络图片加载,图片自动刷新

package com.teffy.viewpager; import java.util.ArrayList; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; import android.annotation.SuppressLint; import android.app.Act