【问题标题】:java.lang.OutOfMemoryError for small images小图像的 java.lang.OutOfMemoryError
【发布时间】:2015-03-04 22:38:48
【问题描述】:

在我正在开发的应用程序中,您可以在多个背景之间进行选择,每次我为布局选择背景时,我都会设置它

relativeLayout.setBackground(getResources().getDrawable(R.drawable.background));

每个背景的分辨率为 1440x2560 像素,但每个只有大约 12 KB 和 4 位深度。

问题是有时当我选择后台应用程序时会崩溃并出现错误java.lang.OutOfMemoryError

为什么会发生这种情况以及如何解决?

【问题讨论】:

  • 文件大小不相关。这些图像很大。 1440 x 2560 x 4 字节约为 11MB。
  • 图像可能在 12 MB 左右,而不是 12 KB...

标签: android


【解决方案1】:

问题很简单。每次单击按钮更改位图时都需要回收位图,否则它将留在内存中并最终引发内存不足异常。

无论如何,如果您想解决此问题,请在您的活动中保留对位图的引用。

私有位图 currentBitmap;

public void changeBitmap(Bitmap bitmap){
  relativeLayout.setBackgroundImage(bitmap);
  if(currentBitmap != null){    
  /*this is where the magic happens, you                
  recycle your old bitmap whose reference you had stored in the global 
  variable*/
    currentBitmap.recycle();
  }
  currentBitmap = bitmap;
}

【讨论】:

    【解决方案2】:

    加载前调整图片大小

     public Bitmap resizeBitmap(int targetW, int targetH) {
        BitmapFactory.Options bmOptions = new BitmapFactory.Options();
        bmOptions.inJustDecodeBounds = true;
        BitmapFactory.decodeFile(photoPath, bmOptions);
        int photoW = bmOptions.outWidth;
        int photoH = bmOptions.outHeight; 
        int scaleFactor = 1;
        if ((targetW > 0) || (targetH > 0)) { 
            scaleFactor = Math.min(photoW/targetW, photoH/targetH); 
        }
        bmOptions.inJustDecodeBounds = false;
        bmOptions.inSampleSize = scaleFactor;
        bmOptions.inPurgeable = true;
    
        return BitmapFactory.decodeFile(photoPath, bmOptions);
    }
    

    【讨论】:

      【解决方案3】:

      <application> 的AndroidManifest 中,quckfix 是android:largeHeap="true" 但我认为在屏幕上显示 Drawable 需要大量 RAM。 Dirty Fix 是,当您以编程方式调用垃圾收集器时。

      我仍在寻找干净的修复方法。

      【讨论】:

      • Android 说 largeheap 并不总是有效,在这种情况下,用户正在加载大分辨率图像,它会导致内存不足异常。我们应该在加载之前调整图像大小
      • 调用 GC 不会做任何事情。
      猜你喜欢
      • 1970-01-01
      • 2010-12-29
      • 1970-01-01
      • 2018-07-29
      • 1970-01-01
      • 2013-12-04
      • 1970-01-01
      • 1970-01-01
      • 2011-04-26
      相关资源
      最近更新 更多