2015-04-28 144 views
2

這是非常簡單和直接的使用來獲得當前的設備API級別:如何獲得人類可讀的Android操作系統版本

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

...使用開關盒?喜歡:'switch(Build.VERSION.SDK_INT){case 1:return「First Android Version ever!」; break;}' –

+0

什麼數據集?我正在尋找包含人類可讀值的數據集,這些值應在設備上的某處可用。 – Graeme

+0

我不認爲在任何地方都有這樣的表格(除了返回「JELLY_BEAN_MR1」的表格)。因此,你會得到'MR1'等。順便說一句,你可以簡單地用''''和''MR''替換''_'''用''維護版本'''替換。所以,你會得到'「JELLY BEAN維護版本1」'。更好的是,如果你**正確的**字符串(每個單詞的第一個字符大寫,其餘小寫),所以最終得到''Jelly Bean維護版本1''。我想不出任何更簡單更好的東西。 –

回答

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 }; 
} 
相關問題