位图大小超过VM预算内存错误

时间:2013-10-29 13:55:43

标签: java android memory bitmap

我正在设置一个位图作为我的背景,工作正常,没有错误。但是,当我按下后退按钮并再次使用后台进行活动时,我得到上述内存不足错误。当活动失去焦点时,我需要清楚一些事情吗?

设置位图的代码:

BitmapFactory.Options options = new BitmapFactory.Options();
    options.inSampleSize = 1;
    options.inJustDecodeBounds = false;
    map = BitmapFactory.decodeFile(mapFile.getAbsolutePath(), options);

然后我使用createScaledBitmap()来设置图像。

这种内存不足问题只发生在我离开活动并重新开始时。它第一次工作正常,所以我猜我在内存中创建多个位图图像,但看不到哪里?

如果存在某些内容,则为decodeFile()方法:

try {
                // decode image size
                BitmapFactory.Options o = new BitmapFactory.Options();
                o.inJustDecodeBounds = true;
                BitmapFactory.decodeStream(new FileInputStream(f), null, o);
                // Find the correct scale value. It should be the power of 2.
                final int REQUIRED_SIZE = 70;
                int width_tmp = o.outWidth, height_tmp = o.outHeight;

                int scale = 1;
                while (true) {
                    if (width_tmp / 2 < REQUIRED_SIZE
                            || height_tmp / 2 < REQUIRED_SIZE)
                        break;
                    width_tmp /= 2;
                    height_tmp /= 2;
                    scale++;
                }

                // decode with inSampleSize
                BitmapFactory.Options o2 = new BitmapFactory.Options();
                o2.inSampleSize = scale;
                return BitmapFactory.decodeStream(new FileInputStream(f), null, o2);
            } catch (FileNotFoundException e) {
            }
            return null;
        }

非常感谢。

2 个答案:

答案 0 :(得分:0)

检查Android training有关位图内存管理的信息。

关于您的问题,请在完成位图后尝试调用Bitmap.recycle(),例如在onDestroy()方法中。

答案 1 :(得分:0)

根据Android Developer

  

Android设备可以为单个应用程序提供少至16MB的内存。

基本上您的图像正在加载但未从应用程序中释放,因此留下的空间较小,因此错误发生的原因。我一直面对这个错误,直到我偶然发现了如何解决它的教程。我建议按照它的步骤。这是tutorial

相关问题