今天工作的时候遇到了这种情况,在app重复不断的开启关闭的时候或者不停切换页面的时候会有BitmapFactory.decodeResource这个方法导致oom的状况,我分析了一下是因为bitmap没有及时释放而且加载的图片占用内存较大造成的。解决方法使用BitmapFactory.decodeStream代替,并且改变图片的质量。代码如下
/**
* 加载图片
*
* @param resources
* @param id
* @return Bitmap
*/
public static Bitmap decodeBitmapResource(Resources resources, int id) {
Bitmap bitmap;
InputStream is = resources.openRawResource(id);
BitmapFactory.Options opts = new BitmapFactory.Options();
opts.inPurgeable = true;
opts.inInputShareable = true;
opts.inPreferredConfig = Bitmap.Config.RGB_565;
bitmap = BitmapFactory.decodeStream(is, null, opts);
return bitmap;
}
/**
* 加载图片
*
* @param resources
* @param id
* @return Drawable
*/
public static Drawable decodeDrawableResource(Resources resources, int id) {
InputStream is = resources.openRawResource(id);
BitmapFactory.Options opts = new BitmapFactory.Options();
opts.inPurgeable = true;
opts.inInputShareable = true;
opts.inPreferredConfig = Bitmap.Config.RGB_565;
return new BitmapDrawable(resources, is);
}
切记inPreferredConfig 不要使用ARGB_8888。