使用以下方法获得当前设备API级别相当简单直接:
Build.VERSION.SDK_INT
使用它也很容易获得Build.VERSION_CODES
的版本名称
public static String getDisplayOS() {
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) {
return fieldName;
}
}
return "";
}
问题是这给出了如下值:
JELLY_BEAN_MR1
HONEYCOMB_MR2
现在,我可以自己手动添加操作系统版本字符串列表 - 这很好但是一旦我们通过API 22,我就必须更新产品只是添加一些额外的字符串。
我的大脑告诉我必须有一个内部字段在操作系统中显示某处的值,但我发现很难找到它的位置。
任何帮助都会有用
答案 0 :(得分:1)
这是一个黑客,所以我真的不想使用它。然而,它设法使用regexing来提取一些非常合理的显示值。
public static String[] getDisplayOS() {
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) {
fieldName = fieldName.replaceAll("_", " ");
String firstLetter = fieldName.substring(0, 1);
fieldName = firstLetter.toUpperCase() + fieldName.substring(1).toLowerCase();
Pattern p = Pattern.compile(" [a-z]");
Matcher m = p.matcher(fieldName);
while (m.find()) {
int index = m.start();
fieldName = fieldName.substring(0, index) + fieldName.substring(index, index+2).toUpperCase() + fieldName.substring(index+2);
}
Pattern mrPattern = Pattern.compile(" (Mr\\d)");
Matcher mrMatcher = mrPattern.matcher(fieldName);
if (mrMatcher.find()) {
fieldName = fieldName.replaceAll(" Mr\\d", "");
return new String[] { fieldName, mrMatcher.group(1).toUpperCase() };
}
return new String[] { fieldName, null };
}
}
return new String[] { null, null };
}