转:android加载大量图片内存溢出的三种解决办法_冰风漫天_新浪博客

方法一:

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

 


  • 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的软引用,进行图片缓存,将经常需要加载的图片,存放在缓存里,避免反复加载。

如果一个对象只具有软引用,若内存空间足够则不会回收它;若不足则会回收该对象的内存。软引用可用来实现内存敏感的高速缓存。

软引用可以与一个引用队列联合使用。如果软引用所使用的对象被垃圾回收器回收,Java虚拟机就会把这个软引用加到与之相关的引用队列中去。以下是实现的一个图片缓存的工具类。

  • public class BitmapCache {
  • static * BitmapCache cache;
  • * Hashtable bitmapRefs;
  • * ReferenceQueue q;
  •  
  • * class BtimapRef extends SoftReference {
  • * Integer _key = 0;
  •  
  • public BtimapRef(Bitmap bmp, ReferenceQueue q, int key) {
  • super(bmp, q);
  • _key = key;
  • }
  • }
  •  
  • * BitmapCache() {
  • bitmapRefs = new Hashtable();
  • q = new ReferenceQueue();
  •  
  • }
  •  
  • public static BitmapCache getInstance() {
  • if (cache == null) {
  • cache = new BitmapCache();
  • }
  • return cache;
  •  
  • }
  •  
  • * void addCacheBitmap(Bitmap bmp, Integer key) {
  • cleanCache();// 清除垃圾引用
  • BtimapRef ref = new BtimapRef(bmp, q, key);
  • bitmapRefs.put(key, ref);
  • }
  •  
  • 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;
  • }
  •  
  • * 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();



转载地址:http://www.360doc.com/content/13/0409/11/7857928_277107102.shtml

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

冰风漫天

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值