Retrieving Android API version programmatically

前端 未结 11 2147
长情又很酷
长情又很酷 2020-11-22 04:54

Is there any way to get the API version that the phone is currently running?

11条回答
  •  没有蜡笔的小新
    2020-11-22 05:27

    Taking into account all said, here is the code I use for detecting if device has Froyo or newer 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;
    }
    

    Obviously, you can modify that if condition to take into account 1.0 & 1.5 versions of Android in case you need generic checker. You will probably end up with something like this:

    // 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;
        }
    }
    

    Let me know if code is not working for you.

提交回复
热议问题