3

I have been using the method described here in this answer: https://stackoverflow.com/a/6893818/457059

Here is the line which does the check:

if ((reqsize + allocNativeHeap + heapPad) >= Runtime.getRuntime().maxMemory())

Unfortunately I was still ending up with OutOfMemory Exceptions sometimes. So I did some debugging, and found out, that on my Galaxy S3 (Ice cream sandwich), the memory which is currently used by the app, is not taken into consideration with the approach above.

My theory is that above answer is only targeting android 2.x and below, where images were saved in native heap.

I changed the check to following:

public static boolean checkBitmapFitsInMemory(long bmpwidth,long bmpheight, int bmpdensity ){
    long required=bmpwidth*bmpheight*bmpdensity;
    long allocated = Runtime.getRuntime().totalMemory() + Debug.getNativeHeapAllocatedSize() + Tools.getHeapPad();

    if ((required + allocated) >= Runtime.getRuntime().maxMemory()) {
        return false;
    }

    return true;
}

This works much better on my S3, but I am still not sure whether I am it doing correctly. Especially those things are not clear to me:

  1. why is there a stackoverflow answer to this question, which was up-rated 8 times although it's not correct?
  2. I am using Runtime.getRuntime().totalMemory() to retrieve the currently used memory of the app, and its working great on my S3, but the API description of totalMemory() does tell me something completely different: "Returns the total amount of memory which is available to the running program." why is that?
  3. Will my approach work on Android 2.x as well?
Community
  • 1
  • 1
stoefln
  • 14,498
  • 18
  • 79
  • 138
  • The theory is that bitmaps are allocated on the native heap. I'm not sure why you have to included totalMemory as well, may look into it if I have time. – jjm Jan 12 '13 at 17:13

0 Answers0