如何从我的Android应用程序克服OutOfMemory错误。

时间:2014-09-06 04:39:51

标签: android bitmap bitmapfactory android-bitmap

我正在创建一个应用程序,它将六个位图作为按钮背景加载,以便在用户对此执行某些操作时更改按钮状态,但有时会出现错误,如

  

java.lang.OutOfMemoryError:位图大小超过VM预算

我在MainActivity中使用以下方法来设置位图:

            on_duty.setBackgroundDrawable(GetApplicationDrawable
                    .Button3(R.drawable.on_duty_d));
            off_duty.setBackgroundDrawable(GetApplicationDrawable
                    .Button3(R.drawable.off_duty));
            journey_start.setBackgroundDrawable(GetApplicationDrawable
                    .Button3(R.drawable.journey));
            journey_end.setBackgroundDrawable(GetApplicationDrawable
                    .Button3(R.drawable.destination_d));
            metting_in.setBackgroundDrawable(GetApplicationDrawable
                    .Button3(R.drawable.meeting));
            metting_out.setBackgroundDrawable(GetApplicationDrawable
                    .Button3(R.drawable.over_d));

我的GetApplicationDrawable类中的Button3方法与下面的解码位图

相似
public static Drawable Button3(int res_id) {
    Bitmap bitmap = null;
    try {
        bitmap = BitmapFactory.decodeResource(context.getResources(),
                res_id);

    } catch (Exception e) {
        e.printStackTrace();
    }
    int width = bitmap.getWidth();
    int height = bitmap.getHeight();
    float newWidth = (float) ((float) wt / 3);
    float scaleWidth = ((float) newWidth) / width;
    float newHeight = (float) ((float) wt / 4);
    float scaleHeight = ((float) newHeight) / height;
    Matrix matrix = new Matrix();
    matrix.postScale(scaleWidth, scaleHeight);
    Bitmap mannagedBitmap = bitmapMannagement(context.getResources(),
            res_id, width, height);
    Bitmap resizedBitmap = Bitmap.createScaledBitmap(mannagedBitmap,
            (int) newWidth, (int) newHeight, true);
    Drawable d = new BitmapDrawable(context.getResources(), resizedBitmap);
    return d;
}

感谢。

1 个答案:

答案 0 :(得分:0)

当此代码失败时,您需要退出该功能或正常处理它。

try {
    bitmap = BitmapFactory.decodeResource(context.getResources(),
            res_id);

} catch (Exception e) {
    e.printStackTrace();
    // here you need to get out of the function 
    // or recover gracefully
    //TODO set the bitmap to a default bitmap.
    //TODO or return a null;
}