【问题标题】:App crashes due to out of memory exception at setCotentView(R.layout_file_name) line由于 setCotentView(R.layout_file_name) 行的内存不足异常,应用程序崩溃
【发布时间】:2016-08-06 02:38:58
【问题描述】:

它的内存不足错误在-

        setContentView(R.layout.activity_home);

错误日志是-

USER_COMMENT=null
ANDROID_VERSION=5.0 
APP_VERSION_NAME=1.0
BRAND=samsung
PHONE_MODEL=SM-G900H
CUSTOM_DATA=
STACK_TRACE=java.lang.OutOfMemoryError: Failed to allocate a 944652 byte allocation with 751892 free bytes and 734KB until OOM
...........................      

有时在同一行充气时也会出现二进制 xml 错误。 每次运行代码时,偶尔都会出现错误。 有谁也见过或知道原因吗?提前致谢。

【问题讨论】:

  • 有根据的猜测:您的布局中有一个巨大的图像作为背景。
  • 简单的方法是将 largeHeap=true 放在清单中,但上面的评论可能是正确的。
  • @laalto,我也在想这个,但是我们如何解决它,因为那个图像非常重要。
  • @Nanoc,但我已经读过使用它来解决内存不足错误的好习惯。
  • 也许几年前这更有意义,但现在有了比我的 PC 更多 RAM 的手机,它就不再那么重要了。无论如何,android 应用程序堆限制很低。

标签: android android-layout error-handling runtime-error


【解决方案1】:

正如 cmets 所建议的那样,您正在加载的图像的大小存在问题。

首先仅将图像用作目标屏幕大小的资源,然后使用具有不同密度和大小的资源文件夹为每个设备提供适当的图像。 (HDPI、XHDPI、ETC)

还要考虑到内存分配与位图的2次方有关,所以可能稍微小一点的尺寸会有很大的不同,你可以用BitmapFactory这样的东西来测试一下。

public static int calculateInSampleSize(
        BitmapFactory.Options options, int reqWidth, int reqHeight) {
// Raw height and width of image
final int height = options.outHeight;
final int width = options.outWidth;
int inSampleSize = 1;

if (height > reqHeight || width > reqWidth) {

    final int halfHeight = height / 2;
    final int halfWidth = width / 2;

    // Calculate the largest inSampleSize value that is a power of 2 and keeps both
    // height and width larger than the requested height and width.
    while ((halfHeight / inSampleSize) > reqHeight
            && (halfWidth / inSampleSize) > reqWidth) {
        inSampleSize *= 2;
    }
}

return inSampleSize;

}

来自android doc处理位图:http://developer.android.com/intl/es/training/displaying-bitmaps/load-bitmap.html#load-bitmap

【讨论】:

    【解决方案2】:

    从 cmets 看来,您的背景图像很大,因此您需要采取几个步骤来减少内存需求。

    首先压缩图像(例如使用 Photoshop 的“导出为 Web”选项)。

    如果导出的图像是具有透明度或 alpha 的 PNG,则将导出的图像设为 JPG 可能是明智之举,因为背景不需要此信息。

    一旦您拥有压缩大小的图像,请确保您使用的是适合您设备的版本 - 不要为您的最大目标设备制作足够大的单个大图像,但也要为您的低规格设备制作较小的版本需要放置在特定于设备组的可绘制文件夹中。

    您可以在 Supporting Multiple Screen Sizes 文档中查看这些组,但您需要的文件夹是

    • res/drawable-mdpi/graphic.png // 中等密度的位图
    • res/drawable-hdpi/graphic.png // 高密度位图(约480*720)
    • res/drawable-xhdpi/graphic.png // 超高密度位图
    • res/drawable-xxhdpi/graphic.png //(根据Gurvinders 的评论,大约为 960 * 1,440)

    【讨论】:

      猜你喜欢
      • 2011-04-29
      • 2013-06-15
      • 2012-07-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-04-18
      • 2022-01-08
      相关资源
      最近更新 更多