Android在小内存手机(运存2G)加载图片Java.lang.OutOfMemeoryError
程序员文章站
2022-04-26 23:29:12
...
问题的发现
测试给提了个bug :选择图片上传APP闪退。我随手拿起手机测试,并未复现,随即拿上测试用的机型,依然没有,找测试——》又出现了——》我说你给我操作一次,然后一调试发现是Java.lang.OutOfMemeoryError异常,还是gradle引入的库里面的,换框架成本太高,算了,调试一把,定位问题以后,发现是这行代码报错
随后使用Profiler查看内存,超过128M的时候就报错了,后来测试了半天,发现只有在运行内存2个G的手机上有问题,既然发现了问题,那就针对这个做下改动
问题解决
BitmapFactory.Options options = new BitmapFactory.Options();
float maxMemory = (float) (Runtime.getRuntime().maxMemory() * 1.0/ (1024 * 1024));
Log.d("compress","maxMemory-------------------------"+maxMemory);
if(maxMemory <= 128){//针对内存小的手机进行了优化
options.inSampleSize = computeSize() <= 1 ? computeSize() : computeSize() + 2;
}else {
options.inSampleSize = computeSize();
}
Bitmap tagBitmap = BitmapFactory.decodeFile(srcImg, options);
ByteArrayOutputStream stream = new ByteArrayOutputStream();
tagBitmap = rotatingImage(tagBitmap);
tagBitmap.compress(Bitmap.CompressFormat.JPEG, 90, stream);
tagBitmap.recycle();
FileOutputStream fos = new FileOutputStream(tagImg);
fos.write(stream.toByteArray());
fos.flush();
fos.close();
stream.close();
private int computeSize() {
srcWidth = srcWidth % 2 == 1 ? srcWidth + 1 : srcWidth;
srcHeight = srcHeight % 2 == 1 ? srcHeight + 1 : srcHeight;
int longSide = Math.max(srcWidth, srcHeight);
int shortSide = Math.min(srcWidth, srcHeight);
float scale = ((float) shortSide / longSide);
if (scale <= 1 && scale > 0.5625) {
if (longSide < 1664) {
return 1;
} else if (longSide >= 1664 && longSide < 4990) {
return 2;
} else if (longSide > 4990 && longSide < 10240) {
return 4;
} else {
return longSide / 1280 == 0 ? 1 : longSide / 1280;
}
} else if (scale <= 0.5625 && scale > 0.5) {
return longSide / 1280 == 0 ? 1 : longSide / 1280;
} else {
return (int) Math.ceil(longSide / (1280.0 / scale));
}
}