Skip to content

Most visited

Recently visited

navigation

UiDevice

public class UiDevice
extends Object

java.lang.Object
   ↳ android.support.test.uiautomator.UiDevice


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 clearLastTraversedText()

Clears the text from the last UI traversal event.

boolean click(int x, int y)

Perform a click at arbitrary coordinates 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.

void dumpWindowHierarchy(File dest)

Dump the current window hierarchy to a File.

void dumpWindowHierarchy(OutputStream out)

Dump the current window hierarchy to an OutputStream.

void dumpWindowHierarchy(String fileName)

This method is deprecated. Use dumpWindowHierarchy(File) or dumpWindowHierarchy(OutputStream) instead.

UiObject2 findObject(BySelector selector)

Returns the first object to match the selector criteria.

UiObject findObject(UiSelector selector)

Returns a UiObject which represents a view that matches the specified selector criteria.

List<UiObject2> findObjects(BySelector selector)

Returns all objects that match the selector criteria.

void freezeRotation()

Disables the sensors and freezes the device rotation at its current rotation state.

String getCurrentActivityName()

This method is deprecated. The results returned should be considered unreliable

String getCurrentPackageName()

Retrieves the name of the last package to report accessibility events.

int getDisplayHeight()

Gets the height of the display, in pixels.

int getDisplayRotation()

Returns the current rotation of the display, as defined in Surface

Point getDisplaySizeDp()

Returns the display size in dp (device-independent pixel) The returned display size is adjusted per screen rotation.

int getDisplayWidth()

Gets the width of the display, in pixels.

static UiDevice getInstance()

This method is deprecated. Should use getInstance(Instrumentation) instead. This version hides UiDevice's dependency on having an Instrumentation reference and is prone to misuse.

static UiDevice getInstance(Instrumentation instrumentation)

Retrieves a singleton instance of UiDevice

String getLastTraversedText()

Retrieves the text from the last UI traversal event received.

String getLauncherPackageName()

Retrieves default launcher package name

String getProductName()

Retrieves the product name of the device.

boolean hasAnyWatcherTriggered()

Checks if any registered UiWatcher have triggered.

boolean hasObject(BySelector selector)

Returns whether there is a match for the given selector criteria.

boolean hasWatcherTriggered(String watcherName)

Checks if a specific registered UiWatcher has triggered.

boolean isNaturalOrientation()

Check if the device is in its natural orientation.

boolean isScreenOn()

Checks the power manager if the screen is ON.

boolean openNotification()

Opens the notification shade.

boolean openQuickSettings()

Opens the Quick Settings shade.

<R> R performActionAndWait(Runnable action, EventCondition<R> condition, long timeout)

Performs the provided action and waits for the condition to be met.

boolean pressBack()

Simulates a short press on the BACK button.

boolean pressDPadCenter()

Simulates a short press on the CENTER button.

boolean pressDPadDown()

Simulates a short press on the DOWN button.

boolean pressDPadLeft()

Simulates a short press on the LEFT button.

boolean pressDPadRight()

Simulates a short press on the RIGHT button.

boolean pressDPadUp()

Simulates a short press on the UP button.

boolean pressDelete()

Simulates a short press on the DELETE key.

boolean pressEnter()

Simulates a short press on the ENTER key.

boolean pressHome()

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 pressMenu()

Simulates a short press on the MENU button.

boolean pressRecentApps()

Simulates a short press on the Recent Apps button.

boolean pressSearch()

Simulates a short press on the SEARCH button.

void registerWatcher(String name, UiWatcher watcher)

Registers a UiWatcher to run automatically when the testing framework is unable to find a match using a UiSelector.

void removeWatcher(String name)

Removes a previously registered UiWatcher.

void resetWatcherTriggers()

Resets a UiWatcher that has been triggered.

void runWatchers()

This method forces all registered watchers to run.

void setCompressedLayoutHeirarchy(boolean compressed)

Enables or disables layout hierarchy compression.

void setOrientationLeft()

Simulates orienting the device to the left and also freezes rotation by disabling the sensors.

