Reputation:
I have retrieved the android version by String androidVersion = Build.VERSION.RELEASE
Now i want that if my version is 4.0 i should get IceCreamSandwich instead of 4.0 in a string variable at runtime.Please help if there is any API for codename. Thanks in advance. My sample code is:
String androidVersion = Build.VERSION.RELEASE.toString();
String androidName = "";
String and = "4.1.2";
if(androidVersion == and)
{
androidName = "JellyBeans";
}
else
{
androidName = "Not Having any name";
}
On debugging i m unable to enter the if loop and it is going in else. I don't Know what is the issue. May be the version i m getting and string i m passing to compare are not matching. Thanks in advance.
Upvotes: 0
Views: 2255
Reputation: 630
There is no direct way to get the codename from android. One easy way is to use
private Field[] fields;
fields = Build.VERSION_CODES.class.getFields();
fields[Build.VERSION.SDK_INT + 1].getName()
But this is not stable and caused me a ArrayIndexOutOfBoundsExceptioin
crash in production for few devices.
Manually creating a method to return the codename is very stable for me even in production.
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 "MARSHMALLOW";
}
case 25:{
return "NOUGAT";
}
case 26:{
return "OREO";
}
case 27:{
return "OREO";
}
case 28:{
return "PIE";
}
case 29:{
return "Q";
}
case 30:{
return "R";
}
default: {
return "Android";
}
}
}
Upvotes: 0
Reputation: 1736
Try this
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;
}
Upvotes: 4