在调整大位图的大小以更快地将图像上传到服务器时,我偶尔会遇到 OutOfMemoryErrors。 为了防止这种情况,我计算了所需的内存量并在尝试缩放图像之前检查它是否超过 Runtime.getRuntime().maxMemory()。
但是,即使图像应该很容易适合堆,我仍然会遇到 OOM 错误。
模拟设备 (Galaxy SII API 16) 使用上述方法为我提供了 67108864 字节的最大内存。
在以下代码段中,堆大小为 43975K,并且只有不到 15K 的内存在使用中。对于我的 ~31K 分配,堆应该自动增长到大约 45K,这仍然不接近 64 MiB 的最大大小。 但是正如您所见,dalvik 虚拟机没有扩展堆,而是内存不足。
10-13 20:35:57.223: D/dalvikvm(1201): GC_FOR_ALLOC freed 505K, 67% free 14692K/43975K, paused 31ms, total 31ms
10-13 20:35:57.223: I/dalvikvm-heap(1201): Forcing collection of SoftReferences for 31961100-byte allocation
10-13 20:35:57.251: D/dalvikvm(1201): GC_BEFORE_OOM freed 2K, 67% free 14689K/43975K, paused 29ms, total 29ms
10-13 20:35:57.251: E/dalvikvm-heap(1201): Out of memory on a 31961100-byte allocation.
我想知道这是否也会发生在真实设备上,或者这是否可能是 genymotion 错误。
堆是否保证扩展到 maxMemory()? Runtime.getRuntime().freeMemory() 的 JavaDoc 说它“可能”扩展,不管那是什么意思。
我只需要一个可靠的方法来计算我可以使用的内存量,我就是这样做的,如果我错了请纠正我:
long maxMemory = Runtime.getRuntime().maxMemory();
long usedMemory = Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory();
long availableMemory = maxMemory - usedMemory;
此调用导致 OutOfMemoryError:
// outOptions has an appropriate inSampleSize
BitmapFactory.decodeStream(inputStream, null, outOptions);
最佳答案
Out of memory on a 31961100-byte allocation
你的位图是32M。 VM 无法分配 32M 线性空间来存储位图。堆是 fragment 化的,所以即使你的堆有 32M 的空闲空间,也不总是可以分配这样的线性空间。您可以尝试释放尽可能多的内存并在解码流之前调用 GC。
尝试解码您的位图更多effective way . Or process image in parts . 如果您告诉我们您为什么需要这张图片,我们可以告诉您如何处理它。
关于android - 堆不会在 Genymotion 模拟器上扩展,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26349195/