Android开源框架ImageLoader的完美例子

来源:互联网 发布:广州少儿编程 编辑:程序博客网 时间:2024/06/06 00:46



Android开源框架ImageLoader的完美例子


2013年8月19日开源框架之Universal_Image_Loader学习


很多人都在讨论如何让图片能在异步加载更加流畅,可以显示大量图片,在拖动ListView的时候不会出现卡的现象。关于ImageLoader这个开源框架的使用有很多网友都介绍过,不过还不够清楚,这里有一个关于这个开源项目的完美例子,ListView的图片加载、GridView的图片加载、ViewPager的图片加载、Gallery画廊的图片加载、Widget的使用。很完善的一个例子,在这里我把所有界面效果做出博客分享出来,需要源码的朋友到我的资源页下载

下载地址:http://download.csdn.net/detail/wwj_748/5975847



要使用ImageLoader就要到这里下载jar包:

https://github.com/nostra13/Android-Universal-Image-Loader

然后导入项目中去就行了

用法:


注:下面使用的是包:1.8.4,其他版本包的,DisplayImageOptions defaultOptions和 ImageLoaderConfiguration config2配置不一样,请看官网



我们经常会从网上加载大量的图片,处理不好,经常会出现内存溢出,导致app崩溃,还有下载速度慢登问题。ImageLoader基本避免了这些问题,下载速度快,基本不会出现内存泄漏,还有很好的缓存管理机制,自己感觉很好用的,下面,简单介绍其使用方法:

官方网址:https://github.com/nostra13/Android-Universal-Image-Loader

1.到官方网站下载最新的包,地址上面这个,进入官网,点击zip,就可以下载需要的包了,里面有使用例子。

2.将下载包解压,把downloads里面的包universal-image-loader-1.8.4.jar加入到你项目的libs里面,注意引入项目,点击你的项目,右键——选择build path——configure build path——add jars,选择你项目下面libs里面的包。


点击ok。


3.开始使用了,使用之前,需要进行配置:

官方网站这么写的:

1. Include library

Manual:

  • Download JAR
  • Put the JAR in the libs subfolder of your Android project

or

Maven dependency:

<dependency>    <groupId>com.nostra13.universalimageloader</groupId>    <artifactId>universal-image-loader</artifactId>    <version>1.8.4</version></dependency>这种方法,没用过

2. Android Manifest

<manifest>    <uses-permission android:name="android.permission.INTERNET" />    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />        <application android:name="MyApplication">           </application></manifest>配置文件里面加入访问网络的权限,注册全局使用的类 
MyApplication(下面创建的),不要忘了註冊相應的activity
,应用启动后,会首先调用这个类,然后完成我们希望的初始化操作,类在下面

3. Application class

public class MyApplication extends Application {    @Override    public void onCreate() {        super.onCreate();        // Create global configuration and initialize ImageLoader with this configuration        ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(getApplicationContext())            ...            .build();        ImageLoader.getInstance().init(config);    }}// 创建一个名字叫MyApplicationf的类(名字可以自己隨便取的),繼承Application,重写onreat方法,在里面初始化Imagerloader。完整的初始化代码是这样的,例子里面拷出来的。ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(context)                .threadPriority(Thread.NORM_PRIORITY - 2)                .denyCacheImageMultipleSizesInMemory()                .discCacheFileNameGenerator(new Md5FileNameGenerator())                .tasksProcessingOrder(QueueProcessingType.LIFO)                .enableLogging() // Not necessary in common                .build();        ImageLoader.getInstance().init(config);
这个配置没有把图片缓存起来(但是我们可以在后面,加载图片的时候,设定缓存,看后面使用介绍)。如果你想把使用的图片都缓存起来,可以这样配置:(后面加载图片,就不需要设置缓存了)

