所以我的 ListView
有一个延迟图像加载器。我也用 this tutorial为了更好的内存管理,并将 SoftReference
位图图像存储在我的 ArrayList
中。
我的 ListView
可以从数据库加载 8 张图片,然后一旦用户一直滚动到底部,它就会加载另外 8 张图片,依此类推。当大约有 35 张或更少图片时没有问题,但是,我的应用程序因 OutOfMemoryError
强制关闭。
我无法理解的是我的代码在 try catch 中:
try
{
BitmapFactory.Options o = new BitmapFactory.Options();
o.inJustDecodeBounds = true;
BitmapFactory.decodeByteArray(image, 0, image.length, o);
//Find the correct scale value. It should be the power of 2.
int width_tmp = o.outWidth, height_tmp = o.outHeight;
int scale = 1;
while(true)
{
if(width_tmp/2 < imageWidth || height_tmp/2 < imageHeight)
{
break;
}
width_tmp/=2;
height_tmp/=2;
scale++;
}
//Decode with inSampleSize
BitmapFactory.Options o2 = new BitmapFactory.Options();
o2.inSampleSize = scale;
bitmapImage = BitmapFactory.decodeByteArray(image, 0, image.length, o2);
}
catch (Exception e)
{
e.printStackTrace();
}
但是 try catch block 没有捕捉到 OutOfMemory
异常,据我所知,当应用程序内存不足停止时,应该清除 SoftReference
位图图像抛出 OutOfMemory
异常。
我在这里做错了什么?
最佳答案
我想这篇文章可能会对你有所帮助
//decodes image and scales it to reduce memory consumption
private Bitmap decodeFile(File f){
try {
//Decode image size
BitmapFactory.Options o = new BitmapFactory.Options();
o.inJustDecodeBounds = true;
BitmapFactory.decodeStream(new FileInputStream(f),null,o);
//The new size we want to scale to
final int REQUIRED_SIZE=70;
//Find the correct scale value. It should be the power of 2.
int width_tmp=o.outWidth, height_tmp=o.outHeight;
int scale=1;
while(true){
if(width_tmp/2<REQUIRED_SIZE || height_tmp/2<REQUIRED_SIZE)
break;
width_tmp/=2;
height_tmp/=2;
scale*=2;
}
//Decode with inSampleSize
BitmapFactory.Options o2 = new BitmapFactory.Options();
o2.inSampleSize=scale;
return BitmapFactory.decodeStream(new FileInputStream(f), null, o2);
} catch (FileNotFoundException e) {}
return null;
}
关于java.lang.OutOfMemoryError : bitmap size exceeds VM budget 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3956702/