UiDevice
class UiDevice : Searchable
UiDevice provides access to state information about the device. You can also use this class to simulate user actions on the device, such as pressing the d-pad or pressing the Home and Menu buttons.
Summary
Public functions |
|
|---|---|
Unit |
Clears the text from the last UI traversal event. |
Boolean |
Perform a click at arbitrary coordinates on the default display specified by the user. |
Boolean |
Performs a swipe from one coordinate to another coordinate on the default display. |
Unit |
dumpWindowHierarchy(dest: File)Dumps every window's layout hierarchy to a |
Unit |
This function is deprecated. Use |
Unit |
Dumps every window's layout hierarchy to an |
String |
@Discouraged(message = "Can be useful for simple commands, but lacks support for proper error"
+ " handling, input data, or complex commands (quotes, pipes) that can be obtained "
+ "from UiAutomation#executeShellCommandRwe or similar utilities.")Executes a shell command using shell user identity, and return the standard output in string. |
UiObject2! |
findObject(selector: BySelector)Returns the first object to match the |
UiObject |
findObject(selector: UiSelector)Returns a UiObject which represents a view that matches the specified selector criteria. |
(Mutable)List<UiObject2!> |
findObjects(selector: BySelector)Returns all objects that match the |
UiWindow? |
findWindow(selector: ByWindowSelector)Returns the first top-level window that matches the |
(Mutable)List<UiWindow!> |
findWindows(selector: ByWindowSelector)Returns all windows that match the |
Unit |
Freezes the default display rotation at its current state. |
Unit |
@RequiresApi(value = 30)Freezes the rotation of the display with |
String! |
This function is deprecated. The results returned should be considered unreliable |
String! |
Retrieves the name of the last package to report accessibility events. |
@Px Int |
Gets the height of the default display, in pixels. |
@Px Int |
getDisplayHeight(displayId: Int)Gets the height of the display with |
Int |
|
Int |
getDisplayRotation(displayId: Int) |
Point |
Returns the default display size in dp (device-independent pixel). |
@Px Int |
Gets the width of the default display, in pixels. |
@Px Int |
getDisplayWidth(displayId: Int)Gets the width of the display with |
java-static UiDevice |
This function is deprecated. Should use |
java-static UiDevice |
getInstance(instrumentation: Instrumentation)Retrieves a singleton instance of UiDevice. |
String! |
Retrieves the text from the last UI traversal event received. |
String! |
Retrieves the default launcher package name. |
String |
Retrieves the product name of the device. |
(Mutable)List<AccessibilityNodeInfo!> |
Returns a list containing the root |
Boolean |
Checks if any registered |
Boolean |
hasObject(selector: BySelector)Returns whether there is a match for the given |
Boolean |
hasWatcherTriggered(watcherName: String?)Checks if a specific registered |
Boolean |
hasWindow(selector: ByWindowSelector)Returns whether there is a window match for the given |
Boolean |
|
Boolean |
Checks the power manager if the default display is ON. |
Boolean |
Opens the notification shade. |
Boolean |
Opens the Quick Settings shade. |
U! |
<U> performActionAndWait(Performs the provided |
Boolean |
Simulates a short press on the BACK button. |
Boolean |
Simulates a short press on the CENTER button. |
Boolean |
Simulates a short press on the DOWN button. |
Boolean |
Simulates a short press on the LEFT button. |
Boolean |
Simulates a short press on the RIGHT button. |
Boolean |
Simulates a short press on the UP button. |
Boolean |
Simulates a short press on the DELETE key. |
Boolean |
Simulates a short press on the ENTER key. |
Boolean |
Simulates a short press on the HOME button. |
Boolean |
pressKeyCode(keyCode: Int)Simulates a short press using a key code. |
Boolean |
pressKeyCode(keyCode: Int, metaState: Int)Simulates a short press using a key code. |
Boolean |
pressKeyCodes(keyCodes: IntArray<Int>)Presses one or more keys. |
Boolean |
pressKeyCodes(keyCodes: IntArray<Int>, metaState: Int)Presses one or more keys. |
Boolean |
Simulates a short press on the MENU button. |
Boolean |
Simulates a short press on the Recent Apps button. |
Boolean |
Simulates a short press on the SEARCH button. |
Unit |
registerWatcher(name: String?, watcher: UiWatcher?)Registers a |
Unit |
removeWatcher(name: String?)Removes a previously registered |
Unit |
Resets a |
Unit |
This method forces all registered watchers to run. |
Unit |
This function is deprecated. Typo in function name, should use |
Unit |
setCompressedLayoutHierarchy(compressed: Boolean)Enables or disables layout hierarchy compression. |
Unit |
Orients the default display to its landscape orientation (width >= height) and freezes rotation. |
Unit |
@RequiresApi(value = 30)Orients the display with |
Unit |
Orients the default display to the left and freezes rotation. |
Unit |
@RequiresApi(value = 30)Orients the display with |
Unit |
Orients the default display to its natural orientation and freezes rotation. |
Unit |
@RequiresApi(value = 30)Orients the display with |
Unit |
Orients the default display to its portrait orientation (height >= width) and freezes rotation. |
Unit |
@RequiresApi(value = 30)Orients the display with |
Unit |
Orients the default display to the right and freezes rotation. |
Unit |
@RequiresApi(value = 30)Orients the display with |
Unit |
sleep()This method simply presses the power button if the default display is ON, else it does nothing if the default display is already OFF. |
Boolean |
Performs a swipe between points in the Point array on the default display. |
Boolean |
Performs a swipe from one coordinate to another on the default display using the number of steps to determine smoothness and speed. |
Bitmap? |
Take a screenshot of the default display. |
Boolean |
takeScreenshot(storePath: File)Take a screenshot of the default display and store it as PNG Default scale of 1.0f (original size) and 90% quality is used The screenshot is adjusted per screen rotation |
Boolean |
takeScreenshot(storePath: File, scale: Float, quality: Int)Take a screenshot of the default display and store it as PNG The screenshot is adjusted per screen rotation |
Unit |
Un-freezes the default display rotation allowing its contents to rotate with its physical rotation. |
Unit |
@RequiresApi(value = 30)Un-freezes the rotation of the display with |
U! |
Waits for given the |
U! |
<U> wait(condition: SearchCondition<U!>, timeout: Long)Waits for given the |
Unit |
Waits for the current application to idle. |
Unit |
waitForIdle(timeout: Long)Waits for the current application to idle. |
Boolean |
waitForWindowUpdate(packageName: String?, timeout: Long)Waits for a window content update event to occur. |
Unit |
wakeUp()This method simulates pressing the power button if the default display is OFF, else it does nothing if the default display is already ON. |
Extension functions |
|
|---|---|
AccessibilityWindowInfo |
Returns the active window. |
UiObject2 |
UiDevice.onElement(Performs a DFS on the accessibility tree starting from the root node in the active window and returns the first node matching the given |
UiObject2? |
UiDevice.onElementOrNull(Performs a DFS on the accessibility tree starting from the root node in the active window and returns the first node matching the given |
List<UiObject2> |
UiDevice.onElements(Performs a DFS on the accessibility tree starting from this node and returns all the nodes matching the given |
Unit |
UiDevice.pressDelete(count: Int)Similar to |
Unit |
Types the given |
Boolean |
UiDevice.waitForAppToBeVisible(appPackageName: String, timeoutMs: Long)Waits for an application to become visible. |
AccessibilityNodeInfo |
UiDevice.waitForRootInActiveWindow(Waits for the root node to become available in this window. |
StableResult |
UiDevice.waitForStableInActiveWindow(Waits for the root node of the active window to become stable. |
List<AccessibilityWindowInfo> |
Returns all the windows on all the displays. |
Public functions
clearLastTraversedText
fun clearLastTraversedText(): Unit
Clears the text from the last UI traversal event. See getLastTraversedText.
click
fun click(x: Int, y: Int): Boolean
Perform a click at arbitrary coordinates on the default display specified by the user.
| Returns | |
|---|---|
Boolean |
true if the click succeeded else false |
drag
fun drag(startX: Int, startY: Int, endX: Int, endY: Int, steps: Int): Boolean
Performs a swipe from one coordinate to another coordinate on the default display. You can control the smoothness and speed of the swipe by specifying the number of steps. Each step execution is throttled to the length of a frame per step (throttled by VSync).
| Parameters | |
|---|---|
startX: Int |
X-axis value for the starting coordinate |
startY: Int |
Y-axis value for the starting coordinate |
endX: Int |
X-axis value for the ending coordinate |
endY: Int |
Y-axis value for the ending coordinate |
steps: Int |
is the number of steps for the swipe action |
| Returns | |
|---|---|
Boolean |
true if swipe is performed, false if the operation fails or the coordinates are invalid |
dumpWindowHierarchy
fun dumpWindowHierarchy(dest: File): Unit
Dumps every window's layout hierarchy to a java.io.File in XML format.
| Parameters | |
|---|---|
dest: File |
The file in which to store the window hierarchy information. |
| Throws | |
|---|---|
java.io.IOException |
if an I/O error occurs |
fundumpWindowHierarchy(fileName: String): Unit
Dumps every window's layout hierarchy to a file in XML format.
| Parameters | |
|---|---|
fileName: String |
The file path in which to store the window hierarchy information. Relative file paths are stored the application's internal private storage location. |
dumpWindowHierarchy
fun dumpWindowHierarchy(out: OutputStream): Unit
Dumps every window's layout hierarchy to an java.io.OutputStream in XML format.
| Parameters | |
|---|---|
out: OutputStream |
The output stream that the window hierarchy information is written to. |
| Throws | |
|---|---|
java.io.IOException |
if an I/O error occurs |
executeShellCommand
@Discouraged(message = "Can be useful for simple commands, but lacks support for proper error" + " handling, input data, or complex commands (quotes, pipes) that can be obtained " + "from UiAutomation#executeShellCommandRwe or similar utilities.")
fun executeShellCommand(cmd: String): String
Executes a shell command using shell user identity, and return the standard output in string.
Calling function with large amount of output will have memory impacts, and the function call will block if the command executed is blocking.
| Parameters | |
|---|---|
cmd: String |
the command to run |
| Returns | |
|---|---|
String |
the standard output of the command |
| Throws | |
|---|---|
java.io.IOException |
if an I/O error occurs while reading output |
findObject
fun findObject(selector: BySelector): UiObject2!
Returns the first object to match the selector criteria, or null if no matching objects are found.
findObject
fun findObject(selector: UiSelector): UiObject
Returns a UiObject which represents a view that matches the specified selector criteria.
| Parameters | |
|---|---|
selector: UiSelector |
| Returns | |
|---|---|
UiObject |
UiObject object |
findObjects
fun findObjects(selector: BySelector): (Mutable)List<UiObject2!>
Returns all objects that match the selector criteria.
findWindow
fun findWindow(selector: ByWindowSelector): UiWindow?
Returns the first top-level window that matches the selector criteria, or null if no matching windows are found.
findWindows
fun findWindows(selector: ByWindowSelector): (Mutable)List<UiWindow!>
Returns all windows that match the selector criteria. For convenience the returned list is sorted in descending layer Z-order, ensuring the root of the topmost interactable window is reported first.
freezeRotation
fun freezeRotation(): Unit
Freezes the default display rotation at its current state.
| Throws | |
|---|---|
android.os.RemoteException |
never |
freezeRotation
@RequiresApi(value = 30)
fun freezeRotation(displayId: Int): Unit
Freezes the rotation of the display with displayId at its current state.
Note: Only works on Android API level 30 (R) or above, where multi-display is officially supported.
| Throws | |
|---|---|
java.lang.IllegalArgumentException |
when the display with |
| See also | |
|---|---|
getDisplayId |
fungetCurrentActivityName(): String!
Retrieves the last activity to report accessibility events.
| Returns | |
|---|---|
String! |
String name of activity |
getCurrentPackageName
fun getCurrentPackageName(): String!
Retrieves the name of the last package to report accessibility events.
| Returns | |
|---|---|
String! |
String name of package |
getDisplayHeight
fun getDisplayHeight(): @Px Int
Gets the height of the default display, in pixels. The size is adjusted based on the current orientation of the display.
getDisplayHeight
fun getDisplayHeight(displayId: Int): @Px Int
Gets the height of the display with displayId, in pixels. The size is adjusted based on the current orientation of the display.
| Parameters | |
|---|---|
displayId: Int |
the display ID. Use |
| Throws | |
|---|---|
java.lang.IllegalArgumentException |
when the display with |
getDisplayRotation
fun getDisplayRotation(): Int
| Returns | |
|---|---|
Int |
the current rotation of the default display |
| See also | |
|---|---|
getRotation |
getDisplayRotation
fun getDisplayRotation(displayId: Int): Int
| Returns | |
|---|---|
Int |
the current rotation of the display with |
| Throws | |
|---|---|
java.lang.IllegalArgumentException |
when the display with |
| See also | |
|---|---|
getDisplayId |
|
getRotation |
getDisplaySizeDp
fun getDisplaySizeDp(): Point
Returns the default display size in dp (device-independent pixel).
The returned display size is adjusted per screen rotation. Also this will return the actual size of the screen, rather than adjusted per system decorations (like status bar).
| Returns | |
|---|---|
Point |
a Point containing the display size in dp |
| See also | |
|---|---|
density |
getDisplayWidth
fun getDisplayWidth(): @Px Int
Gets the width of the default display, in pixels. The size is adjusted based on the current orientation of the display.
getDisplayWidth
fun getDisplayWidth(displayId: Int): @Px Int
Gets the width of the display with displayId, in pixels. The size is adjusted based on the current orientation of the display.
| Parameters | |
|---|---|
displayId: Int |
the display ID. Use |
| Throws | |
|---|---|
java.lang.IllegalArgumentException |
when the display with |
java-static fungetInstance(): UiDevice
Retrieves a singleton instance of UiDevice
| Returns | |
|---|---|
UiDevice |
UiDevice instance |
getInstance
java-static fun getInstance(instrumentation: Instrumentation): UiDevice
Retrieves a singleton instance of UiDevice. A new instance will be created if instrumentation is also new.
| Returns | |
|---|---|
UiDevice |
UiDevice instance |
getLastTraversedText
fun getLastTraversedText(): String!
Retrieves the text from the last UI traversal event received. You can use this method to read the contents in a WebView container because the accessibility framework fires events as each text is highlighted. You can write a test to perform directional arrow presses to focus on different elements inside a WebView, and call this method to get the text from each traversed element. If you are testing a view container that can return a reference to a Document Object Model (DOM) object, your test should use the view's DOM instead.
| Returns | |
|---|---|
String! |
text of the last traversal event, else return an empty string |
getLauncherPackageName
fun getLauncherPackageName(): String!
Retrieves the default launcher package name.
As of Android 11 (API level 30), apps must declare the packages and intents they intend to query. To use this method, an app will need to include the following in its manifest:
<queries> <intent> <action android:name="android.intent.action.MAIN"/> <category android:name="android.intent.category.HOME"/> </intent> </queries>
| Returns | |
|---|---|
String! |
package name of the default launcher |
getProductName
fun getProductName(): String
Retrieves the product name of the device. This method provides information on what type of device the test is running on. This value is the same as returned by invoking #adb shell getprop ro.product.name.
| Returns | |
|---|---|
String |
product name of the device |
getWindowRoots
fun getWindowRoots(): (Mutable)List<AccessibilityNodeInfo!>
Returns a list containing the root AccessibilityNodeInfos for each active window. For convenience the returned list is sorted in descending window order, ensuring the root of the topmost visible window is reported first.
hasAnyWatcherTriggered
fun hasAnyWatcherTriggered(): Boolean
Checks if any registered UiWatcher have triggered. See registerWatcher See hasWatcherTriggered
hasObject
fun hasObject(selector: BySelector): Boolean
Returns whether there is a match for the given selector criteria.
hasWatcherTriggered
fun hasWatcherTriggered(watcherName: String?): Boolean
Checks if a specific registered UiWatcher has triggered. See registerWatcher. If a UiWatcher runs and its checkForCondition call returned true, then the UiWatcher is considered triggered. This is helpful if a watcher is detecting errors from ANR or crash dialogs and the test needs to know if a UiWatcher has been triggered.
| Parameters | |
|---|---|
watcherName: String? |
| Returns | |
|---|---|
Boolean |
true if triggered else false |
hasWindow
fun hasWindow(selector: ByWindowSelector): Boolean
Returns whether there is a window match for the given selector criteria.
isNaturalOrientation
fun isNaturalOrientation(): Boolean
| Returns | |
|---|---|
Boolean |
true if default display is in its natural or flipped (180 degrees) orientation |
isScreenOn
fun isScreenOn(): Boolean
Checks the power manager if the default display is ON.
| Returns | |
|---|---|
Boolean |
true if the screen is ON else false |
| Throws | |
|---|---|
android.os.RemoteException |
openNotification
fun openNotification(): Boolean
Opens the notification shade.
| Returns | |
|---|---|
Boolean |
true if successful, else return false |
openQuickSettings
fun openQuickSettings(): Boolean
Opens the Quick Settings shade.
| Returns | |
|---|---|
Boolean |
true if successful, else return false |
performActionAndWait
fun <U> performActionAndWait(
action: Runnable,
condition: EventCondition<U!>,
timeout: Long
): U!
Performs the provided action and waits for the condition to be met.
| Parameters | |
|---|---|
action: Runnable |
The |
condition: EventCondition<U!> |
The |
timeout: Long |
Maximum amount of time to wait in milliseconds. |
| Returns | |
|---|---|
U! |
The final result returned by the condition. |
pressBack
fun pressBack(): Boolean
Simulates a short press on the BACK button.
| Returns | |
|---|---|
Boolean |
true if successful, else return false |
pressDPadCenter
fun pressDPadCenter(): Boolean
Simulates a short press on the CENTER button.
| Returns | |
|---|---|
Boolean |
true if successful, else return false |
pressDPadDown
fun pressDPadDown(): Boolean
Simulates a short press on the DOWN button.
| Returns | |
|---|---|
Boolean |
true if successful, else return false |
pressDPadLeft
fun pressDPadLeft(): Boolean
Simulates a short press on the LEFT button.
| Returns | |
|---|---|
Boolean |
true if successful, else return false |
pressDPadRight
fun pressDPadRight(): Boolean
Simulates a short press on the RIGHT button.
| Returns | |
|---|---|
Boolean |
true if successful, else return false |
pressDPadUp
fun pressDPadUp(): Boolean
Simulates a short press on the UP button.
| Returns | |
|---|---|
Boolean |
true if successful, else return false |
pressDelete
fun pressDelete(): Boolean
Simulates a short press on the DELETE key.
| Returns | |
|---|---|
Boolean |
true if successful, else return false |
pressEnter
fun pressEnter(): Boolean
Simulates a short press on the ENTER key.
| Returns | |
|---|---|
Boolean |
true if successful, else return false |
pressHome
fun pressHome(): Boolean
Simulates a short press on the HOME button.
| Returns | |
|---|---|
Boolean |
true if successful, else return false |
pressKeyCode
fun pressKeyCode(keyCode: Int): Boolean
Simulates a short press using a key code. See KeyEvent
| Returns | |
|---|---|
Boolean |
true if successful, else return false |
pressKeyCode
fun pressKeyCode(keyCode: Int, metaState: Int): Boolean
Simulates a short press using a key code. See KeyEvent.
| Parameters | |
|---|---|
keyCode: Int |
the key code of the event. |
metaState: Int |
an integer in which each bit set to 1 represents a pressed meta key |
| Returns | |
|---|---|
Boolean |
true if successful, else return false |
pressKeyCodes
fun pressKeyCodes(keyCodes: IntArray<Int>): Boolean
Presses one or more keys. Keys that change meta state are supported, and will apply their meta state to following keys. For example, you can simulate taking a screenshot on the device by pressing both the power and volume down keys.
pressKeyCodes(new int[]{KeyEvent.KEYCODE_POWER, KeyEvent.KEYCODE_VOLUME_DOWN})
| Returns | |
|---|---|
Boolean |
true if successful, else return false |
| See also | |
|---|---|
KeyEvent |
pressKeyCodes
fun pressKeyCodes(keyCodes: IntArray<Int>, metaState: Int): Boolean
Presses one or more keys. Keys that change meta state are supported, and will apply their meta state to following keys. For example, you can simulate taking a screenshot on the device by pressing both the power and volume down keys.
pressKeyCodes(new int[]{KeyEvent.KEYCODE_POWER, KeyEvent.KEYCODE_VOLUME_DOWN})
| Parameters | |
|---|---|
keyCodes: IntArray<Int> |
array of key codes. |
metaState: Int |
an integer in which each bit set to 1 represents a pressed meta key |
| Returns | |
|---|---|
Boolean |
true if successful, else return false |
| See also | |
|---|---|
KeyEvent |
pressMenu
fun pressMenu(): Boolean
Simulates a short press on the MENU button.
| Returns | |
|---|---|
Boolean |
true if successful, else return false |
pressRecentApps
fun pressRecentApps(): Boolean
Simulates a short press on the Recent Apps button.
| Returns | |
|---|---|
Boolean |
true if successful, else return false |
| Throws | |
|---|---|
android.os.RemoteException |
never |
pressSearch
fun pressSearch(): Boolean
Simulates a short press on the SEARCH button.
| Returns | |
|---|---|
Boolean |
true if successful, else return false |
registerWatcher
fun registerWatcher(name: String?, watcher: UiWatcher?): Unit
Registers a UiWatcher to run automatically when the testing framework is unable to find a match using a UiSelector. See runWatchers
removeWatcher
fun removeWatcher(name: String?): Unit
Removes a previously registered UiWatcher. See registerWatcher
| Parameters | |
|---|---|
name: String? |
used to register the UiWatcher |
resetWatcherTriggers
fun resetWatcherTriggers(): Unit
Resets a UiWatcher that has been triggered. If a UiWatcher runs and its checkForCondition call returned true, then the UiWatcher is considered triggered. See registerWatcher
runWatchers
fun runWatchers(): Unit
This method forces all registered watchers to run. See registerWatcher
funsetCompressedLayoutHeirarchy(compressed: Boolean): Unit
Enables or disables layout hierarchy compression. If compression is enabled, the layout hierarchy derived from the Acessibility framework will only contain nodes that are important for uiautomator testing. Any unnecessary surrounding layout nodes that make viewing and searching the hierarchy inefficient are removed.
| Parameters | |
|---|---|
compressed: Boolean |
true to enable compression; else, false to disable |
setCompressedLayoutHierarchy
fun setCompressedLayoutHierarchy(compressed: Boolean): Unit
Enables or disables layout hierarchy compression. If compression is enabled, the layout hierarchy derived from the Accessibility framework will only contain nodes that are important for uiautomator testing. Any unnecessary surrounding layout nodes that make viewing and searching the hierarchy inefficient are removed.
| Parameters | |
|---|---|
compressed: Boolean |
true to enable compression; else, false to disable |
setOrientationLandscape
fun setOrientationLandscape(): Unit
Orients the default display to its landscape orientation (width >= height) and freezes rotation. Use unfreezeRotation to un-freeze the rotation.
| Throws | |
|---|---|
android.os.RemoteException |
never |
setOrientationLandscape
@RequiresApi(value = 30)
fun setOrientationLandscape(displayId: Int): Unit
Orients the display with displayId to its landscape orientation (width >= height) and freezes rotation. Use unfreezeRotation to un-freeze the rotation.
Note: Only works on Android API level 30 (R) or above, where multi-display is officially supported.
| Throws | |
|---|---|
java.lang.IllegalArgumentException |
when the display with |
| See also | |
|---|---|
getDisplayId |
setOrientationLeft
fun setOrientationLeft(): Unit
Orients the default display to the left and freezes rotation. Use unfreezeRotation to un-freeze the rotation.
Note: This rotation is relative to the natural orientation which depends on the device type (e.g. phone vs. tablet). Consider using setOrientationPortrait and setOrientationLandscape.
| Throws | |
|---|---|
android.os.RemoteException |
never |
setOrientationLeft
@RequiresApi(value = 30)
fun setOrientationLeft(displayId: Int): Unit
Orients the display with displayId to the left and freezes rotation. Use unfreezeRotation to un-freeze the rotation.
Note: This rotation is relative to the natural orientation which depends on the device type (e.g. phone vs. tablet). Consider using setOrientationPortrait and setOrientationLandscape.
Note: Only works on Android API level 30 (R) or above, where multi-display is officially supported.
| Throws | |
|---|---|
java.lang.IllegalArgumentException |
when the display with |
| See also | |
|---|---|
getDisplayId |
setOrientationNatural
fun setOrientationNatural(): Unit
Orients the default display to its natural orientation and freezes rotation. Use unfreezeRotation to un-freeze the rotation.
Note: The natural orientation depends on the device type (e.g. phone vs. tablet). Consider using setOrientationPortrait and setOrientationLandscape.
| Throws | |
|---|---|
android.os.RemoteException |
never |
setOrientationNatural
@RequiresApi(value = 30)
fun setOrientationNatural(displayId: Int): Unit
Orients the display with displayId to its natural orientation and freezes rotation . Use unfreezeRotation to un-freeze the rotation.
Note: The natural orientation depends on the device type (e.g. phone vs. tablet). Consider using setOrientationPortrait and setOrientationLandscape.
Note: Only works on Android API level 30 (R) or above, where multi-display is officially supported.
| Throws | |
|---|---|
java.lang.IllegalArgumentException |
when the display with |
| See also | |
|---|---|
getDisplayId |
setOrientationPortrait
fun setOrientationPortrait(): Unit
Orients the default display to its portrait orientation (height >= width) and freezes rotation. Use unfreezeRotation to un-freeze the rotation.
| Throws | |
|---|---|
android.os.RemoteException |
never |
setOrientationPortrait
@RequiresApi(value = 30)
fun setOrientationPortrait(displayId: Int): Unit
Orients the display with displayId to its portrait orientation (height >= width) and freezes rotation. Use unfreezeRotation to un-freeze the rotation.
Note: Only works on Android API level 30 (R) or above, where multi-display is officially supported.
| Throws | |
|---|---|
java.lang.IllegalArgumentException |
when the display with |
| See also | |
|---|---|
getDisplayId |
setOrientationRight
fun setOrientationRight(): Unit
Orients the default display to the right and freezes rotation. Use unfreezeRotation to un-freeze the rotation.
Note: This rotation is relative to the natural orientation which depends on the device type (e.g. phone vs. tablet). Consider using setOrientationPortrait and setOrientationLandscape.
| Throws | |
|---|---|
android.os.RemoteException |
never |
setOrientationRight
@RequiresApi(value = 30)
fun setOrientationRight(displayId: Int): Unit
Orients the display with displayId to the right and freezes rotation. Use unfreezeRotation to un-freeze the rotation.
Note: This rotation is relative to the natural orientation which depends on the device type (e.g. phone vs. tablet). Consider using setOrientationPortrait and setOrientationLandscape.
Note: Only works on Android API level 30 (R) or above, where multi-display is officially supported.
| Throws | |
|---|---|
java.lang.IllegalArgumentException |
when the display with |
| See also | |
|---|---|
getDisplayId |
sleep
fun sleep(): Unit
This method simply presses the power button if the default display is ON, else it does nothing if the default display is already OFF.
| Throws | |
|---|---|
android.os.RemoteException |
swipe
fun swipe(segments: Array<Point!>, segmentSteps: Int): Boolean
Performs a swipe between points in the Point array on the default display. Each step execution is throttled to the length of a frame per step (throttled by VSync).
| Parameters | |
|---|---|
segments: Array<Point!> |
is Point array containing at least one Point object |
segmentSteps: Int |
steps to inject between two Points |
| Returns | |
|---|---|
Boolean |
true on success |
swipe
fun swipe(startX: Int, startY: Int, endX: Int, endY: Int, steps: Int): Boolean
Performs a swipe from one coordinate to another on the default display using the number of steps to determine smoothness and speed. Each step execution is throttled to the length of a frame per step (throttled by VSync).
| Parameters | |
|---|---|
startX: Int |
X-axis value for the starting coordinate |
startY: Int |
Y-axis value for the starting coordinate |
endX: Int |
X-axis value for the ending coordinate |
endY: Int |
Y-axis value for the ending coordinate |
steps: Int |
is the number of move steps sent to the system |
| Returns | |
|---|---|
Boolean |
false if the operation fails or the coordinates are invalid |
takeScreenshot
fun takeScreenshot(): Bitmap?
Take a screenshot of the default display.
The screenshot is adjusted per screen rotation.
| Returns | |
|---|---|
Bitmap? |
The screenshot bitmap on success, |
| See also | |
|---|---|
takeScreenshot |
takeScreenshot
fun takeScreenshot(storePath: File): Boolean
Take a screenshot of the default display and store it as PNG Default scale of 1.0f (original size) and 90% quality is used The screenshot is adjusted per screen rotation
| Parameters | |
|---|---|
storePath: File |
where the PNG should be written to |
| Returns | |
|---|---|
Boolean |
true if screen shot is created successfully, false otherwise |
takeScreenshot
fun takeScreenshot(storePath: File, scale: Float, quality: Int): Boolean
Take a screenshot of the default display and store it as PNG The screenshot is adjusted per screen rotation
| Parameters | |
|---|---|
storePath: File |
where the PNG should be written to |
scale: Float |
scale the screenshot down if needed; 1.0f for original size |
quality: Int |
quality of the PNG compression; range: 0-100 |
| Returns | |
|---|---|
Boolean |
true if screen shot is created successfully, false otherwise |
unfreezeRotation
fun unfreezeRotation(): Unit
Un-freezes the default display rotation allowing its contents to rotate with its physical rotation. During testing, it is best to keep the default display frozen in a specific orientation.
Note: Need to wait a short period for the rotation animation to complete before performing another operation.
| Throws | |
|---|---|
android.os.RemoteException |
never |
unfreezeRotation
@RequiresApi(value = 30)
fun unfreezeRotation(displayId: Int): Unit
Un-freezes the rotation of the display with displayId allowing its contents to rotate with its physical rotation. During testing, it is best to keep the display frozen in a specific orientation.
Note: Need to wait a short period for the rotation animation to complete before performing another operation.
Note: Some secondary displays don't have rotation sensors and therefore won't respond to this method.
Note: Only works on Android API level 30 (R) or above, where multi-display is officially supported.
| See also | |
|---|---|
getDisplayId |
wait
fun <U> wait(condition: Condition<UiDevice!, U!>, timeout: Long): U!
Waits for given the condition to be met.
| Parameters | |
|---|---|
condition: Condition<UiDevice!, U!> |
The |
timeout: Long |
Maximum amount of time to wait in milliseconds. |
| Returns | |
|---|---|
U! |
The final result returned by the |
wait
fun <U> wait(condition: SearchCondition<U!>, timeout: Long): U!
Waits for given the condition to be met.
| Parameters | |
|---|---|
condition: SearchCondition<U!> |
The |
timeout: Long |
Maximum amount of time to wait in milliseconds. |
| Returns | |
|---|---|
U! |
The final result returned by the |
waitForIdle
fun waitForIdle(): Unit
Waits for the current application to idle.
Note: Usage of this API in tests will result in non-deterministic tests. So this API should only be used as a last resort and only when there are no other alternatives available.
Default wait timeout is 10 seconds
waitForIdle
fun waitForIdle(timeout: Long): Unit
Waits for the current application to idle.
Note: Usage of this API in tests will result in non-deterministic tests. So this API should only be used as a last resort and only when there are no other alternatives available.
| Parameters | |
|---|---|
timeout: Long |
in milliseconds |
waitForWindowUpdate
fun waitForWindowUpdate(packageName: String?, timeout: Long): Boolean
Waits for a window content update event to occur. If a package name for the window is specified, but the current window does not have the same package name, the function returns immediately.
| Parameters | |
|---|---|
packageName: String? |
the specified window package name (can be |
timeout: Long |
the timeout for the wait |
| Returns | |
|---|---|
Boolean |
true if a window update occurred, false if timeout has elapsed or if the current window does not have the specified package name |
wakeUp
fun wakeUp(): Unit
This method simulates pressing the power button if the default display is OFF, else it does nothing if the default display is already ON.
If the default display was OFF and it just got turned ON, this method will insert a 500ms delay for the device to wake up and accept input.
| Throws | |
|---|---|
android.os.RemoteException |
Extension functions
UiDevice.activeWindow
fun UiDevice.activeWindow(): AccessibilityWindowInfo
Returns the active window.
UiDevice.onElement
fun UiDevice.onElement(
timeoutMs: Long = 10000,
pollIntervalMs: Long = 100,
block: AccessibilityNodeInfo.() -> Boolean
): UiObject2
Performs a DFS on the accessibility tree starting from the root node in the active window and returns the first node matching the given block. The node is returned as an UiObject2 that allows interacting with it. If the requested node doesn't exist, a ElementNotFoundException is thrown. Internally it works searching periodically every pollIntervalMs.
Example:
uiDevice.onElement { textAsString == "Search" }.click()
| Parameters | |
|---|---|
timeoutMs: Long = 10000 |
a timeout to find the element that satisfies the given condition. |
pollIntervalMs: Long = 100 |
an interval to wait before rechecking the accessibility tree for updates. |
block: AccessibilityNodeInfo.() -> Boolean |
a block that specifies a condition on the node to find. |
UiDevice.onElementOrNull
fun UiDevice.onElementOrNull(
timeoutMs: Long = 10000,
pollIntervalMs: Long = 100,
block: AccessibilityNodeInfo.() -> Boolean
): UiObject2?
Performs a DFS on the accessibility tree starting from the root node in the active window and returns the first node matching the given block. The node is returned as an UiObject2 that allows interacting with it. If the requested node doesn't exist, null is returned. Internally it works searching periodically every pollIntervalMs.
Example:
uiDevice.onElement { textAsString == "Search" }.click()
| Parameters | |
|---|---|
timeoutMs: Long = 10000 |
a timeout to find the element that satisfies the given condition. |
pollIntervalMs: Long = 100 |
an interval to wait before rechecking the accessibility tree for updates. |
block: AccessibilityNodeInfo.() -> Boolean |
a block that specifies a condition on the node to find. |
UiDevice.onElements
fun UiDevice.onElements(
timeoutMs: Long = 10000,
pollIntervalMs: Long = 100,
block: AccessibilityNodeInfo.() -> Boolean
): List<UiObject2>
Performs a DFS on the accessibility tree starting from this node and returns all the nodes matching the given block. This method stops waiting as soon as a single node with the given condition is returned. The nodes returned are UiObject2 that allow interacting with them. Internally it works searching periodically every pollIntervalMs.
Example:
node.onElements { className == Button::class.java.name }
If multiple nodes are expected but they appear at different times, it's recommended to call androidx.test.uiautomator.waitForStable before, to ensure any operation is complete.
| Parameters | |
|---|---|
timeoutMs: Long = 10000 |
a timeout to find the element that satisfies the given condition. |
pollIntervalMs: Long = 100 |
an interval to wait before rechecking the accessibility tree for updates. |
block: AccessibilityNodeInfo.() -> Boolean |
a block that specifies a condition on the node to find. |
UiDevice.pressDelete
fun UiDevice.pressDelete(count: Int): Unit
Similar to type but presses the delete key for the given count times.
| Parameters | |
|---|---|
count: Int |
how many times the press delete key should be pressed. |
UiDevice.type
fun UiDevice.type(text: String): Unit
Types the given text string simulating key press through Instrumentation.sendKeySync. This is similar to tapping the keys on a virtual keyboard and will trigger the same listeners in the target app, as opposed to AccessibilityNodeInfo.setText that programmatically sets the given text in the target node.
| Parameters | |
|---|---|
text: String |
the text to type. |
UiDevice.waitForAppToBeVisible
fun UiDevice.waitForAppToBeVisible(
appPackageName: String,
timeoutMs: Long = 10000
): Boolean
Waits for an application to become visible. Note that internally it checks if an accessibility node with the given appPackageName exists in the accessibility tree.
| Parameters | |
|---|---|
appPackageName: String |
the package name of the app to wait for. By default is the target app package name. |
timeoutMs: Long = 10000 |
a timeout for the app to become visible. |
| Returns | |
|---|---|
Boolean |
whether the app became visible in the given timeout. |
UiDevice.waitForRootInActiveWindow
fun UiDevice.waitForRootInActiveWindow(
timeoutMs: Long = 10000,
sleepIntervalMs: Long = 100,
clearCache: Boolean = true
): AccessibilityNodeInfo
Waits for the root node to become available in this window.
| Parameters | |
|---|---|
timeoutMs: Long = 10000 |
a timeout for the root node to become available. |
sleepIntervalMs: Long = 100 |
a interval to wait before retrying checking if the node is available. |
clearCache: Boolean = true |
whether the accessibility nodes cache should be cleared when checking. |
| Returns | |
|---|---|
AccessibilityNodeInfo |
the root node for this window. |
| Throws | |
|---|---|
IllegalStateException |
if the root node in the active window cannot be acquired before the give timeout |
UiDevice.waitForStableInActiveWindow
fun UiDevice.waitForStableInActiveWindow(
stableTimeoutMs: Long = 3000,
stableIntervalMs: Long = 500,
stablePollIntervalMs: Long = 50,
requireStableScreenshot: Boolean = true
): StableResult
Waits for the root node of the active window to become stable.
A node is considered stable when it and its descendants have not changed over an interval of time. Optionally also the node image can be checked. Internally it works checking periodically that the internal properties of the node have not changed.
Note: Usage of this API in tests will result in non-deterministic tests. So, this API should only be used as a last resort and only when there are no other alternatives available.
| Parameters | |
|---|---|
stableTimeoutMs: Long = 3000 |
a timeout for the wait operation, to ensure not waiting forever for stability. |
stableIntervalMs: Long = 500 |
the interval during which the node should not be changing, in order to be considered stable. |
stablePollIntervalMs: Long = 50 |
specifies how often the ui should be checked for changes. |
requireStableScreenshot: Boolean = true |
specifies if also the bitmap of the node should not change over the specified |
| Returns | |
|---|---|
StableResult |
a |
UiDevice.windows
fun UiDevice.windows(): List<AccessibilityWindowInfo>
Returns all the windows on all the displays.