旨在替代adb shell dumpsys meminfo packageName,在log打印meminfo,以便分析内存情况
ActivityManager.MemoryInfo memoryInfo = new ActivityManager.MemoryInfo(); activityManager.getMemoryInfo(memoryInfo); long totalMemory = Runtime.getRuntime().totalMemory();
这种代码获取的内存信息用处不大,需要使用Debug.MemoryInfo
Debug.MemoryInfo memoryInfo = new Debug.MemoryInfo(); Debug.getMemoryInfo(memoryInfo); memoryInfo.getMemoryStats();
log打印如下:
关键代码如下:
private static final String TAG_MEM_INFO = "MemInfo-packageName";private static void printDebugMeminfo() {Debug.MemoryInfo memoryInfo = new Debug.MemoryInfo();Debug.getMemoryInfo(memoryInfo);int getTotalPss = memoryInfo.getTotalPss();int nativePss = memoryInfo.nativePss;int dalvikPss = memoryInfo.dalvikPss;int otherPss = memoryInfo.otherPss;Log.i(TAG_MEM_INFO, "DebugMeminfo getTotalPss:" + aiKBToM(getTotalPss) + " nativePss:" + aiKBToM(nativePss)+ " dalvikPss:" + aiKBToM(dalvikPss) + " otherPss:" + aiKBToM(otherPss));Map<String, String> memStats = memoryInfo.getMemoryStats();for (Map.Entry<String, String> entry : memStats.entrySet()) {String key = entry.getKey();String value = entry.getValue();Log.i(TAG_MEM_INFO, "DebugMeminfo key = " + String.format("%-22s", key) + " value = " + aiKBToM(value));}}private static String aiKBToM(String kb) {int k = Integer.parseInt(kb);if (k > 100 * 1024) {return (k / 1024) + " M";} else {return kb + " KB";}}private static String aiKBToM(long kb) {if (kb > 100 * 1024) {return (kb / 1024) + " M";} else {return kb + " KB";}}private static void printMeminfo(Activity activity) {ActivityManager activityManager = (ActivityManager) activity.getSystemService(Context.ACTIVITY_SERVICE);ActivityManager.MemoryInfo memoryInfo = new ActivityManager.MemoryInfo();activityManager.getMemoryInfo(memoryInfo);long totalMemory = Runtime.getRuntime().totalMemory();long freeMemory = Runtime.getRuntime().freeMemory();long usedMemory = totalMemory - freeMemory;long availableMemory = memoryInfo.availMem;Log.i(TAG_MEM_INFO, "Meminfo totalMemory:" + aiKBToM(totalMemory / 1024) + " freeMemory:" + aiKBToM(freeMemory / 1024) +" usedMemory:" + aiKBToM(usedMemory / 1024) + " availableMemory:" + aiKBToM(availableMemory / 1024));}