Appium auto-retrieve Device name & Android Version

Greetings ! This is a short tutorial on how to auto-retrieve device name and Android version which is required for mobile automation testing.

OLD WAY

First, let’s look at the old way or I would say the manual way to doing it.
1. Android version: Finding it is easy. It can be found in the phone’s setting.
2. Device name: Using the below shell command

#Get the device name from ADB
adb devices -l

So, what is wrong with the above ?? None. As we mobile tester are aware that we just don’t test on 1 device but multiple devices. In that case, keeping track of so many device names and Android version name becomes very tedious to maintain in the sheet as well as in code. Below is the code, which we normally use,

DesiredCapabilities capabilities = new DesiredCapabilities();
capabilities.setCapability(MobileCapabilityType.DEVICE_NAME, "Xytsns12323"); //Random device name
capabilities.setCapability(MobileCapabilityType.PLATFORM_VERSION, "9");

NEW WAY

In the new way, we can programmtically find both values and its quite easy. Let me first show implementation and then explain it.

DesiredCapabilities capabilities = new DesiredCapabilities();
capabilities.setCapability(MobileCapabilityType.DEVICE_NAME, getDeviceName());
capabilities.setCapability(MobileCapabilityType.PLATFORM_VERSION, getPlatformVersion());
static String getDeviceName() {
    String deviceName = "";
    String shellCommand = "adb get-serialno"; // For platform use : adb shell getprop ro.build.version.release

    try {
        ProcessBuilder builder = new ProcessBuilder("cmd.exe", "/c", shellCommand);
        builder.redirectErrorStream(true);
        Process prc = builder.start();
        BufferedReader output = new BufferedReader(new InputStreamReader(prc.getInputStream()));
        deviceName = output.readLine();
        prc.waitFor();
    } catch (Exception e) {
        e.printStackTrace();
    }

    return deviceName;
}

The trick is to get them using adb as shown above,
* Device name – adb get-serialno
* Android version – adb shell getprop ro.build.version.release

THE END

Leave a Reply

Your email address will not be published.