scripting-adb-for-ci

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Scripting adb For CI — Bash Idioms, Exit Codes, Fan-out

为 CI 编写 adb 脚本——Bash 惯用法、退出码与扇出

This skill is the connective tissue that turns the other ADB skills into a CI pipeline: exit-code propagation, retries, timeouts, parallel device fan-out, port forwarding, idempotent setup, capture-on-failure, and Test Orchestrator wiring. Each section cross-links to the skill that owns the underlying primitive.
此 skill 是将其他 ADB skills 接入 CI pipeline 的纽带:涵盖退出码传递、重试、超时、并行设备扇出、端口转发、幂等设置、失败时捕获,以及 Test Orchestrator 接入。每个章节都会交叉链接到负责底层原语的 skill。

When to use this skill

何时使用此 skill

  • A CI job invokes
    adb shell am instrument
    and "passes" even when tests fail — it gates on
    $?
    , but
    am instrument
    always exits
    0
    ; the real status lives in
    INSTRUMENTATION_STATUS_CODE
    lines on stdout (and
    -w
    is needed just to get that stdout at all).
  • The team has multiple physical devices on a single agent and wants to run sharded tests in parallel.
  • adb forward
    and
    adb reverse
    are confused — most teams have at least one bug from the opposite argument order.
  • Transient
    error: device not found
    /
    error: closed
    failures are not retried; the job fails on the first hiccup.
  • A script lacks cleanup so leaked port forwards or modified
    settings put global ...
    survive into the next run.
  • The team wires Test Orchestrator with
    androidTestImplementation
    — the build silently fails to install the orchestrator APK.
  • CI job 调用
    adb shell am instrument
    ,即使测试失败也会显示“通过”——它根据
    $?
    设置门禁,但
    am instrument
    始终退出
    0
    ;真实状态位于 stdout 的
    INSTRUMENTATION_STATUS_CODE
    行中(而且必须使用
    -w
    才能获得该 stdout)。
  • 团队在单个 agent 上连接了多台物理设备,希望并行运行分片测试。
  • 团队混淆了
    adb forward
    和
    adb reverse
    ——多数团队至少存在一个因参数顺序相反而导致的 bug。
  • 瞬时
    error: device not found
    /
    error: closed
    失败没有重试机制,job 会在首次小故障后直接失败。
  • 脚本缺少清理逻辑,导致残留的端口转发或被修改的
    settings put global ...
    延续到下一次运行。
  • 团队使用
    androidTestImplementation
    接入 Test Orchestrator,导致构建无法静默安装 orchestrator APK。

When NOT to use this skill

何时不使用此 skill

  • The single primitive (logcat, screencap, pull, push, settings, input, am instrument) is not yet understood. Read the relevant sibling skill first.
  • The CI itself (Gradle plugin, Firebase Test Lab cloud config). Use FTL's own docs for that layer.
  • Compose / instrumentation test mechanics. Use
    ../../../compose/synchronization/synchronizing-with-idle/SKILL.md
    and friends.
  • 尚未理解单个原语(logcat、screencap、pull、push、settings、input、am instrument)。请先阅读对应的同系列 skill。
  • CI 本身(Gradle plugin、Firebase Test Lab 云配置)。这一层请使用 FTL 自身的文档。
  • Compose / instrumentation test 机制。请使用
    ../../../compose/synchronization/synchronizing-with-idle/SKILL.md
    等相关文档。

Prerequisites

前置条件

  • Bash (zsh works for most of this; macOS users should
    brew install coreutils
    for
    gtimeout
    if relying on
    timeout
    ).
  • Platform Tools 24+ on the host. On older toolchains
    adb shell
    exit codes are unreliable.
  • Devices on API 24+ for reliable shell exit-code propagation. Pre-Nougat use a sentinel
    __ADB_RC=$?
    in stdout and grep on the host.
  • Bash(大多数场景也支持 zsh;macOS 用户如果依赖
    timeout
    ,应通过
    brew install coreutils
    安装
    gtimeout
    )。
  • 主机上的 Platform Tools 24+。在较旧的工具链中,
    adb shell
    的退出码不可靠。
  • 设备为 API 24+,才能可靠地传递 shell 退出码。对于 Nougat 之前的版本,应在 stdout 中使用哨兵值
    __ADB_RC=$?
    ,并在主机端执行 grep。

Exit codes — what adb propagates

退出码——adb 会传递哪些退出码

OperationBehavior
adb push
/
adb pull
0
on success, non-zero on transport or filesystem failure. Always check.
adb install
/
adb uninstall
0
on success. Modern adb returns non-zero on
INSTALL_FAILED_*
, but old versions exit
0
even on package-manager failure — verify by piping stderr.
adb wait-for-device
(and
wait-for-usb-device
,
wait-for-local-recovery
, etc.)
Block until the state is reached, then exit
0
. Useful boot gate: `adb wait-for-device shell getprop sys.boot_completed
adb shell <cmd>
On platform-tools ≥ 24 and device adbd ≥ Android 7.0 (Nougat / API 24), the device-side command's exit code is propagated. Older devices always returned
0
regardless.
adb -t <transport-id>
Transport ID, NOT a timeout. Most common scripting confusion.
am instrument
Always exits
0
, pass or fail — AOSP
Instrument.java
ends
run()
with an unconditional
System.exit(0)
and AndroidJUnitRunner calls
finish(Activity.RESULT_OK, …)
regardless of test outcome.
-w
makes the shell wait for the runner so its stdout is complete; without
-w
the shell returns immediately with nothing usable. Either way, gate CI on parsed
INSTRUMENTATION_STATUS_CODE
lines (below), never on
$?
.
adb shell
exit-code propagation can be disabled with
-x
:
shell [-e ESCAPE] [-n] [-Tt] [-x] [COMMAND...]
   -x: disable remote exit codes and stdout/stderr separation
You almost never want
-x
in CI. The default is what you want.
操作行为
adb push
/
adb pull
成功时为
0
,传输或文件系统失败时为非零。始终应检查退出码。
adb install
/
adb uninstall
成功时为
0
。现代 adb 在出现
INSTALL_FAILED_*
时会返回非零,但旧版本即使包管理器失败也会退出
0
——应通过管道传递 stderr 进行验证。
adb wait-for-device
(以及
wait-for-usb-device
、
wait-for-local-recovery
等)
阻塞直到达到指定状态,然后退出
0
。可用作启动门禁:`adb wait-for-device shell getprop sys.boot_completed
adb shell <cmd>
当 platform-tools ≥ 24 且设备端 adbd ≥ Android 7.0(Nougat / API 24)时,会传递设备端命令的退出码。较旧的设备无论结果如何始终返回
0
。
adb -t <transport-id>
表示 Transport ID,而不是超时。这是脚本中最常见的混淆。
am instrument
无论通过还是失败都始终退出
0
——AOSP
Instrument.java
的
run()
最后无条件调用
System.exit(0)
,且 AndroidJUnitRunner 无论测试结果如何都会调用
finish(Activity.RESULT_OK, …)
。
-w
让 shell 等待 runner,从而获得完整 stdout;不加
-w
时 shell 会立即返回且没有可用输出。无论哪种情况,CI 都应根据解析出的
INSTRUMENTATION_STATUS_CODE
行设置门禁(下文),绝不能依赖
$?
。
使用
-x
可以禁用
adb shell
的退出码传递:
shell [-e ESCAPE] [-n] [-Tt] [-x] [COMMAND...]
   -x: disable remote exit codes and stdout/stderr separation
