Loading...
Loading...
Use this skill to drive cross-app and system-UI flows from instrumentation tests using UiAutomator 2.3.0 — `UiDevice`, `BySelector` / `UiObject2` (modern), `UiSelector` / `UiObject` (legacy), `Until` conditions, and `Configurator` global timeouts. Covers the singleton acquisition (`UiDevice.getInstance(InstrumentationRegistry.getInstrumentation())`), `pressBack/pressHome/pressRecentApps`, `device.findObject(By...)` cached-node refresh and `StaleObjectException` recovery, the `executeShellCommand` `@Discouraged` path vs `Context.startActivity` plus `<queries>`, and the full `By` factory catalog. Use when the user reports `StaleObjectException`, `Espresso InjectEventSecurityException`, `findObject returns null`, asks "how do I open Settings from a test", "toggle Wi-Fi", "dismiss notification shade", or "test that spans my app and another".
npx skill4agent add skydoves/android-testing-skills cross-app-tests-with-uiautomatorInjectEventSecurityExceptionAccessibilityNodeInfoBySelectorUiObject2StaleObjectExceptionInjectEventSecurityExceptionStaleObjectExceptionBySelectorUiSelector../../espresso/writing-espresso-tests/SKILL.md../../runner/running-instrumented-tests-with-androidjunit4/SKILL.md../../../adb/control/injecting-input-and-state/SKILL.md../../../adb/observability/extracting-logs-with-logcat/SKILL.md../../runner/running-instrumented-tests-with-androidjunit4/SKILL.mdandroidTestImplementation("androidx.test.uiautomator:uiautomator:2.3.0")accessibility_serviceContext.startActivity<queries>UiDevicegetInstance()@DeprecatedIllegalStateExceptionimport androidx.test.platform.app.InstrumentationRegistry
import androidx.test.uiautomator.UiDevice
private lateinit var device: UiDevice
@Before fun setUp() {
device = UiDevice.getInstance(InstrumentationRegistry.getInstrumentation())
}UiDevicedevice.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 onBySelectorByimport 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"))UiObject2device.findObject(...)findObjectnulldevice.wait(Until.findObject(By...), timeoutMillis)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()UiWatcherStaleObjectExceptionUntil// 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,
)StaleObjectExceptionStaleObjectException extends RuntimeExceptionUiObject2fun 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
}
}RecyclerViewContext.startActivityexecuteShellCommandexecuteShellCommand@DiscouragedUiDevice.java:1432UiAutomation.executeShellCommandRwe<queries><!-- 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>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)Intentdevice.executeShellCommand("am start -n com.android.settings/.Settings")
device.wait(Until.hasObject(By.pkg("com.android.settings")), 5_000)ConfiguratorUiObjectimport 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@DeprecatedUiSelectorUiObjectUiSelectorConfigurator.getWaitForSelectorTimeout()UiObjectNotFoundExceptionBySelectorUiObject2findObject(By.text("..."))By.textBy.pkg(...)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()// 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.// 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()UiDevice.getInstance()// 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.// RIGHT
val device = UiDevice.getInstance(InstrumentationRegistry.getInstrumentation())UiObject2// WRONG
val tile = device.wait(Until.findObject(By.descContains("Wi-Fi")), 5_000)
device.openQuickSettings()
tile.click() // throws StaleObjectException — quick settings replaced the layout// 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()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()@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)
}UiDeviceUiDevice.getInstance(InstrumentationRegistry.getInstrumentation())getInstance()@DeprecatedBySelectorUiObject2UiSelectorUiObjectdevice.wait(Until.hasObject(By.pkg("...")), timeout)findObjectStaleObjectExceptiondevice.wait(Until.findObject(By...), timeout)UiObject2Configurator@AfterConfigurator.setKeyInjectionDelay@DeprecatedexecuteShellCommand@DiscouragedContext.startActivity<queries>device.findObject(By.text("..."))device.wait(Until.findObject(...), timeout)?.click()findObjectclick<queries>UiDevice.getInstance()Configurator.setKeyInjectionDelayUiObject2try { ... } catch (StaleObjectException)<queries>src/androidTest/AndroidManifest.xml./gradlew :<module>:connectedDebugAndroidTestIllegalStateExceptionUiDevice.getInstance()StaleObjectExceptionfindObject(By.text(...))device.wait(Until.hasObject(By.pkg(...)), ...)Configurator@Before@Afterandroidx/test/uiautomator/UiDevice.java@DeprecatedgetInstancegetInstance(Instrumentation)@Discouraged executeShellCommandandroidx/test/uiautomator/By.javaBySelectortext/desc/res/clazz/pkg/depth/checkable/hasChild/hasDescendant/hasParent/hasAncestorandroidx/test/uiautomator/BySelector.java.widget.ButtonandroidmaxDepthdisplayIdandroidx/test/uiautomator/UiObject2.javaclicksetTextswipescrollscrollUntilpinchOpen/CloseflinggetAccessibilityNodeInfo()StaleObjectExceptionandroidx/test/uiautomator/Until.javahasObjectgonefindObjectfindObjectsnewWindowscrollFinishedUiObject2Conditionandroidx/test/uiautomator/Configurator.javawaitForSelectoractionAcknowledgmentsetKeyInjectionDelay@DeprecatedsetDefaultDisplayIdandroidx/test/uiautomator/StaleObjectException.javaextends RuntimeExceptiontasks/research/R4-uiautomator.mdUntildocs/CORPUS.md