以编程方式获取设备的EMUI版本

6

在我的应用程序执行过程中,如何获取EMUI版本?是否有系统方法可以获取EMUI版本?

1个回答

10

通过访问系统属性,例如:

@SuppressLint("PrivateApi")
private fun Any?.readEMUIVersion() : String {
    try {
        val propertyClass = Class.forName("android.os.SystemProperties")
        val method: Method = propertyClass.getMethod("get", String::class.java)
        var versionEmui = method.invoke(propertyClass, "ro.build.version.emui") as String
        if (versionEmui.startsWith("EmotionUI_")) {
            versionEmui = versionEmui.substring(10, versionEmui.length)
        }
        return versionEmui
    } catch (e: ClassNotFoundException) {
        e.printStackTrace()
    } catch (e: NoSuchMethodException) {
        e.printStackTrace()
    } catch (e: IllegalAccessException) {
        e.printStackTrace()
    } catch (e: InvocationTargetException) {
        e.printStackTrace()
    }
    return ""
}

然而,这是一个私有API,如果你的情况不适用,可能可以使用此解决方法(适用于EMUI 9和10,但绝对不适用于EMUI 5或以下版本(~Android 7)):

@TargetApi(3)
fun Any?.extractEmuiVersion() : String {
    return try {
        val line: String = Build.DISPLAY
        val spaceIndex = line.indexOf(" ")
        val lastIndex = line.indexOf("(")
        if (lastIndex != -1) {
            line.substring(spaceIndex, lastIndex)
        } else line.substring(spaceIndex)
    } catch (e: Exception) { "" }
}

非常欢迎各位提出改进答案的建议!


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接