void setOrientationNatural()

Simulates orienting the device into its natural orientation and also freezes rotation by disabling the sensors.

void setOrientationRight()

Simulates orienting the device to the right and also freezes rotation by disabling the sensors.

void sleep()

This method simply presses the power button if the screen is ON else it does nothing if the screen is already OFF.

boolean swipe(int startX, int startY, int endX, int endY, int steps)

Performs a swipe from one coordinate to another using the number of steps to determine smoothness and speed.

boolean swipe(Point[] segments, int segmentSteps)

Performs a swipe between points in the Point array.

boolean takeScreenshot(File storePath, float scale, int quality)

Take a screenshot of current window and store it as PNG The screenshot is adjusted per screen rotation

boolean takeScreenshot(File storePath)

Take a screenshot of current window and store it as PNG Default scale of 1.0f (original size) and 90% quality is used The screenshot is adjusted per screen rotation

void unfreezeRotation()

Re-enables the sensors and un-freezes the device rotation allowing its contents to rotate with the device physical rotation.

<R> R wait(SearchCondition<R> condition, long timeout)

Waits for given the condition to be met.

void waitForIdle(long timeout)

Waits for the current application to idle.

void waitForIdle()

Waits for the current application to idle.

boolean waitForWindowUpdate(String packageName, long timeout)

Waits for a window content update event to occur.

void wakeUp()

This method simulates pressing the power button if the screen is OFF else it does nothing if the screen is already ON.

Inherited methods

From class java.lang.Object

Public methods

clearLastTraversedText

void clearLastTraversedText ()

Clears the text from the last UI traversal event. See getLastTraversedText().

click

boolean click (int x, 
                int y)

Perform a click at arbitrary coordinates specified by the user

Parameters
x int: coordinate
y int: coordinate
Returns
boolean true if the click succeeded else false

drag

boolean drag (int startX, 
                int startY, 
                int endX, 
                int endY, 
                int steps)

Performs a swipe from one coordinate to another coordinate. 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
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

void dumpWindowHierarchy (File dest)

Dump the current window hierarchy to a File.

Parameters
dest File: The file in which to store the window hierarchy information.
Throws
IOException

dumpWindowHierarchy

void dumpWindowHierarchy (OutputStream out)

Dump the current window hierarchy to an OutputStream.

Parameters
out OutputStream: The output stream that the window hierarchy information is written to.
Throws
IOException

dumpWindowHierarchy

void dumpWindowHierarchy (String fileName)

This method is deprecated.
Use dumpWindowHierarchy(File) or dumpWindowHierarchy(OutputStream) instead.

Helper method used for debugging to dump the current window's layout hierarchy. Relative file paths are stored the application's internal private storage location.

findObject

UiObject2 findObject (BySelector selector)

Returns the first object to match the selector criteria.

Parameters
selector BySelector
Returns
UiObject2

findObject

UiObject findObject (UiSelector selector)

Returns a UiObject which represents a view that matches the specified selector criteria.

Returns
UiObject UiObject object

findObjects

List<UiObject2> findObjects (BySelector selector)

Returns all objects that match the selector criteria.

Parameters
selector BySelector
Returns
List<UiObject2>

freezeRotation

void freezeRotation ()

Disables the sensors and freezes the device rotation at its current rotation state.

Throws
RemoteException
RemoteException

getCurrentActivityName

String getCurrentActivityName ()

This method is deprecated.
The results returned should be considered unreliable

Retrieves the last activity to report accessibility events.

Returns
String String name of activity

getCurrentPackageName

String getCurrentPackageName ()

Retrieves the name of the last package to report accessibility events.

Returns
String String name of package

getDisplayHeight

int getDisplayHeight ()

Gets the height of the display, in pixels. The size is adjusted based on the current orientation of the display.

Returns
int height in pixels or zero on failure

getDisplayRotation

int getDisplayRotation ()

Returns the current rotation of the display, as defined in Surface

Returns
int

getDisplaySizeDp

Point getDisplaySizeDp ()

Returns the 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

