有人知道我如何通过编程检查系统版本(例如1.0、2.2等)吗?


当前回答

使用这种方法:

 public static String getAndroidVersion() {
        String versionName = "";

        try {
             versionName = String.valueOf(Build.VERSION.RELEASE);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return versionName;
    }

其他回答

我不能评论这些答案,但在Kaushik的回答中有一个巨大的错误: SDK_INT与系统版本不同,实际上是指API级别。

if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH){
    //this code will be executed on devices running ICS or later
}

值Build.VERSION_CODES。ICE_CREAM_SANDWICH = 14。 14是Ice Cream Sandwich的API等级,而系统版本是4.0。因此,如果您编写4.0,您的代码将在从Donut开始的所有设备上执行,因为4是Donut (Build.VERSION_CODES)的API级别。甜甜圈= 4)。

if(Build.VERSION.SDK_INT >= 4.0){
    //this code will be executed on devices running on DONUT (NOT ICS) or later
}

这个例子说明了为什么使用“魔数”是一个坏习惯。

例如,一个特性只适用于api21上面,下面我们修复api21下面的bug

    if(Build.VERSION.SDK_INT >= 21) {
    //only api 21 above
    }else{
   //only api 21 down
    }

检查android.os.Build.VERSION。

CODENAME:当前的开发代码名,如果这是一个发布版本,则为字符串“REL”。 INCREMENTAL:底层源代码控制用来表示此构建的内部值。 RELEASE:用户可见的版本字符串。

如果你的android设备上有bash,你可以使用这个bash函数:

function androidCodeName {
    androidRelease=$(getprop ro.build.version.release)
    androidCodeName=$(getprop ro.build.version.codename)

    # Time "androidRelease" x10 to test it as an integer
    case $androidRelease in
        [0-9].[0-9]|[0-9].[0-9].|[0-9].[0-9].[0-9])  androidRelease=$(echo $androidRelease | cut -d. -f1-2 | tr -d .);;
        [0-9].) androidRelease=$(echo $androidRelease | sed 's/\./0/');;
        [0-9]) androidRelease+="0";;
    esac

    [ -n "$androidRelease" ] && [ $androidCodeName = REL ] && {
    # Do not use "androidCodeName" when it equals to "REL" but infer it from "androidRelease"
        androidCodeName=""
        case $androidRelease in
        10) androidCodeName+=NoCodename;;
        11) androidCodeName+="Petit Four";;
        15) androidCodeName+=Cupcake;;
        20|21) androidCodeName+=Eclair;;
        22) androidCodeName+=FroYo;;
        23) androidCodeName+=Gingerbread;;
        30|31|32) androidCodeName+=Honeycomb;;
        40) androidCodeName+="Ice Cream Sandwich";;
        41|42|43) androidCodeName+="Jelly Bean";;
        44) androidCodeName+=KitKat;;
        50|51) androidCodeName+=Lollipop;;
        60) androidCodeName+=Marshmallow;;
        70|71) androidCodeName+=Nougat;;
        80|81) androidCodeName+=Oreo;;
        90) androidCodeName+=Pie;;
        100) androidCodeName+=ToBeReleased;;
        *) androidCodeName=unknown;;
        esac
    }
    echo $androidCodeName
}
if (Build.VERSION.SDK_INT >= ApiHelper.VERSION_CODES.HONEYCOMB_MR2) {
//do anything you  like.
}