使用volley的人肯定都遇到过OOM的错误,这几天我使用NetWorkImageView进行了大量图片的下载采样!绑定在GridView上面,却出现了OOM异常,后来查询了很多资料,再加上查看volley源码进行了分析,大胆猜想如果我把RequestQueue对象进行固定,以单利模式实现想过将会如何呢?因为我在volley的newRequestQueue方法中看到了RequestQueue queue = new RequestQueue(new DiskBasedCache(cacheDir), network);
所以重写了Volley类
public class MyVolley extends Volley {
private static RequestQueue rq = null;
public synchronized static RequestQueue getInstance(Context context) {
if (rq == null) {
rq = Volley.newRequestQueue(context);
}
return rq;
}
}
然后利用MyVolley获取请求队列进行ImageLoader的实现
public class MyImageLoader extends ImageLoader {
private MyImageLoader(RequestQueue queue, ImageCache imageCache) {
super(queue, imageCache);
}
public MyImageLoader(Context context) throws Exception {
super(MyVolley.getInstance(context), new BitMapCache(context));
}
}
然后实现BitmapCache缓存
public class BitMapCache implements ImageCache {
// 上下文菜单
private Context context = null;
// 缓存本地SD卡的最大空间大小
public static final int SD_MAX_CACHE_SIZE = 15;
/**
* 构造方法
*/
public BitMapCache(Context context) {
MySQLiteOpenHelper ms = new MySQLiteOpenHelper(context);
SQLiteUtils.deleteCache(ms);
this.context = context;
}
/**
* 获取本地缓存的图片
*/
@Override
public Bitmap getBitmap(String url) {
return MyLruCache.getBitMap(context, url);
}
/**
* 将得到的图片缓存到本地
*/
@Override
public void putBitmap(String key, Bitmap value) {
new MyThread(context, key, value).start();
}
class MyThread extends Thread {
private Context context = null;
private String key = null;
private Bitmap bitmap = null;
public MyThread(Context context, String key, Bitmap value) {
this.context = context;
this.key = key;
this.bitmap = value;
}
@Override
public void run() {
MyLruCache.putBitmap(context, key, bitmap);
}
}
}