android加载大量图片内存溢出的三种解决办法

方法一:

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


/**

  1. * 按照路径加载图片
  2. * @param path 图片资源的存放路径
  3. * @param scalSize 缩小的倍数
  4. * @return
  5. */
  6. public static Bitmap loadResBitmap(String path, int scalSize) {
  7. BitmapFactory.Options options = new BitmapFactory.Options();
  8. options.inJustDecodeBounds = false;
  9. options.inSampleSize = scalSize;
  10. Bitmap bmp = BitmapFactory.decodeFile(path, options);
  11. return bmp;
  12. }

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

方法二:

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

/**

  1. *
  2. * @author larson.liu
  3. * 该类用于图片缓存,防止内存溢出
  4. */
  5. public class BitmapCache {
  6. static * BitmapCache cache;
  7. /** 用于Chche内容的存储*/
  8. * Hashtable bitmapRefs;
  9. /** 垃圾Reference的队列(所引用的对象已经被回收,则将该引用存入队列中)*/
  10. * ReferenceQueue q;
  11.  
  12. /**
  13. * 继承SoftReference,使得每一个实例都具有可识别的标识。
  14. */
  15. * class BtimapRef extends SoftReference {
  16. * Integer _key = 0;
  17.  
  18. public BtimapRef(Bitmap bmp, ReferenceQueue q, int key) {
  19. super(bmp, q);
  20. _key = key;
  21. }
  22. }
  23.  
  24. * BitmapCache() {
  25. bitmapRefs = new Hashtable();
  26. q = new ReferenceQueue();
  27.  
  28. }
  29.  
  30. /**
  31. * 取得缓存器实例
  32. */
  33. public static BitmapCache getInstance() {
  34. if (cache == null) {
  35. cache = new BitmapCache();
  36. }
  37. return cache;
  38.  
  39. }
  40.  
  41. /**
  42. * 以软引用的方式对一个Bitmap对象的实例进行引用并保存该引用
  43. */
  44. * void addCacheBitmap(Bitmap bmp, Integer key) {
  45. cleanCache();// 清除垃圾引用
  46. BtimapRef ref = new BtimapRef(bmp, q, key);
  47. bitmapRefs.put(key, ref);
  48. }
  49.  
  50. /**
  51. * 依据所指定的drawable下的图片资源ID号(可以根据自己的需要从网络或本地path下获取),重新获取相应Bitmap对象的实例
  52. */
  53. public Bitmap getBitmap(int resId, Context context) {
  54. Bitmap bmp = null;
  55. // 缓存中是否有该Bitmap实例的软引用,如果有,从软引用中取得。
  56. if (bitmapRefs.containsKey(resId)) {
  57. BtimapRef ref = (BtimapRef) bitmapRefs.get(resId);
  58. bmp = (Bitmap) ref.get();
  59. }
  60. // 如果没有软引用,或者从软引用中得到的实例是null,重新构建一个实例,
  61. // 并保存对这个新建实例的软引用
  62. if (bmp == null) {
  63. bmp = BitmapFactory.decodeResource(context.getResources(), resId);
  64. this.addCacheBitmap(bmp, resId);
  65. }
  66. return bmp;
  67. }
  68.  
  69. * void cleanCache() {
  70. BtimapRef ref = null;
  71. while ((ref = (BtimapRef) q.poll()) != null) {
  72. bitmapRefs.remove(ref._key);
  73. }
  74. }
  75.  
  76. // 清除Cache内的全部内容
  77. public void clearCache() {
  78. cleanCache();
  79. bitmapRefs.clear();
  80. System.gc();
  81. System.runFinalization();
  82. }
  83.  
  84. }

在程序代码中调用该类:

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()

猜你喜欢

转载自blog.csdn.net/u010112268/article/details/82745451
今日推荐