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


当前回答

使用实例:

if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.GINGERBREAD) {
     // only for gingerbread and newer versions
}

其他回答

使用实例:

if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.GINGERBREAD) {
     // only for gingerbread and newer versions
}

如果你的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
}

要检查设备版本大于或等于Marshmallow,请使用此代码。

if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.M){

    }

如果要检查其他的,只需要更改VERSION_CODES, K代表kitkat, L代表棒棒糖 N代表牛轧糖等等……

根据Android文档:

release - "用户可见的版本字符串。例如,“1.0” 或者"3.4b5"或者"香蕉"

为了得到一个普通的Android版本(2.3,5.1,12.0等),我使用这个函数:

private fun getVersion(): Float {
    val release = Build.VERSION.RELEASE
    val parsedVersion = "\\d+(\\.\\d+)?".toRegex()
        .find(release)?.value
    if (parsedVersion.isNullOrBlank()) return 0f
    return try {
        parsedVersion.toFloat()
    } catch (e: Exception) {
        0f
    }
}

使用这种方法:

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

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