 DisplayImageOptions defaultOptions = new DisplayImageOptions.Builder()
            .cacheInMemory()  //1.8.6包使用时候,括号里面传入参数true
            .cacheOnDisc()    //1.8.6包使用时候,括号里面传入参数true
            .build();
         ImageLoaderConfiguration config2 = new ImageLoaderConfiguration.Builder(context)  //contex上下文,在activity里面填入 this即可
          .defaultDisplayImageOptions(defaultOptions)
            .threadPriority(Thread.NORM_PRIORITY - 2)
            .denyCacheImageMultipleSizesInMemory()
            .discCacheFileNameGenerator(new Md5FileNameGenerator())
            .tasksProcessingOrder(QueueProcessingType.LIFO)
            .enableLogging() // Not necessary in common   //1.8.6包,把这句删除
            .build();

怎加录色部分代码就是了。

也就是说第3步骤完整的应该是这样:(注意快捷键ctrl+shift+o  引入相应包)

//没有把图片缓存的sdcard的

public class MyApplication extends Application {    @Override    public void onCreate() {        super.onCreate();
ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(getApplicationContext())                .threadPriority(Thread.NORM_PRIORITY - 2)                .denyCacheImageMultipleSizesInMemory()                .discCacheFileNameGenerator(new Md5FileNameGenerator())                .tasksProcessingOrder(QueueProcessingType.LIFO)                .enableLogging() // Not necessary in common   //1.8.6包,把这句删除                .build();        ImageLoader.getInstance().init(config);
}}

//有緩存的配置:
public class MyApplication extends Application {    @Override    public void onCreate() {        super.onCreate();
 DisplayImageOptions defaultOptions = new DisplayImageOptions.Builder()            .cacheInMemory()  //1.8.6包使用时候,括号里面传入参数true            .cacheOnDisc()    //同上            .build();         ImageLoaderConfiguration config2 = new ImageLoaderConfiguration.Builder(context)          .defaultDisplayImageOptions(defaultOptions)            .threadPriority(Thread.NORM_PRIORITY - 2)            .denyCacheImageMultipleSizesInMemory()            .discCacheFileNameGenerator(new Md5FileNameGenerator())            .tasksProcessingOrder(QueueProcessingType.LIFO)            .enableLogging() //  1.8.6,把这句删除            .build();
           ImageLoader.getInstance().init(config);
}
}
//配置的参数介绍请看官方文档


好了,配置完成后,我们就可以在任何想用它的地方使用了。具体使用如下(有多種):

就列常用的几种吧:

1.   ImageLoader.getInstance().displayImage(url, ImageView); 

在你需要加載圖片的地方調用上面這句話就ok了,url为图片的url地址,Imageview为你要显示的imageview

如果你在上面配置的是有緩存的,那麼使用這個加載圖片,图片也会被缓存起来的

2.     DisplayImageOptions  options = new DisplayImageOptions.Builder()
        .showStubImage(R.drawable.ic_stub)         加载开始默认的图片      
        .showImageForEmptyUri(R.drawable.ic_empty)     //url爲空會显示该图片,自己放在drawable里面的
        .showImageOnFail(R.drawable.ic_error)                //加载图片出现问题,会显示该图片
        .cacheInMemory()                                               //缓存用
        .cacheOnDisc()                                                    //缓存用
        .displayer(new RoundedBitmapDisplayer(5))       //图片圆角显示,值为整数
        .build();

    ImageLoader.getInstance().displayImage(url, imageView,options); 

多了一個options上面已经有注解。当我们在初始化imagerloader时候,没有加缓存的话,我们可以在这里来配置,

还有可以实现图片圆角额

3.     

ImageLoader.getInstance().loadImage(url, new SimpleImageLoadingListener()
        {
            public void onLoadingComplete(String imageUri, android.view.View view, android.graphics.Bitmap loadedImage) {
                imageView.setImageBitmap(loadedImage);   //imageView,你要显示的imageview控件对象,布局文件里面//配置的
            };
        }
        );


//还可以给它弄个监听事件SimpleImageLoadingListener,url还是图片url地址,SimpleImageLoadingListener里面有好几个方法,上面这个是图片下载完成后,我们需要做什么操作。这里是,把获取的bitmap,显示在imageview上面。

也就是说,可以用这个方法获取一个bitmap对象

SimpleImageLoadingListener里面还有几个重要方法,根据需要在里面进行相应处理

public void onLoadingFailed(String imageUri, android.view.View view, com.nostra13.universalimageloader.core.assist.FailReason failReason) {
            Toast.makeText(ShowOneImage.this,"加载失败", Toast.LENGTH_LONG).show();
        };
        @Override
        public void onLoadingStarted(String imageUri, View view) {
            
        }
        @Override
        public void onLoadingCancelled(String imageUri, View view) {
        }


例子下载地址:http://download.csdn.net/detail/hhhccckkk/5347331







1.9.0下载地址:1.9.0新包配置:在Application里面的oncreat()里面如下配置或者在第一个activity里面配置如下:


DisplayImageOptions options = new DisplayImageOptions.Builder()

.cacheInMemory(true).cacheOnDisc(true)

.imageScaleType(ImageScaleType.IN_SAMPLE_INT) 

.bitmapConfig(Bitmap.Config.RGB_565)// 防止内存溢出的,图片太多就这这个。还有其他设置

//如Bitmap.Config.ARGB_8888

.showImageOnLoading(R.drawable.ic_launcher)   //默认图片       

                .showImageForEmptyUri(R.drawable.kedou)    //url爲空會显示该图片,自己放在drawable里面的

                .showImageOnFail(R.drawable.k2k2k2k)// 加载失败显示的图片

.displayer(new RoundedBitmapDisplayer(5))  //圆角,不需要请删除