在 CI 中几乎从不应使用
-x
;默认行为正是所需行为。

AndroidJUnitRunner status codes

AndroidJUnitRunner 状态码

am instrument -w -r
emits per-test
INSTRUMENTATION_STATUS_CODE: <int>
followed by a final
INSTRUMENTATION_CODE: <int>
:
CodeSymbolic nameMeaning
1
REPORT_VALUE_RESULT_START
Test started
0
REPORT_VALUE_RESULT_OK
Test passed
-1
REPORT_VALUE_RESULT_ERROR
Unexpected error (process death, runner failure)
-2
REPORT_VALUE_RESULT_FAILURE
Assertion failed
-3
REPORT_VALUE_RESULT_IGNORED
(AndroidJUnitRunner extension)
@Ignore
d / filtered out
-4
REPORT_VALUE_RESULT_ASSUMPTION_FAILURE
(AndroidJUnitRunner extension)
JUnit
assumeXxx
returned false
Don't treat
-3
or
-4
as failures
— they are skips; only
-1
and
-2
are failures. The trailing
INSTRUMENTATION_CODE
line is unrelated: it's an
Activity.RESULT_*
value (
-1
=
RESULT_OK
= no runner-level crash;
0
=
RESULT_CANCELED
= runner died) and, like the shell
$?
(always
0
), it does not reflect test pass/fail. Grep stdout for per-test
INSTRUMENTATION_STATUS_CODE: -1
/
-2
(see the WRONG/RIGHT pattern below).
am instrument -w -r
会为每个测试输出
INSTRUMENTATION_STATUS_CODE: <int>
,并在最后输出
INSTRUMENTATION_CODE: <int>
:
状态码符号名称含义
1
REPORT_VALUE_RESULT_START
测试已开始
0
REPORT_VALUE_RESULT_OK
测试通过
-1
REPORT_VALUE_RESULT_ERROR
意外错误(进程死亡、runner 失败)
-2
REPORT_VALUE_RESULT_FAILURE
断言失败
-3
REPORT_VALUE_RESULT_IGNORED
(AndroidJUnitRunner 扩展)
被
@Ignore
忽略或被过滤掉
-4
REPORT_VALUE_RESULT_ASSUMPTION_FAILURE
(AndroidJUnitRunner 扩展)
JUnit
assumeXxx
返回 false
不要将
-3
或
-4
视为失败
——它们表示跳过;只有
-1
和
-2
才是失败。末尾的
INSTRUMENTATION_CODE
行与测试结果无关:它是一个
Activity.RESULT_*
值(
-1
=
RESULT_OK
= runner 级别没有崩溃;
0
=
RESULT_CANCELED
= runner 已死亡),而且与 shell 的
$?
(始终为
0
)一样,不会反映测试通过或失败。请在 stdout 中 grep 每个测试对应的
INSTRUMENTATION_STATUS_CODE: -1
/
-2
(参见下方的错误/正确模式)。

Port forwarding —
adb forward
vs
adb reverse

端口转发——
adb forward
与
adb reverse

The argument order is opposite. This is the most common scripting bug.
adb forward [--no-rebind] LOCAL  REMOTE        # host → device.  LOCAL  REMOTE
adb reverse [--no-rebind] REMOTE LOCAL         # device → host.  REMOTE LOCAL
DirectionUse caseRecipe
adb forward
Host needs to drive a device-side service.
adb forward tcp:9222 localabstract:chrome_devtools_remote
adb reverse
Device needs to reach a local-only host service (CI runner, dev laptop).
adb reverse tcp:8080 tcp:8080
(Metro/local backend)
Token grammar (from
adb help
):
TokenWhere
tcp:<port>
Either side.
tcp:0
on LOCAL = pick any free port; chosen port is printed to stdout.
localabstract:<name>
Linux abstract Unix domain socket. Used by Chrome DevTools / Stetho / Flipper.
localreserved:<name>
Reserved Unix socket namespace.
localfilesystem:<name>
Filesystem-backed Unix socket.
jdwp:<pid>
REMOTE only. Java Debug Wire Protocol for the given device-side pid.
vsock:<CID>:<port>
REMOTE only. virtio-vsock (emulator).
dev:<char-device>
Character device passthrough.
acceptfd:<fd>
LOCAL only — listen on a pre-opened fd.
Cleanup is the same surface:
--list
,
--remove
,
--remove-all
. Always remove what was added in a
trap
so re-runs on the same agent don't fail with "cannot bind: address already in use".
两者的参数顺序相反。 这是脚本中最常见的 bug。
adb forward [--no-rebind] LOCAL  REMOTE        # host → device.  LOCAL  REMOTE
adb reverse [--no-rebind] REMOTE LOCAL         # device → host.  REMOTE LOCAL
方向使用场景示例
adb forward
主机需要访问设备端服务。
adb forward tcp:9222 localabstract:chrome_devtools_remote
adb reverse
设备需要访问仅限本机的主机服务(CI runner、开发笔记本)。
adb reverse tcp:8080 tcp:8080
(Metro/本地后端)
Token 语法(来自
adb help
):
Token所在位置
tcp:<port>
任一端均可。LOCAL 上的
tcp:0
表示自动选择空闲端口;选定的端口会打印到 stdout。
localabstract:<name>
Linux 抽象 Unix domain socket。用于 Chrome DevTools / Stetho / Flipper。
localreserved:<name>
保留的 Unix socket 命名空间。
localfilesystem:<name>
基于文件系统的 Unix socket。
jdwp:<pid>
仅限 REMOTE。指定设备端 pid 的 Java Debug Wire Protocol。
vsock:<CID>:<port>
仅限 REMOTE。virtio-vsock(模拟器)。
dev:<char-device>
字符设备透传。
acceptfd:<fd>
仅限 LOCAL——监听预先打开的 fd。
清理时使用同一组接口:
--list
、
--remove
、
--remove-all
。应始终在
trap
中移除本次添加的内容,避免在同一 agent 上重新运行时因“cannot bind: address already in use”而失败。

Timeouts — wrap with
timeout
, not
adb -t

超时——使用
timeout
包装器,而不是
adb -t

