Android:如何检查剩余多少内存?

ab1*_*b11 30 android

下面是我检查剩余内存量的公式(不是当前堆中剩余多少内存,而是在应用程序崩溃之前可以使用多少内存).我不是很确定这是对的,是吗?

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 nativeUsage = 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); 
Run Code Online (Sandbox Code Playgroud)

Muz*_*ant 22

请尝试以下代码.这应该会给你你想要的结果(特别是Pss字段).你可以在这里阅读更多相关信息

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);
Run Code Online (Sandbox Code Playgroud)

  • @先生.Roland,我不确定我是否正确阅读,这是我的解释:在3.0之前,位图分配是根据堆限制计算的,但不会显示在davlik堆中.在3.0之后,分配实际上是在davlik堆中? (2认同)