How to retrieve device serial number programmatically

I’m currently writing automation tests for retrieving received OTP codes. I followed this method and it’s working fine. Basically, as a workaround for interacting with the native messaging app, which is different for each device manufacturer, a third party sms app is installed as part of the code.

The issue is, the code requires that I provide the device serial number (from adb devices) prior to execution. This becomes a problem when we want to run our tests on multiple devices in parallel. Is there a way for appium to retrieve the serial number from the device?

try mobile: deviceInfo endpoint (http://appium.io/docs/en/commands/mobile-command/)

Sadly, it didn’t work. Device Info only gives the android ID, but I need the serial number (the one that comes out when using adb devices)

This is needed to install the third party sms app into the device, we need the serial number to distinguish between multiple devices.

You could use mobile: shell then. The command to retrieve the serial number is adb shell getprop | grep ro.boot.serialno

2 Likes

Got it working, thanks!

The only problem I see is, when running parallel tests on multiple devices, the initial call to adb shell might call a different device. For example, a test running on device A, calls the adb shell command to get the serial number of device B.

I haven’t tested how reliable it is though, but it’s work fine right now when I have one device connected and two emulators running.

Here’s the code I used in case there’s anyone out there that wants to try it out too:
Map<String, Object> cmd = new HashMap<>();
cmd.put("command", "getprop");
cmd.put("args", Lists.newArrayList("|", "grep", "ro.boot.serialno"));
String serialNumber = localDriver.executeScript("mobile:shell", cmd).toString().replaceAll("(\\[.*?\\]: |\\[|\\])", "");

1 Like

I “believe” you can add the same device id flag to the adb shell command to target a device by it’s id?

the device id must be added automatically and this is visible in the server logs: https://github.com/appium/appium-android-driver/blob/903df0c340422ea064e04673462b044202b3c55c/lib/commands/shell.js#L25

1 Like