android - 位图被垃圾收集后是否可以使用?

标签 android bitmap garbage-collection imageview bitmapfactory

我在看这个视频,它讨论了位图的内存分配和垃圾回收:

DevBytes: Bitmap Allocation

Chet 正在谈论它是如何在 SDK 11 之前由开发人员管理的通过使用 .recycle()SDK 11 之后它由 GC 管理.

对于一个更实际的案例,目前我正在编写一个应用程序,它位于 Activities 中的一个中。我创建了许多 fragment ,它们基​​本上包含一个可滚动的布局 ImageViews .这些图像是从设备相机创建的。所以我遇到了 OutOfMemory问题并意识到我必须重新调整从相机获得的图像的大小,因为结果非常高分辨率并且占用了我所有的应用程序内存。

所以现在我正在使用这种方法重新调整大小并设置非常小的图像:

img.setImageBitmap(decodeSampledBitmapFromFile(imagePath, 100, 70));

decodeSampledBitmapFromFile是:

    public static Bitmap decodeSampledBitmapFromFile(String path, int reqWidth, int reqHeight) 
{ // BEST QUALITY MATCH

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

    // Calculate inSampleSize
        // Raw height and width of image
        final int height = options.outHeight;
        final int width = options.outWidth;
        options.inPreferredConfig = Bitmap.Config.RGB_565;
        int inSampleSize = 1;

        if (height > reqHeight) {
            inSampleSize = Math.round((float)height / (float)reqHeight);
        }

        int expectedWidth = width / inSampleSize;

        if (expectedWidth > reqWidth) {
            //if(Math.round((float)width / (float)reqWidth) > inSampleSize) // If bigger SampSize..
            inSampleSize = Math.round((float)width / (float)reqWidth);
        }
    options.inSampleSize = inSampleSize;

    // Decode bitmap with inSampleSize set
    options.inJustDecodeBounds = false;

    return BitmapFactory.decodeFile(path, options);
  }

但我仍然没有调用 .recycle()任何位图上的方法,因为我需要它们全部出现在屏幕上。

我的问题是:

1.如果我调用.recycle()在已经设置为 ImageView 的位图上使用 setImageBitmap这是否意味着它会从屏幕上消失或者我可能会收到异常?

2. 如果我不打电话 .recycle()但我在 Galaxy S3 上运行我的应用程序 (4.2.1)例如,当我的申请是 minSDK is 8 . GC 会为我完成这项工作吗?

3. 在视频中,他使用 BitmapFactory 谈论位图重用对象,有没有办法在 SDK 11 之前做到这一点?

最佳答案

Recycle documentation

  1. 我从来没有以这种方式使用过它。根据文档,您有异常的风险
  2. 是的。如果您已将对位图的所有引用都设置为 null,它将被收集。

    This operation cannot be reversed, so it should only be called if you are sure there are no further uses for the bitmap. This is an advanced call, and normally need not be called, since the normal GC process will free up this memory when there are no more references to this bitmap.

  3. 不知道以这种方式“重用”位图。查看“Managing Bitmap Memory”和“Caching Bitmaps”主题以获取更多信息。

关于android - 位图被垃圾收集后是否可以使用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15954718/

相关文章:

android - 如何确定手机是否有缺口

java - 每 x 秒检查一次 html 页面

Android,从不同的 Activity 在缓存中保存和加载位图

Python 垃圾收集器文档

swift - 如何识别 Swift 中的强引用循环?

android - ionic 应用程序不能在 4.x android 平台上运行

android - 华为 protected 应用程序的 Intent

Android View 到具有透明度的位图

位图上的 C++ 模糊效果有效但颜色已更改

C#:收集 WeakReference 之前的通知?