adb -t <transport-id>
is unrelated to timeout. The host has no per-command adb timeout flag. Wrap with the GNU/BSD
timeout
utility:
bash
timeout 60s adb -s emulator-5554 shell am instrument -w -r ...
echo $?
adb -t <transport-id>
与超时无关。主机端没有按命令设置 adb 超时的标志。请使用 GNU/BSD
timeout
工具:
bash
timeout 60s adb -s emulator-5554 shell am instrument -w -r ...
echo $?

124 = timeout reached (process killed); 137 = had to escalate to SIGKILL.

124 = timeout reached (process killed); 137 = had to escalate to SIGKILL.

0 just means am instrument exited (it always does) — see the timeout pattern below for pass/fail parsing.

0 just means am instrument exited (it always does) — see the timeout pattern below for pass/fail parsing.


On macOS `timeout` is `gtimeout` from `coreutils` (`brew install coreutils`).

For background captures, set a max duration so a stuck job doesn't fill the disk:

```bash
( timeout 600s adb logcat -v threadtime > artifacts/logcat.txt ) &
LOGCAT_PID=$!
trap 'kill $LOGCAT_PID 2>/dev/null' EXIT

在 macOS 上,`timeout` 是 `coreutils` 提供的 `gtimeout`(`brew install coreutils`)。

对于后台捕获任务,应设置最大持续时间,避免卡住的 job 占满磁盘:

```bash
( timeout 600s adb logcat -v threadtime > artifacts/logcat.txt ) &
LOGCAT_PID=$!
trap 'kill $LOGCAT_PID 2>/dev/null' EXIT

Retries on transient errors

瞬时错误重试

The usual offenders:
error: device 'XYZ' not found
,
error: closed
,
error: protocol fault
,
error: device offline
. A
kill-server
+ reconnect resolves most.
bash
retry() {
  local n=0 max=3 delay=2
  until "$@"; do
    n=$((n+1))
    [ "$n" -ge "$max" ] && return 1
    echo "[retry] $* failed (attempt $n); restarting adb"
    adb kill-server; adb start-server
    sleep "$delay"
  done
}

retry adb install -r app.apk
retry adb shell am instrument -w -r ...
For
am instrument
retries specifically, also
pm clear
the test pkg first — otherwise transient state leaks across attempts. Note
retry
only re-runs on transport errors (the
adb
host binary exits non-zero); a genuine test failure leaves
am instrument
exiting
0
, so it won't be retried — detect those by parsing the output, not by exit code.
常见诱因:
error: device 'XYZ' not found
、
error: closed
、
error: protocol fault
、
error: device offline
。执行
kill-server
并重新连接通常可以解决大部分问题。
bash
retry() {
  local n=0 max=3 delay=2
  until "$@"; do
    n=$((n+1))
    [ "$n" -ge "$max" ] && return 1
    echo "[retry] $* failed (attempt $n); restarting adb"
    adb kill-server; adb start-server
    sleep "$delay"
  done
}

retry adb install -r app.apk
retry adb shell am instrument -w -r ...
对于
am instrument
的重试,还应先对测试包执行
pm clear
——否则瞬时状态会在多次尝试之间泄漏。注意,
retry
只会重跑传输层错误(即
adb
主机二进制返回非零);真实测试失败时
am instrument
仍退出
0
,因此不会触发重试——应通过解析输出检测,而不是依赖退出码。

Parallel device fan-out

并行设备扇出

bash
adb devices \
  | tail -n +2 \
  | awk '$2=="device"{print $1}' \
  | xargs -I {} -P 4 adb -s {} <command>
Key fragments:
  • tail -n +2
    skips the
    List of devices attached
    header.
  • awk '$2=="device"'
    filters out
    unauthorized
    ,
    offline
    ,
    recovery
    , etc.
  • -P 4
    runs 4 in parallel; tune to physical USB-hub count.
  • adb -s {}
    targets a serial.
    $ANDROID_SERIAL
    is the env-var equivalent inside the spawned shells.
For tests with shared device-state (logcat clear, app install), serialise the prep then parallelise the run:
bash
SERIALS=$(adb devices | awk '$2=="device"{print $1}')
echo "$SERIALS" | xargs -I {} -P 0 adb -s {} install -r app-debug.apk
echo "$SERIALS" | xargs -I {} -P 0 adb -s {} install -r app-debug-androidTest.apk
bash
adb devices \
  | tail -n +2 \
  | awk '$2=="device"{print $1}' \
  | xargs -I {} -P 4 adb -s {} <command>
关键片段:
  • tail -n +2
    跳过
    List of devices attached
    标题行。
  • awk '$2=="device"'
    过滤掉
    unauthorized
    、
    offline
    、
    recovery
    等状态。
  • -P 4
    表示并行运行 4 个任务;应根据物理 USB hub 的数量进行调整。
  • adb -s {}
    用于指定目标设备序列号。
    $ANDROID_SERIAL
    是派生 shell 中对应的环境变量形式。
对于会共享设备状态的测试(清理 logcat、安装应用),应先串行执行准备阶段,再并行运行测试:
bash
SERIALS=$(adb devices | awk '$2=="device"{print $1}')
echo "$SERIALS" | xargs -I {} -P 0 adb -s {} install -r app-debug.apk
echo "$SERIALS" | xargs -I {} -P 0 adb -s {} install -r app-debug-androidTest.apk

Distribute shards across devices (one shard per device)

Distribute shards across devices (one shard per device)

i=0 for S in $SERIALS; do adb -s "$S" logcat -c adb -s "$S" shell am instrument -w -r
-e numShards $(echo "$SERIALS" | wc -l) -e shardIndex "$i"
com.example.test/androidx.test.runner.AndroidJUnitRunner
> "results-$S.txt" & i=$((i+1)) done wait
i=0 for S in $SERIALS; do adb -s "$S" logcat -c adb -s "$S" shell am instrument -w -r
-e numShards $(echo "$SERIALS" | wc -l) -e shardIndex "$i"
com.example.test/androidx.test.runner.AndroidJUnitRunner
> "results-$S.txt" & i=$((i+1)) done wait

am instrument always exits 0 — derive pass/fail from the captured output:

am instrument always exits 0 — derive pass/fail from the captured output:

if grep -qE '^INSTRUMENTATION_STATUS_CODE: -[12]$' results-*.txt; then echo "test failures detected"; exit 1 fi

(`xargs -P 0` runs as many concurrently as there are inputs.)
if grep -qE '^INSTRUMENTATION_STATUS_CODE: -[12]$' results-*.txt; then echo "test failures detected"; exit 1 fi

(`xargs -P 0` 的并发数与输入数量相同。)

Sharding via
numShards
/
shardIndex

通过
numShards
/
shardIndex
进行分片

