android加载大量图片内存溢出bitmap size exceeds VM budget的解决办法。

来源:互联网 发布:唯一约束 mysql 编辑:程序博客网 时间:2024/05/22 17:06

方法一:

在从网络或本地加载图片的时候,只加载缩略图。

/**  * 按照路径加载图片  * @param path 图片资源的存放路径  * @param scalSize 缩小的倍数  * @return  */ public static Bitmap loadResBitmap(String path, int scalSize) {     BitmapFactory.Options options = new BitmapFactory.Options();     options.inJustDecodeBounds = false;     options.inSampleSize = scalSize;        Bitmap bmp = BitmapFactory.decodeFile(path, options);  return bmp; }

这个方法的确能够少占用不少内存,可是它的致命的缺点就是,因为加载的是缩略图,所以图片失真比较严重,对于对图片质量要求很高的应用,可以采用下面的方法。

方法二:

运用JAVA的软引用,进行图片缓存,将经常需要加载的图片,存放在缓存里,避免反复加载。

关于软引用(SoftReference)的详细说明,请参看http://blog.csdn.net/helixiuqqq/article/details/6610199。下面是我写的一个图片缓存的工具类。


/** * * @author larson.liu * 该类用于图片缓存,防止内存溢出 */public class BitmapCache { static private BitmapCache cache; /** 用于Chche内容的存储*/ private Hashtable<Integer, BtimapRef> bitmapRefs; /** 垃圾Reference的队列(所引用的对象已经被回收,则将该引用存入队列中)*/ private ReferenceQueue<Bitmap> q; /**  * 继承SoftReference,使得每一个实例都具有可识别的标识。  */ private class BtimapRef extends SoftReference<Bitmap> {  private Integer _key = 0;  public BtimapRef(Bitmap bmp, ReferenceQueue<Bitmap> q, int key) {   super(bmp, q);   _key = key;  } } private BitmapCache() {  bitmapRefs = new Hashtable<Integer, BtimapRef>();  q = new ReferenceQueue<Bitmap>(); } /**  * 取得缓存器实例  */ public static BitmapCache getInstance() {  if (cache == null) {   cache = new BitmapCache();  }  return cache; } /**  * 以软引用的方式对一个Bitmap对象的实例进行引用并保存该引用  */ private void addCacheBitmap(Bitmap bmp, Integer key) {  cleanCache();// 清除垃圾引用  BtimapRef ref = new BtimapRef(bmp, q, key);  bitmapRefs.put(key, ref); } /**  * 依据所指定的drawable下的图片资源ID号(可以根据自己的需要从网络或本地path下获取),重新获取相应Bitmap对象的实例  */ public Bitmap getBitmap(int resId, Context context) {  Bitmap bmp = null;  // 缓存中是否有该Bitmap实例的软引用,如果有,从软引用中取得。  if (bitmapRefs.containsKey(resId)) {   BtimapRef ref = (BtimapRef) bitmapRefs.get(resId);   bmp = (Bitmap) ref.get();  }  // 如果没有软引用,或者从软引用中得到的实例是null,重新构建一个实例,  // 并保存对这个新建实例的软引用  if (bmp == null) {   bmp = BitmapFactory.decodeResource(context.getResources(), resId);   this.addCacheBitmap(bmp, resId);  }  return bmp; } private void cleanCache() {  BtimapRef ref = null;  while ((ref = (BtimapRef) q.poll()) != null) {   bitmapRefs.remove(ref._key);  } } // 清除Cache内的全部内容 public void clearCache() {  cleanCache();  bitmapRefs.clear();  System.gc();  System.runFinalization(); }}

在程序代码中调用该类:

imageView.setImageBitmap(bmpCache.getBitmap(R.drawable.kind01, this));

这样当你的imageView需要来回变换背景图片时,就不需要再重复加载。

方法三:

及时销毁不再使用的Bitmap对象。

if (bitmap != null && b!itmap.isRecycled()){

bitmap.recycle();

bitmap = null; // recycle()是个比较漫长的过程,设为null,然后在最后调用System.gc(),效果能好很多

}

System.gc();

方法四:

尽可能少的使用图片资源。

这个有点像废话哈。但我只知道我们经理说服客户改了一下需求,然后在一个动态的listView里(最多时能有100多项),就一下子少加载了几十张网络图片,这该能节约多少内存啊!

综合运用以上四种方法,一般的项目,应该就能避免oom的错误。欢迎一起探讨更好的关于“图片内存溢出问题”的解决方案。