If I run several emulators with -no-window option in one machine. The command "adb devices" shows:
List of devices attached
emulator-5554 device
emulator-5556 device
emulator-5558 device
...
However, according to this output, I can't tell the difference between each emulator device at all. I need to know which emulator runs on what AVD, then I can install APKs or send commands to the emulator.
How can I recognize each emulator device or get the serial number of emulator after it runs?
Always start the same AVD on the same ports, don't let emulator decide.
Use
$ emulator -ports X,Y @avd_X
then, the serial number will be emulator-X and your avd_X will always be on ports X,Y, so you can run your commands with this serial number, like for example
$ adb -s emulator-X shell cmd
To kill the emulator run
$ adb -s emulator-X emu kill
The same string (e.g., emulator-5554
) is show in the title bar of the emulator window.
There are 2 ways that I know of to perform a reverse Serial Number to AVD name lookup
The Telnet option - The Ugly Way
As pointed out in this SO answer... you can reverse lookup the AVD name for each serial number using Telnet. This is kind of weak, because all you're doing is finding an instance of the emulator launched given a particular AVD name. It doesn't uniquely identify the emulator you are wanting to work on. It also suffers from the need to use telnet and parsing out the port number for each emulator.
First get the currently running serial numbers
adb devices
then telnet to each device's port number
telnet localhost 5554
and issue the command
avd name
which will return the AVD name of that emulator.
The UUID option - The Right Way
I originally saw this done in a project called DCMTK. Generate a UUID uuidgen
and set a property on the emulator at launch! My example launches an emulator to perform some compile time checks for libraries that require running code on the target to determine type information.
emulator -avd nexus19-arm -no-window -no-boot-anim -noaudio -prop emu.uuid=7a6f8701-43c2-4e16-988a-8b4992c0bf8d >/dev/null </dev/null 2>&1 &
Then when you want to find that specific instance of the emulator you just roll through all running emulators and look for that UUID.
adb -s emulator-5556 shell getprop emu.uuid
in a loop:
for SERIAL_NUMBER in `adb devices| grep emulator| cut -f1`; do
UUID=`adb -s ${SERIAL_NUMBER} shell getprop emu.uuid | tr -d '\r\n'`
echo ${SERIAL_NUMBER} ${UUID}
done
Tracking the whole emulator lifecycle
- Launch the emulator with a UUID property
- Then kick off a loop that checks each device to be online and/or having the matching UUID
- Once you get a match call
adb -s ${SERIAL_NUMBER} wait-for-device
so you know when you can talk to the emulator
- If you need the system to be fully online check for the property
sys.boot_completed
- When you're done just kill of the emulator with
adb -s ${SERIAL_NUMBER} emu kill