Android开发利用Volley框架下载和缓存网络图片

      2013年Google I/O大会上推出了一种新的网络通信框架——Volley,Volley可是说是把AsyncHttpClient和Universal-Image-Loader的优点集于了一身,既可以像AsyncHttpClient一样非常简单地进行HTTP通信,也可以像Universal-Image-Loader一样轻松加载网络上的图片。除了简单易用之外,Volley在性能方面也进行了大幅度的调整,它的设计目标就是非常适合去进行数据量不大,但通信频繁的网络操作,而对于大数据量的网络操作,比如说下载文件等,Volley的表现就会非常糟糕。volley.jar下载

一.使用Volley框架下载网络图片

(1)首先,创建Application类,声明并且实例话RequestQueue。

App.java文件中:

public class App extends Application

{

     private static RequestQueuequeues;// Volley加载队列

     @Override

     public void onCreate()

     {

          super.onCreate();

          queues =Volley.newRequestQueue(getApplicationContext());// 实列话

     }

}

[注意]需要在AndroidManifest.xml中配置这个APP类:

<application

       android:name=".App"

       android:allowBackup="true"

       android:icon="@drawable/ic_launcher"

       android:label="@string/app_name"

       android:theme="@style/AppTheme">

...........

</application>

(2)在需要下载图片的地方,使用Volley框架进行网络操作(如ListView的Adapter中,在getView方法中可以使用)

ImageView iv = (ImageView)findViewById(R.id.iv);

String url = "http://.............../test.png"  // 图片的地址

 

ImageRequest request =new ImageRequest(url,new Listener<Bitmap>()

{

     @Override

     public void onResponse(Bitmap response)

     {// 加载成功,显示头像

          iv.setImageBitmap(response);

     }

},0,0,Config.RGB_565,new ErrorListener()

{

     @Override

     public void onErrorResponse(VolleyError error)

     { // 加载出错调用的函数

          iv.setImageBitmap(BitmapFactory.decodeResource(this.getResources(), R.drawable.error));

     }

});

if (! url.equals(""))

{     

 

      App.getHttpQueue().add(request);

}

[说明]

 

Volley.ImageRequest(String url,Listener<Bitmap> listener, int maxWidth, int maxHeight,Config decodeConfig,ErrorListenererrorListener)

url:为图片下载的地址;

listener:为下载成功的监听, 其onResponse方法中的Bitmap对象就是获得成功之后得到的图片(Bitmap response);

maxWidth与maxHeight:与系统对图片处理(压缩和拉伸),若设置为0,则系统不对图片进行这些处理;

errorListener:拉取图片出错的监听。

[注意]上面的方法,实现了数量不大,但频繁的网络加载图片的操作,可以用在ListView图片加载以及单一图片加载的过程,但是有一个缺点,比如在ListView中加载,会加载当前现实的ListView的Item的图片,上下滑动的过程中,对于显示出的Item,会重现进行网络下载,这样就浪费了流量,因此我们需要结合图片缓存机制和Volley一起进行网络图片加载使用。

二.Volley框架+BitmapCache进行网络图片加载和缓存

(1)首先,创建Application类,声明并且实例话RequestQueue。

APP.java文件中:

public class APP extends Application

{

     private static RequestQueue queues// Volley加载队列

     @Override

     public void onCreate()

     {

          super.onCreate();

          queues = Volley.newRequestQueue(getApplicationContext()); // 实列话

     }

}

[注意]需要在AndroidManifest.xml中配置这个APP类:

<application

        android:name=".App"

        android:allowBackup="true"

        android:icon="@drawable/ic_launcher"

        android:label="@string/app_name"

        android:theme="@style/AppTheme" >

...........

</application>

(2).创建图片缓存类BitmapCache.java(借助了LruCache实现缓存)

import android.graphics.Bitmap;

import android.support.v4.util.LruCache;

 

import com.android.volley.toolbox.ImageLoader.ImageCache;

 

//用来图片缓存的类

public class BitmapCache implements ImageCache

{

 

     public LruCache<String,Bitmap>cache;

     public int max =10 *1024 *1024;// 设置缓存的最大为10M

 

     public BitmapCache()

     {

          cache =new LruCache<String,Bitmap>(max)

          {

               @Override

               protected int sizeOf(String key,Bitmap value)

               {

                    return value.getRowBytes() *value.getHeight();

               }

          };

}

 

     @Override

     public Bitmap getBitmap(String url)

     {

          returncache.get(url);

     }

 

     @Override

     public void putBitmap(String url,Bitmap bitmap)

     {

          cache.put(url,bitmap);

     }

}

(3)调用Volley进行下载和缓存图片:

String url = "http://.........../test.png";

ImageView img = (ImageView)findViewById(R.id.img);

ImageLoader loader =new ImageLoader(App.getHttpQueue(),new BitmapCache());

ImageListener listener =ImageLoader.getImageListener(img,R.drawable.default_icon,R.drawable.error_icon);

loader.get(url, listener);

 

 

<注意>上面的操作由于需要网络支持,以及会在内存中读写内容,因此需要在AndroidManifest.xml中加入必要的操作权限:

<uses-permissionandroid:name="android.permission.INTERNET"/>

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

 

原文地址:https://www.cnblogs.com/android-blogs/p/5012030.html