如何获得android os版本的代号

时间:2012-11-07 08:30:35

标签: android api

我通过String检索了android版本androidVersion = Build.VERSION.RELEASE

现在我希望如果我的版本是4.0,我应该在运行时在字符串变量中获取IceCreamSandwich而不是4.0。如果有代号的API,请帮助。提前致谢。 我的示例代码是:

     String androidVersion = Build.VERSION.RELEASE.toString();
     String androidName = "";
     String and = "4.1.2";
        if(androidVersion == and)
        {
        androidName = "JellyBeans";
        }
    else
    {
        androidName = "Not Having any name";

    }

在调试时,我无法进入if循环,而是在其他地方。我不知道是什么问题。可能是我得到的版本和传递给比较的字符串不匹配。提前谢谢。

2 个答案:

答案 0 :(得分:3)

试试这个

public String getSDKCodeName(){
    String codeName = "";
        Field[] fields = Build.VERSION_CODES.class.getFields();
        for (Field field : fields) {
            String fieldName = field.getName();
            int fieldValue = -1;

            try {
                fieldValue = field.getInt(new Object());
            } catch (IllegalArgumentException e) {
                e.printStackTrace();
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            } catch (NullPointerException e) {
                e.printStackTrace();
            }

            if (fieldValue == Build.VERSION.SDK_INT) {
                codeName = fieldName;
            }
        }
    return codeName;
}

答案 1 :(得分:0)

没有直接方法可从android获取代号。 一种简单的方法是使用

private Field[] fields;
fields = Build.VERSION_CODES.class.getFields();
fields[Build.VERSION.SDK_INT + 1].getName()

但这不稳定,并导致少数设备在生产中发生ArrayIndexOutOfBoundsExceptioin崩溃。

即使在生产中,手动创建返回代号的方法对我来说也是非常稳定的。

String codeName = getVersionCode(Build.VERSION.SDK_INT)

private String getVersionCode(int code){
switch (code){
  case 0:{
    return "BASE";
  }
  case 1:{
    return "BASE_1_1";
  }
  case 2:{
    return "CUPCAKE";
  }
  case 3:{
    return "CUR_DEVELOPMENT";
  }
  case 4:{
    return "DONUT";
  }
  case 5:{
    return "ECLAIR";
  }
  case 6:{
    return "ECLAIR_0_1";
  }
  case 7:{
    return "ECLAIR_MR1";
  }
  case 8:{
    return "FROYO";
  }
  case 9:{
    return "GINGERBREAD";
  }
  case 10:{
    return "GINGERBREAD_MR1";
  }
  case 11:{
    return "HONEYCOMB";
  }
  case 12:{
    return "HONEYCOMB_MR1";
  }
  case 13:{
    return "HONEYCOMB_MR2";
  }
  case 14:{
    return "ICE_CREAM_SANDWICH";
  }
  case 15:{
    return "ICE_CREAM_SANDWICH_MR1";
  }
  case 16:{
    return "JELLY_BEAN";
  }
  case 17:{
    return "JELLY_BEAN_MR1";
  }
  case 18:{
    return "JELLY_BEAN_MR2";
  }
  case 19:{
    return "KITKAT";
  }
  case 20:{
    return "KITKAT_WATCH";
  }
  case 21:{
    return "L";
  }
  case 22:{
    return "LOLLIPOP";
  }
  case 23:{
    return "LOLLIPOP_MR1";
  }
  case 24:{
    return "M";
  }
  case 25:{
    return "N";
  }
  case 26:{
    return "OREO";
  }
  case 27:{
    return "OREO";
  }
  case 28:{
    return "PIE";
  }
  default: {
    return "Android";
  }
}

}