【问题标题】:How to overcome OutOfMemory error from my android app.?如何克服我的 android 应用程序中的 OutOfMemory 错误。?
【发布时间】:2014-09-06 04:39:50
【问题描述】:

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

的错误

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;
}

谢谢。

【问题讨论】:

  • Eeek,为什么是静态的?和大写?我建议您使用较小的位图——它们有多大? -- 并清理不必要的静态代码。
  • 我已经删除了静态,问题仍然存在。

标签: android bitmap bitmapfactory android-bitmap


【解决方案1】:

当这段代码失败时,你需要退出函数或优雅地处理它。

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;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-07-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多