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


当前回答

综上所述,以下是我用来检测设备是否有Froyo或更新的Android OS(2.2+)的代码:

public static boolean froyoOrNewer() {
    // SDK_INT is introduced in 1.6 (API Level 4) so code referencing that would fail
    // Also we can't use SDK_INT since some modified ROMs play around with this value, RELEASE is most versatile variable
    if (android.os.Build.VERSION.RELEASE.startsWith("1.") ||
        android.os.Build.VERSION.RELEASE.startsWith("2.0") ||
        android.os.Build.VERSION.RELEASE.startsWith("2.1"))
        return false;

    return true;
}

显然,如果你需要通用的检查器,你可以修改if条件来考虑1.0和1.5版本的Android。你可能会得到这样的结果:

// returns true if current Android OS on device is >= verCode 
public static boolean androidMinimum(int verCode) {
    if (android.os.Build.VERSION.RELEASE.startsWith("1.0"))
        return verCode == 1;
    else if (android.os.Build.VERSION.RELEASE.startsWith("1.1")) {
        return verCode <= 2;
    } else if (android.os.Build.VERSION.RELEASE.startsWith("1.5")) {
        return verCode <= 3;
    } else {
        return android.os.Build.VERSION.SDK_INT >= verCode;
    }
}

如果代码不适合你,请告诉我。

其他回答

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

int whichAndroidVersion;

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

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

我改进了我使用的代码

public static float getAPIVerison() {

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

    return f;
}

试试这个:

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

SDK。INT支持Android 1.6及以上版本

所有版本都支持SDK

所以我这样做:

String sdk_version_number = android.os.Build.VERSION.SDK;

出处:CommonsWare

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

  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();
}