cross-app-tests-with-uiautomator
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseCross-App Tests with UiAutomator — Drive System UI and Other Apps
使用 UiAutomator 进行跨应用测试——驱动系统 UI 和其他应用
UiAutomator is the only AndroidX test framework that can drive UI across process boundaries — Settings, the dialer, system notifications, another app's activity. Espresso refuses () when an event would cross to a foreign window. UiAutomator works against the platform tree, so it sees every window. This skill encodes the modern / API, the singleton acquisition, the recovery pattern, and the cross-app launch path.
InjectEventSecurityExceptionAccessibilityNodeInfoBySelectorUiObject2StaleObjectExceptionUiAutomator 是唯一能够跨进程边界驱动 UI 的 AndroidX 测试框架——包括 Settings、拨号器、系统通知和另一个应用的 activity。当事件需要跨到外部窗口时,Espresso 会拒绝执行()。UiAutomator 基于平台 树工作,因此能够看到所有窗口。本 skill 涵盖现代 / API、单例获取、 恢复模式以及跨应用启动路径。
InjectEventSecurityExceptionAccessibilityNodeInfoBySelectorUiObject2StaleObjectExceptionWhen to use this skill
何时使用此 skill
- The test must drive system UI (Settings, dialer, system notifications, quick settings, recents).
- The test spans the developer's app and another app (share sheet, contacts picker, camera).
- Espresso threw because the test reached a foreign window.
InjectEventSecurityException - The user reports and is debugging cached-node lifetime.
StaleObjectException - The user asks how to send the device home, press recents, or toggle airplane mode in a test.
- The user mixes and
BySelectorin the same test and is confused which is current.UiSelector
- 测试必须控制系统 UI(Settings、拨号器、系统通知、快速设置、最近任务)。
- 测试跨越被测应用与另一个应用(分享面板、联系人选择器、相机)。
- Espresso 抛出 ,因为测试进入了外部窗口。
InjectEventSecurityException - 用户报告 ,正在排查缓存节点的生命周期。
StaleObjectException - 用户询问如何在测试中将设备返回主屏幕、打开最近任务或切换飞行模式。
- 用户在同一个测试中混用 和
BySelector,不清楚哪个是当前推荐的 API。UiSelector
When NOT to use this skill
何时不应使用此 skill
- The UI is entirely inside the developer's app — Espresso (Views) or Compose tests are faster and more reliable. See for Views.
../../espresso/writing-espresso-tests/SKILL.md - The runner stack is not yet set up — start with .
../../runner/running-instrumented-tests-with-androidjunit4/SKILL.md - The user only needs to push device-side state changes (animations off, intent stub) — see .
../../../adb/control/injecting-input-and-state/SKILL.md - The test only needs to scrape logs after a run — see .
../../../adb/observability/extracting-logs-with-logcat/SKILL.md
- UI 完全位于被测应用内部——Espresso(Views)或 Compose 测试更快、更可靠。Views 请参阅 。
../../espresso/writing-espresso-tests/SKILL.md - 测试运行器栈尚未配置——请先参阅 。
../../runner/running-instrumented-tests-with-androidjunit4/SKILL.md - 用户只需要改变设备端状态(关闭动画、Intent stub)——请参阅 。
../../../adb/control/injecting-input-and-state/SKILL.md - 测试只需要在运行后抓取日志——请参阅 。
../../../adb/observability/extracting-logs-with-logcat/SKILL.md
Prerequisites
前置条件
- Runner stack from .
../../runner/running-instrumented-tests-with-androidjunit4/SKILL.md - .
androidTestImplementation("androidx.test.uiautomator:uiautomator:2.3.0") - A real or virtual Android device with the available (the default).
accessibility_service - For to a foreign package on API 30+, a
Context.startActivityentry in the test APK manifest naming the target package or intent action.<queries>
- 测试运行器栈,参见 。
../../runner/running-instrumented-tests-with-androidjunit4/SKILL.md - 。
androidTestImplementation("androidx.test.uiautomator:uiautomator:2.3.0") - 一台可用的真实或虚拟 Android 设备,并且 可用(默认提供)。
accessibility_service - 在 API 30+ 上,如果要通过 启动外部包,测试 APK 的 manifest 中必须包含一个
Context.startActivity条目,用于指定目标包或 intent action。<queries>
Workflow
工作流
- 1. Acquire once per test, via the singleton with explicit instrumentation. The no-arg
UiDeviceisgetInstance()(R4 lines 56-58) — it throws@Deprecatedif not previously initialized:IllegalStateException
kotlin
import androidx.test.platform.app.InstrumentationRegistry
import androidx.test.uiautomator.UiDevice
private lateinit var device: UiDevice
@Before fun setUp() {
device = UiDevice.getInstance(InstrumentationRegistry.getInstrumentation())
}- 2. Send hard keys and global actions via methods. Source: R4 lines 88-104.
UiDevice
kotlin
device.pressBack()
device.pressHome()
device.pressMenu()
device.pressRecentApps() // GLOBAL_ACTION_RECENTS
device.pressKeyCode(KeyEvent.KEYCODE_VOLUME_DOWN)
device.openNotification() // GLOBAL_ACTION_NOTIFICATIONS
device.openQuickSettings() // GLOBAL_ACTION_QUICK_SETTINGS
device.wakeUp() // power-on if off
device.sleep() // power-off if on- 3. Find UI elements with (modern) via the
BySelectorfactory. Selectors are immutable-ish builders; the package-private constructor enforces use of the static factories. Criteria are joined as implicit AND. Source: R4 lines 185-258.By
kotlin
import androidx.test.uiautomator.By
By.text("Submit") // exact, case-sensitive
By.textContains("ubmi") // case-sensitive substring
By.textMatches("Sub.*") // Pattern.compile regex
By.desc("Open menu") // content description
By.res("com.example.app", "submit_btn") // package + res id
By.res("com.example.app:id/submit_btn") // qualified res id
By.clazz("android.widget.Button") // fully-qualified, or ".widget.Button" auto-prefixed with "android"
By.clazz(android.widget.Button::class.java)
By.pkg("com.android.settings")
By.depth(2) // depth from window root
By.checkable(true)
By.hasChild(By.text("Inner")) // sugar for hasDescendant(child, 1)
By.hasDescendant(By.text("anywhere"))
By.hasParent(By.clazz("...LinearLayout"))
By.hasAncestor(By.res("...container"))- 4. Resolve to via
UiObject2and act.device.findObject(...)returnsfindObjectwhen no match (NEVER throws). For interactions, prefernullso the lookup is robust to slow renders:device.wait(Until.findObject(By...), timeoutMillis)
kotlin
import androidx.test.uiautomator.Until
val submit = device.wait(Until.findObject(By.res("com.example", "submit")), 5_000)
?: error("Submit not found within 5s")
submit.click()
submit.longClick()
submit.setText("hello")
submit.clear()
submit.swipe(Direction.LEFT, 0.8f) // percent ∈ [0,1]
submit.scroll(Direction.DOWN, 1.0f)
submit.scrollUntil(Direction.DOWN, Until.findObject(By.text("Bottom")))
submit.pinchOpen(0.5f)
submit.pinchClose(0.5f)UiObject2AccessibilityNodeInfogetAccessibilityNodeInfo()device.waitForIdle()mCachedNode.refresh()UiWatcherStaleObjectException- 5. Wait for asynchronous UI states with conditions. Three condition flavors per R4 lines 495-540:
Until
kotlin
// SearchCondition (consume the device tree)
device.wait(Until.hasObject(By.text("Loaded")), 5_000)
device.wait(Until.gone(By.text("Loading")), 5_000)
val obj: UiObject2? = device.wait(Until.findObject(By.text("OK")), 5_000)
val list: List<UiObject2>? = device.wait(Until.findObjects(By.clazz("...Button")), 3_000)
// UiObject2Condition (consume a UiObject2 — for state predicates)
val checked = button.wait(Until.checked(true), 5_000)
// EventCondition (consume AccessibilityEvents — for window transitions)
val newWindowFired = device.performActionAndWait(
{ button.click() }, Until.newWindow(), 10_000,
)- 6. Recover from by re-finding.
StaleObjectException— unchecked, must be handled when holding a long-livedStaleObjectException extends RuntimeException:UiObject2
kotlin
fun clickRetry(selector: BySelector, timeoutMillis: Long = 5_000) {
val obj = device.wait(Until.findObject(selector), timeoutMillis)
?: error("Not found: $selector")
try {
obj.click()
} catch (e: StaleObjectException) {
device.wait(Until.findObject(selector), timeoutMillis)?.click()
?: throw e
}
}Better: re-look-up before each interaction instead of holding a long-lived reference. Common causes: activity transition, Compose recomposition replacing semantic nodes, recycle, configuration change (R4 lines 639-645).
RecyclerView- 7. Launch foreign packages — prefer over
Context.startActivity.executeShellCommandisexecuteShellCommandper R4 lines 147-151 (@Discouraged); the Javadoc recommendsUiDevice.java:1432for stdin/stderr. For routine app launches, use the in-process intent route plus aUiAutomation.executeShellCommandRwemanifest entry on API 30+:<queries>
xml
<!-- src/androidTest/AndroidManifest.xml -->
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
<queries>
<package android:name="com.android.settings" />
<intent>
<action android:name="android.settings.SETTINGS" />
</intent>
</queries>
<!-- ... -->
</manifest>kotlin
val ctx = ApplicationProvider.getApplicationContext<Context>()
ctx.startActivity(
Intent(android.provider.Settings.ACTION_WIFI_SETTINGS)
.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TOP)
)
device.wait(Until.hasObject(By.pkg("com.android.settings").depth(0)), 10_000)If the user really needs the shell route (e.g. a deep-link no resolves):
Intentkotlin
device.executeShellCommand("am start -n com.android.settings/.Settings")
device.wait(Until.hasObject(By.pkg("com.android.settings")), 5_000)- 8. Tune global timeouts when needed; restore on teardown. Settings are process-wide. Defaults (R4 lines 550-558): wait-for-idle 10s, wait-for-selector 10s (legacy
Configuratoronly), action-acknowledgment 3s, scroll-event-wait 1s.UiObject
kotlin
import androidx.test.uiautomator.Configurator
@Before fun setUp() {
val c = Configurator.getInstance()
originalIdle = c.waitForIdleTimeout
c.waitForIdleTimeout = 5_000 // tighter for fast tests
}
@After fun tearDown() {
Configurator.getInstance().waitForIdleTimeout = originalIdle
}setKeyInjectionDelay@Deprecated-
9. Recognize when to fall back to legacy/
UiSelector.UiObjectre-resolves the node on every action viaUiSelector, so it cannot go stale, but every call is more expensive and uses the checkedConfigurator.getWaitForSelectorTimeout(). The modernUiObjectNotFoundException/BySelectoris the recommended default. Use legacy only for interop with old test code or when re-resolution semantics are mandatory. R4 lines 594-619.UiObject2 -
10. Never callimmediately after launch and assume it sees the target window.
findObject(By.text("..."))matches whatever is on screen now, which may be a transient splash or the previous app. Always combine withBy.textor wait explicitly:By.pkg(...)
kotlin
device.pressHome()
ctx.startActivity(Intent(Settings.ACTION_SETTINGS).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK))
device.wait(Until.hasObject(By.pkg("com.android.settings")), 5_000) // gate on package
device.wait(Until.findObject(By.text("Network & internet")), 5_000)?.click()- 1. 每个测试通过带显式 instrumentation 的单例获取一次 。 无参
UiDevice已被弃用(R4 第 56-58 行)——如果此前没有初始化单例,它会抛出getInstance():IllegalStateException
kotlin
import androidx.test.platform.app.InstrumentationRegistry
import androidx.test.uiautomator.UiDevice
private lateinit var device: UiDevice
@Before fun setUp() {
device = UiDevice.getInstance(InstrumentationRegistry.getInstrumentation())
}- 2. 通过 方法发送硬按键和执行全局操作。 来源:R4 第 88-104 行。
UiDevice
kotlin
device.pressBack()
device.pressHome()
device.pressMenu()
device.pressRecentApps() // GLOBAL_ACTION_RECENTS
device.pressKeyCode(KeyEvent.KEYCODE_VOLUME_DOWN)
device.openNotification() // GLOBAL_ACTION_NOTIFICATIONS
device.openQuickSettings() // GLOBAL_ACTION_QUICK_SETTINGS
device.wakeUp() // power-on if off
device.sleep() // power-off if on- 3. 使用 工厂通过
By(现代 API)查找 UI 元素。 选择器是近似不可变的构建器;包级私有构造函数强制使用静态工厂方法。各项条件通过隐式 AND 组合。来源:R4 第 185-258 行。BySelector
kotlin
import androidx.test.uiautomator.By
By.text("Submit") // exact, case-sensitive
By.textContains("ubmi") // case-sensitive substring
By.textMatches("Sub.*") // Pattern.compile regex
By.desc("Open menu") // content description
By.res("com.example.app", "submit_btn") // package + res id
By.res("com.example.app:id/submit_btn") // qualified res id
By.clazz("android.widget.Button") // fully-qualified, or ".widget.Button" auto-prefixed with "android"
By.clazz(android.widget.Button::class.java)
By.pkg("com.android.settings")
By.depth(2) // depth from window root
By.checkable(true)
By.hasChild(By.text("Inner")) // sugar for hasDescendant(child, 1)
By.hasDescendant(By.text("anywhere"))
By.hasParent(By.clazz("...LinearLayout"))
By.hasAncestor(By.res("...container"))- 4. 通过 解析为
device.findObject(...)并执行操作。UiObject2在没有匹配项时返回findObject(绝不会抛出异常)。进行交互时,优先使用null,让查找能够稳健应对渲染缓慢的情况:device.wait(Until.findObject(By...), timeoutMillis)
kotlin
import androidx.test.uiautomator.Until
val submit = device.wait(Until.findObject(By.res("com.example", "submit")), 5_000)
?: error("Submit not found within 5s")
submit.click()
submit.longClick()
submit.setText("hello")
submit.clear()
submit.swipe(Direction.LEFT, 0.8f) // percent ∈ [0,1]
submit.scroll(Direction.DOWN, 1.0f)
submit.scrollUntil(Direction.DOWN, Until.findObject(By.text("Bottom")))
submit.pinchOpen(0.5f)
submit.pinchClose(0.5f)UiObject2AccessibilityNodeInfogetAccessibilityNodeInfo()device.waitForIdle()mCachedNode.refresh()UiWatcherStaleObjectException- 5. 使用 条件等待异步 UI 状态。 根据 R4 第 495-540 行,条件分为三种:
Until
kotlin
// SearchCondition (consume the device tree)
device.wait(Until.hasObject(By.text("Loaded")), 5_000)
device.wait(Until.gone(By.text("Loading")), 5_000)
val obj: UiObject2? = device.wait(Until.findObject(By.text("OK")), 5_000)
val list: List<UiObject2>? = device.wait(Until.findObjects(By.clazz("...Button")), 3_000)
// UiObject2Condition (consume a UiObject2 — for state predicates)
val checked = button.wait(Until.checked(true), 5_000)
// EventCondition (consume AccessibilityEvents — for window transitions)
val newWindowFired = device.performActionAndWait(
{ button.click() }, Until.newWindow(), 10_000,
)- 6. 通过重新查找从 中恢复。
StaleObjectException——它是一个未检查异常,在长时间持有StaleObjectException extends RuntimeException时必须处理:UiObject2
kotlin
fun clickRetry(selector: BySelector, timeoutMillis: Long = 5_000) {
val obj = device.wait(Until.findObject(selector), timeoutMillis)
?: error("Not found: $selector")
try {
obj.click()
} catch (e: StaleObjectException) {
device.wait(Until.findObject(selector), timeoutMillis)?.click()
?: throw e
}
}更好的做法是:每次交互前重新查找,而不是长期持有引用。常见原因包括:activity 切换、Compose 重组替换语义节点、 回收、配置变更(R4 第 639-645 行)。
RecyclerView- 7. 启动外部包——优先使用 ,而不是
Context.startActivity。 根据 R4 第 147-151 行(executeShellCommand),UiDevice.java:1432已被标记为executeShellCommand;Javadoc 建议在需要 stdin/stderr 时改用@Discouraged。常规应用启动应使用进程内 intent 路径,并在 API 30+ 上配合UiAutomation.executeShellCommandRwemanifest 条目:<queries>
xml
<!-- src/androidTest/AndroidManifest.xml -->
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
<queries>
<package android:name="com.android.settings" />
<intent>
<action android:name="android.settings.SETTINGS" />
</intent>
</queries>
<!-- ... -->
</manifest>kotlin
val ctx = ApplicationProvider.getApplicationContext<Context>()
ctx.startActivity(
Intent(android.provider.Settings.ACTION_WIFI_SETTINGS)
.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TOP)
)
device.wait(Until.hasObject(By.pkg("com.android.settings").depth(0)), 10_000)如果用户确实需要 shell 路径(例如某个 deep link 没有可解析的 ):
Intentkotlin
device.executeShellCommand("am start -n com.android.settings/.Settings")
device.wait(Until.hasObject(By.pkg("com.android.settings")), 5_000)- 8. 必要时调整 全局超时,并在 teardown 时恢复。 这些设置作用于整个进程。默认值(R4 第 550-558 行):等待空闲 10 秒、等待选择器 10 秒(仅适用于旧版
Configurator)、操作确认 3 秒、滚动事件等待 1 秒。UiObject
kotlin
import androidx.test.uiautomator.Configurator
@Before fun setUp() {
val c = Configurator.getInstance()
originalIdle = c.waitForIdleTimeout
c.waitForIdleTimeout = 5_000 // tighter for fast tests
}
@After fun tearDown() {
Configurator.getInstance().waitForIdleTimeout = originalIdle
}setKeyInjectionDelay-
9. 识别何时应回退到旧版/
UiSelector。UiObject会在每次操作时通过UiSelector重新解析节点,因此不会变为 stale,但每次调用的开销更高,并且使用受检异常Configurator.getWaitForSelectorTimeout()。现代的UiObjectNotFoundException/BySelector是推荐默认方案。仅在需要与旧测试代码互操作,或必须使用重新解析语义时,才使用旧版 API。R4 第 594-619 行。UiObject2 -
10. 绝不要在启动后立即调用并假定它能看到目标窗口。
findObject(By.text("..."))会匹配当前屏幕上的任何内容,而此时屏幕上可能仍是瞬时启动页或上一个应用。始终结合By.text,或者显式等待:By.pkg(...)
kotlin
device.pressHome()
ctx.startActivity(Intent(Settings.ACTION_SETTINGS).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK))
device.wait(Until.hasObject(By.pkg("com.android.settings")), 5_000) // gate on package
device.wait(Until.findObject(By.text("Network & internet")), 5_000)?.click()Patterns
模式
Pattern: WRONG vs RIGHT — driving Settings without waiting on package transition
模式:错误与正确——驱动 Settings 时未等待包切换
kotlin
// WRONG
device.findObject(By.text("Settings")).click()
// WRONG because: at the moment of the call, By.text("Settings") matches whatever text reads
// "Settings" anywhere on the current screen — that might be a launcher tile, a notification,
// or a previous-app menu item. The test silently navigates to the wrong place.kotlin
// RIGHT
device.pressHome()
device.executeShellCommand("am start -a android.settings.SETTINGS")
device.wait(Until.hasObject(By.pkg("com.android.settings")), 5_000)
device.wait(Until.findObject(By.text("Network & internet")), 5_000)?.click()kotlin
// WRONG
device.findObject(By.text("Settings")).click()
// WRONG because: at the moment of the call, By.text("Settings") matches whatever text reads
// "Settings" anywhere on the current screen — that might be a launcher tile, a notification,
// or a previous-app menu item. The test silently navigates to the wrong place.kotlin
// RIGHT
device.pressHome()
device.executeShellCommand("am start -a android.settings.SETTINGS")
device.wait(Until.hasObject(By.pkg("com.android.settings")), 5_000)
device.wait(Until.findObject(By.text("Network & internet")), 5_000)?.click()Pattern: WRONG vs RIGHT — UiDevice.getInstance()
no-arg
UiDevice.getInstance()模式:错误与正确——UiDevice.getInstance()
无参用法
UiDevice.getInstance()kotlin
// WRONG
val device = UiDevice.getInstance()
// WRONG because: UiDevice.java:344 — the no-arg getInstance() is @Deprecated and throws
// IllegalStateException if the singleton has not been previously initialized with the
// instrumentation argument. Setting it implicitly via androidTest is unreliable across
// runner versions.kotlin
// RIGHT
val device = UiDevice.getInstance(InstrumentationRegistry.getInstrumentation())kotlin
// WRONG
val device = UiDevice.getInstance()
// WRONG because: UiDevice.java:344 — the no-arg getInstance() is @Deprecated and throws
// IllegalStateException if the singleton has not been previously initialized with the
// instrumentation argument. Setting it implicitly via androidTest is unreliable across
// runner versions.kotlin
// RIGHT
val device = UiDevice.getInstance(InstrumentationRegistry.getInstrumentation())Pattern: WRONG vs RIGHT — long-lived UiObject2
across a transition
UiObject2模式:错误与正确——在界面切换期间长期持有 UiObject2
UiObject2kotlin
// WRONG
val tile = device.wait(Until.findObject(By.descContains("Wi-Fi")), 5_000)
device.openQuickSettings()
tile.click() // throws StaleObjectException — quick settings replaced the layoutkotlin
// RIGHT — re-acquire after the transition
device.openQuickSettings()
val tile = device.wait(Until.findObject(By.descContains("Wi-Fi").clickable(true)), 5_000)
tile?.click()
device.pressBack()kotlin
// WRONG
val tile = device.wait(Until.findObject(By.descContains("Wi-Fi")), 5_000)
device.openQuickSettings()
tile.click() // throws StaleObjectException — quick settings replaced the layoutkotlin
// RIGHT — re-acquire after the transition
device.openQuickSettings()
val tile = device.wait(Until.findObject(By.descContains("Wi-Fi").clickable(true)), 5_000)
tile?.click()
device.pressBack()Pattern: dismissing all notifications
模式:关闭所有通知
kotlin
device.openNotification()
val shade = device.wait(
Until.findObject(By.res("com.android.systemui:id/notification_stack_scroller")),
5_000,
) ?: error("Notification shade not visible")
for (n in shade.findObjects(By.res("com.android.systemui:id/notification_layout"))) {
n.swipe(Direction.RIGHT, 1.0f)
}
device.pressBack()kotlin
device.openNotification()
val shade = device.wait(
Until.findObject(By.res("com.android.systemui:id/notification_stack_scroller")),
5_000,
) ?: error("Notification shade not visible")
for (n in shade.findObjects(By.res("com.android.systemui:id/notification_layout"))) {
n.swipe(Direction.RIGHT, 1.0f)
}
device.pressBack()Pattern: launching the app under test from a clean state
模式:从干净状态启动被测应用
kotlin
@Before fun launchAppFromHome() {
device.pressHome()
val ctx = ApplicationProvider.getApplicationContext<Context>()
val launch = ctx.packageManager.getLaunchIntentForPackage("com.example.app")!!
.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP)
ctx.startActivity(launch)
device.wait(Until.hasObject(By.pkg("com.example.app").depth(0)), 5_000)
}kotlin
@Before fun launchAppFromHome() {
device.pressHome()
val ctx = ApplicationProvider.getApplicationContext<Context>()
val launch = ctx.packageManager.getLaunchIntentForPackage("com.example.app")!!
.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP)
ctx.startActivity(launch)
device.wait(Until.hasObject(By.pkg("com.example.app").depth(0)), 5_000)
}Mandatory rules
强制规则
- MUST acquire via
UiDevice. The no-argUiDevice.getInstance(InstrumentationRegistry.getInstrumentation())isgetInstance()and unreliable.@Deprecated - MUST prefer /
BySelectoroverUiObject2/UiSelectorfor new tests. Legacy is for interop only.UiObject - MUST wait on a transition with before resolving inner elements after a cross-window change. Bare
device.wait(Until.hasObject(By.pkg("...")), timeout)runs against the current window without gating.findObject - MUST handle (re-find via
StaleObjectException) when keeping adevice.wait(Until.findObject(By...), timeout)reference across recompose, transition, or recyclerview recycle.UiObject2 - MUST restore settings in
Configuratorif a test mutated them. Settings are process-wide and leak across tests.@After - MUST NOT call —
Configurator.setKeyInjectionDelayand a no-op.@Deprecated - MUST NOT rely on for routine app launches — it is
executeShellCommand. Use@Discouragedplus aContext.startActivitymanifest entry on API 30+.<queries> - MUST NOT use without gating on package — text matches the current window contents, which may be a transient splash.
device.findObject(By.text("...")) - PREFERRED: wrap any single interaction in a rather than calling
device.wait(Until.findObject(...), timeout)?.click()thenfindObjecttwo lines apart. The two-step form races with rendering.click - PREFERRED: add for any foreign package the test launches — silent failures on API 30+ otherwise.
<queries>
- 必须通过 获取
UiDevice.getInstance(InstrumentationRegistry.getInstrumentation())。无参UiDevice已弃用且不可靠。getInstance() - 必须在新测试中优先使用 /
BySelector,而不是UiObject2/UiSelector。旧版 API 仅用于互操作。UiObject - 必须在跨窗口变更后解析内部元素之前,通过 等待界面切换。直接调用
device.wait(Until.hasObject(By.pkg("...")), timeout)会在当前窗口上执行,不会进行门控。findObject - 必须在跨重组、界面切换或 RecyclerView 回收后继续持有 引用时处理
UiObject2,通过StaleObjectException重新查找。device.wait(Until.findObject(By...), timeout) - 必须在测试修改了 设置时,于
Configurator中恢复原值。这些设置作用于整个进程,会泄漏到其他测试。@After - 不得调用 ——它已弃用且没有任何作用。
Configurator.setKeyInjectionDelay - 不得在常规应用启动中依赖 ——它已被标记为
executeShellCommand。应使用@Discouraged,并在 API 30+ 上配合Context.startActivitymanifest 条目。<queries> - 不得在没有包名门控的情况下使用 ——文本会匹配当前窗口内容,而该窗口可能仍是瞬时启动页。
device.findObject(By.text("...")) - **推荐:**将任何单次交互封装为 ,而不是先调用
device.wait(Until.findObject(...), timeout)?.click(),再隔两行调用findObject。两步写法会与渲染过程产生竞态。click - **推荐:**为测试启动的所有外部包添加 ——否则在 API 30+ 上可能会静默失败。
<queries>
Verification
验证
- No source file calls with no arguments.
UiDevice.getInstance() - No source file calls .
Configurator.setKeyInjectionDelay - Every long-lived reference has a
UiObject2around its action — or the test re-finds before each interaction.try { ... } catch (StaleObjectException) - Tests that launch foreign packages have a entry for that package or its intent action in
<queries>.src/androidTest/AndroidManifest.xml - runs without
./gradlew :<module>:connectedDebugAndroidTestfromIllegalStateExceptionand without unhandledUiDevice.getInstance()propagating to the test result.StaleObjectException - No is called immediately after a cross-window transition without a preceding
findObject(By.text(...)).device.wait(Until.hasObject(By.pkg(...)), ...) - If was mutated in
Configurator, an@Beforerestores the original values.@After
- 没有任何源文件调用无参 。
UiDevice.getInstance() - 没有任何源文件调用 。
Configurator.setKeyInjectionDelay - 每个长期持有的 引用,其操作都由
UiObject2包围——或者测试会在每次交互前重新查找。try { ... } catch (StaleObjectException) - 启动外部包的测试在 中包含目标包或其 intent action 对应的
src/androidTest/AndroidManifest.xml条目。<queries> - 运行 时,不会出现由
./gradlew :<module>:connectedDebugAndroidTest引起的UiDevice.getInstance(),也不会出现未处理的IllegalStateException传播到测试结果。StaleObjectException - 跨窗口切换后,如果没有事先执行 ,则不会调用
device.wait(Until.hasObject(By.pkg(...)), ...)。findObject(By.text(...)) - 如果测试在 中修改了
@Before,则会在Configurator中恢复原值。@After
References
参考资料
- Android Developers — UiAutomator overview: https://developer.android.com/training/testing/other-components/ui-automator
- AndroidX Test (UiAutomator) release notes: https://developer.android.com/jetpack/androidx/releases/test
- UiAutomator API reference: https://developer.android.com/reference/androidx/test/uiautomator/package-summary
- — the singleton entry point. Lines 344 (
androidx/test/uiautomator/UiDevice.javano-arg@Deprecated), 357 (currentgetInstance), 1432 (getInstance(Instrumentation)).@Discouraged executeShellCommand - — static factory for
androidx/test/uiautomator/By.java. Source forBySelector.text/desc/res/clazz/pkg/depth/checkable/hasChild/hasDescendant/hasParent/hasAncestor - (838 lines) — full criteria catalog. Lines 128 (auto-prefix
androidx/test/uiautomator/BySelector.javawith.widget.Button), 198/211/224 (regex / contains / starts-with conventions), 605-650 (android), 660 (maxDepth).displayId - (1152 lines) —
androidx/test/uiautomator/UiObject2.java,click,setText,swipe,scroll,scrollUntil,pinchOpen/Close. Line 1031 —flingthrowsgetAccessibilityNodeInfo()after refresh failure + watcher retry.StaleObjectException - lines 43-456 —
androidx/test/uiautomator/Until.java,hasObject,gone,findObject,findObjects,newWindow, plusscrollFinishedpredicates.UiObject2Condition - lines 36 (warning to restore), 108 (
androidx/test/uiautomator/Configurator.javalegacy-only), 163 (waitForSelectorlegacy-only), 189 (actionAcknowledgmentsetKeyInjectionDelay), 295 (@Deprecated).setDefaultDisplayId - —
androidx/test/uiautomator/StaleObjectException.java.extends RuntimeException - — full UiAutomator 2.3.0 deep-dive. Lines 56-58 (deprecated singleton), 185-258 (BySelector catalog), 268-369 (UiObject2 actions), 495-540 (
tasks/research/R4-uiautomator.mdconditions), 594-619 (modern vs legacy table), 622-662 (StaleObjectException recovery).Until - Section H.6 — UiAutomator essentials and the StaleObjectException recovery summary.
docs/CORPUS.md
- Android Developers — UiAutomator 概览:https://developer.android.com/training/testing/other-components/ui-automator
- AndroidX Test(UiAutomator)发行说明:https://developer.android.com/jetpack/androidx/releases/test
- UiAutomator API 参考:https://developer.android.com/reference/androidx/test/uiautomator/package-summary
- ——单例入口点。第 344 行(已弃用的无参
androidx/test/uiautomator/UiDevice.java)、第 357 行(当前的getInstance)、第 1432 行(getInstance(Instrumentation))。@Discouraged executeShellCommand - ——
androidx/test/uiautomator/By.java的静态工厂。BySelector的来源。text/desc/res/clazz/pkg/depth/checkable/hasChild/hasDescendant/hasParent/hasAncestor - (838 行)——完整条件目录。第 128 行(自动为
androidx/test/uiautomator/BySelector.java添加.widget.Button前缀)、第 198/211/224 行(regex / contains / starts-with 约定)、第 605-650 行(android)、第 660 行(maxDepth)。displayId - (1152 行)——
androidx/test/uiautomator/UiObject2.java、click、setText、swipe、scroll、scrollUntil、pinchOpen/Close。第 1031 行——fling在刷新失败并重试getAccessibilityNodeInfo()后抛出watcher。StaleObjectException - 第 43-456 行——
androidx/test/uiautomator/Until.java、hasObject、gone、findObject、findObjects、newWindow,以及scrollFinished谓词。UiObject2Condition - ——第 36 行(有关恢复设置的警告)、第 108 行(
androidx/test/uiautomator/Configurator.java,仅限旧版)、第 163 行(waitForSelector,仅限旧版)、第 189 行(actionAcknowledgment,setKeyInjectionDelay)、第 295 行(@Deprecated)。setDefaultDisplayId - ——
androidx/test/uiautomator/StaleObjectException.java。extends RuntimeException - ——UiAutomator 2.3.0 深度解析。第 56-58 行(已弃用的单例)、第 185-258 行(BySelector 目录)、第 268-369 行(UiObject2 操作)、第 495-540 行(
tasks/research/R4-uiautomator.md条件)、第 594-619 行(现代版与旧版对比表)、第 622-662 行(StaleObjectException 恢复)。Until - H.6 节——UiAutomator 基础知识和 StaleObjectException 恢复摘要。
docs/CORPUS.md