getDisplayWidth

int getDisplayWidth ()

Gets the width of the display, in pixels. The width and height details are reported based on the current orientation of the display.

Returns
int width in pixels or zero on failure

getInstance

UiDevice getInstance ()

This method is deprecated.
Should use getInstance(Instrumentation) instead. This version hides UiDevice's dependency on having an Instrumentation reference and is prone to misuse.

Retrieves a singleton instance of UiDevice

Returns
UiDevice UiDevice instance

getInstance

UiDevice getInstance (Instrumentation instrumentation)

Retrieves a singleton instance of UiDevice

Parameters
instrumentation Instrumentation
Returns
UiDevice UiDevice instance

getLastTraversedText

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

String getLauncherPackageName ()

Retrieves default launcher package name

Returns
String package name of the default launcher

getProductName

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.

Returns
String product name of the device

hasAnyWatcherTriggered

boolean hasAnyWatcherTriggered ()

Checks if any registered UiWatcher have triggered. See registerWatcher(String, UiWatcher) See hasWatcherTriggered(String)

Returns
boolean

hasObject

boolean hasObject (BySelector selector)

Returns whether there is a match for the given selector criteria.

Parameters
selector BySelector
Returns
boolean

hasWatcherTriggered

boolean hasWatcherTriggered (String watcherName)

Checks if a specific registered UiWatcher has triggered. See registerWatcher(String, UiWatcher). 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

isNaturalOrientation

boolean isNaturalOrientation ()

Check if the device is in its natural orientation. This is determined by checking if the orientation is at 0 or 180 degrees.

Returns
boolean true if it is in natural orientation

isScreenOn

boolean isScreenOn ()

Checks the power manager if the screen is ON.

Returns
boolean true if the screen is ON else false
Throws
RemoteException
RemoteException

openNotification

boolean openNotification ()

Opens the notification shade.

Returns
boolean true if successful, else return false

openQuickSettings

boolean openQuickSettings ()

Opens the Quick Settings shade.

Returns
boolean true if successful, else return false

performActionAndWait

R performActionAndWait (Runnable action, 
                EventCondition<R> condition, 
                long timeout)

Performs the provided action and waits for the condition to be met.

Parameters
action Runnable: The Runnable action to perform.
condition EventCondition: The EventCondition to evaluate.
timeout long: Maximum amount of time to wait in milliseconds.
Returns
R The final result returned by the condition.

pressBack

boolean pressBack ()

Simulates a short press on the BACK button.

Returns
boolean true if successful, else return false

pressDPadCenter

boolean pressDPadCenter ()

Simulates a short press on the CENTER button.

Returns
boolean true if successful, else return false

pressDPadDown

boolean pressDPadDown ()

Simulates a short press on the DOWN button.

Returns
boolean true if successful, else return false

pressDPadLeft

boolean pressDPadLeft ()

Simulates a short press on the LEFT button.

Returns
boolean true if successful, else return false

pressDPadRight

boolean pressDPadRight ()

Simulates a short press on the RIGHT button.

Returns
boolean true if successful, else return false

pressDPadUp

boolean pressDPadUp ()

Simulates a short press on the UP button.

Returns
boolean true if successful, else return false

pressDelete

boolean pressDelete ()

Simulates a short press on the DELETE key.

Returns
boolean true if successful, else return false

pressEnter

boolean pressEnter ()

Simulates a short press on the ENTER key.

Returns
boolean true if successful, else return false

pressHome

boolean pressHome ()

Simulates a short press on the HOME button.

Returns
boolean true if successful, else return false

pressKeyCode

boolean pressKeyCode (int keyCode)

Simulates a short press using a key code. See KeyEvent

Parameters
keyCode int
Returns
boolean true if successful, else return false

pressKeyCode

boolean pressKeyCode (int keyCode, 
                int metaState)

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

pressMenu

boolean pressMenu ()

Simulates a short press on the MENU button.

Returns
boolean true if successful, else return false

pressRecentApps

boolean pressRecentApps ()

Simulates a short press on the Recent Apps button.