"If you need to parallelize the execution of your tests ... use the
-e numShards
option to specify the number of separate shards to create and the
-e shardIndex
option to specify which shard to run." — AndroidJUnitRunner docs.
Distribution is hash-bucketed by test name — deterministic across runs given the same test set. Adding/removing tests reshuffles buckets.
“如果需要并行执行测试……请使用
-e numShards
选项指定要创建的分片数量,并使用
-e shardIndex
选项指定要运行的分片。”——AndroidJUnitRunner 文档。
分发方式会根据测试名称进行 hash 分桶——在测试集合保持不变时,每次运行的结果都是确定的。添加或移除测试会重新打乱各个分桶。

Per-device artefact paths

按设备划分的 artefact 路径

Always namespace by serial:
bash
artifact_dir() { echo "artifacts/${1//[:_]/-}"; }
for S in $(adb devices | awk '$2=="device"{print $1}'); do
  D=$(artifact_dir "$S"); mkdir -p "$D"
  adb -s "$S" logcat -d -v threadtime > "$D/logcat.txt"
  adb -s "$S" shell screencap -p /sdcard/last.png
  adb -s "$S" pull /sdcard/last.png "$D/last.png"
done
始终使用序列号划分命名空间:
bash
artifact_dir() { echo "artifacts/${1//[:_]/-}"; }
for S in $(adb devices | awk '$2=="device"{print $1}'); do
  D=$(artifact_dir "$S"); mkdir -p "$D"
  adb -s "$S" logcat -d -v threadtime > "$D/logcat.txt"
  adb -s "$S" shell screencap -p /sdcard/last.png
  adb -s "$S" pull /sdcard/last.png "$D/last.png"
done

Idempotent setup + cleanup with
trap

幂等设置与使用
trap
清理

Never assume clean state from a previous run. Bake cleanup into setup, and use
trap
to enforce teardown.
永远不要假设上次运行后仍处于干净状态。应将清理纳入设置流程,并使用
trap
强制执行 teardown。

Minimal setup preamble

最小设置前导代码

bash
adb wait-for-device
adb shell input keyevent 82                         # wake; no-op if already on
adb shell pm clear com.example.app                  # wipe app data + cache
adb shell pm clear com.example.app.test             # wipe test process state
adb shell am force-stop com.example.app
bash
adb wait-for-device
adb shell input keyevent 82                         # wake; no-op if already on
adb shell pm clear com.example.app                  # wipe app data + cache
adb shell pm clear com.example.app.test             # wipe test process state
adb shell am force-stop com.example.app

Hermetic animations

Hermetic animations

adb shell settings put global window_animation_scale 0 adb shell settings put global transition_animation_scale 0 adb shell settings put global animator_duration_scale 0

(See `../../control/injecting-input-and-state/SKILL.md` for the full `pm clear` vs `am force-stop` reasoning.)
adb shell settings put global window_animation_scale 0 adb shell settings put global transition_animation_scale 0 adb shell settings put global animator_duration_scale 0

(有关 `pm clear` 与 `am force-stop` 的完整选型分析,请参阅 `../../control/injecting-input-and-state/SKILL.md`。)

trap
cleanup

trap
清理

bash
cleanup() {
  adb shell am force-stop com.example.app                       || true
  adb shell pm clear     com.example.app                        || true
  adb uninstall          com.example.app                        || true
  adb forward --remove tcp:6100                                 || true
  adb reverse --remove-all                                      || true
  adb shell settings put global window_animation_scale 1        || true
  adb shell settings put global transition_animation_scale 1    || true
  adb shell settings put global animator_duration_scale 1       || true
}
trap cleanup EXIT
Each step is
|| true
— partial-state cleanup must never mask the original failure exit code.
bash
cleanup() {
  adb shell am force-stop com.example.app                       || true
  adb shell pm clear     com.example.app                        || true
  adb uninstall          com.example.app                        || true
  adb forward --remove tcp:6100                                 || true
  adb reverse --remove-all                                      || true
  adb shell settings put global window_animation_scale 1        || true
  adb shell settings put global transition_animation_scale 1    || true
  adb shell settings put global animator_duration_scale 1       || true
}
trap cleanup EXIT
每个步骤都使用
|| true
——部分状态清理失败绝不能掩盖原始的失败退出码。

Capture-on-failure

失败时捕获

bash
set +e
./gradlew connectedDebugAndroidTest
RC=$?
set -e

if [ "$RC" -ne 0 ]; then
  mkdir -p artifacts
  adb shell screencap -p /sdcard/fail.png
  adb pull /sdcard/fail.png artifacts/fail.png
  adb logcat -d -v threadtime              > artifacts/logcat.txt
  adb logcat -d -b crash    -v threadtime  > artifacts/crash.txt
  adb logcat -d -b events   -v descriptive > artifacts/events.txt
  adb shell dumpsys activity               > artifacts/dumpsys-activity.txt
fi
exit $RC
(See
../../capture/capturing-screenshots-and-screenrecord/SKILL.md
and
../../observability/extracting-logs-with-logcat/SKILL.md
for the underlying primitives.)
bash
set +e
./gradlew connectedDebugAndroidTest
RC=$?
set -e

if [ "$RC" -ne 0 ]; then
  mkdir -p artifacts
  adb shell screencap -p /sdcard/fail.png
  adb pull /sdcard/fail.png artifacts/fail.png
  adb logcat -d -v threadtime              > artifacts/logcat.txt
  adb logcat -d -b crash    -v threadtime  > artifacts/crash.txt
  adb logcat -d -b events   -v descriptive > artifacts/events.txt
  adb shell dumpsys activity               > artifacts/dumpsys-activity.txt
fi
exit $RC
(有关底层原语,请参阅
../../capture/capturing-screenshots-and-screenrecord/SKILL.md
和
../../observability/extracting-logs-with-logcat/SKILL.md
。)

Test Orchestrator wiring

Test Orchestrator 接入

"Android Test Orchestrator collects JUnit tests at the beginning of your test suite run, but it then executes each test separately, in its own instance of
Instrumentation
." — developer.android.com.
Each
@Test
runs in its own
Instrumentation
invocation, so process state, statics, and
Application
singletons are reset between tests.
“Android Test Orchestrator 会在测试套件开始时收集 JUnit 测试,但随后在独立的
Instrumentation
实例中分别执行每个测试。”——developer.android.com。
每个
@Test
都在独立的
Instrumentation
调用中运行,因此进程状态、静态变量和
Application
单例会在测试之间重置。

Gradle wiring —
androidTestUtil
, NOT
androidTestImplementation

Gradle 接入——使用
androidTestUtil
,而不是
androidTestImplementation

gradle
android {
  defaultConfig {
    testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
    testInstrumentationRunnerArguments clearPackageData: 'true'
  }
  testOptions {
    execution 'ANDROIDX_TEST_ORCHESTRATOR'
  }
}

