【问题标题】:Get memory leak when decode small jpg image in Android在 Android 中解码小 jpg 图像时出现内存泄漏
【发布时间】:2014-01-15 11:55:31
【问题描述】:

我在我的应用中将一个小的 jpg 图像解码为位图。

图像只有 40K。

我使用这些方法:

public Bitmap decodeSampledBitmapFromResource(String pathName,int reqWidth, int reqHeight) {

    // First decode with inJustDecodeBounds=true to check dimensions
    final BitmapFactory.Options options = new BitmapFactory.Options();
    options.inJustDecodeBounds = true;
    BitmapFactory.decodeFile(pathName, options);

    // Calculate inSampleSize
    options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);

    // Decode bitmap with inSampleSize set
    options.inJustDecodeBounds = false;
    Bitmap bmp=BitmapFactory.decodeFile(pathName, options);
    return bmp;
}

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

当程序转到:

Bitmap bmp=BitmapFactory.decodeFile(pathName, options);
我在 LogCat 中得到 GC_Concurrent,

为什么?

【问题讨论】:

  • 什么语言?什么平台?
  • Eclipse 中的 Adroid (Java)
  • 你如何确定有泄漏? GC_CONCURRENT 消息只是来自垃圾收集器的正常状态消息,并不表示任何形式的泄漏。也就是说,到底是什么问题?
  • 知道 GC_CONCURRENT 是坏的并且可能导致 OUT OF MEMORY ERROR。另请参阅本课 youtube.com/watch?v=_CruQY55HOk

标签: android memory bitmap imageview


【解决方案1】:

GC_CONCURRENT 本身还不错。这只是垃圾收集器正在执行其工作的状态消息。图像解码涉及内存分配,看到垃圾收集器运行是正常的。

【讨论】:

  • 非常感谢 laalto :)
  • GC_FOR_ALLOC 是另一回事吗?这个警告是不是很糟糕?
  • 不一定。这只是由内存分配触发的另一个 GC 运行。
  • 但是我一次又一次地看到这个按摩,并且千字节的数量在增加,直到我得到OOM错误。我是否需要释放列表视图中不再可见的位图?
  • 您应该确保没有任何东西持有对您不再需要的对象的引用,以便 GC 可以回收内存。
猜你喜欢
  • 2015-11-22
  • 1970-01-01
  • 2020-09-21
  • 1970-01-01
  • 2011-04-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多