Detect application heap size in Android

后端 未结 9 2095
-上瘾入骨i
-上瘾入骨i 2020-11-22 07:38

How do you programmatically detect the application heap size available to an Android app?

I heard there\'s a function that does this in later versions of the SDK. In

9条回答
  •  暗喜
    暗喜 (楼主)
    2020-11-22 08:08

    Here's how you do it:

    Getting the max heap size that the app can use:

    Runtime runtime = Runtime.getRuntime();
    long maxMemory=runtime.maxMemory();
    

    Getting how much of the heap your app currently uses:

    long usedMemory=runtime.totalMemory() - runtime.freeMemory();
    

    Getting how much of the heap your app can now use (available memory) :

    long availableMemory=maxMemory-usedMemory;
    

    And, to format each of them nicely, you can use:

    String formattedMemorySize=Formatter.formatShortFileSize(context,memorySize); 
    

提交回复
热议问题