API

class uiautomator2.Device(host='127.0.0.1', port=7912)[source]
adb_shell(*args)[source]
Example:
adb_shell(‘pwd’) adb_shell(‘ls’, ‘-l’) adb_shell(‘ls -l’)
Returns:
string for stdout merged with stderr, after the entire shell command is completed.
app_clear(pkg_name)[source]

Stop and clear app data: pm clear

app_current()[source]
Returns:
dict(package, activity, pid?)
Raises:
EnvironementError
For developer:
Function reset_uiautomator need this function, so can’t use jsonrpc here.
app_icon(package_name: str)[source]
Returns:
PIL.Image
Raises:
UiaError
app_info(pkg_name)[source]

Get app info

Args:
pkg_name (str): package name
Return example:
{
“mainActivity”: “com.github.uiautomator.MainActivity”, “label”: “ATX”, “versionName”: “1.1.7”, “versionCode”: 1001007, “size”:1760809

}

Raises:
UiaError
app_install(url, installing_callback=None, server=None)[source]

{u’message’: u’downloading’, “progress”: {u’totalSize’: 407992690, u’copiedSize’: 49152}}

Returns:
packageName
Raises:
RuntimeError
app_list(filter: str = None) → list[source]
Args:
filter: [-f] [-d] [-e] [-s] [-3] [-i] [-u] [–user USER_ID] [FILTER]
Returns:
list of apps by filter
app_list_running() → list[source]
Returns:
list of running apps
app_start(package_name, activity=None, extras={}, wait=False, stop=False, unlock=False, launch_timeout=None, use_monkey=False)[source]

Launch application Args:

package_name (str): package name activity (str): app activity stop (bool): Stop app before starting the activity. (require activity) use_monkey (bool): use monkey command to start app when activity is not given wait (bool): wait until app started. default False
Raises:
SessionBrokenError
app_stop(pkg_name)[source]

Stop one application: am force-stop

app_stop_all(excludes=[])[source]

Stop all third party applications Args:

excludes (list): apps that do now want to kill
Returns:
a list of killed apps
app_uninstall(pkg_name) → bool[source]

Uninstall an app

Returns:
bool: success
app_uninstall_all(excludes=[], verbose=False)[source]

Uninstall all apps

app_wait(package_name: str, timeout: float = 20.0, front=False) → int[source]

Wait until app launched Args:

package_name (str): package name timeout (float): maxium wait time front (bool): wait until app is current app
Returns:
pid (int) 0 if launch failed
disable_popups(enable=True)[source]

Automatic click all popups TODO: need fix

healthcheck()[source]

Reset device into health state

Raises:
RuntimeError
hooks_apply(stage, func_name, args=(), kwargs={}, ret=None)[source]
Args:
stage(str): one of “before” or “after”
hooks_register(func)[source]
Args:
func: should accept 3 args. func_name:string, args:tuple, kwargs:dict
jsonrpc

Make jsonrpc call easier For example:

self.jsonrpc.pressKey(“home”)
jsonrpc_call(method, params=[], http_timeout=60)[source]

jsonrpc2 call Refs:

open_identify(theme='black')[source]
Args:
theme (str): black or red
pull(src: str, dst: str)[source]

Pull file from device to local

Raises:
FileNotFoundError(py3) OSError(py2)

Require atx-agent >= 0.0.9

pull_content(src: str) → bytes[source]

Read remote file content

Raises:
FileNotFoundError
push(src, dst, mode=420)[source]
Args:
src (path or fileobj): source file dst (str): destination can be folder or file path
Returns:

dict object, for example:

{“mode”: “0660”, “size”: 63, “target”: “/sdcard/ABOUT.rst”}

Since chmod may fail in android, the result “mode” may not same with input args(mode)

Raises:
IOError(if push got something wrong)
push_url(url, dst, mode=420)[source]
Args:
url (str): http url address dst (str): destination mode (str): file mode
Raises:
FileNotFoundError(py3) OSError(py2)
request_agent(relative_url: str, method='get', timeout=60.0)[source]

send http-request to atx-agent

reset_uiautomator(reason='unknown')[source]

Reset uiautomator

Raises:
RuntimeError
Orders:
  • stop uiautomator keeper
  • am force-stop com.github.uiautomator
  • start uiautomator keeper(am instrument -w …)
  • wait until uiautomator service is ready
screenshot(*args, **kwargs)[source]

Take screenshot of device

Returns:
PIL.Image
service(name)[source]

Manage service start or stop

Example:
d.service(“uiautomator”).start() d.service(“uiautomator”).stop()
session(pkg_name=None, attach=False, launch_timeout=None, strict=False)[source]

Create a new session

Args:

pkg_name (str): android package name attach (bool): attach to already running app launch_timeout (int): launch timeout strict (bool): used along with attach,

when attach and strict both true, SessionBrokenError will raise if app not running
Raises:
requests.HTTPError, SessionBrokenError
set_new_command_timeout(timeout: int)[source]

default 3 minutes Args:

timeout (int): seconds
setup_jsonrpc(jsonrpc_url=None)[source]

Wrap jsonrpc call into object Usage example:

