Android - 跟踪BitmapFactory的内存泄漏

时间:2013-11-17 22:08:05

标签: android memory-leaks bitmapfactory

我正在尝试修复内存泄漏问题/了解我的应用中发生了什么。我将代码缩减为这个简单的测试(加载13575x8145像素的巨大图像,inSampleSize为6):

File file = new File("/storage/sdcard0/Documents/test_13575x8145.png");
BitmapFactory.Options options = new BitmapFactory.Options();
options.inSampleSize = 6;
Utils.printMemoryUsage();
Bitmap b = BitmapFactory.decodeFile(file.getAbsolutePath(), options);
b.recycle();
b = null;
Utils.printMemoryUsage();

Utils.printMemoryUsage()是以下方法:

public static void printMemoryUsage() {

    //Getting the runtime reference from system
    float mb = 1024*1024;
    Runtime runtime = Runtime.getRuntime();

    Log.i("Utils", "------------------------");
    Log.i("Utils", "Memory usage :");
    Log.i("Utils", "Used Memory:" + (float)(runtime.totalMemory() - runtime.freeMemory()) / mb);
    Log.i("Utils", "Free Memory:" + (float)runtime.freeMemory() / mb);
    Log.i("Utils", "Total Memory:" + (float)runtime.totalMemory() / mb);
    Log.i("Utils", "Max Memory:" + (float)runtime.maxMemory() / mb);
    Log.i("Utils", "------------------------");
}

我的示例代码的哪些输出:

11-17 22:53:08.631: I/Utils(12974): ------------------------
11-17 22:53:08.631: I/Utils(12974): Memory usage :
11-17 22:53:08.631: I/Utils(12974): Used Memory:7.999222
11-17 22:53:08.631: I/Utils(12974): Free Memory:0.82084656
11-17 22:53:08.631: I/Utils(12974): Total Memory:8.820282
11-17 22:53:08.636: I/Utils(12974): Max Memory:64.0
11-17 22:53:08.636: I/Utils(12974): ------------------------
...
11-17 22:53:15.276: I/Utils(12974): ------------------------
11-17 22:53:15.276: I/Utils(12974): Memory usage :
11-17 22:53:15.276: I/Utils(12974): Used Memory:20.07035
11-17 22:53:15.276: I/Utils(12974): Free Memory:0.62480164
11-17 22:53:15.276: I/Utils(12974): Total Memory:20.695282
11-17 22:53:15.281: I/Utils(12974): Max Memory:64.0
11-17 22:53:15.281: I/Utils(12974): ------------------------

这是正常的吗?我知道对recycle()的调用不会立即生效,但即使我稍后打印内存使用情况,也不会释放内存。 感谢

编辑:如果我多次运行代码,堆不再增长(这是正常的,堆足够大,可以再次加载图像)。但是仍然没有释放内存(runtime.freeMemory()仍然接近0)

0 个答案:

没有答案