Returns
boolean true if successful, else return false
Throws
RemoteException
RemoteException

pressSearch

boolean pressSearch ()

Simulates a short press on the SEARCH button.

Returns
boolean true if successful, else return false

registerWatcher

void registerWatcher (String name, 
                UiWatcher watcher)

Registers a UiWatcher to run automatically when the testing framework is unable to find a match using a UiSelector. See runWatchers()

Parameters
name String: to register the UiWatcher
watcher UiWatcher: UiWatcher

removeWatcher

void removeWatcher (String name)

Removes a previously registered UiWatcher. See registerWatcher(String, UiWatcher)

Parameters
name String: used to register the UiWatcher

resetWatcherTriggers

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(String, UiWatcher)

runWatchers

void runWatchers ()

This method forces all registered watchers to run. See registerWatcher(String, UiWatcher)

setCompressedLayoutHeirarchy

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
compressed boolean: true to enable compression; else, false to disable

setOrientationLeft

void setOrientationLeft ()

Simulates orienting the device to the left and also freezes rotation by disabling the sensors. If you want to un-freeze the rotation and re-enable the sensors see unfreezeRotation().

Throws
RemoteException
RemoteException

setOrientationNatural

void setOrientationNatural ()

Simulates orienting the device into its natural orientation and also freezes rotation by disabling the sensors. If you want to un-freeze the rotation and re-enable the sensors see unfreezeRotation().

Throws
RemoteException
RemoteException

setOrientationRight

void setOrientationRight ()

Simulates orienting the device to the right and also freezes rotation by disabling the sensors. If you want to un-freeze the rotation and re-enable the sensors see unfreezeRotation().

Throws
RemoteException
RemoteException

sleep

void sleep ()

This method simply presses the power button if the screen is ON else it does nothing if the screen is already OFF.

Throws
RemoteException
RemoteException

swipe

boolean swipe (int startX, 
                int startY, 
                int endX, 
                int endY, 
                int steps)

Performs a swipe from one coordinate to another 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
steps int: is the number of move steps sent to the system
Returns
boolean false if the operation fails or the coordinates are invalid

swipe

boolean swipe (Point[] segments, 
                int segmentSteps)

Performs a swipe between points in the Point array. 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
segments Point: is Point array containing at least one Point object
segmentSteps int: steps to inject between two Points
Returns
boolean true on success

takeScreenshot

boolean takeScreenshot (File storePath, 
                float scale, 
                int quality)

Take a screenshot of current window 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

takeScreenshot

boolean takeScreenshot (File storePath)

Take a screenshot of current window 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

unfreezeRotation

void unfreezeRotation ()

Re-enables the sensors and un-freezes the device rotation allowing its contents to rotate with the device physical rotation. During a test execution, it is best to keep the device frozen in a specific orientation until the test case execution has completed.

Throws
RemoteException

wait

R wait (SearchCondition<R> condition, 
                long timeout)

Waits for given the condition to be met.

Parameters
condition SearchCondition: The SearchCondition to evaluate.
timeout long: Maximum amount of time to wait in milliseconds.
Returns
R The final result returned by the condition.

waitForIdle

void waitForIdle (long timeout)

Waits for the current application to idle.

Parameters
timeout long: in milliseconds

waitForIdle

void waitForIdle ()

Waits for the current application to idle. Default wait timeout is 10 seconds

waitForWindowUpdate

boolean waitForWindowUpdate (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
packageName String: the specified window package name (can be null). If null, a window update from any front-end window will end the wait
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

void wakeUp ()

This method simulates pressing the power button if the screen is OFF else it does nothing if the screen is already ON. If the screen was OFF and it just got turned ON, this method will insert a 500ms delay to allow the device time to wake up and accept input.

Throws
RemoteException
RemoteException
This site uses cookies to store your preferences for site-specific language and display options.

Hooray!

This class requires API level or higher

This doc is hidden because your selected API level for the documentation is . You can change the documentation API level with the selector above the left navigation.

For more information about specifying the API level your app requires, read Supporting Different Platform Versions.