[安卓开发] ImageView加载图片内存溢出oom解决方案

时间:2022-10-16 20:58:23

工具类加一个静态方法:


/**
* 以最省内存的方式读取本地资源的图片
* @param context 上下文
* @param resId 资源Id
* @return 返回bitmap
*/

public static Bitmap readBitMap(Context context, int resId){
BitmapFactory.Options opt = new BitmapFactory.Options();
//压缩编码
opt.inPreferredConfig = Bitmap.Config.RGB_565;
//下面两个过时了,但没影响
opt.inPurgeable = true;
opt.inInputShareable = true;

InputStream is = context.getResources().openRawResource(resId);
return BitmapFactory.decodeStream(is,null,opt);
}

调用的时候:

imageView.setImageBitmap(bitmap);
bitmap.recycle(); //回收
System.gc(); //提醒系统几时回收

这时候问题来了,你会发现recycle报错,这时候我们需要重写一下ImageView:

public class ExcetionImageView extends ImageView{
public ExcetionImageView(Context context) {
super(context);
}

public ExcetionImageView(Context context, AttributeSet attrs) {
super(context, attrs);
}

@Override
protected void onDraw(Canvas canvas) {
try {
super.onDraw(canvas);
}catch (Exception e){
e.printStackTrace();
}
}
}

ps: 本文由网上资料总结而来