简介
CPU、FPS 都已介绍过了,自然避免不了要介绍一波内存。
内存分为两大类:RAM 和 ROM。
- RAM:RAM 为运行内存,比如,手机助手的悬浮窗,经常提示的运行内存超过 80% 之类的,指的都是运行内存。
- ROM:ROM 为存储数据的内存,比如,系统设置界面显示的“总空间128G,剩余32.2G”,指的是 ROM。
本篇所说的性能检测-内存,主要说的就是 RAM。
实现
原理
在你对某件事无从下手的时候,不妨去看看大佬们的写法。
Debug.MemoryInfo
这个类我们或许都没听说过,不过从大佬们的源码中,不难发现,检测内存的方法主要依赖于此类。
既然主要依赖此类,我们不妨看看此类主要功能?
/**
* This class is used to retrieved various statistics about the memory mappings for this
* process. The returned info is broken down by dalvik, native, and other. All results are in kB.
* 翻译:这个类用于检索关于这个进程的内存映射的各种统计信息。返回的信息包括 dalvik、native 和 other。所有结果都以kB为单位。
*/
public static class MemoryInfo implements Parcelable {
//此处省略部分代码
}
从官方文档的解释中我们可以看出,要检测 RAM 可以从这个类出发。
Debug.getMemoryInfo()
要想要使用 MemoryInfo 来检测 RAM,我们首先要能够获取到 MemoryInfo。
我们可以很轻松的发现 Debug 类中有获取 MemoryInfo 的方法:
ActivityManager
从上图中可以看出,此方法对 Android Q 不太友好,因此我们只能在 sdk<=28 的时候使用此方法。
代码实现
val memoryData: Float
get() {
var mem = 0.0f
try {
var memInfo: Debug.MemoryInfo? = null
//28 为Android P
if (Build.VERSION.SDK_INT > 28) {
// 统计进程的内存信息 totalPss
memInfo = Debug.MemoryInfo()
Debug.getMemoryInfo(memInfo)
} else {
// As of Android Q, for regular apps this method will only return information about the memory info for the processes running as the caller's uid;
// no other process memory info is available and will be zero. Also of Android Q the sample rate allowed by this API is significantly limited, if called faster the limit you will receive the same data as the previous call.
val memInfos = mActivityManager.getProcessMemoryInfo(intArrayOf(Process.myPid()))
if (memInfos != null && memInfos.size > 0) {
memInfo = memInfos[0]
}
}
val totalPss = memInfo?.totalPss ?: 0
if (totalPss >= 0) {
// Mem in MB
mem = totalPss / 1024.0f
}
} catch (e: Exception) {
e.printStackTrace()
}
return mem
}
上文若存在问题,欢迎指出!