                           .build();  


ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(

this)

.memoryCacheExtraOptions(480, 800)// 缓存在内存的图片的宽和高度

.discCacheExtraOptions(480, 800, CompressFormat.PNG, 70,null)//CompressFormat.PNG类型,70质量(0-100)

.memoryCache(new WeakMemoryCache()) 

.memoryCacheSize(2 * 1024 * 1024) //缓存到内存的最大数据

.discCacheSize(50 * 1024 * 1024).  //缓存到文件的最大数据

discCacheFileCount(1000)            //文件数量

.defaultDisplayImageOptions(options).  //上面的options对象,一些属性配置

build();

ImageLoader.getInstance().init(config); //初始化




使用,就一句话搞定

ImageLoader.getInstance().displayImage(imageUrl,imageView);

/**

  imageUrl,图片的url地址,imageView ImageView控件对象

*/

ImageLoader.getInstance().displayImage("http://img10.3lian.com/c1/newpic/05/32/52.jpg",imageView);


//获取一个Bitmap对象,url为图片的url地址

Bitmapbmp = ImageLoader.getInstance().loadImageSync(url);



出现内存溢出,实在不行,试试把cacheInMemory(false),设置成false,不缓存在内存




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.   
  24. //  2.单例ImageLoader类的初始化  
  25. ImageLoader imageLoader = ImageLoader.getInstance();  
  26. imageLoader.init(config);  
  27.   
  28. //  3.DisplayImageOptions实例对象的配置  
  29. //      以下的设置再调用displayImage()有效,使用loadImage()无效  
  30. DisplayImageOptions options = new DisplayImageOptions.Builder()  
  31.     .showStubImage(R.drawable.ic_stub)          // image在加载过程中,显示的图片  
  32.     .showImageForEmptyUri(R.drawable.ic_empty)  // empty URI时显示的图片  
  33.     .showImageOnFail(R.drawable.ic_error)       // 不是图片文件 显示图片  
  34.     .resetViewBeforeLoading(false)  // default  
  35.     .delayBeforeLoading(1000)  
  36.     .cacheInMemory(false)           // default 不缓存至内存  
  37.     .cacheOnDisc(false)             // default 不缓存至手机SDCard  
  38.     .preProcessor(...)  
  39.     .postProcessor(...)  
  40.     .extraForDownloader(...)  
  41.     .imageScaleType(ImageScaleType.IN_SAMPLE_POWER_OF_2)// default  
  42.     .bitmapConfig(Bitmap.Config.ARGB_8888)              // default  
  43.     .decodingOptions(...)  
  44.     .displayer(new SimpleBitmapDisplayer()) // default 可以设置动画,比如圆角或者渐变  
  45.     .handler(new Handler())                             // default  
  46.     .build();  
  47.       
  48. //  4图片加载  
  49. //  4.1 调用displayImage  
  50. imageLoader.displayImage(  
  51.     uri,        /* 
  52.                     String imageUri = "http://site.com/image.png";      // from Web 
  53.                     String imageUri = "file:///mnt/sdcard/image.png";   // from SD card 
  54.                     String imageUri = "content://media/external/audio/albumart/13"; // from content provider 
  55.                     String imageUri = "assets://image.png";             // from assets 
  56.                     */  
  57.     imageView,      // 对应的imageView控件  
  58.     options);       // 与之对应的image显示方式选项  
  59.   
  60. //  4.2 调用loadImage  
  61. //      对于部分DisplayImageOptions对象的设置不起作用  
  62. imageLoader.loadImage(  
  63.         uri,   
  64.         options,   
  65.         new MyImageListener()); //ImageLoadingListener  
  66. class MyImageListener extends SimpleImageLoadingListener{  
  67.   
  68.     @Override  
  69.     public void onLoadingStarted(String imageUri, View view) {  
  70.         imageView.setImageResource(R.drawable.loading);  
  71.         super.onLoadingStarted(imageUri, view);  
  72.     }  
  73.   
  74.     @Override  
  75.     public void onLoadingFailed(String imageUri, View view,  
  76.             FailReason failReason) {  
  77.         imageView.setImageResource(R.drawable.no_pic);  
  78.         super.onLoadingFailed(imageUri, view, failReason);  
  79.     }  
  80.   
  81.     @Override  
  82.     public void onLoadingComplete(String imageUri, View view,  
  83.             Bitmap loadedImage) {  
  84.         imageView.setImageBitmap(loadedImage);  
  85.         super.onLoadingComplete(imageUri, view, loadedImage);  
  86.     }  
  87.   
  88.     @Override  
  89.     public void onLoadingCancelled(String imageUri, View view) {  
  90.         imageView.setImageResource(R.drawable.cancel);  
  91.         super.onLoadingCancelled(imageUri, view);  
  92.     }  
  93.       
  94. }  

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)  

加载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.   
  14. ImageLoader.getInstance().displayImage(imageUrl, imageView);    /* 
  15.                                             默认为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.

 


0 0
原创粉丝点击