Android获取本应用内存占用的方法

我们知道可以通过 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 ;
 }

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/d7971c24a24efb250954df3b8e1e5d1e.html