有没有办法获得手机当前正在运行的API版本?


当前回答

明白了。它使用Context类的getApplicationInfo()方法。

其他回答

Build.VERSION.RELEASE;

这将给你你的版本的实际数字;又名2.3.3或2.2。 使用Build.VERSION的问题。SDK_INT是如果你有一个根手机或自定义rom,你可能有一个非标准的操作系统(也就是我的android是运行2.3.5),这将返回null时使用Build.VERSION。所以Build.VERSION.RELEASE无论是否使用标准Android版本都可以正常工作!

要使用它,你可以这样做;

String androidOS = Build.VERSION.RELEASE;

如Android文档中所述,手机正在运行的SDK级别(整数)可在:

android.os.Build.VERSION.SDK_INT

这个int对应的类在android.os.Build中。VERSION_CODES类。

代码示例:

if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP){
    // Do something for lollipop and above versions
} else{
    // do something for phones running an SDK before lollipop
}

编辑:这个SDK_INT从Donut (android 1.6 / API4)开始就可用了,所以请确保您的应用程序在使用它时不与Cupcake (android 1.5 / API3)向后兼容,否则您的应用程序将崩溃(感谢程序员Bruce的精度)。

对应的android文档在这里和这里

我更喜欢把版本作为数字来处理,而不是这样写:

  public static float getAPIVerison() {

    Float f = null;
    try {
        StringBuilder strBuild = new StringBuilder();
        strBuild.append(android.os.Build.VERSION.RELEASE.substring(0, 2));
        f = new Float(strBuild.toString());
    } catch (NumberFormatException e) {
        Log.e("", "error retriving api version" + e.getMessage());
    }

    return f.floatValue();
}

我通常喜欢在函数中添加这些代码来获得Android版本:

int whichAndroidVersion;

whichAndroidVersion= Build.VERSION.SDK_INT;
textView.setText("" + whichAndroidVersion); //If you don't use "" then app crashes.

例如,上面的代码将文本设置到我的textView为“29”现在。

明白了。它使用Context类的getApplicationInfo()方法。