android - 加载 Bitmap 后释放内存

标签 android memory bitmap

在我的应用程序中,我放置了两个位图。当方向是垂直时,显示第一张图片,如果是水平,则显示第二张图片。使用

Log.i("log","Total memory " + title + " = " + (int) (Runtime.getRuntime().totalMemory()/1024));

我发现在我多次更改手机的方向后,总内存会增加。但是,我希望内存保持不变,似乎程序没有正确释放内存。

这是我的代码

public  Bitmap decodeSampledBitmapFromResource(int path, int reqWidth, int reqHeight, Context ctx){
    // Читаем с inJustDecodeBounds=true для определения размеров
    final BitmapFactory.Options options = new BitmapFactory.Options();
    options.inJustDecodeBounds = true;
    Bitmap b = BitmapFactory.decodeResource(ctx.getResources(), path, options);

    // Вычисляем inSampleSize
    options.inSampleSize = calculateInSampleSize(options, reqWidth,
            reqHeight);

    // Читаем с использованием inSampleSize коэффициента
    options.inJustDecodeBounds = false;
    return BitmapFactory.decodeResource(ctx.getResources(), path, options);
}

public static int calculateInSampleSize(BitmapFactory.Options options,int reqWidth, int reqHeight) {
    // Реальные размеры изображения
    Log.i("log", "inSampleSize" + reqWidth);
    Log.i("log", "inSampleSize" + reqHeight);
    final int height = options.outHeight;
    Log.i("log", "height" + height);
    final int width = options.outWidth;
    Log.i("log", "height" + width);
    int inSampleSize = 1;

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

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

        // Вычисляем наибольший inSampleSize, который будет кратным двум
        // и оставит полученные размеры больше, чем требуемые
        while ((halfHeight / inSampleSize) > reqHeight
                && (halfWidth / inSampleSize) > reqWidth) {
            inSampleSize *= 2;
            Log.i("log", "inSampleSize" + inSampleSize);
        }
    }

    return inSampleSize;
}

private void readImage(int draw) {

    //int px = getResources().getDimensionPixelSize(draw);
    int pxW = displaymetrics.widthPixels;
    int pxH = displaymetrics.heightPixels;
    ***if(bitmap != null){
        bitmap.recycle();
        bitmap = null;
    }***

    bitmap = decodeSampledBitmapFromResource(draw, My_px_W, My_px_H, this);
    ivStart.setImageBitmap(bitmap);

}

这里是onCreate

 if(getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT) {

        My_px_W = 200;
        My_px_H = 150;

        readImage(R.drawable.im2);



        logMemory("'vertical'");
    }
    else if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) {

        My_px_W = 400;
        My_px_H = 200;

        readImage(R.drawable.s2);
        logMemory("'horizontal'");

    }

最佳答案

如果要立即释放,需要在调用recycle后调用System.gc()

单独回收是不够的,因为没有调用垃圾收集器。

Free the native object associated with this bitmap, and clear the reference to the pixel data. This will not free the pixel data synchronously; it simply allows it to be garbage collected if there are no other references. The bitmap is marked as "dead", meaning it will throw an exception if getPixels() or setPixels() is called, and will draw nothing. 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.

关于android - 加载 Bitmap 后释放内存,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29993822/

相关文章:

android - adb push libdvm.so

android - 如何以编程方式设置 TabHost 选中和未选中图标?

java - 如何从 Android 应用程序的 Java 代码配置 Pushwoosh

c - 释放调用者中由被调用者重新分配的内存?

Android 小部件 Canvas - java.lang.IllegalArgumentException

Android 从 Canvas 中获取位图

java - 创建位图不起作用

java - 如何在 Fragment 中解决这个问题?

c# -- 堆栈 cookie 检测代码检测到基于堆栈的缓冲区溢出

java - 尽管有足够的可用内存,但巨大的数组仍会耗尽内存