我目前正在努力解决 Android 平台的一个奇怪行为——位图/Java 堆内存限制。根据设备的不同,Android 将应用程序开发人员的 Java 堆空间限制为 16、24 或 32 MiB(或者您可能会在已 root 的手机上找到任何随机值)。这可以说是相当小,但相对简单,因为我可以使用以下 API 来测量使用情况:
Runtime rt = Runtime.getRuntime();
long javaBytes = rt.totalMemory() - rt.freeMemory();
long javaLimit = rt.maxMemory();
很简单;现在是转折点。在 Android 中,除了少数异常(exception),位图都存储在 native 堆中,并且不计入 Java 堆。谷歌的一些目光敏锐、纯粹主义的开发人员认为这是“糟糕的”,并允许开发人员获得“超过他们应得的份额”。因此,有一段漂亮的小代码可以计算位图以及可能的其他资源所产生的 native 内存使用量,并将其与 Java 堆相加,如果您查看..... java.lang.OutOfMemory。 哎呀
不过没什么大不了的。我有很多位图,并不总是需要所有的。我可以“调出”一些目前未使用的内容:
因此,对于尝试 #1,我重构了代码,以便可以使用 try/catch 包装每个位图加载:
while(true) {
try {
return BitmapFactory.decodeResource(context.getResources(), android_id, bitmapFactoryOptions);
} catch (java.lang.OutOfMemory e) {
// Do some logging
// Now free some space (the code below is a simplified version of the real thing)
Bitmap victim = selectVictim();
victim.recycle();
System.gc(); // REQUIRED; else, weird behavior ensues
}
}
看,这是一个不错的小日志 fragment ,显示了我的代码捕获异常并回收了一些位图:
E/Epic (23221): OUT_OF_MEMORY (caught java.lang.OutOfMemory) I/Epic (23221): ArchPlatform[android].logStats() - I/Epic (23221): LoadedClassCount=0.00M I/Epic (23221): GlobalAllocSize=0.00M I/Epic (23221): GlobalFreedSize=0.02M I/Epic (23221): GlobalExternalAllocSize=0.00M I/Epic (23221): GlobalExternalFreedSize=0.00M I/Epic (23221): EpicPixels=26.6M (this is 4 * #pixels in all loaded bitmaps) I/Epic (23221): NativeHeapSize=29.4M I/Epic (23221): NativeHeapAllocSize=25.2M I/Epic (23221): ThreadAllocSize=0.00M I/Epic (23221): totalMemory()=9.1M I/Epic (23221): maxMemory()=32.0M I/Epic (23221): freeMemory()=4.4M W/Epic (23221): Recycling bitmap 'game_word_puzzle_11_aniframe_005' I/Epic (23221): BITMAP_RECYCLING: recycled 1 bitmaps worth 1.1M). age=294
请注意,totalMemory - freeMemory 只有 4.7 MiB,但大约有 26 MiB?位图占用的 native 内存为 MiB,我们在 31/32 MiB 范围内达到了极限。我在这里仍然有点困惑,因为所有加载的位图的运行计数为 26.6 MiB,但 native 分配大小仅为 25.2 MiB。所以我算错了。但这一切都在大概范围内,并且明确地证明了内存限制下发生的跨池“求和”。
我以为我已经修好了。但不,Android 不会那么轻易放弃......
以下是我从四个测试设备中的两个获得的结果:
I/dalvikvm-heap(17641): Clamp target GC heap from 32.687MB to 32.000MB D/dalvikvm(17641): GC_FOR_MALLOC freed <1K, 41% free 4684K/7815K, external 24443K/24443K, paused 24ms D/dalvikvm(17641): GC_EXTERNAL_ALLOC freed <1K, 41% free 4684K/7815K, external 24443K/24443K, paused 29ms E/dalvikvm-heap(17641): 1111200-byte external allocation too large for this process. E/dalvikvm(17641): Out of memory: Heap Size=7815KB, Allocated=4684KB, Bitmap Size=24443KB, Limit=32768KB E/dalvikvm(17641): Trim info: Footprint=7815KB, Allowed Footprint=7815KB, Trimmed=880KB E/GraphicsJNI(17641): VM won't let us allocate 1111200 bytes I/dalvikvm-heap(17641): Clamp target GC heap from 32.686MB to 32.000MB D/dalvikvm(17641): GC_FOR_MALLOC freed <1K, 41% free 4684K/7815K, external 24443K/24443K, paused 17ms I/DEBUG ( 1505): *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** I/DEBUG ( 1505): Build fingerprint: 'verizon_wwe/htc_mecha/mecha:2.3.4/GRJ22/98797:user/release-keys' I/DEBUG ( 1505): pid: 17641, tid: 17641 I/DEBUG ( 1505): signal 11 (SIGSEGV), code 1 (SEGV_MAPERR), fault addr 00000000 I/DEBUG ( 1505): r0 0055dab8 r1 00000000 r2 00000000 r3 0055dadc I/DEBUG ( 1505): r4 0055dab8 r5 00000000 r6 00000000 r7 00000000 I/DEBUG ( 1505): r8 000002b7 r9 00000000 10 00000000 fp 00000384 I/DEBUG ( 1505): ip 0055dab8 sp befdb0c0 lr 00000000 pc ab14f11c cpsr 60000010 I/DEBUG ( 1505): d0 414000003f800000 d1 2073646565637834 I/DEBUG ( 1505): d2 4de4b8bc426fb934 d3 42c80000007a1f34 I/DEBUG ( 1505): d4 00000008004930e0 d5 0000000000000000 I/DEBUG ( 1505): d6 0000000000000000 d7 4080000080000000 I/DEBUG ( 1505): d8 0000025843e7c000 d9 c0c0000040c00000 I/DEBUG ( 1505): d10 40c0000040c00000 d11 0000000000000000 I/DEBUG ( 1505): d12 0000000000000000 d13 0000000000000000 I/DEBUG ( 1505): d14 0000000000000000 d15 0000000000000000 I/DEBUG ( 1505): d16 afd4242840704ab8 d17 0000000000000000 I/DEBUG ( 1505): d18 0000000000000000 d19 0000000000000000 I/DEBUG ( 1505): d20 0000000000000000 d21 0000000000000000 I/DEBUG ( 1505): d22 0000000000000000 d23 0000000000000000 I/DEBUG ( 1505): d24 0000000000000000 d25 0000000000000000 I/DEBUG ( 1505): d26 0000000000000000 d27 0000000000000000 I/DEBUG ( 1505): d28 00ff00ff00ff00ff d29 00ff00ff00ff00ff I/DEBUG ( 1505): d30 0000000000000000 d31 3fe55167807de022 I/DEBUG ( 1505): scr 68000012
这是一次 native 崩溃。一个段错误也不少(sig11)。根据定义,段错误始终是一个错误。这绝对是处理 GC 和/或内存限制检查的 native 代码中的 Android 错误。但我的应用程序仍然崩溃,导致差评、返回和销量下降。
所以我必须自己计算极限。 除了我在这里挣扎过。我尝试自己添加像素(EpicPixels),但我仍然定期遇到内存崩溃,所以我低估了一些东西。我尝试将 javaBytes(总计 - 免费)添加到 NativeHeapAllocSize,但这偶尔会导致我的应用程序变得“厌食症”,不断释放位图,直到没有任何内容需要清除。
有人知道用于计算内存限制和触发 java.lang.OutOfMemory 的精确计算吗?
还有其他人遇到过这个问题并解决过吗?你有什么智慧珍珠吗?有谁知道是哪位 Google 员工策划了这个计划,这样我就可以打他,因为他毁了我大约 40 个小时的生活? j/k罢工>
答案:限制是 NativeHeapAllocSize < maxMemory();然而,由于内存 fragment ,Android 早在实际限制之前就崩溃了。因此,您必须将自己限制为略小于实际限制的值。这个“安全因素”取决于应用程序,但几个 MiB 似乎对大多数人来说都有效。 (我只能说我对这种行为的破坏程度感到震惊)
最佳答案
使用这个 fragment ,对我有用
/**
* Checks if a bitmap with the specified size fits in memory
* @param bmpwidth Bitmap width
* @param bmpheight Bitmap height
* @param bmpdensity Bitmap bpp (use 2 as default)
* @return true if the bitmap fits in memory false otherwise
*/
public static boolean checkBitmapFitsInMemory(long bmpwidth,long bmpheight, int bmpdensity ){
long reqsize=bmpwidth*bmpheight*bmpdensity;
long allocNativeHeap = Debug.getNativeHeapAllocatedSize();
final long heapPad=(long) Math.max(4*1024*1024,Runtime.getRuntime().maxMemory()*0.1);
if ((reqsize + allocNativeHeap + heapPad) >= Runtime.getRuntime().maxMemory())
{
return false;
}
return true;
}
这是一个使用示例
BitmapFactory.Options bmpFactoryOptions = new BitmapFactory.Options();
bmpFactoryOptions.inJustDecodeBounds=true;
BitmapFactory.decodeFile(path,bmpFactoryOptions);
if ( (runInSafeMemoryMode()) && (!Manager.checkBitmapFitsInMemory(bmpFactoryOptions.outWidth, bmpFactoryOptions.outHeight, 2)) ){
Log.w(TAG,"Aborting bitmap load for avoiding memory crash");
return null;
}
关于Android 位图限制 - 防止 java.lang.OutOfMemory,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6892676/