Java: Get name and serial number of cell phone connected to the computer

Asked

Viewed 754 times

1

Dear first: This is not an issue involving Android development.

I am doing automation in java, and I would like to know if there is any way to store the name and serial number of the device when connecting it via USB on the computer. Currently I do this manually by entering the "My Computer > Selecting the Phone with Right Button > Properties" and then copying that information.

Is there any way to do this via Java?

From now on,

Thank you!

1 answer

-1

Fala Luís,

The serial is simple, just call build, example:

String deviceSerial;

try {
   deviceSerial = (String) Build.class.getField("SERIAL").get(null);
 } catch (IllegalAccessException e) {
      e.printStackTrace();
 } catch (NoSuchFieldException e) {
      e.printStackTrace();
 }

Log.d("serial", deviceSerial);

And to get the name, it’s a little more complicated, example:

public static String getDeviceName() {
    String manufacturer = Build.MANUFACTURER;
    String model = Build.MODEL;
    if (model.startsWith(manufacturer)) {
        return capitalize(model);
    }
    return capitalize(manufacturer) + " " + model;
}

private static String capitalize(String str) {
    if (TextUtils.isEmpty(str)) {
        return str;
    }
    char[] arr = str.toCharArray();
    boolean capitalizeNext = true;

    StringBuilder phrase = new StringBuilder();
    for (char c : arr) {
        if (capitalizeNext && Character.isLetter(c)) {
            phrase.append(Character.toUpperCase(c));
            capitalizeNext = false;
            continue;
        } else if (Character.isWhitespace(c)) {
            capitalizeNext = true;
        }
        phrase.append(c);
    }

    return phrase.toString();
}

There to call the result, you do:

String deviceName = getDeviceName();

Hugs.

  • First of all, thank you so much for your help..! I tried the first one to get the serial Umber, but it’s returning null... I simply opened a class in java, imported the android by Maven, and inserted this string into a system.out to see what would happen. Should I have done something before?

  • Strange to be coming as null, I changed my answer with a new code to catch the serial, a check.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.