How to find the Android version name in programming?

I write code to find such an Android version

String version=Build.VERSION.RELEASE;

By using this code I get the version number but I want the version name.
How to get the version name?

As mentioned earlier, reflection seems to be the key to this problem. StringBuilder and additional formatting are not required , It is only used to illustrate the usage.

import java.lang.reflect.Field;
...

StringBuilder builder = new StringBuilder();
builder.append("android: ").append(Build.VERSION.RELEASE);

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

try {< br /> 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) {
builder.append(": ").append(fieldName).append(": ");
builder.append("sdk=").append(fieldValue);
}
}

Log.d(LOG_TAG, "OS: "+ builder.toString());

On my 4.1 simulator, I get This output:

D/MainActivity( 1551): OS: android: 4.1.1: JELLY_BEAN: sdk=16

Please enjoy!

I write code to find such an Android version

String version=Build.VERSION.RELEASE; 

By using this code I get the version number but I want the version name.
How to get the version name?

As mentioned earlier, reflection seems to be the key to this problem. StringBuilder and additional formatting are not required, it is only used to illustrate the usage.

import java.lang.reflect.Field;
...

StringBuilder builder = new StringBuilder();
builder.append("android: ").append(Build.VERSION.RELEASE);

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) {
builder.append(" : ").append(fieldName).append(": ");
builder.append("sdk=").append(fieldValue);
}
}
< br />Log.d(LOG_TAG, "OS: "+ builder. toString());

On my 4.1 emulator, I got this output:

D/MainActivity( 1551): OS: android : 4.1.1: JELLY_BEAN: sdk=16

Please enjoy!

Leave a Comment

Your email address will not be published.