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); 

请尝试以下代码。 这应该会给你你想要的结果(特别是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); 

这是一个旧线程,但这似乎工作:

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

totalMemory-freeMemory是当前使用的内存。

所以这归结为:

(maximum possible memory)-(current used memory)

编辑添加:freeMemory不计算可用于垃圾收集的内存,因此您可以尝试Runtime.getRuntime()。gc(),虽然意识到可能有其自身的后果(如果在UI线程上运行时视觉打嗝)。