开发者

Android: how to check how much memory is remaining?

Below is my formula to check how much memory is remaining (not how much memory remains in the current heap, but how much more memory may be utilized before the application crashes). I'm not remotely sure this is correct, is it?

double max = Runtime.getRuntime().maxMemory(); //the maximum memory the app can use
double heapSize = Runtime.getRuntime().totalMemory(); //current heap size
double heapRemaining = Runtime.getRuntime().freeMemory(); //amount available in heap
double nativeU开发者_高级运维sage = Debug.getNativeHeapAllocatedSize(); //is this right? I only want to account for native memory that my app is being "charged" for.  Is this the proper way to account for that?

//heapSize - heapRemaining = heapUsed + nativeUsage = totalUsage
double remaining = max - (heapSize - heapRemaininng + nativeUsage); 


Try the following code. that should give you the results you are after (especially the Pss field). You can read more about it here

Debug.MemoryInfo memoryInfo = new Debug.MemoryInfo();
Debug.getMemoryInfo(memoryInfo);

String memMessage = String.format(
    "Memory: Pss=%.2f MB, Private=%.2f MB, Shared=%.2f MB",
    memoryInfo.getTotalPss() / 1024.0,
    memoryInfo.getTotalPrivateDirty() / 1024.0,
    memoryInfo.getTotalSharedDirty() / 1024.0);


This is an old thread, but this seems to work:

  Runtime.getRuntime().gc();
  long memoryAvailable = (Runtime.getRuntime().maxMemory() -
        Runtime.getRuntime().totalMemory() +
        Runtime.getRuntime().freeMemory());

totalMemory-freeMemory is the current used memory.

So this boils down to:

(maximum possible memory)-(current used memory)

Edit to add: freeMemory does not count memory available for garbage collection, so you can try Runtime.getRuntime().gc(), although realize that can have its own consequences (like visual hiccups if run on the UI thread).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