背景
有时候需要根据设备性能返回是否低端机还是高端机,来决定某些功能或者酷炫效果是否展示,如过渡动画等,所以需要封装这样一套全局使用的工具去判断
过程分析
获取设备总内存
- mem.totalMem ushr 20 这一句将获取到的内存值由bytes转成MB
kotlin
fun getTotalMemory(context: Context): Int {
try {
val mem = ActivityManager.MemoryInfo()
val activityManager = context.getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager
activityManager.getMemoryInfo(mem)
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN) {
totalMemory = 1024
} else {
totalMemory = (mem.totalMem ushr 20).toInt()
}
} catch (_: Throwable) {
}
return totalMemory
}
获取内存水平
- 系统会预留部分内存,所以实际出来的内存值是小于等于预定的
- 2G或以下的低端配置,2-4G中低端配置,6G中端配置,8G高端配置,8G以上旗舰机配置
kotlin
private fun getMemoryLevel(context: Context): Int {
val ramMB: Long = getTotalMemory(context)
return if (ramMB <= 2000) {
0
} else if (ramMB <= 4000) {
1
} else if (ramMB <= 6000) {
2
} else if (ramMB <= 8000) {
3
} else {
4
}
}
获取CPU水平
- getCpuCoreCount()获取cpu核心线程数,小于4是直接是最低端配置
- getMaxCpuFreq() 获取cpu最高频率,小于等于1.8GHz为低端配置, 小于等于2GHz为低中端配置,小于等于2.5GHz为中高端配置,其余为高端配置
kotlin
private fun getCPULevel(): Int {
var level = -1
// String cpuName = getHardWare();
val cpuCoreCount: Int = getCpuCoreCount()
level = if (cpuCoreCount <= 4) {
0
} else {
val maxCpuFreq: Long = getMaxCpuFreq()
if (maxCpuFreq <= 0) {
2
} else {
val freqMHz = (maxCpuFreq / 100000 * 100).toInt()
if (freqMHz <= 1800) {
0
} else if (freqMHz <= 2000) {
1
} else if (freqMHz <= 2500) {
2
} else {
3
}
}
}
return level
}
汇总判断设备类型
- 系统版本小于8的直接定义为低端机
- 这里还加入显卡名称为PowerVR Rogue来判断
kotlin
fun getPhoneLevel(context: Context): Int {
var level: Int = PHONE_LEVEL_UNKNOWN
val isLowSDK = Build.VERSION.SDK_INT < Build.VERSION_CODES.O
val memoryLevel = getMemoryLevel(context)
val cpuLevel = getCPULevel()
val gpuName = getGpuName()
if (isLowSDK || memoryLevel == 0 || memoryLevel == 1 || cpuLevel == 0) {
level = if (!isLowSDK && cpuLevel >= 1 && memoryLevel > 0 && !gpuName.startsWith("PowerVR Rogue")) {
PHONE_LEVEL_MIDDLE
} else {
PHONE_LEVEL_LOW
}
} else if (memoryLevel == 2 && cpuLevel >= 1 && !gpuName.startsWith("PowerVR Rogue")) {
level = PHONE_LEVEL_MIDDLE
} else if (memoryLevel > 2) {
level = if (cpuLevel > 2) {
PHONE_LEVEL_HIGH
} else if (!gpuName.startsWith("PowerVR Rogue")){
PHONE_LEVEL_MIDDLE
} else {
PHONE_LEVEL_LOW
}
}
return level
}
测试代码
kotlin
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
}
fun onClick(view: View) {
val memory = PhoneLevelUtils.getTotalMemory(this)
val cpuFreq = PhoneLevelUtils.getMaxCpuFreq()
val maxCpuFreq = (cpuFreq / 100000 * 100).toInt()
val gpuName = PhoneLevelUtils.getGpuName()
Log.d("萌面小侠Plus", "手机内存为:$memory MB, cpu主频为:$maxCpuFreq Mhz, gpu名称为:$gpuName")
val level = PhoneLevelUtils.getPhoneLevel(this)
val res = when(level) {
PhoneLevelUtils.PHONE_LEVEL_HIGH -> "高端机"
PhoneLevelUtils.PHONE_LEVEL_MIDDLE -> "中端机"
PhoneLevelUtils.PHONE_LEVEL_LOW -> "低端机"
else -> "未知"
}
Log.d("萌面小侠Plus", "手机性能级别为:$res")
}
}