项目介绍:
Android上最让人头疼的莫过于从网络获取图片、显示、回收,不论什么一个环节有问题都可能直接OOM。这个项目也许能帮到你。Universal Image Loader for Android的目的是为了实现异步的网络图片载入、缓存及显示,支持多线程异步载入

它最初来源于Fedor Vlasov的项目,且自此之后,经过大规模的重构和改进。
特性列举:
多线程下载图片,图片能够来源于网络,文件系统,项目目录assets中以及drawable中等
支持任意的配置ImageLoader。比如线程池,图片下载器,内存缓存策略,硬盘缓存策略。图片显示选项以及其它的一些配置
支持图片的内存缓存。文件系统缓存或者SD卡缓存
支持图片下载过程的监听
依据控件(ImageView)的大小对Bitmap进行裁剪,降低Bitmap占用过多的内存
较好的控制图片的载入过程。比如暂停图片载入,又一次開始载入图片,一般使用在ListView,GridView中。滑动过程中暂停载入图片,停止滑动的时候去载入图片
提供在较慢的网络下对图片进行载入
使用过程:
创建默认的ImageLoader,全部的操作都由ImageLoader控制。该类使用单例设计模式,所以假设要获取该类的实力。须要调用getInstance()方法。

在使用ImageLoader显示图片之前。你首先要初始化它的配置,调用ImageLoaderConfiguration的init()方法,然后你就能够实现各种的显示了。

//创建默认的ImageLoader配置參数

ImageLoaderConfiguration configuration = ImageLoaderConfiguration
.createDefault(this);
//Initialize ImageLoader with configuration.
ImageLoader.getInstance().init(configuration);

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

File cacheDir =StorageUtils.getOwnCacheDirectory(this, "imageloader/Cache");  
ImageLoaderConfigurationconfig = new ImageLoaderConfiguration   
          .Builder(this)   
          .memoryCacheExtraOptions(480, 800) // maxwidth, max height,即保存的每一个缓存文件的最大长宽   
          .threadPoolSize(3)//线程池内载入的数量   
          .threadPriority(Thread.NORM_PRIORITY -2)   
          .denyCacheImageMultipleSizesInMemory()   
           .memoryCache(new UsingFreqLimitedMemoryCache(2* 1024 * 1024)) // You can pass your own memory cache implementation/你能够通过自己的内存缓存实现   
           .memoryCacheSize(2 * 1024 * 1024)     
          .discCacheSize(50 * 1024 * 1024)     
          .discCacheFileNameGenerator(newMd5FileNameGenerator())//将保存的时候的URI名称用MD5 加密   
           .tasksProcessingOrder(QueueProcessingType.LIFO)   
           .discCacheFileCount(100) //缓存的文件数量   
           .discCache(new UnlimitedDiscCache(cacheDir))//自己定义缓存路径   
           .defaultDisplayImageOptions(DisplayImageOptions.createSimple())   
           .imageDownloader(new BaseImageDownloader(this,5 * 1000, 30 * 1000)) // connectTimeout (5 s), readTimeout (30 s)超时时间   
           .writeDebugLogs() // Remove for releaseapp   
          .build();//開始构建   
ImageLoader.getInstance().init(config);  

得到imageLoader

ImageLoader imageLoader imageLoader = ImageLoader.getInstance();  

使用过程:
(1)图像操作是否參与缓存以及图像效果的配置操作

DisplayImageOptions options = new DisplayImageOptions.Builder()  
          .showImageOnLoading(R.drawable.ic_stub)            //载入图片时的图片  
          .showImageForEmptyUri(R.drawable.ic_empty)         //没有图片资源时的默认图片  
          .showImageOnFail(R.drawable.ic_error)              //载入失败时的图片  
          .cacheInMemory(true)                               //启用内存缓存  
          .cacheOnDisk(true)                                 //启用外存缓存  
          .considerExifParams(true)                          //启用EXIF和JPEG图像格式  
          .displayer(new RoundedBitmapDisplayer(20))         //设置显示风格这里是圆角矩形  
          .build();  

DisplayImageOptions以下是全部默认配置參数依据需求能够自己定义配置

private int imageResOnLoading = 0;  
 private int imageResForEmptyUri = 0;  
 private int imageResOnFail = 0;  
 private Drawable imageOnLoading = null;  
 private Drawable imageForEmptyUri = null;  
 private Drawable imageOnFail = null;  
 private boolean resetViewBeforeLoading = false;  
 private boolean cacheInMemory = false;  
 private boolean cacheOnDisk = false;  
 private ImageScaleType imageScaleType = ImageScaleType.IN_SAMPLE_POWER_OF_2;  
 private Options decodingOptions = new Options();  
 private int delayBeforeLoading = 0;  
 private boolean considerExifParams = false;  
 private Object extraForDownloader = null;  
 private BitmapProcessor preProcessor = null;  
 private BitmapProcessor postProcessor = null;  
 private BitmapDisplayer displayer = DefaultConfigurationFactory.createBitmapDisplayer();  
 private Handler handler = null;  
 private boolean isSyncLoading = false;  

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

ImageLoadingListener animateFirstListener = new AnimateFirstDisplayListener();  
private static class AnimateFirstDisplayListener extends SimpleImageLoadingListener {  
        static final List<String> displayedImages = Collections.synchronizedList(new LinkedList<String>());  
         @Override  
         public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) {  
              if (loadedImage != null) {  
                  ImageView imageView = (ImageView) view;  
                  boolean firstDisplay = !displayedImages.contains(imageUri);  
                  if (firstDisplay) {  
                       FadeInBitmapDisplayer.animate(imageView, 500);  
                       displayedImages.add(imageUri);  
                    }  
              }  
        }  
}  

(3)简单设置就能够给ImageView加入图片了

imageLoader.displayImage(imageUrl, imageview, options, animateFirstListener);  

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

@Override
public void onDestroy() {
super.onDestroy();
imageLoader.clearMemoryCache();
imageLoader.clearDiskCache();
}

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

listView.setOnScrollListener(new PauseOnScrollListener(imageLoader, pauseOnScroll, pauseOnFling));    
gridView.setOnScrollListener(new PauseOnScrollListener(imageLoader, pauseOnScroll, pauseOnFling));  

第一个參数就是我们的图片载入对象ImageLoader, 第二个是控制是否在滑动过程中暂停载入图片,假设须要暂停传true即可了。第三个參数控制猛的滑动界面的时候图片是否载入

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

  1. 降低线程池中线程的个数,在ImageLoaderConfiguration中threadPoolSize中配置,推荐配置1-5
  2. 在DisplayImageOptions选项中配置bitmapConfigBitmap.Config.RGB_565,由于默认是ARGB_8888, 使用RGB_565会比使用ARGB_8888少消耗2倍的内存
  3. 在ImageLoaderConfiguration中配置图片的内存缓存为memoryCache(newWeakMemoryCache()) 或者不使用内存缓存
  4. 在DisplayImageOptions选项中设置ImageScale.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设定的值来裁剪图片

希望能大家对图片的载入有到帮助,如有补充,敬请提出,我会更新在后面,谢谢