UiDevice
public class UiDevice implements 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 methods |
|
|---|---|
void |
Clears the text from the last UI traversal event. |
boolean |
click(int x, int y)Perform a click at arbitrary coordinates on the default display specified by the user. |
boolean |
drag(int startX, int startY, int endX, int endY, int steps)Performs a swipe from one coordinate to another coordinate on the default display. |
void |
dumpWindowHierarchy(@NonNull File dest)Dumps every window's layout hierarchy to a |
void |
This method is deprecated. Use |
void |
Dumps every window's layout hierarchy to an |
@NonNull 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(@NonNull BySelector selector)Returns the first object to match the |
@NonNull UiObject |
findObject(@NonNull UiSelector selector)Returns a UiObject which represents a view that matches the specified selector criteria. |
@NonNull List<UiObject2> |
findObjects(@NonNull BySelector selector)Returns all objects that match the |
@Nullable UiWindow |
findWindow(@NonNull ByWindowSelector selector)Returns the first top-level window that matches the |
@NonNull List<UiWindow> |
findWindows(@NonNull ByWindowSelector selector)Returns all windows that match the |
void |
Freezes the default display rotation at its current state. |
void |
@RequiresApi(value = 30)Freezes the rotation of the display with |
String |
This method 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(int displayId)Gets the height of the display with |
int |
|
int |
getDisplayRotation(int displayId) |
@NonNull 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(int displayId)Gets the width of the display with |
static @NonNull UiDevice |
This method is deprecated. Should use |
static @NonNull UiDevice |
getInstance(@NonNull 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. |
@NonNull String |
Retrieves the product name of the device. |
@NonNull List<AccessibilityNodeInfo> |
Returns a list containing the root |
boolean |
Checks if any registered |
boolean |
hasObject(@NonNull BySelector selector)Returns whether there is a match for the given |
boolean |
hasWatcherTriggered(@Nullable String watcherName)Checks if a specific registered |
boolean |
hasWindow(@NonNull ByWindowSelector selector)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(int keyCode)Simulates a short press using a key code. |
boolean |
pressKeyCode(int keyCode, int metaState)Simulates a short press using a key code. |
boolean |
pressKeyCodes(@NonNull int[] keyCodes)Presses one or more keys. |
boolean |
pressKeyCodes(@NonNull int[] keyCodes, int metaState)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. |
void |
registerWatcher(@Nullable String name, @Nullable UiWatcher watcher)Registers a |
void |
removeWatcher(@Nullable String name)Removes a previously registered |
void |
Resets a |
void |
This method forces all registered watchers to run. |
void |
This method is deprecated. Typo in function name, should use |
void |
setCompressedLayoutHierarchy(boolean compressed)Enables or disables layout hierarchy compression. |
void |
Orients the default display to its landscape orientation (width >= height) and freezes rotation. |
void |
@RequiresApi(value = 30)Orients the display with |
void |
Orients the default display to the left and freezes rotation. |
void |
@RequiresApi(value = 30)Orients the display with |
void |
Orients the default display to its natural orientation and freezes rotation. |
void |
@RequiresApi(value = 30)Orients the display with |
void |
Orients the default display to its portrait orientation (height >= width) and freezes rotation. |
void |
@RequiresApi(value = 30)Orients the display with |
void |
Orients the default display to the right and freezes rotation. |
void |
@RequiresApi(value = 30)Orients the display with |
void |
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 |
swipe(int startX, int startY, int endX, int endY, int steps)Performs a swipe from one coordinate to another on the default display using the number of steps to determine smoothness and speed. |
@Nullable Bitmap |
Take a screenshot of the default display. |
boolean |
takeScreenshot(@NonNull File storePath)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(@NonNull File storePath, float scale, int quality)Take a screenshot of the default display and store it as PNG The screenshot is adjusted per screen rotation |
void |
Un-freezes the default display rotation allowing its contents to rotate with its physical rotation. |
void |
@RequiresApi(value = 30)Un-freezes the rotation of the display with |
U |
Waits for given the |
U |
<U> wait(@NonNull SearchCondition<U> condition, long timeout)Waits for given the |
void |
Waits for the current application to idle. |
void |
waitForIdle(long timeout)Waits for the current application to idle. |
boolean |
waitForWindowUpdate(@Nullable String packageName, long timeout)Waits for a window content update event to occur. |
void |
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 |
|
|---|---|
final @NonNull AccessibilityWindowInfo |
UiDeviceExt.activeWindow(@NonNull UiDevice receiver)Returns the active window. |
final @NonNull UiObject2 |
UiDeviceExt.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 |
final UiObject2 |
UiDeviceExt.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 |
final @NonNull List<@NonNull UiObject2> |
UiDeviceExt.onElements(Performs a DFS on the accessibility tree starting from this node and returns all the nodes matching the given |
final void |
UiDeviceExt.pressDelete(@NonNull UiDevice receiver, int count)Similar to |
final void |
Types the given |
final boolean |
UiDeviceExt.waitForAppToBeVisible(Waits for an application to become visible. |
final @NonNull AccessibilityNodeInfo |
UiDeviceExt.waitForRootInActiveWindow(Waits for the root node to become available in this window. |
final @NonNull StableResult |
UiDeviceExt.waitForStableInActiveWindow(Waits for the root node of the active window to become stable. |
final @NonNull List<@NonNull AccessibilityWindowInfo> |
UiDeviceExt.windows(@NonNull UiDevice receiver)Returns all the windows on all the displays. |
Public methods
clearLastTraversedText
public void clearLastTraversedText()
Clears the text from the last UI traversal event. See getLastTraversedText.
click
public boolean click(int x, int y)
Perform a click at arbitrary coordinates on the default display specified by the user.
| Parameters | |
|---|---|
int x |
coordinate |
int y |
coordinate |
| Returns | |
|---|---|
boolean |
true if the click succeeded else false |
drag
public boolean drag(int startX, int startY, int endX, int endY, int steps)
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 5 milliseconds per step, so for a 100 steps, the swipe will take around 0.5 seconds to complete.
| Parameters | |
|---|---|
int startX |
X-axis value for the starting coordinate |
int startY |
Y-axis value for the starting coordinate |
int endX |
X-axis value for the ending coordinate |
int endY |
Y-axis value for the ending coordinate |
int steps |
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
public void dumpWindowHierarchy(@NonNull File dest)
Dumps every window's layout hierarchy to a java.io.File in XML format.
| Throws | |
|---|---|
java.io.IOException |
if an I/O error occurs |
public voiddumpWindowHierarchy(@NonNull String fileName)
Dumps every window's layout hierarchy to a file in XML format.
dumpWindowHierarchy
public void dumpWindowHierarchy(@NonNull OutputStream out)
Dumps every window's layout hierarchy to an java.io.OutputStream in XML format.
| Parameters | |
|---|---|
@NonNull OutputStream out |
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.")
public @NonNull String executeShellCommand(@NonNull String cmd)
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.
| Throws | |
|---|---|
java.io.IOException |
if an I/O error occurs while reading output |
findObject
public UiObject2 findObject(@NonNull BySelector selector)
Returns the first object to match the selector criteria, or null if no matching objects are found.
findObject
public @NonNull UiObject findObject(@NonNull UiSelector selector)
Returns a UiObject which represents a view that matches the specified selector criteria.
| Parameters | |
|---|---|
@NonNull UiSelector selector |
findObjects
public @NonNull List<UiObject2> findObjects(@NonNull BySelector selector)
Returns all objects that match the selector criteria.
findWindow
public @Nullable UiWindow findWindow(@NonNull ByWindowSelector selector)
Returns the first top-level window that matches the selector criteria, or null if no matching windows are found.
findWindows
public @NonNull List<UiWindow> findWindows(@NonNull ByWindowSelector selector)
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
public void freezeRotation()
Freezes the default display rotation at its current state.
| Throws | |
|---|---|
android.os.RemoteException |
never |
freezeRotation
@RequiresApi(value = 30)
public void freezeRotation(int displayId)
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 |
public StringgetCurrentActivityName()
Retrieves the last activity to report accessibility events.
| Returns | |
|---|---|
String |
String name of activity |
getCurrentPackageName
public String getCurrentPackageName()
Retrieves the name of the last package to report accessibility events.
| Returns | |
|---|---|
String |
String name of package |
getDisplayHeight
public @Px int getDisplayHeight()
Gets the height of the default display, in pixels. The size is adjusted based on the current orientation of the display.
| Returns | |
|---|---|
@Px int |
height in pixels |
getDisplayHeight
public @Px int getDisplayHeight(int displayId)
Gets the height of the display with displayId, in pixels. The size is adjusted based on the current orientation of the display.
| Parameters | |
|---|---|
int displayId |
the display ID. Use |
| Returns | |
|---|---|
@Px int |
height in pixels |
| Throws | |
|---|---|
java.lang.IllegalArgumentException |
when the display with |
getDisplayRotation
public int getDisplayRotation()
| Returns | |
|---|---|
int |
the current rotation of the default display |
| See also | |
|---|---|
getRotation |
getDisplayRotation
public int getDisplayRotation(int displayId)
| Returns | |
|---|---|
int |
the current rotation of the display with |
| Throws | |
|---|---|
java.lang.IllegalArgumentException |
when the display with |
| See also | |
|---|---|
getDisplayId |
|
getRotation |
getDisplaySizeDp
public @NonNull Point getDisplaySizeDp()
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).
| See also | |
|---|---|
density |
getDisplayWidth
public @Px int getDisplayWidth()
Gets the width of the default display, in pixels. The size is adjusted based on the current orientation of the display.
| Returns | |
|---|---|
@Px int |
width in pixels |
getDisplayWidth
public @Px int getDisplayWidth(int displayId)
Gets the width of the display with displayId, in pixels. The size is adjusted based on the current orientation of the display.
| Parameters | |
|---|---|
int displayId |
the display ID. Use |
| Returns | |
|---|---|
@Px int |
width in pixels |
| Throws | |
|---|---|
java.lang.IllegalArgumentException |
when the display with |
getInstance
public static @NonNull UiDevice getInstance(@NonNull Instrumentation instrumentation)
Retrieves a singleton instance of UiDevice. A new instance will be created if instrumentation is also new.
getLastTraversedText
public String getLastTraversedText()
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
public String getLauncherPackageName()
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
public @NonNull String getProductName()
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.
getWindowRoots
public @NonNull List<AccessibilityNodeInfo> getWindowRoots()
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
public boolean hasAnyWatcherTriggered()
Checks if any registered UiWatcher have triggered. See registerWatcher See hasWatcherTriggered
hasObject
public boolean hasObject(@NonNull BySelector selector)
Returns whether there is a match for the given selector criteria.
hasWatcherTriggered
public boolean hasWatcherTriggered(@Nullable String watcherName)
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.
| Returns | |
|---|---|
boolean |
true if triggered else false |
hasWindow
public boolean hasWindow(@NonNull ByWindowSelector selector)
Returns whether there is a window match for the given selector criteria.
isNaturalOrientation
public boolean isNaturalOrientation()
| Returns | |
|---|---|
boolean |
true if default display is in its natural or flipped (180 degrees) orientation |
isScreenOn
public boolean isScreenOn()
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
public boolean openNotification()
Opens the notification shade.
| Returns | |
|---|---|
boolean |
true if successful, else return false |
openQuickSettings
public boolean openQuickSettings()
Opens the Quick Settings shade.
| Returns | |
|---|---|
boolean |
true if successful, else return false |
performActionAndWait
public U <U> performActionAndWait(
@NonNull Runnable action,
@NonNull EventCondition<U> condition,
long timeout
)
Performs the provided action and waits for the condition to be met.
| Parameters | |
|---|---|
@NonNull Runnable action |
The |
@NonNull EventCondition<U> condition |
The |
long timeout |
Maximum amount of time to wait in milliseconds. |
| Returns | |
|---|---|
U |
The final result returned by the condition. |
pressBack
public boolean pressBack()
Simulates a short press on the BACK button.
| Returns | |
|---|---|
boolean |
true if successful, else return false |
pressDPadCenter
public boolean pressDPadCenter()
Simulates a short press on the CENTER button.
| Returns | |
|---|---|
boolean |
true if successful, else return false |
pressDPadDown
public boolean pressDPadDown()
Simulates a short press on the DOWN button.
| Returns | |
|---|---|
boolean |
true if successful, else return false |
pressDPadLeft
public boolean pressDPadLeft()
Simulates a short press on the LEFT button.
| Returns | |
|---|---|
boolean |
true if successful, else return false |
pressDPadRight
public boolean pressDPadRight()
Simulates a short press on the RIGHT button.
| Returns | |
|---|---|
boolean |
true if successful, else return false |
pressDPadUp
public boolean pressDPadUp()
Simulates a short press on the UP button.
| Returns | |
|---|---|
boolean |
true if successful, else return false |
pressDelete
public boolean pressDelete()
Simulates a short press on the DELETE key.
| Returns | |
|---|---|
boolean |
true if successful, else return false |
pressEnter
public boolean pressEnter()
Simulates a short press on the ENTER key.
| Returns | |
|---|---|
boolean |
true if successful, else return false |
pressHome
public boolean pressHome()
Simulates a short press on the HOME button.
| Returns | |
|---|---|
boolean |
true if successful, else return false |
pressKeyCode
public boolean pressKeyCode(int keyCode)
Simulates a short press using a key code. See KeyEvent
| Returns | |
|---|---|
boolean |
true if successful, else return false |
pressKeyCode
public boolean pressKeyCode(int keyCode, int metaState)
Simulates a short press using a key code. See KeyEvent.
| Parameters | |
|---|---|
int keyCode |
the key code of the event. |
int metaState |
an integer in which each bit set to 1 represents a pressed meta key |
| Returns | |
|---|---|
boolean |
true if successful, else return false |
pressKeyCodes
public boolean pressKeyCodes(@NonNull int[] keyCodes)
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 | |
|---|---|
@NonNull int[] keyCodes |
array of key codes. |
| Returns | |
|---|---|
boolean |
true if successful, else return false |
| See also | |
|---|---|
KeyEvent |
pressKeyCodes
public boolean pressKeyCodes(@NonNull int[] keyCodes, int metaState)
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 | |
|---|---|
@NonNull int[] keyCodes |
array of key codes. |
int metaState |
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
public boolean pressMenu()
Simulates a short press on the MENU button.
| Returns | |
|---|---|
boolean |
true if successful, else return false |
pressRecentApps
public boolean pressRecentApps()
Simulates a short press on the Recent Apps button.
| Returns | |
|---|---|
boolean |
true if successful, else return false |
| Throws | |
|---|---|
android.os.RemoteException |
never |
pressSearch
public boolean pressSearch()
Simulates a short press on the SEARCH button.
| Returns | |
|---|---|
boolean |
true if successful, else return false |
registerWatcher
public void registerWatcher(@Nullable String name, @Nullable UiWatcher watcher)
Registers a UiWatcher to run automatically when the testing framework is unable to find a match using a UiSelector. See runWatchers
removeWatcher
public void removeWatcher(@Nullable String name)
Removes a previously registered UiWatcher. See registerWatcher
resetWatcherTriggers
public void resetWatcherTriggers()
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
public void runWatchers()
This method forces all registered watchers to run. See registerWatcher
public void setCompressedLayoutHeirarchy(boolean compressed)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 | |
|---|---|
boolean compressed |
true to enable compression; else, false to disable |
setCompressedLayoutHierarchy
public void setCompressedLayoutHierarchy(boolean compressed)
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 | |
|---|---|
boolean compressed |
true to enable compression; else, false to disable |
setOrientationLandscape
public void setOrientationLandscape()
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)
public void setOrientationLandscape(int displayId)
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
public void setOrientationLeft()
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)
public void setOrientationLeft(int displayId)
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
public void setOrientationNatural()
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)
public void setOrientationNatural(int displayId)
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
public void setOrientationPortrait()
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)
public void setOrientationPortrait(int displayId)
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
public void setOrientationRight()
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)
public void setOrientationRight(int displayId)
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
public void 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.
| Throws | |
|---|---|
android.os.RemoteException |
swipe
public boolean swipe(@NonNull Point[] segments, int segmentSteps)
Performs a swipe between points in the Point array on the default display. Each step execution is throttled to 5ms per step. So for a 100 steps, the swipe will take about 1/2 second to complete.
| Parameters | |
|---|---|
@NonNull Point[] segments |
is Point array containing at least one Point object |
int segmentSteps |
steps to inject between two Points |
| Returns | |
|---|---|
boolean |
true on success |
swipe
public boolean swipe(int startX, int startY, int endX, int endY, int steps)
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 5ms per step. So for a 100 steps, the swipe will take about 1/2 second to complete.
| Parameters | |
|---|---|
int startX |
X-axis value for the starting coordinate |
int startY |
Y-axis value for the starting coordinate |
int endX |
X-axis value for the ending coordinate |
int endY |
Y-axis value for the ending coordinate |
int steps |
is the number of move steps sent to the system |
| Returns | |
|---|---|
boolean |
false if the operation fails or the coordinates are invalid |
takeScreenshot
public @Nullable Bitmap takeScreenshot()
Take a screenshot of the default display.
The screenshot is adjusted per screen rotation.
| See also | |
|---|---|
takeScreenshot |
takeScreenshot
public boolean takeScreenshot(@NonNull File storePath)
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
| Returns | |
|---|---|
boolean |
true if screen shot is created successfully, false otherwise |
takeScreenshot
public boolean takeScreenshot(@NonNull File storePath, float scale, int quality)
Take a screenshot of the default display and store it as PNG The screenshot is adjusted per screen rotation
| Parameters | |
|---|---|
@NonNull File storePath |
where the PNG should be written to |
float scale |
scale the screenshot down if needed; 1.0f for original size |
int quality |
quality of the PNG compression; range: 0-100 |
| Returns | |
|---|---|
boolean |
true if screen shot is created successfully, false otherwise |
unfreezeRotation
public void unfreezeRotation()
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)
public void unfreezeRotation(int displayId)
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
public U <U> wait(@NonNull Condition<UiDevice, U> condition, long timeout)
Waits for given the condition to be met.
| Parameters | |
|---|---|
@NonNull Condition<UiDevice, U> condition |
The |
long timeout |
Maximum amount of time to wait in milliseconds. |
| Returns | |
|---|---|
U |
The final result returned by the |
wait
public U <U> wait(@NonNull SearchCondition<U> condition, long timeout)
Waits for given the condition to be met.
| Parameters | |
|---|---|
@NonNull SearchCondition<U> condition |
The |
long timeout |
Maximum amount of time to wait in milliseconds. |
| Returns | |
|---|---|
U |
The final result returned by the |
waitForIdle
public void waitForIdle()
Waits for the current application to idle. Default wait timeout is 10 seconds
waitForIdle
public void waitForIdle(long timeout)
Waits for the current application to idle.
| Parameters | |
|---|---|
long timeout |
in milliseconds |
waitForWindowUpdate
public boolean waitForWindowUpdate(@Nullable String packageName, long timeout)
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 | |
|---|---|
@Nullable String packageName |
the specified window package name (can be |
long timeout |
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
public void 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.
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
UiDeviceExt.activeWindow
public final @NonNull AccessibilityWindowInfo UiDeviceExt.activeWindow(@NonNull UiDevice receiver)
Returns the active window.
UiDeviceExt.onElement
public final @NonNull UiObject2 UiDeviceExt.onElement(
@NonNull UiDevice receiver,
long timeoutMs,
long pollIntervalMs,
@NonNull Function1<@NonNull AccessibilityNodeInfo, @NonNull Boolean> block
)
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 | |
|---|---|
long timeoutMs |
a timeout to find the element that satisfies the given condition. |
long pollIntervalMs |
an interval to wait before rechecking the accessibility tree for updates. |
@NonNull Function1<@NonNull AccessibilityNodeInfo, @NonNull Boolean> block |
a block that specifies a condition on the node to find. |
UiDeviceExt.onElementOrNull
public final UiObject2 UiDeviceExt.onElementOrNull(
@NonNull UiDevice receiver,
long timeoutMs,
long pollIntervalMs,
@NonNull Function1<@NonNull AccessibilityNodeInfo, @NonNull Boolean> block
)
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 | |
|---|---|
long timeoutMs |
a timeout to find the element that satisfies the given condition. |
long pollIntervalMs |
an interval to wait before rechecking the accessibility tree for updates. |
@NonNull Function1<@NonNull AccessibilityNodeInfo, @NonNull Boolean> block |
a block that specifies a condition on the node to find. |
UiDeviceExt.onElements
public final @NonNull List<@NonNull UiObject2> UiDeviceExt.onElements(
@NonNull UiDevice receiver,
long timeoutMs,
long pollIntervalMs,
@NonNull Function1<@NonNull AccessibilityNodeInfo, @NonNull Boolean> block
)
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 | |
|---|---|
long timeoutMs |
a timeout to find the element that satisfies the given condition. |
long pollIntervalMs |
an interval to wait before rechecking the accessibility tree for updates. |
@NonNull Function1<@NonNull AccessibilityNodeInfo, @NonNull Boolean> block |
a block that specifies a condition on the node to find. |
UiDeviceExt.pressDelete
public final void UiDeviceExt.pressDelete(@NonNull UiDevice receiver, int count)
Similar to type but presses the delete key for the given count times.
| Parameters | |
|---|---|
int count |
how many times the press delete key should be pressed. |
UiDeviceExt.type
public final void UiDeviceExt.type(@NonNull UiDevice receiver, @NonNull String text)
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 programmaticaly sets the given text in the target node.
UiDeviceExt.waitForAppToBeVisible
public final boolean UiDeviceExt.waitForAppToBeVisible(
@NonNull UiDevice receiver,
@NonNull String appPackageName,
long timeoutMs
)
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 | |
|---|---|
@NonNull String appPackageName |
the package name of the app to wait for. By default is the target app package name. |
long timeoutMs |
a timeout for the app to become visible. |
| Returns | |
|---|---|
boolean |
whether the app became visible in the given timeout. |
UiDeviceExt.waitForRootInActiveWindow
public final @NonNull AccessibilityNodeInfo UiDeviceExt.waitForRootInActiveWindow(
@NonNull UiDevice receiver,
long timeoutMs,
long sleepIntervalMs,
boolean clearCache
)
Waits for the root node to become available in this window.
| Parameters | |
|---|---|
long timeoutMs |
a timeout for the root node to become available. |
long sleepIntervalMs |
a interval to wait before retrying checking if the node is available. |
boolean clearCache |
whether the accessibility nodes cache should be cleared when checking. |
| Returns | |
|---|---|
@NonNull AccessibilityNodeInfo |
the root node for this window. |
| Throws | |
|---|---|
kotlin.IllegalStateException |
if the root node in the active window cannot be acquired before the give timeout |
UiDeviceExt.waitForStableInActiveWindow
public final @NonNull StableResult UiDeviceExt.waitForStableInActiveWindow(
@NonNull UiDevice receiver,
long stableTimeoutMs,
long stableIntervalMs,
long stablePollIntervalMs,
boolean requireStableScreenshot
)
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.
| Parameters | |
|---|---|
long stableTimeoutMs |
a timeout for the wait operation, to ensure not waiting forever for stability. |
long stableIntervalMs |
the interval during which the node should not be changing, in order to be considered stable. |
long stablePollIntervalMs |
specifies how often the ui should be checked for changes. |
boolean requireStableScreenshot |
specifies if also the bitmap of the node should not change over the specified |
| Returns | |
|---|---|
@NonNull StableResult |
a |
UiDeviceExt.windows
public final @NonNull List<@NonNull AccessibilityWindowInfo> UiDeviceExt.windows(@NonNull UiDevice receiver)
Returns all the windows on all the displays.