计算dalvik虚拟机剩余可分配内存

由于Android设定的dalvik虚拟机并不是一开始就分配dalvik虚拟机的上限,dalvik倾向于先回收后再分配使用。

对于某些占用内存很大的APP,就需要管理内存。

那么如何计算dalvik虚拟机剩余最大可分配内存呢?

Runtime runtime = Runtime.getRuntime();
long left = runtime.maxMemory()- (runtime.totalMemory()-runtime.freeMemory());
其中runtime.totalMemory()-runtime.freeMemory()为APP当前已经使用的虚拟机内存。

runtime.maxMemory()为虚拟机最大可以使用的内存(heapsize上限)。

public long maxMemory ()

Added in API level 1

Returns the maximum number of bytes the heap can expand to. SeetotalMemory()for the current number of bytes taken by the heap, andfreeMemory()for the current number of those bytes actually used by live objects.

返回堆可以分配的最大字节数。


public long totalMemory ()

Added in API level 1

Returns the number of bytes taken by the heap at its current size. The heap may expand or contract over time, as the number of live objects increases or decreases. SeemaxMemory()for the maximum heap size, andfreeMemory()for an idea of how much the heap could currently contract.

返回堆当前占用的字节数。堆的大小可能会随着活动对象的增长或者减少而增大或收缩。

public long freeMemory ()

Added in API level 1

Returns the number of bytes currently available on the heap without expanding the heap. SeetotalMemory()for the heap's current size. When these bytes are exhausted, the heap may expand. SeemaxMemory()for that limit.

返回在不增大堆大小的情况下当前可以继续分配使用的字节数。


你可能感兴趣的:(计算dalvik虚拟机剩余可分配内存)