1

I am building an Android Library and have a method getting some information about the device. Our target is to support 2.2 and up but was wondering if there is a way to collect information introduced in later versions (ex device serial in 2.3) and have the application set with version 2.2 to compile.

After searching around I found people using code like:

private static String getHardwareSerial() {
    try {  
        return Build.SERIAL;
    } catch (VerifyError e) {
        //Android 8 and previous did not have this information
        return Build.UNKNOWN;  
    }
}

However, with this code present, my sample application using our library fails to build when setting the build target to 8. Any suggestions or do we have to live with our clients setting their target to 9 to get this info?

kjsteuer
  • 617
  • 1
  • 6
  • 14

1 Answers1

1

You could do it through reflection:

public static String getHardwareSerial() {
    try {
        Field serialField = Build.class.getDeclaredField("SERIAL");
        return (String)serialField.get(null);
    }
    catch (NoSuchFieldException nsf) {
    } 
    catch (IllegalAccessException ia) {
    }
    return Build.UNKNOWN;
}

If the field isn't found (on earlier versions of the OS) it'll throw an exception that will be ignored and then fall through to return Build.UNKNOWN.

goto10
  • 4,370
  • 1
  • 22
  • 33