dependencies {
  androidTestImplementation 'androidx.test:runner:1.7.0'
  androidTestUtil           'androidx.test:orchestrator:1.6.1'   // NOT androidTestImplementation
}
clearPackageData: 'true'
makes the Orchestrator run
pm clear <pkg>
between tests — the strongest isolation knob.
gradle
android {
  defaultConfig {
    testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
    testInstrumentationRunnerArguments clearPackageData: 'true'
  }
  testOptions {
    execution 'ANDROIDX_TEST_ORCHESTRATOR'
  }
}

dependencies {
  androidTestImplementation 'androidx.test:runner:1.7.0'
  androidTestUtil           'androidx.test:orchestrator:1.6.1'   // NOT androidTestImplementation
}
clearPackageData: 'true'
会让 Orchestrator 在测试之间执行
pm clear <pkg>
——这是最强的隔离选项。

Direct ADB invocation (non-Gradle)

直接通过 ADB 调用(非 Gradle)

bash
adb install --force-queryable -r path/to/orchestrator-1.6.1.apk
adb install --force-queryable -r path/to/test-services-1.6.0.apk

adb shell 'CLASSPATH=$(pm path androidx.test.services) app_process / \
 androidx.test.services.shellexecutor.ShellMain am instrument -w -e \
 targetInstrumentation com.example.test/androidx.test.runner.AndroidJUnitRunner \
 androidx.test.orchestrator/.AndroidTestOrchestrator'
--force-queryable
is needed on API 30+ so the Orchestrator can
bindService
into the target despite package-visibility rules.
bash
adb install --force-queryable -r path/to/orchestrator-1.6.1.apk
adb install --force-queryable -r path/to/test-services-1.6.0.apk

adb shell 'CLASSPATH=$(pm path androidx.test.services) app_process / \
 androidx.test.services.shellexecutor.ShellMain am instrument -w -e \
 targetInstrumentation com.example.test/androidx.test.runner.AndroidJUnitRunner \
 androidx.test.orchestrator/.AndroidTestOrchestrator'
在 API 30+ 上需要使用
--force-queryable
,这样 Orchestrator 才能在包可见性规则下通过
bindService
绑定到目标应用。

Tradeoffs

取舍

  • Pros: each test starts from a known-good
    Application
    ; one crash doesn't kill the rest of the run;
    pm clear
    between tests is real, not "I cleaned up in
    @After
    ".
  • Cons: per-test process spin-up adds ~1–2 s. A 500-test suite goes from ~5 minutes to ~15+ minutes. Reserve for integration suites where state leakage actually bites.
  • 优点: 每个测试都从状态已知的
    Application
    开始;单个测试崩溃不会终止其余测试;测试之间的
    pm clear
    是真实执行的,而不是仅在
    @After
    中“清理”。
  • 缺点: 每个测试启动独立进程会增加约 1–2 秒。一个包含 500 个测试的套件可能从约 5 分钟增加到 15 分钟以上。仅在状态泄漏确实会造成问题时,将其用于集成测试套件。

Patterns

模式

Pattern: WRONG — gating CI on
am instrument
's exit code

模式:错误——根据
am instrument
的退出码设置 CI 门禁

bash
undefined
bash
undefined

WRONG

WRONG

adb shell am instrument -w -r com.example.test/androidx.test.runner.AndroidJUnitRunner RC=$? [ "$RC" -eq 0 ] && echo "tests passed" || echo "tests failed (rc=$RC)"
adb shell am instrument -w -r com.example.test/androidx.test.runner.AndroidJUnitRunner RC=$? [ "$RC" -eq 0 ] && echo "tests passed" || echo "tests failed (rc=$RC)"

WRONG because: am instrument calls System.exit(0) (AOSP Instrument.java) and AndroidJUnitRunner's

WRONG because: am instrument calls System.exit(0) (AOSP Instrument.java) and AndroidJUnitRunner's

finish() reports RESULT_OK regardless. $? is 0 even when tests fail — with OR without -w.

finish() reports RESULT_OK regardless. $? is 0 even when tests fail — with OR without -w.


```bash

```bash

RIGHT — keep -w (so stdout is complete) and -r (raw, parseable), then parse the stream

RIGHT — keep -w (so stdout is complete) and -r (raw, parseable), then parse the stream

adb shell am instrument -w -r com.example.test/androidx.test.runner.AndroidJUnitRunner
| tee instrument.log
adb shell am instrument -w -r com.example.test/androidx.test.runner.AndroidJUnitRunner
| tee instrument.log

-1 = error, -2 = failure; -3 (ignored) and -4 (assumption failure) are skips, not failures.

-1 = error, -2 = failure; -3 (ignored) and -4 (assumption failure) are skips, not failures.

if grep -qE '^INSTRUMENTATION_STATUS_CODE: -[12]$' instrument.log; then echo "tests failed"; exit 1 fi echo "tests passed"
undefined
if grep -qE '^INSTRUMENTATION_STATUS_CODE: -[12]$' instrument.log; then echo "tests failed"; exit 1 fi echo "tests passed"
undefined

Pattern: WRONG — confusing
adb forward
and
adb reverse
argument order

模式:错误——混淆
adb forward
和
adb reverse
的参数顺序

bash
undefined
bash
undefined

WRONG — copy/pasted the forward syntax for reverse

WRONG — copy/pasted the forward syntax for reverse

adb reverse tcp:8080 tcp:8080 # ambiguous (works because both are tcp:8080) adb reverse tcp:9000 tcp:8080 # this means: device port 9000 → host port 8080
adb reverse tcp:8080 tcp:8080 # ambiguous (works because both are tcp:8080) adb reverse tcp:9000 tcp:8080 # this means: device port 9000 → host port 8080

Developer expected: host service on 8080 reachable as 9000 on device.

Developer expected: host service on 8080 reachable as 9000 on device.

WRONG because: reverse argument order is REMOTE LOCAL. The device tries to dial 8080 on

WRONG because: reverse argument order is REMOTE LOCAL. The device tries to dial 8080 on

the host, but the dev meant to expose the local 8080 to the device on port 9000.

the host, but the dev meant to expose the local 8080 to the device on port 9000.


```bash

```bash

RIGHT — adb reverse REMOTE LOCAL

RIGHT — adb reverse REMOTE LOCAL

Expose host service on 8080 to the device as 9000:

Expose host service on 8080 to the device as 9000:

adb reverse tcp:9000 tcp:8080
adb reverse tcp:9000 tcp:8080

In the app code: open a connection to localhost:9000 — it terminates at the host's :8080.

In the app code: open a connection to localhost:9000 — it terminates at the host's :8080.

Or, simpler, identical port:

Or, simpler, identical port:

adb reverse tcp:8080 tcp:8080 # device 8080 ⇆ host 8080
undefined
adb reverse tcp:8080 tcp:8080 # device 8080 ⇆ host 8080
undefined

