Android:如何检查剩余的内存?

下面是我的公式来检查有多less内存剩余(没有多less内存仍然在当前的堆,但多less内存可能被利用之前,应用程序崩溃)。 我并不确定这是否正确,是吗?

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

Solutions Collecting From Web of "Android:如何检查剩余的内存?"

尝试下面的代码。 这应该给你后面的结果(尤其是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线程上运行的视觉打嗝)。