下面是我的公式,用于检查剩余多少内存(不是当前堆中剩余多少内存,而是在应用程序崩溃之前可以使用多少内存)。我不是很确定这是对的,不是吗?
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);
答案 0 :(得分:22)
尝试以下代码。这应该会给你你想要的结果(特别是Pss字段)。您可以阅读更多相关信息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);
答案 1 :(得分:3)
这是一个旧线程,但这似乎有效:
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线程上运行时会出现视觉打嗝)