Pattern: WRONG —
androidTestImplementation
for the orchestrator APK

模式:错误——使用
androidTestImplementation
引入 orchestrator APK

gradle
// WRONG
dependencies {
  androidTestImplementation 'androidx.test:orchestrator:1.6.1'
}
// WRONG because: the orchestrator is a SEPARATE APK, not a library. androidTestImplementation
// merges it into the test APK's classpath, which AGP rejects (or silently ignores). The
// correct configuration is androidTestUtil, which AGP installs as an additional APK.
gradle
// RIGHT
dependencies {
  androidTestImplementation 'androidx.test:runner:1.7.0'
  androidTestUtil           'androidx.test:orchestrator:1.6.1'
}
gradle
// WRONG
dependencies {
  androidTestImplementation 'androidx.test:orchestrator:1.6.1'
}
// WRONG because: the orchestrator is a SEPARATE APK, not a library. androidTestImplementation
// merges it into the test APK's classpath, which AGP rejects (or silently ignores). The
// correct configuration is androidTestUtil, which AGP installs as an additional APK.
gradle
// RIGHT
dependencies {
  androidTestImplementation 'androidx.test:runner:1.7.0'
  androidTestUtil           'androidx.test:orchestrator:1.6.1'
}

Pattern: timeout an instrumentation invocation

模式:为 instrumentation 调用设置超时

bash
timeout 600s adb shell am instrument -w -r \
  com.example.test/androidx.test.runner.AndroidJUnitRunner | tee instrument.log
RC=${PIPESTATUS[0]}   # exit of `timeout`, not `tee`
case "$RC" in
  124) echo "timed out at 600s"; exit 124 ;;
  137) echo "timed out and had to be SIGKILLed"; exit 137 ;;
esac
bash
timeout 600s adb shell am instrument -w -r \
  com.example.test/androidx.test.runner.AndroidJUnitRunner | tee instrument.log
RC=${PIPESTATUS[0]}   # exit of `timeout`, not `tee`
case "$RC" in
  124) echo "timed out at 600s"; exit 124 ;;
  137) echo "timed out and had to be SIGKILLed"; exit 137 ;;
esac

RC is 0 whether tests passed or failed (am instrument always exits 0); pass/fail comes from the stream:

RC is 0 whether tests passed or failed (am instrument always exits 0); pass/fail comes from the stream:

if grep -qE '^INSTRUMENTATION_STATUS_CODE: -[12]$' instrument.log; then echo "failed"; exit 1 fi echo "passed"
undefined
if grep -qE '^INSTRUMENTATION_STATUS_CODE: -[12]$' instrument.log; then echo "failed"; exit 1 fi echo "passed"
undefined

Pattern: retry-with-server-bounce

模式:通过重启 server 进行重试

bash
retry adb -s "$SERIAL" install -r app-debug.apk
retry adb -s "$SERIAL" shell am instrument -w -r \
  -e clearPackageData true \
  com.example.test/androidx.test.runner.AndroidJUnitRunner
The
retry
helper bounces the adb server on transient failure (see "Retries on transient errors" above).
bash
retry adb -s "$SERIAL" install -r app-debug.apk
retry adb -s "$SERIAL" shell am instrument -w -r \
  -e clearPackageData true \
  com.example.test/androidx.test.runner.AndroidJUnitRunner
retry
helper 会在瞬时失败时重启 adb server(参见上文“瞬时错误重试”)。

Pattern: parallel sharded fan-out with per-device artefacts

模式:并行分片扇出并按设备保存 artefact

