Universal-Image-Loader(android图片缓存)

最近需要做选择sd卡图片的任务,这篇博客是转载的

转载请注明http://write.blog.csdn.net/postedit?ref=toolbar


Android上最让人头疼的莫过于从网络获取图片、显示、回收,任何一个环节有问题都可能直接OOM,这个项目或许能帮到你。Universal Image Loader for Android的目的是为了实现异步的网络图片加载、缓存及显示,支持多线程异步加载。它最初来源于Fedor Vlasov的项目,且自此之后,经过大规模的重构和改进。

特性列举:

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

使用过程:

创建默认的ImageLoader,所有的操作都由ImageLoader控制。该类使用单例设计模式,所以如果要获取该类的实力,需要调用getInstance()方法。在使用ImageLoader显示图片之前,你首先要初始化它的配置,调用ImageLoaderConfiguration的init()方法,然后你就可以实现各种的显示了。

  
  
[java] view plain copy 在CODE上查看代码片 派生到我的代码片
  1. //创建默认的ImageLoader配置参数    
  2. ImageLoaderConfiguration configuration = ImageLoaderConfiguration    
  3.         .createDefault(this);    
  4. //Initialize ImageLoader with configuration.    
  5. ImageLoader.getInstance().init(configuration);   

自定义配置imageloader, 就像你已经知道的,首先,你需要使用ImageLoaderConfiguration对象来初始化ImageLoader。由于ImageLoader是单例,所以在程序开始的时候只需要初始化一次就好了。建议你在Activity的onCreate()方法中初始化。如果一个ImageLoader已经初始化过,再次初始化不会有任何效果。下面我们通过ImageLoaderConfiguration.Builder创建一个设置

