Skip to content

Commit d5afe70

Browse files
committed
Improve emulator serial detection for UI tests
1 parent 2d2f834 commit d5afe70

File tree

1 file changed

+42
-14
lines changed

1 file changed

+42
-14
lines changed

scripts/build-android-app.sh

Lines changed: 42 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -425,6 +425,8 @@ create_avd "$AVDMANAGER_BIN" "$AVD_NAME" "$SYSTEM_IMAGE" "$AVD_HOME"
425425

426426
ANDROID_AVD_HOME="$AVD_HOME" "$ADB_BIN" start-server >/dev/null
427427

428+
mapfile -t EXISTING_EMULATORS < <("$ADB_BIN" devices | awk '/^emulator-/{print $1}')
429+
428430
EMULATOR_PORT="${EMULATOR_PORT:-5560}"
429431
if ! [[ "$EMULATOR_PORT" =~ ^[0-9]+$ ]]; then
430432
EMULATOR_PORT=5560
@@ -441,22 +443,48 @@ EMULATOR_PID=$!
441443
trap stop_emulator EXIT
442444

443445
sleep 5
444-
EMULATOR_READY=0
445-
for _ in $(seq 1 30); do
446-
if "$ADB_BIN" -s "$EMULATOR_SERIAL" get-state >/dev/null 2>&1; then
447-
EMULATOR_READY=1
448-
break
446+
447+
detect_emulator_serial() {
448+
local deadline current_devices serial existing
449+
deadline=$((SECONDS + 180))
450+
while [ $SECONDS -lt $deadline ]; do
451+
mapfile -t current_devices < <("$ADB_BIN" devices | awk '/^emulator-/{print $1}')
452+
for serial in "${current_devices[@]}"; do
453+
for existing in "${EXISTING_EMULATORS[@]}"; do
454+
if [ "$serial" = "$existing" ]; then
455+
# already present before launch; ignore unless it matches requested serial
456+
if [ "$serial" = "$EMULATOR_SERIAL" ]; then
457+
EMULATOR_SERIAL="$serial"
458+
return 0
459+
fi
460+
serial=""
461+
break
462+
fi
463+
done
464+
if [ -n "$serial" ]; then
465+
EMULATOR_SERIAL="$serial"
466+
return 0
467+
fi
468+
done
469+
sleep 2
470+
done
471+
return 1
472+
}
473+
474+
if ! detect_emulator_serial; then
475+
mapfile -t CURRENT_EMULATORS < <("$ADB_BIN" devices | awk '/^emulator-/{print $1}')
476+
if [ -z "${EMULATOR_SERIAL:-}" ] && [ ${#CURRENT_EMULATORS[@]} -gt 0 ]; then
477+
EMULATOR_SERIAL="${CURRENT_EMULATORS[0]}"
449478
fi
450-
sleep 2
451-
done
452-
if [ "$EMULATOR_READY" -ne 1 ]; then
453-
ba_log "Failed to connect to emulator serial $EMULATOR_SERIAL" >&2
454-
if [ -f "$EMULATOR_LOG" ]; then
455-
ba_log "Emulator log tail:" >&2
456-
tail -n 40 "$EMULATOR_LOG" | sed 's/^/[build-android-app] | /' >&2
479+
if [ -z "${EMULATOR_SERIAL:-}" ] || ! printf '%s\n' "${CURRENT_EMULATORS[@]}" | grep -Fxq "$EMULATOR_SERIAL"; then
480+
ba_log "Failed to detect emulator serial after launch" >&2
481+
if [ -f "$EMULATOR_LOG" ]; then
482+
ba_log "Emulator log tail:" >&2
483+
tail -n 40 "$EMULATOR_LOG" | sed 's/^/[build-android-app] | /' >&2
484+
fi
485+
stop_emulator
486+
exit 1
457487
fi
458-
stop_emulator
459-
exit 1
460488
fi
461489
ba_log "Using emulator serial $EMULATOR_SERIAL"
462490

0 commit comments

Comments
 (0)