bash
SERIALS=( $(adb devices | awk '$2=="device"{print $1}') )
N=${#SERIALS[@]}
mkdir -p artifacts

pids=()
for i in "${!SERIALS[@]}"; do
  S="${SERIALS[$i]}"
  D="artifacts/${S//[:_]/-}"
  mkdir -p "$D"
  (
    adb -s "$S" logcat -c
    adb -s "$S" shell pm clear com.example.app
    adb -s "$S" shell am instrument -w -r \
         -e numShards "$N" -e shardIndex "$i" \
         com.example.test/androidx.test.runner.AndroidJUnitRunner \
         > "$D/results.txt"
    # am instrument exits 0 regardless — pass/fail is in the captured stream.
    if grep -qE '^INSTRUMENTATION_STATUS_CODE: -[12]$' "$D/results.txt"; then
      adb -s "$S" shell screencap -p /sdcard/fail.png
      adb -s "$S" pull /sdcard/fail.png "$D/fail.png"
      adb -s "$S" logcat -d -v threadtime > "$D/logcat.txt"
      exit 1
    fi
  ) &
  pids+=($!)
done

rc=0
for p in "${pids[@]}"; do wait "$p" || rc=1; done   # fail the job if any shard failed
exit $rc
bash
SERIALS=( $(adb devices | awk '$2=="device"{print $1}') )
N=${#SERIALS[@]}
mkdir -p artifacts

pids=()
for i in "${!SERIALS[@]}"; do
  S="${SERIALS[$i]}"
  D="artifacts/${S//[:_]/-}"
  mkdir -p "$D"
  (
    adb -s "$S" logcat -c
    adb -s "$S" shell pm clear com.example.app
    adb -s "$S" shell am instrument -w -r \
         -e numShards "$N" -e shardIndex "$i" \
         com.example.test/androidx.test.runner.AndroidJUnitRunner \
         > "$D/results.txt"
    # am instrument exits 0 regardless — pass/fail is in the captured stream.
    if grep -qE '^INSTRUMENTATION_STATUS_CODE: -[12]$' "$D/results.txt"; then
      adb -s "$S" shell screencap -p /sdcard/fail.png
      adb -s "$S" pull /sdcard/fail.png "$D/fail.png"
      adb -s "$S" logcat -d -v threadtime > "$D/logcat.txt"
      exit 1
    fi
  ) &
  pids+=($!)
done

rc=0
for p in "${pids[@]}"; do wait "$p" || rc=1; done   # fail the job if any shard failed
exit $rc

Mandatory rules

强制规则

  • MUST pass
    -w -r
    to
    am instrument
    so the shell waits for the runner and emits raw, parseable output. Without
    -w
    the shell returns before any output is produced.
  • MUST NOT gate CI on
    $?
    from
    am instrument
    — it calls
    System.exit(0)
    regardless of test outcome (with or without
    -w
    ). Detect failures by grepping stdout for
    INSTRUMENTATION_STATUS_CODE: -1
    (error) and
    -2
    (failure).
  • MUST distinguish
    -3
    IGNORED and
    -4
    ASSUMPTION_FAILURE from real failures when parsing
    INSTRUMENTATION_STATUS_CODE
    .
    -1
    and
    -2
    are the failure codes.
  • MUST remember that
    adb forward
    is
    LOCAL REMOTE
    (host first) and
    adb reverse
    is
    REMOTE LOCAL
    (device first). The argument orders are opposite.
  • MUST wrap long-running adb commands with
    timeout <N>s
    (or
    gtimeout
    on macOS).
    adb
    has no built-in timeout flag —
    adb -t
    is transport ID, not timeout.
  • MUST use
    androidTestUtil("androidx.test:orchestrator:1.6.1")
    , not
    androidTestImplementation
    . The orchestrator is a separate APK, not a library.
  • MUST retry transient adb errors (
    device not found
    ,
    closed
    ,
    protocol fault
    ) with a bounded
    retry
    helper that calls
    adb kill-server; adb start-server
    between attempts.
  • MUST install a
    trap cleanup EXIT
    that removes port forwards (
    adb forward --remove-all
    ,
    adb reverse --remove-all
    ), restores animation scales, and
    pm clear
    s the app under test. Each step
    || true
    so cleanup never masks the test exit code.
  • MUST
    pm clear <pkg>
    (not just
    am force-stop
    ) before each test run. See
    ../../control/injecting-input-and-state/SKILL.md
    .
  • MUST NOT rely on
    adb shell
    exit-code propagation on devices below API 24. Use a sentinel
    __ADB_RC=$?
    in stdout for older targets, or pin minSdk for the test infra.
  • MUST NOT confuse
    adb -t <transport-id>
    with
    timeout
    . They share zero semantics.
  • MUST NOT parallelise without serialising the install / setup phase — concurrent
    adb install
    to the same device race.
  • PREFERRED: Test Orchestrator +
    clearPackageData: 'true'
    for hermetic isolation; pair with
    useTestStorageService: 'true'
    for routed artefacts (see
    ../../transfer/extracting-test-artifacts/SKILL.md
    ).
  • PREFERRED: namespace artefacts by serial (
    artifacts/${SERIAL//[:_]/-}/
    ) so
    archive artifacts/**/*
    in CI captures everything cleanly.
  • 必须对
    am instrument
    传入
    -w -r
    ,使 shell 等待 runner 并输出原始、可解析的结果。不使用
    -w
    时,shell 会在产生任何输出之前返回。
  • 禁止根据
    am instrument
    的
    $?
    设置 CI 门禁——无论测试结果如何,它都会调用
    System.exit(0)
    (是否使用
    -w
    均如此)。应通过在 stdout 中查找
    INSTRUMENTATION_STATUS_CODE: -1
    (错误)和
    -2
    (失败)来检测失败。
  • 必须在解析
    INSTRUMENTATION_STATUS_CODE
    时区分
    -3
    IGNORED 和
    -4
    ASSUMPTION_FAILURE 与真实失败。
    -1
    和
    -2
    才是失败状态码。
  • 必须记住
    adb forward
    的顺序是
    LOCAL REMOTE
    (主机在前),而
    adb reverse
    的顺序是
    REMOTE LOCAL
    (设备在前)。两者的参数顺序相反。
  • 必须使用
    timeout <N>s
    (macOS 上使用
    gtimeout
    )包装长时间运行的 adb 命令。
    adb
    没有内置的超时标志——
    adb -t
    表示 transport ID,而不是 timeout。
  • 必须使用
    androidTestUtil("androidx.test:orchestrator:1.6.1")
    ,而不是
    androidTestImplementation
    。Orchestrator 是独立的 APK,而不是库。
  • 必须使用有次数上限的
    retry
    helper 重试瞬时 adb 错误(
    device not found
    、
    closed
    、
    protocol fault
    ),并在尝试之间调用
    adb kill-server; adb start-server
    。
  • 必须安装
    trap cleanup EXIT
    ,用于移除端口转发(
    adb forward --remove-all
    、
    adb reverse --remove-all
    )、恢复动画缩放设置,并执行
    pm clear
    清理被测应用。每个步骤都应使用
    || true
    ,确保清理不会掩盖测试退出码。
  • 必须在每次测试运行前执行
    pm clear <pkg>
    ,而不能只使用
    am force-stop
    。请参阅
    ../../control/injecting-input-and-state/SKILL.md
    。
  • 禁止依赖 API 24 以下设备上的
    adb shell
    退出码传递。对于较旧的目标设备,应在 stdout 中使用哨兵值
    __ADB_RC=$?
    ,或在测试基础设施中固定 minSdk。
  • 禁止混淆
    adb -t <transport-id>
    与
    timeout
    。两者没有任何语义关联。
  • 禁止在未串行化安装/设置阶段的情况下进行并行化——对同一台设备并发执行
    adb install
    会产生竞态。
  • 首选: 使用 Test Orchestrator 配合
    clearPackageData: 'true'
    实现隔离式测试;结合
    useTestStorageService: 'true'
    路由 artefact(请参阅
    ../../transfer/extracting-test-artifacts/SKILL.md
    )。
  • 首选: 使用序列号划分 artefact 命名空间(
    artifacts/${SERIAL//[:_]/-}/
    ),确保 CI 中的
    archive artifacts/**/*
    能够整齐地收集所有文件。

Verification

验证

  • Every
    am instrument
    invocation in scripts/Gradle has
    -w -r
    , and no script branches on its
    $?
    as a pass/fail signal — failures are detected by parsing
    INSTRUMENTATION_STATUS_CODE: -1
    /
    -2
    from stdout.
  • adb forward
    and
    adb reverse
    appear with arguments in the documented order; CI passes a smoke test that the host can reach the device service and vice versa.
  • androidTestUtil('androidx.test:orchestrator:...')
    (not
    androidTestImplementation
    ) —
    ./gradlew :app:dependencies --configuration androidTestUtil
    shows the orchestrator.
  • trap cleanup EXIT
    is installed in the top-level CI script.
  • All long-running adb commands are wrapped with
    timeout
    .
  • CI run completes 50 iterations without a "leaked port forward" or "previous run's animation scale" flake.
  • Status-code parsing treats
    -3
    and
    -4
    as skips, not failures.
  • Per-device artefact directories are namespaced by serial; CI artefact archive shows them in the expected layout.
  • Retry helper bounces
    adb kill-server; adb start-server
    between attempts on transient errors.
  • 脚本/Gradle 中的每次
    am instrument
    调用都使用了
    -w -r
    ,且没有脚本将其
    $?
    作为通过/失败信号——失败是通过解析 stdout 中的
    INSTRUMENTATION_STATUS_CODE: -1
    /
    -2
    检测的。
  • adb forward
    和
    adb reverse
    的参数均采用文档规定的顺序;CI 通过冒烟测试,验证主机可以访问设备服务,反之亦然。
  • 使用
    androidTestUtil('androidx.test:orchestrator:...')
    ,而不是
    androidTestImplementation
    ——
    ./gradlew :app:dependencies --configuration androidTestUtil
    显示 orchestrator。
  • 顶层 CI 脚本中安装了
    trap cleanup EXIT
    。
  • 所有长时间运行的 adb 命令都使用了
    timeout
    包装。
  • CI 连续运行 50 次后,没有出现“leaked port forward”或“previous run's animation scale”类不稳定问题。
  • 状态码解析将
    -3
    和
    -4
    视为跳过,而不是失败。
  • 每台设备的 artefact 目录均按序列号划分命名空间;CI artefact 归档结果符合预期布局。
  • Retry helper 会在瞬时错误发生时,在尝试之间执行
    adb kill-server; adb start-server
    。

References

参考资料

  • developer.android.com/tools/adb —
    forward
    /
    reverse
    syntax, transport, server.
  • developer.android.com/studio/test/command-line —
    am instrument -w -r
    ,
    -e numShards
    /
    -e shardIndex
    , AndroidJUnitRunner arguments, output dirs.
  • developer.android.com/training/testing/instrumented-tests — Test Orchestrator overview.
  • developer.android.com/reference/android/app/Instrumentation —
    REPORT_VALUE_RESULT_*
    constants (
    OK = 0
    ,
    START = 1
    ,
    ERROR = -1
    ,
    FAILURE = -2
    ).
  • firebase.google.com/docs/test-lab/android/command-line — Firebase Test Lab CI exit codes (
    0
    pass,
    10
    test failure,
    15
    indeterminate,
    18
    incompatible,
    20
    infra error).
  • Research note
    tasks/research/A3-adb-observability-automation.md
    — full bash idioms, exit-code propagation matrix, port-forward token grammar, parallel fan-out, retries, capture-on-failure, Test Orchestrator wiring.
  • Research note
    tasks/research/A2-adb-shell-commands.md
    —
    am instrument
    arguments, status codes, AndroidJUnitRunner
    -3
    /
    -4
    extensions.
  • Sibling skill:
    ../../architecture/understanding-adb-architecture/SKILL.md
    — server / daemon /
    adb kill-server
    .
  • Sibling skill:
    ../../devices/connecting-to-devices/SKILL.md
    — device states,
    wait-for-device
    .
  • Sibling skill:
    ../../devices/connecting-over-wifi/SKILL.md
    —
    adb pair
    /
    adb connect
    for headless CI.
  • Sibling skill:
    ../../apps/installing-and-managing-apps/SKILL.md
    —
    pm install
    /
    pm uninstall
    /
    pm clear
    .
  • Sibling skill:
    ../../tests/running-instrumented-tests-via-adb/SKILL.md
    —
    am instrument -w -r
    deep dive.
  • Sibling skill:
    ../../control/injecting-input-and-state/SKILL.md
    — hermetic preamble (animations to 0,
    pm clear
    ,
    am force-stop
    ).
  • Sibling skill:
    ../../capture/capturing-screenshots-and-screenrecord/SKILL.md
    —
    screencap
    /
    screenrecord
    capture-on-failure.
  • Sibling skill:
    ../../observability/extracting-logs-with-logcat/SKILL.md
    —
    logcat -d
    capture-on-failure.
  • Sibling skill:
    ../../transfer/extracting-test-artifacts/SKILL.md
    —
    pull
    /
    push
    /
    run-as
    /
    TestStorage
    .
  • Cross-set:
    ../../../instrumentation/runner/running-instrumented-tests-with-androidjunit4/SKILL.md
    — runner internals.
  • Cross-set:
    ../../../instrumentation/scenarios/launching-activities-with-activityscenario/SKILL.md
    — Activity scenarios under instrumentation.
  • Cross-set:
    ../../../fundamentals/strategies/applying-testing-strategies/SKILL.md
    — when to invest in CI orchestration vs simpler tooling.
  • developer.android.com/tools/adb——
    forward
    /
    reverse
    语法、transport、server。
  • developer.android.com/studio/test/command-line——
    am instrument -w -r
    、
    -e numShards
    /
    -e shardIndex
    、AndroidJUnitRunner 参数、输出目录。
  • developer.android.com/training/testing/instrumented-tests——Test Orchestrator 概览。
  • developer.android.com/reference/android/app/Instrumentation——
    REPORT_VALUE_RESULT_*
    常量(
    OK = 0
    、
    START = 1
    、
    ERROR = -1
    、
    FAILURE = -2
    )。
  • firebase.google.com/docs/test-lab/android/command-line——Firebase Test Lab CI 退出码(
    0
    通过、
    10
    测试失败、
    15
    结果不确定、
    18
    不兼容、
    20
    基础设施错误)。
  • 研究笔记
    tasks/research/A3-adb-observability-automation.md
    ——完整的 Bash 惯用法、退出码传递矩阵、端口转发 token 语法、并行扇出、重试、失败时捕获、Test Orchestrator 接入。
  • 研究笔记
    tasks/research/A2-adb-shell-commands.md
    ——
    am instrument
    参数、状态码、AndroidJUnitRunner 的
    -3
    /
    -4
    扩展。
  • 同系列 skill:
    ../../architecture/understanding-adb-architecture/SKILL.md
    ——server / daemon /
    adb kill-server
    。
  • 同系列 skill:
    ../../devices/connecting-to-devices/SKILL.md
    ——设备状态、
    wait-for-device
    。
  • 同系列 skill:
    ../../devices/connecting-over-wifi/SKILL.md
    ——用于无头 CI 的
    adb pair
    /
    adb connect
    。
  • 同系列 skill:
    ../../apps/installing-and-managing-apps/SKILL.md
    ——
    pm install
    /
    pm uninstall
    /
    pm clear
    。
  • 同系列 skill:
    ../../tests/running-instrumented-tests-via-adb/SKILL.md
    ——深入讲解
    am instrument -w -r
    。
  • 同系列 skill:
    ../../control/injecting-input-and-state/SKILL.md
    ——隔离式前导代码(将动画设为 0、
    pm clear
    、
    am force-stop
    )。
  • 同系列 skill:
    ../../capture/capturing-screenshots-and-screenrecord/SKILL.md
    ——通过
    screencap
    /
    screenrecord
    在失败时捕获。
  • 同系列 skill:
    ../../observability/extracting-logs-with-logcat/SKILL.md
    ——通过
    logcat -d
    在失败时捕获。
  • 同系列 skill:
    ../../transfer/extracting-test-artifacts/SKILL.md
    ——
    pull
    /
    push
    /
    run-as
    /
    TestStorage
    。
  • Cross-set:
    ../../../instrumentation/runner/running-instrumented-tests-with-androidjunit4/SKILL.md
    ——runner 内部机制。
  • Cross-set:
    ../../../instrumentation/scenarios/launching-activities-with-activityscenario/SKILL.md
    ——使用 ActivityScenario 进行 instrumentation 测试。
  • Cross-set:
    ../../../fundamentals/strategies/applying-testing-strategies/SKILL.md
    ——何时值得投入 CI 编排,何时采用更简单的工具。