[java]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. File cacheDir =StorageUtils.getOwnCacheDirectory(this"imageloader/Cache");  
  2. ImageLoaderConfigurationconfig = new ImageLoaderConfiguration   
  3.           .Builder(this)   
  4.           .memoryCacheExtraOptions(480800// maxwidth, max height,即保存的每个缓存文件的最大长宽   
  5.           .threadPoolSize(3)//线程池内加载的数量   
  6.           .threadPriority(Thread.NORM_PRIORITY -2)   
  7.           .denyCacheImageMultipleSizesInMemory()   
  8.            .memoryCache(new UsingFreqLimitedMemoryCache(21024 * 1024)) // You can pass your own memory cache implementation/你可以通过自己的内存缓存实现   
  9.            .memoryCacheSize(2 * 1024 * 1024)     
  10.           .discCacheSize(50 * 1024 * 1024)     
  11.           .discCacheFileNameGenerator(newMd5FileNameGenerator())//将保存的时候的URI名称用MD5 加密   
  12.            .tasksProcessingOrder(QueueProcessingType.LIFO)   
  13.            .discCacheFileCount(100//缓存的文件数量   
  14.            .discCache(new UnlimitedDiscCache(cacheDir))//自定义缓存路径   
  15.            .defaultDisplayImageOptions(DisplayImageOptions.createSimple())   
  16.            .imageDownloader(new BaseImageDownloader(this,5 * 100030 * 1000)) // connectTimeout (5 s), readTimeout (30 s)超时时间   
  17.            .writeDebugLogs() // Remove for releaseapp   
  18.           .build();//开始构建   
  19. ImageLoader.getInstance().init(config);  


得到imageLoader

  
  
[java] view plain copy 在CODE上查看代码片 派生到我的代码片
  1. ImageLoader imageLoader imageLoader = ImageLoader.getInstance();  

使用过程:

(1)图像操作是否参与缓存以及图像效果的配置操作

  
  
[java] view plain copy 在CODE上查看代码片 派生到我的代码片
  1. DisplayImageOptions options = new DisplayImageOptions.Builder()  
  2.           .showImageOnLoading(R.drawable.ic_stub)            //加载图片时的图片  
  3.           .showImageForEmptyUri(R.drawable.ic_empty)         //没有图片资源时的默认图片  
  4.           .showImageOnFail(R.drawable.ic_error)              //加载失败时的图片  
  5.           .cacheInMemory(true)                               //启用内存缓存  
  6.           .cacheOnDisk(true)                                 //启用外存缓存  
  7.           .considerExifParams(true)                          //启用EXIF和JPEG图像格式  
  8.           .displayer(new RoundedBitmapDisplayer(20))         //设置显示风格这里是圆角矩形  
  9.           .build();  

DisplayImageOptions以下是所有默认配置参数根据需求可以自定义配置

 
  
  
[java] view plain copy 在CODE上查看代码片 派生到我的代码片
  1. private int imageResOnLoading = 0;  
  2.  private int imageResForEmptyUri = 0;  
  3.  private int imageResOnFail = 0;  
  4.  private Drawable imageOnLoading = null;  
  5.  private Drawable imageForEmptyUri = null;  
  6.  private Drawable imageOnFail = null;  
  7.  private boolean resetViewBeforeLoading = false;  
  8.  private boolean cacheInMemory = false;  
  9.  private boolean cacheOnDisk = false;  
  10.  private ImageScaleType imageScaleType = ImageScaleType.IN_SAMPLE_POWER_OF_2;  
  11.  private Options decodingOptions = new Options();  
  12.  private int delayBeforeLoading = 0;  
  13.  private boolean considerExifParams = false;  
  14.  private Object extraForDownloader = null;  
  15.  private BitmapProcessor preProcessor = null;  
  16.  private BitmapProcessor postProcessor = null;  
  17.  private BitmapDisplayer displayer = DefaultConfigurationFactory.createBitmapDisplayer();  
  18.  private Handler handler = null;  
  19.  private boolean isSyncLoading = false;  

(2)图片加载监听器在这里吧可以设置加载时的动画或者进度条之类的东西这里

  
  
[java] view plain copy 在CODE上查看代码片 派生到我的代码片
  1. ImageLoadingListener animateFirstListener = new AnimateFirstDisplayListener();  
  2. private static class AnimateFirstDisplayListener extends SimpleImageLoadingListener {  
  3.         static final List<String> displayedImages = Collections.synchronizedList(new LinkedList<String>());  
  4.          @Override  
  5.          public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) {  
  6.               if (loadedImage != null) {  
  7.                   ImageView imageView = (ImageView) view;  
  8.                   boolean firstDisplay = !displayedImages.contains(imageUri);  
  9.                   if (firstDisplay) {  
  10.                        FadeInBitmapDisplayer.animate(imageView, 500);  
  11.                        displayedImages.add(imageUri);  
  12.                     }  
  13.               }  
  14.         }  
  15. }  

(3)简单设置就可以给ImageView添加图片了

  
  
[java] view plain copy 在CODE上查看代码片 派生到我的代码片
  1. imageLoader.displayImage(imageUrl, imageview, options, animateFirstListener);  

缓存的清理:

       缓存的清理可以按需求来定,可以再每个Activity的生命周期函数onDestroy中清理也可以单独设置让用户自行清理。

  
  
[java] view plain copy 在CODE上查看代码片 派生到我的代码片
  1. @Override  
  2. public void onDestroy() {  
  3.           super.onDestroy();  
  4.           imageLoader.clearMemoryCache();  
  5.           imageLoader.clearDiskCache();  
  6. }  

GirdView,ListView加载图片:

相信大部分人都是使用GridView,ListView来显示大量的图片,而当我们快速滑动GridView,ListView,我们希望能停止图片的加载,而在GridView,ListView停止滑动的时候加载当前界面的图片,这个框架当然也提供这个功能,使用起来也很简单,它提供了PauseOnScrollListener这个类来控制ListView,GridView滑动过程中停止去加载图片,该类使用的是代理模式

  
  
[java] view plain copy 在CODE上查看代码片 派生到我的代码片
  1. listView.setOnScrollListener(new PauseOnScrollListener(imageLoader, pauseOnScroll, pauseOnFling));    
  2. gridView.setOnScrollListener(new PauseOnScrollListener(imageLoader, pauseOnScroll, pauseOnFling));  

第一个参数就是我们的图片加载对象ImageLoader, 第二个是控制是否在滑动过程中暂停加载图片,如果需要暂停传true就行了,第三个参数控制猛的滑动界面的时候图片是否加载

OutOfMemoryError:

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

减少线程池中线程的个数,在ImageLoaderConfiguration中的(.threadPoolSize)中配置,推荐配置1-5

在DisplayImageOptions选项中配置bitmapConfig为Bitmap.Config.RGB_565,因为默认是ARGB_8888, 使用RGB_565会比使用ARGB_8888少消耗2倍的内存

在ImageLoaderConfiguration中配置图片的内存缓存为memoryCache(newWeakMemoryCache()) 或者不使用内存缓存

在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 and/or android:maxHeight设定的值来裁剪图片


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值