我写了一个函数来防止调用Bitmap.createBitmap()
,如果它会抛出一个OutOfMemoryError: bitmap size exceeds VM budget
,但我并不总是工作,我该如何纠正它?这是一个返回 true 而不是 false 的示例:
if(isSufficientRAM(width*height)){
Bitmap bmp=Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
...
}
public static boolean isSufficientRAM(int length){
int minRamAfter=1024*1024; //1048576 bytes (always leave at least 1MB free)
long imgSize=length*4; //this is 31961088 bytes in this case, as it is a 3264 x 2448 argb image
long freeRAM = Runtime.getRuntime().freeMemory(); //this was 34415992 bytes when I run it
boolean hasRAM=freeRAM>imgSize+minRamAfter; //this is true as freeMemory() shows enough RAM available
return hasRAM;
}
当我运行它时,该函数将返回 true,并且 Bitmap.createBitmap() 给出以下错误。我的 isSufficientRAM() 函数中缺少什么?
11-15 09:01:47.965: minRamAfter=1048576
11-15 09:01:47.965: imgSize=31961088
11-15 09:01:47.970: freeRAM=34415992
11-15 09:01:48.020: hasRAM=true
11-15 09:01:48.060: D/dalvikvm(2538): GC_EXTERNAL_ALLOC freed 79K, 92% free 3850K/44679K, external 2343K/3018K, paused 37ms
11-15 09:01:48.080: E/dalvikvm-heap(2538): 31961088-byte external allocation too large for this process.
11-15 09:01:48.115: E/GraphicsJNI(2538): VM won't let us allocate 31961088 bytes
11-15 09:01:48.115: D/dalvikvm(2538): GC_FOR_MALLOC freed 0K, 92% free 3850K/44679K, external 2343K/3018K, paused 22ms
11-15 09:01:48.115: W/dalvikvm(2538): threadid=12: thread exiting with uncaught exception (group=0x4001e578)
11-15 09:01:48.115: E/AndroidRuntime(2538): FATAL EXCEPTION: Test thread name
11-15 09:01:48.115: E/AndroidRuntime(2538): java.lang.OutOfMemoryError: bitmap size exceeds VM budget
11-15 09:01:48.115: E/AndroidRuntime(2538): at android.graphics.Bitmap.nativeCreate(Native Method)
11-15 09:01:48.115: E/AndroidRuntime(2538): at android.graphics.Bitmap.createBitmap(Bitmap.java:477)