在做Andriod应用性能相关的测试中,很关心的一点就是应用所占用的内存了。
我们知道可以通过 adb shell dumpsys meminfo + 包名命令来获取应用占用的内存,但是在代码中怎么获取呢?
这里我们需要用到 Debug.MemoryInfo 这个类。
获取本应用占用内存的方法:
@TargetApi(Build.VERSION_CODES.KITKAT)
public static int getMemory() {
Debug.MemoryInfo memoryInfo = new Debug.MemoryInfo();
Debug.getMemoryInfo(memoryInfo);
// dalvikPrivateClean + nativePrivateClean + otherPrivateClean;
int totalPrivateClean = memoryInfo.getTotalPrivateClean();
// dalvikPrivateDirty + nativePrivateDirty + otherPrivateDirty;
int totalPrivateDirty = memoryInfo.getTotalPrivateDirty();
// dalvikPss + nativePss + otherPss;
int totalPss = memoryInfo.getTotalPss();
// dalvikSharedClean + nativeSharedClean + otherSharedClean;
int totalSharedClean = memoryInfo.getTotalSharedClean();
// dalvikSharedDirty + nativeSharedDirty + otherSharedDirty;
int totalSharedDirty = memoryInfo.getTotalSharedDirty();
// dalvikSwappablePss + nativeSwappablePss + otherSwappablePss;
int totalSwappablePss = memoryInfo.getTotalSwappablePss();
int total = totalPrivateClean + totalPrivateDirty + totalPss + totalSharedClean + totalSharedDirty + totalSwappablePss;
return total ;
}