self.setup_jsonrpc().pressKey(“home”)
shell(cmdargs, stream=False, timeout=60)[source]

Run adb shell command with arguments and return its output. Require atx-agent >=0.3.3

Args:
cmdargs: str or list, example: “ls -l” or [“ls”, “-l”] timeout: seconds of command run, works on when stream is False stream: bool used for long running process.
Returns:
(output, exit_code) when stream is False requests.Response when stream is True, you have to close it after using
Raises:
RuntimeError

For atx-agent is not support return exit code now. When command got something wrong, exit_code is always 1, otherwise exit_code is always 0

unlock()[source]

unlock screen

wait_activity(activity, timeout=10)[source]

wait activity Args:

activity (str): name of activity timeout (float): max wait time
Returns:
bool of activity
window_size()[source]

return (width, height)

class uiautomator2.Session(server, pkg_name=None, pid=None)[source]
clear_text()[source]

clear text Raises:

EnvironmentError
clear_traversed_text()[source]

clear the last traversed text.

click(x, y)[source]

click position

close()[source]

close app

current_ime()[source]

Current input method Returns:

(method_id(str), shown(bool)
Example output:
(“com.github.uiautomator/.FastInputIME”, True)
double_click(x, y, duration=0.1)[source]

double click position

drag(sx, sy, ex, ey, duration=0.5)[source]

Swipe from one point to another point.

dump_hierarchy(compressed=False, pretty=False) → str[source]
Args:
shell (bool): use “adb shell uiautomator dump” to get hierarchy pretty (bool): format xml
Same as
content = self.jsonrpc.dumpWindowHierarchy(compressed, None)

But through GET /dump/hierarchy will be more robust when dumpHierarchy fails, the atx-agent will restart uiautomator again, then retry

v-1.3.4 change back to jsonrpc.dumpWindowHierarchy

freeze_rotation(freeze=True)[source]

freeze or unfreeze the device rotation in current status.

implicitly_wait(seconds=None)[source]

set default wait timeout Args:

seconds(float): to wait element show up
Deprecated:
recommend use: d.settings[‘wait_timeout’] = 10
last_traversed_text

get last traversed text. used in webview for highlighted text.

long_click(x, y, duration=None)[source]

long click at arbitrary coordinates. Args:

duration (float): seconds of pressed
make_toast(text, duration=1.0)[source]

Show toast Args:

text (str): text to show duration (float): seconds of display
orientation

orienting the devie to left/right or natural. left/l: rotation=90 , displayRotation=1 right/r: rotation=270, displayRotation=3 natural/n: rotation=0 , displayRotation=0 upsidedown/u: rotation=180, displayRotation=2

press(key, meta=None)[source]
press key via name or key code. Supported key name includes:
home, back, left, right, up, down, center, menu, search, enter, delete(or del), recent(recent apps), volume_up, volume_down, volume_mute, camera, power.
restart(use_monkey=False)[source]

Stop app and start

Raises:
RuntimeError
running()[source]

Check is session is running. return bool

screenshot(filename=None, format='pillow')[source]

Image format is JPEG

Args:
filename (str): saved filename format (string): used when filename is empty. one of “pillow” or “opencv”
Raises:
IOError, SyntaxError
Examples:
screenshot(“saved.jpg”) screenshot().save(“saved.png”) cv2.imwrite(‘saved.jpg’, screenshot(format=’opencv’))
send_action(code)[source]

Simulate input method edito code

Args:
code (str or int): input method editor code
Examples:
send_action(“search”), send_action(3)
Refs:
https://developer.android.com/reference/android/view/inputmethod/EditorInfo
send_keys(text: str, clear: bool = False)[source]
Args:
text (str): text to set clear (bool): clear before set text
Raises:
EnvironmentError
set_clipboard(text, label=None)[source]
Args:
text: The actual text in the clip. label: User-visible label for the clip data.
set_fastinput_ime(enable=True)[source]

Enable of Disable FastInputIME

set_orientation(value)[source]

setter of orientation property.

swipe(fx, fy, tx, ty, duration=0.1, steps=None)[source]
Args:
fx, fy: from position tx, ty: to position duration (float): duration steps: 1 steps is about 5ms, if set, duration will be ignore
Documents:
uiautomator use steps instead of duration As the document say: Each step execution is throttled to 5ms per step.
Links:
https://developer.android.com/reference/android/support/test/uiautomator/UiDevice.html#swipe%28int,%20int,%20int,%20int,%20int%29
swipe_points(points, duration=0.5)[source]
Args:
points: is point array containg at least one point object. eg [[200, 300], [210, 320]] duration: duration to inject between two points
Links:
https://developer.android.com/reference/android/support/test/uiautomator/UiDevice.html#swipe(android.graphics.Point[], int)
tap(x, y)[source]

alias of click

touch

ACTION_DOWN: 0 ACTION_MOVE: 2 touch.down(x, y) touch.move(x, y) touch.up()

wait_fastinput_ime(timeout=5.0)[source]

wait FastInputIME is ready Args:

timeout(float): maxium wait time
Raises:
EnvironmentError