彻底解决Android因加载多个大图引起的OutOfMemoryError,内存溢出的问题(二)
nSideLength == -1) {
return lowerBound;
} else {
return upperBound;
}
}
然后在我需要加载图片BitMap的地方来调用Util.decodeBitmap():
[java]
Bitmap bitmap = BitmapFactory.decodeByteArray(Util.decodeBitmap(imagePath), 0, Util.decodeBitmap(imagePath).length);
imageCache.put(imagePath, new SoftReference(bitmap));
上面这两行是我的AsyncImageLoaderByPath类中的代码,用来加载SD卡里面的图片,该类完整代码是:
[java]
package com.pioneer.travel.util;
import java.io.IOException;
import java.io.InputStream;
import java.lang.ref.SoftReference;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.HashMap;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.BitmapFactory.Options;
import android.graphics.drawable.Drawable;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.util.Log;
import android.widget.ImageView;
public class AsyncImageLoaderByPath {
//SoftReference是软引用,是为了更好的为了系统回收变量
private HashMap> imageCache;
private Context context;
public AsyncImageLoaderByPath(Context context) {
this.imageCache = new HashMap
>();
this.context = context;
}
public Bitmap loadBitmapByPath(final String imagePath, final ImageView imageView, final ImageCallback imageCallback){
if (imageCache.containsKey(imagePath)) {
//从缓存中获取
SoftReference softReference = imageCache.get(imagePath);
Bitmap bitmap = softReference.get();
if (bitmap != null) {
return bitmap;
}
}
final Handler handler = new Handler() {
public void handleMessage(Message message) {
imageCallback.imageLoaded((Bitmap) message.obj, imageView, imagePath);
}
};
//建立新一个获取SD卡的图片
new Thread() {
@Override
public void run() {
Bitmap bitmap = BitmapFactory.decodeByteArray(Util.decodeBitmap(imagePath), 0, Util.decodeBitmap(imagePath).length);
imageCache.put(imagePath, new SoftReference(bitmap));
Message message = handler.obtainMessage(0, bitmap);
handler.sendMessage(message);
}
}.start();
return null;
}
//回调接口
public interface ImageCallback {
public void imageLoaded(Bitmap imageBitmap,ImageView imageView, String imagePath);
}
}
通过这个实例,我验证了一下,一次性获取20张5MB的照片,都可以加载的很流畅,完全没有再出现报OOM的错误了