Skip to content
Back to search

uiautomator2

Android Uiautomator2 Python Wrapper

Safety scan

A static text scan, not a guarantee. Select the badge to see what was scanned and every finding.

Checked today

Check it deeper on your machine

It has changed since its scan on 11 Nov 2026.

As a Claude Code plugin, install it and then ask Claude Code:

/plugin marketplace add keithmackay/mackayi/plugin install scanskillsafety@mackayiDo a deep scan of https://github.com/openatx/uiautomator2 with scanskillsafety

Or from a terminal, clone it and run it:

git clone https://github.com/keithmackay/scanskillsafety-skill ~/.claude/skills/scanskillsafetynode ~/.claude/skills/scanskillsafety/cli.cjs --deep 'https://github.com/openatx/uiautomator2'

It checks the exact commit: every file, its packages against OSV (api.osv.dev), how it compares with this page's scan (findsafeskills.com receives the repository's address), and, if you agree, Claude reading every file with your own Claude subscription. It never runs the code.

Badge for your README
findsafeskills safety rating

Markdown

[![findsafeskills safety rating](/api/listings/openatx--uiautomator2/badge.svg)](/listings/openatx--uiautomator2)

HTML

<a href="/listings/openatx--uiautomator2"><img src="/api/listings/openatx--uiautomator2/badge.svg" alt="findsafeskills safety rating" /></a>

Install

i

Install instructions from the README

As written by the repo's author. findsafeskills has not verified these steps.

pip install uiautomator2

# Check if installation was successful, normally it will output the library version
uiautomator2 version
# or: python -m uiautomator2 version

Install element inspection tool (optional, but highly recommended):

> For more detailed usage instructions, refer to: https://github.com/uiautodev/uiautodev QQ:536481989

# Recommended: launch via npx (requires Node.js), it will automatically open the browser
npx uiautodev -open

# If Node.js is not installed, download the standalone binary for your platform
# from https://get.uiauto.dev and run it directly.

# Alternative: install the Python version via pip
pip install uiautodev
uiautodev
# or: python -m uiautodev

Alternatives: uiautomatorviewer, Appium Inspector

What was scanned

The files the safety scan read, as written by the repository's author and shown as plain text. Lines with a finding are marked.

README.md · README · 1,410 lines

View this file on GitHub (read at the repository's current version: the scan did not record which commit it read)

This file has changed since it was scanned, so this is not exactly the text that was scanned, and no line is marked. The findings are listed with the safety scan above.

  1. <!-- filepath: /Users/codeskyblue/Codes/uiautomator2/README.md -->
  2. # uiautomator2
  3. [![PyPI](https://img.shields.io/pypi/v/uiautomator2.svg)](https://pypi.python.org/pypi/uiautomator2)
  4. ![PyPI](https://img.shields.io/pypi/pyversions/uiautomator2.svg)
  5. [![codecov](https://codecov.io/gh/openatx/uiautomator2/graph/badge.svg?token=d0ZLkqorBu)](https://codecov.io/gh/openatx/uiautomator2)
  6. [📖 Read the Chinese version](README_CN.md)
  7. A simple, easy-to-use, and stable Android automation library.
  8. - QQ Group: 815453846
  9. - Discord: <https://discord.gg/PbJhnZJKDd>
  10. > Users still on version 2.x.x, please check [2to3](docs/2to3.md) before deciding to upgrade to 3.x.x (Upgrade is highly recommended).
  11. ## How it Works
  12. This framework mainly consists of two parts:
  13. 1. **Device Side**: Runs an HTTP service based on UiAutomator, providing various interfaces for Android automation.
  14. 2. **Python Client**: Communicates with the device side via HTTP protocol, invoking UiAutomator's various functions.
  15. Simply put, it exposes Android automation capabilities to Python through HTTP interfaces. This design makes Python-side code writing simpler and more intuitive.
  16. > The Device Side run with a jar file which is also open source. see <https://github.com/openatx/android-uiautomator-server-jar>
  17. # Dependencies
  18. - Android version 4.4+
  19. - Python 3.8+
  20. # Installation
  21. ```sh
  22. pip install uiautomator2
  23. # Check if installation was successful, normally it will output the library version
  24. uiautomator2 version
  25. # or: python -m uiautomator2 version
  26. ```
  27. Install element inspection tool (optional, but highly recommended):
  28. > For more detailed usage instructions, refer to: https://github.com/uiautodev/uiautodev QQ:536481989
  29. ```sh
  30. # Recommended: launch via npx (requires Node.js), it will automatically open the browser
  31. npx uiautodev -open
  32. # If Node.js is not installed, download the standalone binary for your platform
  33. # from https://get.uiauto.dev and run it directly.
  34. # Alternative: install the Python version via pip
  35. pip install uiautodev
  36. uiautodev
  37. # or: python -m uiautodev
  38. ```
  39. Alternatives: uiautomatorviewer, Appium Inspector
  40. # Quick Start
  41. Prepare an Android phone with `Developer options` enabled, connect it to the computer, and ensure that `adb devices` shows the connected device.
  42. Open a Python interactive window. Then, input the following commands into the window.
  43. ```python
  44. import uiautomator2 as u2
  45. d = u2.connect() # Specify device serial number if multiple devices are connected
  46. print(d.info)
  47. # Expected output
  48. # {'currentPackageName': 'net.oneplus.launcher', 'displayHeight': 1920, 'displayRotation': 0, 'displaySizeDpX': 411, 'displaySizeDpY': 731, 'displayWidth': 1080, 'productName': 'OnePlus5', 'screenOn': True, 'sdkInt': 27, 'naturalOrientation': True}
  49. ```
  50. Example script:
  51. ```python
  52. import uiautomator2 as u2
  53. d = u2.connect('Q5S5T19611004599')
  54. d.app_start('tv.danmaku.bili', stop=True) # Start Bilibili
  55. d.wait_activity('.MainActivityV2')
  56. d.sleep(5) # Wait for splash screen ad to disappear
  57. d.xpath('//*[@text="我的"]').click() # Click "My"
  58. # Get fan count
  59. fans_count = d.xpath('//*[@resource-id="tv.danmaku.bili:id/fans_count"]').text
  60. print(f"Fan count: {fans_count}")
  61. ```
  62. # Documentation
  63. ## Connecting to Device
  64. Method 1: Connect using device serial number, e.g., `Q5S5T19611004599` (seen from `adb devices`)
  65. ```python
  66. import uiautomator2 as u2
  67. d = u2.connect('Q5S5T19611004599') # alias for u2.connect_usb('123456f')
  68. print(d.info)
  69. ```
  70. To connect on a non-default port (default is `9008`):
  71. ```python
  72. d = u2.connect('Q5S5T19611004599', port=9009)
  73. ```
  74. Method 2: Serial number can be passed via environment variable `ANDROID_SERIAL`
  75. ```python
  76. # export ANDROID_SERIAL=Q5S5T19611004599
  77. d = u2.connect()
  78. ```
  79. Method 3: Specify device via transport_id
  80. ```sh
  81. $ adb devices -l
  82. Q5S5T19611004599 device 0-1.2.2 product:ELE-AL00 model:ELE_AL00 device:HWELE transport_id:6
  83. ```
  84. Here you can see `transport_id:6`.
  85. > You can also get all connected transport_ids via `adbutils.adb.list(extended=True)`
  86. > Refer to https://github.com/openatx/adbutils
  87. ```python
  88. import adbutils # Requires version >=2.9.1
  89. import uiautomator2 as u2
  90. dev = adbutils.device(transport_id=6)
  91. d = u2.connect(dev)
  92. ```
  93. ### u2.jar Location on Device
  94. `u2.jar` is pushed to `/data/local/tmp/u2.jar` and launched with
  95. `CLASSPATH=/data/local/tmp/u2.jar`. On some devices that path is a directory
  96. (left over by another tool or by a failed push), which used to make adb push
  97. write `/data/local/tmp/u2.jar/u2.jar` and fail with
  98. `Push not complete, expect pushed ...`. A directory found at the jar path is now
  99. removed before pushing.
  100. If your device scans `/data/local/tmp` (risk-control software), or if that
  101. directory is read-only, point uiautomator2 somewhere else with the `U2_JAR_PATH`
  102. environment variable. The whole path is the jar file itself; its parent
  103. directory is created on the device when missing:
  104. ```sh
  105. export U2_JAR_PATH=/data/local/tmp/u2dir/u2.jar
  106. ```
  107. ```python
  108. import uiautomator2 as u2
  109. d = u2.connect() # pushes u2.jar to U2_JAR_PATH and uses it as CLASSPATH
  110. ```
  111. The value is read when the device connection is created, and the same path is
  112. used for the push and for the launch command. Note that a directory sitting at
  113. the jar path is deleted recursively, so keep other files out of it.
  114. ## Operating Elements with XPath
  115. What is XPath:
  116. XPath is a query language for locating content in XML or HTML documents. It uses simple syntax rules to establish a path from the root node to the desired element.
  117. Basic Syntax:
  118. - `/` - Select from the root node
  119. - `//` - Select from any position starting from the current node
  120. - `.` - Select the current node
  121. - `..` - Select the parent of the current node
  122. - `@` - Select attributes
  123. - `[]` - Predicate expression, used for filtering conditions
  124. You can quickly generate XPath using [UIAutoDev](https://uiauto.dev).
  125. Common Usage:
  126. ```python
  127. d.xpath('//*[@text="私人FM"]').click() # Click element with text "私人FM"
  128. # Syntactic sugar
  129. d.xpath('@personal-fm') # Equivalent to d.xpath('//*[@resource-id="personal-fm"]')
  130. sl = d.xpath("@com.example:id/home_searchedit") # sl is an XPathSelector object
  131. sl.click()
  132. sl.click(timeout=10) # Specify timeout, throws XPathElementNotFoundError if not found
  133. sl.click_exists() # Click if exists, returns whether click was successful
  134. sl.click_exists(timeout=10) # Wait up to 10s
  135. # Wait for the corresponding element to appear, returns XMLElement
  136. # Default wait time is 10s
  137. el = sl.wait()
  138. el = sl.wait(timeout=15) # Wait 15s, returns None if not found
  139. # Wait for element to disappear
  140. sl.wait_gone()
  141. sl.wait_gone(timeout=15)
  142. # Similar to wait, but throws XPathElementNotFoundError if not found
  143. el = sl.get()
  144. el = sl.get(timeout=15)
  145. sl.get_text() # Get component text
  146. sl.set_text("") # Clear input field
  147. sl.set_text("hello world") # Input "hello world" into input field
  148. ```
  149. For more usage, refer to [XPath Interface Document](XPATH.md)
  150. ## Plugins
  151. - webview: https://github.com/YuYoungG/uiautomator2-webview
  152. - flutter: https://github.com/assassinaj602/u2_flutter - Flutter driver plugin, lets you locate and operate Flutter widgets (e.g., `flutter.find_by_key("submit_btn").tap()`) instead of the empty native view hierarchy. See [proposal #1191](https://github.com/openatx/uiautomator2/issues/1191).
  153. To maintain the project's simplicity and extensibility, future plugins will be integrated as third-party libraries.
  154. ## Operating Elements with UiAutomator API
  155. ### Element Wait Timeout
  156. Set element search wait time (default 20s)
  157. ```python
  158. d.implicitly_wait(10.0) # Can also be modified via d.settings['wait_timeout'] = 10.0
  159. print("wait timeout", d.implicitly_wait()) # get default implicit wait
  160. # Throws UiObjectNotFoundError if "Settings" does not appear in 10s
  161. d(text="Settings").click()
  162. ```
  163. Wait timeout affects the following functions: `click`, `long_click`, `drag_to`, `get_text`, `set_text`, `clear_text`.
  164. ### Get Device Information
  165. Information obtained via UiAutomator:
  166. ```python
  167. d.info
  168. # Output
  169. {'currentPackageName': 'com.android.systemui',
  170. 'displayHeight': 1560,
  171. 'displayRotation': 0,
  172. 'displaySizeDpX': 360,
  173. 'displaySizeDpY': 780,
  174. 'displayWidth': 720,
  175. 'naturalOrientation': True,
  176. 'productName': 'ELE-AL00',
  177. 'screenOn': True,
  178. 'sdkInt': 29}
  179. ```
  180. Get device information (based on `adb shell getprop` command):
  181. ```python
  182. print(d.device_info)
  183. # output
  184. {'arch': 'arm64-v8a',
  185. 'brand': 'google',
  186. 'model': 'sdk_gphone64_arm64',
  187. 'sdk': 34,
  188. 'serial': 'EMULATOR34X1X19X0',
  189. 'version': 14}
  190. ```
  191. Get screen physical size (depends on `adb shell wm size`):
  192. ```python
  193. print(d.window_size())
  194. # device upright output example: (1080, 1920)
  195. # device horizontal output example: (1920, 1080)
  196. ```
  197. Get current App (depends on `adb shell`):
  198. ```python
  199. print(d.app_current())
  200. # Output example 1: {'activity': '.Client', 'package': 'com.netease.example', 'pid': 23710}
  201. # Output example 2: {'activity': '.Client', 'package': 'com.netease.example'}
  202. # Output example 3: {'activity': None, 'package': None}
  203. ```
  204. Wait for Activity (depends on `adb shell`):
  205. ```python
  206. d.wait_activity(".ApiDemos", timeout=10) # default timeout 10.0 seconds
  207. # Output: true or false
  208. ```
  209. Get device serial number:
  210. ```python
  211. print(d.serial)
  212. # output example: 74aAEDR428Z9
  213. ```
  214. Get device WLAN IP (depends on `adb shell`):
  215. ```python
  216. print(d.wlan_ip)
  217. # output example: 10.0.0.1 or None
  218. ```
  219. ### Clipboard
  220. Set or get clipboard content.
  221. * clipboard/set_clipboard
  222. ```python
  223. # Set clipboard
  224. d.clipboard = 'hello-world'
  225. # or
  226. d.set_clipboard('hello-world', 'label')
  227. # Get clipboard
  228. # Depends on input method (com.github.uiautomator/.AdbKeyboard)
  229. d.set_input_ime()
  230. print(d.clipboard)
  231. ```
  232. ### Key Events
  233. * Turn on/off screen
  234. ```python
  235. d.screen_on() # turn on the screen
  236. d.screen_off() # turn off the screen
  237. ```
  238. * Get current screen status
  239. ```python
  240. d.info.get('screenOn')
  241. ```
  242. * Press hard/soft key
  243. ```python
  244. d.press("home") # press the home key, with key name
  245. d.press("back") # press the back key, with key name
  246. d.press(0x07, 0x02) # press keycode 0x07('0') with META ALT(0x02)
  247. ```
  248. * These key names are currently supported:
  249. - home
  250. - back
  251. - left
  252. - right
  253. - up
  254. - down
  255. - center
  256. - menu
  257. - search
  258. - enter
  259. - delete ( or del)
  260. - recent (recent apps)
  261. - volume_up
  262. - volume_down
  263. - volume_mute
  264. - camera
  265. - power
  266. You can find all key code definitions at [Android KeyEvent](https://developer.android.com/reference/android/view/KeyEvent.html)
  267. * Unlock screen
  268. ```python
  269. d.unlock()
  270. # This is equivalent to
  271. # 1. press("power")
  272. # 2. swipe from left-bottom to right-top
  273. ```
  274. ### Gesture interaction with the device
  275. * Click on the screen
  276. ```python
  277. d.click(x, y)
  278. ```
  279. * Double click
  280. ```python
  281. d.double_click(x, y)
  282. d.double_click(x, y, 0.1) # default duration between two clicks is 0.1s
  283. ```
  284. * Long click on the screen
  285. ```python
  286. d.long_click(x, y)
  287. d.long_click(x, y, 0.5) # long click 0.5s (default)
  288. ```
  289. * Swipe
  290. ```python
  291. d.swipe(sx, sy, ex, ey)
  292. d.swipe(sx, sy, ex, ey, 0.5) # swipe for 0.5s (default)
  293. ```
  294. * SwipeExt (Extended functionality)
  295. ```python
  296. d.swipe_ext("right") # Swipe right, 4 options: "left", "right", "up", "down"
  297. d.swipe_ext("right", scale=0.9) # Default 0.9, swipe distance is 90% of screen width
  298. d.swipe_ext("right", box=(0, 0, 100, 100)) # Swipe within the area (0,0) -> (100, 100)
  299. # In practice, starting swipe from the midpoint for up/down swipes has a higher success rate
  300. d.swipe_ext("up", scale=0.8)
  301. # Can also use Direction as a parameter
  302. from uiautomator2 import Direction
  303. d.swipe_ext(Direction.FORWARD) # Scroll down page, equivalent to d.swipe_ext("up"), but easier to understand
  304. d.swipe_ext(Direction.BACKWARD) # Scroll up page
  305. d.swipe_ext(Direction.HORIZ_FORWARD) # Scroll page horizontally right
  306. d.swipe_ext(Direction.HORIZ_BACKWARD) # Scroll page horizontally left
  307. ```
  308. * Drag
  309. ```python
  310. d.drag(sx, sy, ex, ey)
  311. d.drag(sx, sy, ex, ey, 0.5) # drag for 0.5s (default)
  312. ```
  313. * Swipe points
  314. ```python
  315. # swipe from point(x0, y0) to point(x1, y1) then to point(x2, y2)
  316. # time will be 0.2s between two points
  317. d.swipe_points([(x0, y0), (x1, y1), (x2, y2)], 0.2)
  318. ```
  319. Often used for pattern unlock, get relative coordinates of each point beforehand (supports percentages).
  320. For more detailed usage, refer to this post [Using u2 to implement pattern unlock](https://testerhome.com/topics/11034)
  321. * Touch and drag (Beta)
  322. This is a lower-level raw interface, feels incomplete but usable. Note: percentages are not supported here.
  323. ```python
  324. d.touch.down(10, 10) # Simulate press down
  325. time.sleep(.01) # Delay between down and move, control it yourself
  326. d.touch.move(15, 15) # Simulate move
  327. d.touch.up(10, 10) # Simulate release
  328. ```
  329. Note: click, swipe, drag operations support percentage position values. Example:
  330. `d.long_click(0.5, 0.5)` means long click center of screen.
  331. ### Screen Related APIs
  332. * Retrieve/Set device orientation
  333. The possible orientations:
  334. - `natural` or `n`
  335. - `left` or `l`
  336. - `right` or `r`
  337. - `upsidedown` or `u` (cannot be set)
  338. ```python
  339. # retrieve orientation. the output could be "natural" or "left" or "right" or "upsidedown"
  340. orientation = d.orientation
  341. # WARNING: did not pass testing on my TT-M1
  342. # set orientation and freeze rotation.
  343. # notes: setting "upsidedown" requires Android>=4.3.
  344. d.set_orientation('l') # or "left"
  345. d.set_orientation("r") # or "right"
  346. d.set_orientation("n") # or "natural"
  347. ```
  348. * Freeze/Un-freeze rotation
  349. ```python
  350. # freeze rotation
  351. d.freeze_rotation()
  352. # un-freeze rotation
  353. d.freeze_rotation(False)
  354. ```
  355. * Take screenshot
  356. ```python
  357. # take screenshot and save to a file on the computer, requires Android>=4.2.
  358. d.screenshot("home.jpg")
  359. # get PIL.Image formatted images. Naturally, you need Pillow installed first
  360. image = d.screenshot() # default format="pillow"
  361. image.save("home.jpg") # or home.png. Currently, only png and jpg are supported
  362. # get OpenCV formatted images. Naturally, you need numpy and cv2 installed first
  363. import cv2
  364. image = d.screenshot(format='opencv')
  365. cv2.imwrite('home.jpg', image)
  366. # get raw jpeg data
  367. imagebin = d.screenshot(format='raw')
  368. with open("some.jpg", "wb") as f:
  369. f.write(imagebin)
  370. ```
  371. * Dump UI hierarchy
  372. ```python
  373. # get the UI hierarchy dump content
  374. xml = d.dump_hierarchy()
  375. # compressed=True: include non-important nodes (default False)
  376. # pretty: format xml (default False)
  377. # max_depth: limit xml depth, default 50
  378. xml = d.dump_hierarchy(compressed=False, pretty=True, max_depth=30)
  379. # root_in_active=True: dump only the active window root
  380. xml = d.dump_hierarchy(root_in_active=True)
  381. ```
  382. * Open notification or quick settings
  383. ```python
  384. d.open_notification()
  385. d.open_quick_settings()
  386. ```
  387. * Show touch trace on device screen
  388. ```python
  389. # show touch trace on device screen
  390. d.show_touch_trace()
  391. # hide touch trace
  392. d.show_touch_trace(pointer_location=False, show_touches=False)
  393. ```
  394. ### Selector
  395. Selector is a handy mechanism to identify a specific UI object in the current window.
  396. ```python
  397. # Select the object with text 'Clock' and its className is 'android.widget.TextView'
  398. d(text='Clock', className='android.widget.TextView')
  399. ```
  400. Selector supports the below parameters. Refer to [UiSelector Java doc](http://developer.android.com/tools/help/uiautomator/UiSelector.html) for detailed information.
  401. * `text`, `textContains`, `textMatches`, `textStartsWith`
  402. * `className`, `classNameMatches`
  403. * `description`, `descriptionContains`, `descriptionMatches`, `descriptionStartsWith`
  404. * `checkable`, `checked`, `clickable`, `longClickable`
  405. * `scrollable`, `enabled`,`focusable`, `focused`, `selected`
  406. * `packageName`, `packageNameMatches`
  407. * `resourceId`, `resourceIdMatches`
  408. * `index`, `instance`
  409. #### Children and siblings
  410. * children
  411. ```python
  412. # get the children or grandchildren
  413. d(className="android.widget.ListView").child(text="Bluetooth")
  414. ```
  415. * siblings
  416. ```python
  417. # get siblings
  418. d(text="Google").sibling(className="android.widget.ImageView")
  419. ```
  420. * children by text or description or instance
  421. ```python
  422. # get the child matching the condition className="android.widget.LinearLayout"
  423. # and also its children or grandchildren with text "Bluetooth"
  424. d(className="android.widget.ListView", resourceId="android:id/list") \
  425. .child_by_text("Bluetooth", className="android.widget.LinearLayout")
  426. # get children by allowing scroll search
  427. d(className="android.widget.ListView", resourceId="android:id/list") \
  428. .child_by_text(
  429. "Bluetooth",
  430. allow_scroll_search=True, # default False
  431. className="android.widget.LinearLayout"
  432. )
  433. ```
  434. - `child_by_description` is to find children whose grandchildren have
  435. the specified description, other parameters being similar to `child_by_text`.
  436. - `child_by_instance` is to find children which have a child UI element anywhere
  437. within its sub-hierarchy that is at the instance specified. It is performed
  438. on visible views **without scrolling**.
  439. See below links for detailed information:
  440. - [UiScrollable](http://developer.android.com/tools/help/uiautomator/UiScrollable.html), `getChildByDescription`, `getChildByText`, `getChildByInstance`
  441. - [UiCollection](http://developer.android.com/tools/help/uiautomator/UiCollection.html), `getChildByDescription`, `getChildByText`, `getChildByInstance`
  442. Above methods support chained invoking, e.g. for the below hierarchy:
  443. ```xml
  444. <node index="0" text="" resource-id="android:id/list" class="android.widget.ListView" ...>
  445. <node index="0" text="WIRELESS & NETWORKS" resource-id="" class="android.widget.TextView" .../>
  446. <node index="1" text="" resource-id="" class="android.widget.LinearLayout" ...>
  447. <node index="1" text="" resource-id="" class="android.widget.RelativeLayout" ...>
  448. <node index="0" text="Wi‑Fi" resource-id="android:id/title" class="android.widget.TextView" .../>
  449. </node>
  450. <node index="2" text="ON" resource-id="com.android.settings:id/switchWidget" class="android.widget.Switch" .../>
  451. </node>
  452. ...
  453. </node>
  454. ```
  455. ![settings](https://raw.github.com/xiaocong/uiautomator/master/docs/img/settings.png)
  456. To click the switch widget right to the TextView 'Wi‑Fi', we need to select the switch widget first. However, according to the UI hierarchy, more than one switch widget exists and has almost the same properties. Selecting by className will not work. Alternatively, the below selecting strategy would help:
  457. ```python
  458. d(className="android.widget.ListView", resourceId="android:id/list") \
  459. .child_by_text("Wi‑Fi", className="android.widget.LinearLayout") \
  460. .child(className="android.widget.Switch") \
  461. .click()
  462. ```
  463. * relative positioning
  464. Also, we can use the relative positioning methods to get the view: `left`, `right`, `up`, `down`.
  465. - `d(A).left(B)`, selects B on the left side of A.
  466. - `d(A).right(B)`, selects B on the right side of A.
  467. - `d(A).up(B)`, selects B above A.
  468. - `d(A).down(B)`, selects B under A.
  469. So for the above cases, we can alternatively select it with:
  470. ```python
  471. ## select "switch" on the right side of "Wi‑Fi"
  472. d(text="Wi‑Fi").right(className="android.widget.Switch").click()
  473. ```
  474. * Multiple instances
  475. Sometimes the screen may contain multiple views with the same properties, e.g. text. Then you will
  476. have to use the "instance" property in the selector to pick one of the qualifying instances, like below:
  477. ```python
  478. d(text="Add new", instance=0) # which means the first instance with text "Add new"
  479. ```
  480. In addition, uiautomator2 provides a list-like API (similar to jQuery):
  481. ```python
  482. # get the count of views with text "Add new" on current screen
  483. print(d(text="Add new").count)
  484. # same as count property
  485. print(len(d(text="Add new")))
  486. # get the instance via index
  487. obj = d(text="Add new")[0]
  488. obj = d(text="Add new")[1]
  489. # ...
  490. # iterator
  491. for view in d(text="Add new"):
  492. print(view.info) # ...
  493. ```
  494. **Notes**: when using selectors in a code block that walks through the result list, you must ensure that the UI elements on the screen
  495. remain unchanged. Otherwise, an Element-Not-Found error could occur when iterating through the list.
  496. #### Get the selected UI object status and its information
  497. * Check if the specific UI object exists
  498. ```python
  499. if d(text="Settings").exists: # True if exists, else False
  500. print("Settings button exists")
  501. # alias of above property.
  502. if d.exists(text="Settings"):
  503. print("Settings button exists")
  504. # advanced usage
  505. if d(text="Settings").exists(timeout=3): # wait for Settings to appear in 3s, same as .wait(3)
  506. print("Settings button appeared within 3 seconds")
  507. ```
  508. * Retrieve the info of the specific UI object
  509. ```python
  510. info = d(text="Settings").info
  511. print(info)
  512. ```
  513. Below is a possible output:
  514. ```json
  515. {
  516. "contentDescription": "",
  517. "checked": false,
  518. "scrollable": false,
  519. "text": "Settings",
  520. "packageName": "com.android.launcher",
  521. "selected": false,
  522. "enabled": true,
  523. "bounds": {
  524. "top": 385,
  525. "right": 360,
  526. "bottom": 585,
  527. "left": 200
  528. },
  529. "className": "android.widget.TextView",
  530. "focused": false,
  531. "focusable": true,
  532. "clickable": true,
  533. "childCount": 0,
  534. "longClickable": true,
  535. "visibleBounds": {
  536. "top": 385,
  537. "right": 360,
  538. "bottom": 585,
  539. "left": 200
  540. },
  541. "checkable": false
  542. }
  543. ```
  544. * Get/Set/Clear text of an editable field (e.g., EditText widgets)
  545. ```python
  546. text_content = d(className="android.widget.EditText").get_text() # get widget text
  547. d(className="android.widget.EditText").set_text("My text...") # set the text
  548. d(className="android.widget.EditText").clear_text() # clear the text
  549. ```
  550. * Get Widget center point
  551. ```python
  552. x, y = d(text="Settings").center()
  553. # x, y = d(text="Settings").center(offset=(0, 0)) # left-top x, y
  554. ```
  555. * Take screenshot of widget
  556. ```python
  557. im = d(text="Settings").screenshot()
  558. im.save("settings.jpg")
  559. ```
  560. #### Perform the click action on the selected UI object
  561. * Perform click on the specific object
  562. ```python
  563. # click on the center of the specific ui object
  564. d(text="Settings").click()
  565. # wait for element to appear for at most 10 seconds and then click
  566. d(text="Settings").click(timeout=10)
  567. # click with offset(x_offset_ratio, y_offset_ratio) from top-left of the element
  568. # click_x = x_offset_ratio * width + x_left_top
  569. # click_y = y_offset_ratio * height + y_left_top
  570. d(text="Settings").click(offset=(0.5, 0.5)) # Default: center
  571. d(text="Settings").click(offset=(0, 0)) # click left-top
  572. d(text="Settings").click(offset=(1, 1)) # click right-bottom
  573. # click if exists within 10s, default timeout 0s
  574. clicked = d(text='Skip').click_exists(timeout=10.0) # returns bool
  575. # click until element is gone, return bool
  576. is_gone = d(text="Skip").click_gone(maxretry=10, interval=1.0) # maxretry default 10, interval default 1.0s
  577. ```
  578. * Perform long click on the specific UI object
  579. ```python
  580. # long click on the center of the specific UI object
  581. d(text="Settings").long_click()
  582. # long click with duration
  583. d(text="Settings").long_click(duration=1.0) # duration in seconds, default 0.5s
  584. ```
  585. #### Gesture actions for the specific UI object
  586. * Drag the UI object towards another point or another UI object
  587. ```python
  588. # notes : drag cannot be used for Android<4.3.
  589. # drag the UI object to a screen point (x, y), in 0.5 seconds
  590. d(text="Settings").drag_to(x, y, duration=0.5)
  591. # drag the UI object to (the center position of) another UI object, in 0.25 seconds
  592. d(text="Settings").drag_to(text="Clock", duration=0.25)
  593. ```
  594. * Swipe from the center of the UI object to its edge
  595. Swipe supports 4 directions:
  596. - `left`
  597. - `right`
  598. - `up` (Previously 'top')
  599. - `down` (Previously 'bottom')
  600. ```python
  601. d(text="Settings").swipe("right")
  602. d(text="Settings").swipe("left", steps=10) # steps control smoothness/speed
  603. d(text="Settings").swipe("up", steps=20) # 1 step is about 5ms, so 20 steps is about 0.1s
  604. d(text="Settings").swipe("down", steps=20)
  605. ```
  606. * Two-point gesture from one pair of points to another (for pinch/zoom)
  607. ```python
  608. # ((start_x1, start_y1), (start_x2, start_y2)) are initial touch points
  609. # ((end_x1, end_y1), (end_x2, end_y2)) are final touch points
  610. # steps is the number of move steps to take
  611. d(text="Settings").gesture((sx1, sy1), (sx2, sy2), (ex1, ey1), (ex2, ey2), steps=100)
  612. ```
  613. * Two-point gesture on the specific UI object (pinch in/out)
  614. Supports two gestures:
  615. - `in`: from edge to center (pinch in)
  616. - `out`: from center to edge (pinch out)
  617. ```python
  618. # notes : pinch cannot be set until Android 4.3.
  619. # from edge to center.
  620. d(text="Settings").pinch_in(percent=100, steps=10) # percent of object size, steps for smoothness
  621. # from center to edge
  622. d(text="Settings").pinch_out(percent=100, steps=10)
  623. ```
  624. * Wait until the specific UI appears or disappears
  625. ```python
  626. # wait until the ui object appears
  627. appeared = d(text="Settings").wait(timeout=3.0) # return bool
  628. if appeared:
  629. print("Settings appeared")
  630. # wait until the ui object is gone
  631. gone = d(text="Settings").wait_gone(timeout=1.0) # return bool
  632. if gone:
  633. print("Settings disappeared")
  634. ```
  635. The default timeout is 20s. See **Global Settings** for more details.
  636. * Perform fling on the specific UI object (scrollable)
  637. Possible properties:
  638. - `horizontal` or `vertical` (or `horiz`, `vert`)
  639. - `forward` or `backward` or `toBeginning` or `toEnd`
  640. ```python
  641. # fling forward(default) vertically(default)
  642. d(scrollable=True).fling()
  643. # fling forward horizontally
  644. d(scrollable=True).fling.horizontal.forward()
  645. # fling backward vertically
  646. d(scrollable=True).fling.vertical.backward()
  647. # fling to beginning horizontally
  648. d(scrollable=True).fling.horizontal.toBeginning(max_swipes=1000)
  649. # fling to end vertically
  650. d(scrollable=True).fling.vertical.toEnd()
  651. ```
  652. * Perform scroll on the specific UI object (scrollable)
  653. Possible properties:
  654. - `horizontal` or `vertical` (or `horiz`, `vert`)
  655. - `forward` or `backward` or `toBeginning` or `toEnd`, or `to(selector)`
  656. ```python
  657. # scroll forward(default) vertically(default)
  658. d(scrollable=True).scroll(steps=10)
  659. # scroll forward horizontally
  660. d(scrollable=True).scroll.horizontal.forward(steps=100)
  661. # scroll backward vertically
  662. d(scrollable=True).scroll.vertical.backward()
  663. # scroll to beginning horizontally
  664. d(scrollable=True).scroll.horizontal.toBeginning(steps=100, max_swipes=1000)
  665. # scroll to end vertically
  666. d(scrollable=True).scroll.vertical.toEnd()
  667. # scroll forward vertically until specific ui object appears
  668. d(scrollable=True).scroll.vertical.to(text="Security")
  669. ```
  670. ### Input Method (IME)
  671. > IME APK: https://github.com/openatx/android-uiautomator-server/releases (Install this for reliable text input)
  672. ```python
  673. d.send_keys("Hello123abcEFG") # Send text
  674. d.send_keys("Hello123abcEFG", clear=True) # Clear existing text then send
  675. d.clear_text() # Clear all content in the input field
  676. # Automatically performs Enter, Search, etc., based on input field requirements. Added in version 3.1
  677. d.send_action()
  678. # Can also specify the IME action, e.g., d.send_action("search"). Supports go, search, send, next, done, previous.
  679. d.hide_keyboard() # Hide the soft keyboard
  680. ```
  681. When `send_keys` is used, it prioritizes using the clipboard for input. If the clipboard interface is unavailable, it will attempt to install and use an auxiliary IME.
  682. ```python
  683. print(d.current_ime()) # Get current IME ID (package/class)
  684. ```
  685. > For more, refer to: [IME_ACTION_CODE](https://developer.android.com/reference/android/view/inputmethod/EditorInfo)
  686. ### Toast
  687. ```python
  688. last_toast_message = d.toast.get_message(wait_timeout=5, default=None) # Get last toast message text within 5s
  689. print(last_toast_message)
  690. d.toast.reset() # Clear last toast message cache
  691. # d.toast.show("Hello", duration=3) # Show a toast (requires special permissions)
  692. ```
  693. ### WatchContext (Deprecated)
  694. Note: This interface is not highly recommended. It's better to check for pop-ups before clicking elements.
  695. The current `watch_context` uses threading and checks every 2 seconds.
  696. Currently, only `click` is a trigger operation.
  697. ```python
  698. with d.watch_context() as ctx:
  699. # When "Download Now" or "Update Now" and "Cancel" buttons appear simultaneously, click "Cancel"
  700. ctx.when("^(立即下载|立即更新)$").when("取消").click()
  701. ctx.when("同意").click()
  702. ctx.when("确定").click()
  703. # The above three lines execute immediately without waiting.
  704. ctx.wait_stable() # Start pop-up monitoring and wait for the interface to stabilize (stable if no pop-ups in two check cycles)
  705. # Use the call function to trigger a callback
  706. # call supports two parameters, d and el, order doesn't matter, can be omitted. If passed, variable names must be correct.
  707. # e.g., When an element matching "Midsummer Night" appears, click the back button
  708. ctx.when("仲夏之夜").call(lambda d: d.press("back"))
  709. ctx.when("确定").call(lambda el: el.click())
  710. # Other operations
  711. # For convenience, you can also use the default pop-up monitoring logic in the code
  712. # Below is the current built-in default logic. You can join the group and @ the owner to add new logic, or submit a PR directly.
  713. # when("继续使用").click()
  714. # when("移入管控").when("取消").click()
  715. # when("^(立即下载|立即更新)$").when("取消").click()
  716. # when("同意").click()
  717. # when("^(好的|确定)$").click()
  718. with d.watch_context(builtin=True) as ctx:
  719. # Add on top of existing logic
  720. ctx.when("@tb:id/jview_view").when('//*[@content-desc="图片"]').click()
  721. # Other script logic
  722. ```
  723. Alternative way:
  724. ```python
  725. ctx = d.watch_context()
  726. ctx.when("设置").click()
  727. ctx.wait_stable() # Wait until the interface no longer has pop-ups
  728. ctx.start() # if not using with statement
  729. # ... do something ...
  730. ctx.stop() # or ctx.close()
  731. ```
  732. ### Global Settings
  733. ```python
  734. import uiautomator2 as u2
  735. u2.settings['HTTP_TIMEOUT'] = 60 # Default 60s, http default request timeout
  736. ```
  737. Other configurations are mostly centralized in `d.settings`. Configurations may be added or removed based on future needs.
  738. ```python
  739. print(d.settings)
  740. # Output example:
  741. # {'operation_delay': (0, 0), # (before_op_delay, after_op_delay) in seconds
  742. # 'operation_delay_methods': ['click', 'swipe'], # methods to apply delay
  743. # 'wait_timeout': 20.0, # default element wait timeout (native operations, xpath plugin wait time)
  744. # 'xpath_debug': False, # enable xpath debug
  745. # 'xpath_timeout': 10.0 # default xpath wait timeout
  746. # }
  747. # Configure 0.5s delay before click, 1s delay after click
  748. d.settings['operation_delay'] = (0.5, 1)
  749. # Modify methods affected by delay
  750. # double_click, long_click correspond to 'click'
  751. d.settings['operation_delay_methods'] = ['click', 'swipe', 'drag', 'press']
  752. d.settings['wait_timeout'] = 20.0 # Default control wait time
  753. d.settings['max_depth'] = 50 # Default 50, limits dump_hierarchy returned element depth
  754. ```
  755. When settings are deprecated due to version upgrades, a DeprecatedWarning will be shown, but no exception will be raised.
  756. ```python
  757. >>> d.settings['click_before_delay'] = 1
  758. # [W 200514 14:55:59 settings:72] d.settings['click_before_delay'] is deprecated: Use operation_delay instead
  759. ```
  760. UiAutomator timeout settings (hidden methods):
  761. ```python
  762. >>> d.jsonrpc.setConfigurator({"waitForIdleTimeout": 100, "waitForSelectorTimeout": 0})
  763. # Check current configurator settings
  764. >>> print(d.jsonrpc.getConfigurator())
  765. # {'actionAcknowledgmentTimeout': 3000,
  766. # 'keyInjectionDelay': 0,
  767. # 'scrollAcknowledgmentTimeout': 200,
  768. # 'waitForIdleTimeout': 100,
  769. # 'waitForSelectorTimeout': 0}
  770. ```
  771. To prevent client program timeouts, `waitForIdleTimeout` and `waitForSelectorTimeout` are currently set to `0` by default by uiautomator2 itself (not by the underlying uiautomator server).
  772. Refs: [Google uiautomator Configurator](https://developer.android.com/reference/android/support/test/uiautomator/Configurator)
  773. ## Application Management
  774. This part showcases how to perform app management.
  775. ### Install Application
  776. We only support installing an APK from a URL or local path.
  777. ```python
  778. # From URL
  779. d.app_install('http://some-domain.com/some.apk')
  780. # From local path
  781. # d.app_install('/path/to/your/app.apk') # This functionality might depend on adbutils or direct adb calls.
  782. # For local path, usually you'd use adbutils:
  783. # adb = adbutils.AdbClient(host="127.0.0.1", port=5037)
  784. # device = adb.device(serial=d.serial)
  785. # device.install("/path/to/your/app.apk")
  786. # Or ensure atx-agent is installed and use its features if available.
  787. # The simplest way with uiautomator2 if atx-agent is present:
  788. # d.shell(['pm', 'install', '/path/to/app.apk']) # if apk is already on device
  789. # d.push('/local/path/app.apk', '/data/local/tmp/app.apk')
  790. # d.shell(['pm', 'install', '/data/local/tmp/app.apk'])
  791. ```
  792. ### Start Application
  793. ```python
  794. # Default method: first parses APK's mainActivity via atx-agent, then calls am start -n $package/$activity
  795. d.app_start("com.example.hello_world")
  796. # Use monkey -p com.example.hello_world -c android.intent.category.LAUNCHER 1 to start
  797. # This method has a side effect: it automatically turns off the phone's rotation lock.
  798. d.app_start("com.example.hello_world", use_monkey=True) # start with package name
  799. # Start app by specifying main activity, equivalent to calling am start -n com.example.hello_world/.MainActivity
  800. d.app_start("com.example.hello_world", ".MainActivity")
  801. # Stop app before starting
  802. d.app_start("com.example.hello_world", stop=True)
  803. ```
  804. ### Stop Application
  805. ```python
  806. # equivalent to `am force-stop`, thus you could lose data
  807. d.app_stop("com.example.hello_world")
  808. # equivalent to `pm clear` (clears app data)
  809. d.app_clear('com.example.hello_world')
  810. ```
  811. ### Stop All Applications
  812. ```python
  813. # stop all
  814. d.app_stop_all()
  815. # stop all apps except for com.examples.demo
  816. d.app_stop_all(excludes=['com.examples.demo'])
  817. ```
  818. ### Get Application Information
  819. ```python
  820. info = d.app_info("com.example.demo")
  821. print(info)
  822. # expect output
  823. # {
  824. # "mainActivity": "com.github.uiautomator.MainActivity",
  825. # "label": "ATX",
  826. # "versionName": "1.1.7",
  827. # "versionCode": 1001007,
  828. # "size": 1760809 # size in bytes
  829. # }
  830. # save app icon
  831. img = d.app_icon("com.example.demo") # Returns a PIL.Image object
  832. if img:
  833. img.save("icon.png")
  834. ```
  835. ### List All Running Applications
  836. ```python
  837. running_apps = d.app_list_running()
  838. print(running_apps)
  839. # expect output
  840. # ["com.xxxx.xxxx", "com.github.uiautomator", "xxxx"]
  841. ```
  842. ### Wait for Application to Run
  843. ```python
  844. pid = d.app_wait("com.example.android") # Wait for app to run, returns pid (int) or 0 if timeout
  845. if not pid:
  846. print("com.example.android is not running")
  847. else:
  848. print(f"com.example.android pid is {pid}")
  849. # Wait for app to be in the foreground
  850. pid = d.app_wait("com.example.android", front=True)
  851. if pid:
  852. print("com.example.android is in foreground")
  853. # Set custom timeout (default 20.0 seconds)
  854. pid = d.app_wait("com.example.android", timeout=10.0)
  855. ```
  856. ### Push and Pull Files
  857. * Push a file to the device
  858. ```python
  859. # push to a folder (src can be local path or BytesIO)
  860. d.push("foo.txt", "/sdcard/") # Pushes foo.txt to /sdcard/foo.txt
  861. # push and rename
  862. d.push("foo.txt", "/sdcard/bar.txt")
  863. # push fileobj
  864. import io
  865. with io.BytesIO(b"file content") as f:
  866. d.push(f, "/sdcard/from_io.txt")
  867. # push and change file access mode (mode is int, e.g., 0o755)
  868. d.push("foo.sh", "/data/local/tmp/", mode=0o755) # Pushes to /data/local/tmp/foo.sh
  869. ```
  870. * Pull a file from the device
  871. ```python
  872. # pull /sdcard/tmp.txt to local file tmp.txt
  873. d.pull("/sdcard/tmp.txt", "tmp.txt")
  874. # FileNotFoundError will raise if the file is not found on the device
  875. try:
  876. d.pull("/sdcard/some-file-not-exists.txt", "tmp.txt")
  877. except FileNotFoundError:
  878. print("File not found on device")
  879. # Pull file content as bytes
  880. # content_bytes = d.pull("/sdcard/tmp.txt") # This is not a standard feature, use sync.read_bytes for this
  881. # For reading content directly, use the sync object:
  882. # content = d.sync.read_bytes("/sdcard/tmp.txt")
  883. ```
  884. ### Other Application Operations
  885. ```python
  886. # Grant all runtime permissions (requires Android 6.0+ and atx-agent)
  887. # d.app_auto_grant_permissions("io.appium.android.apis") # This might be an older or specific helper
  888. # A more common way to grant permissions is via adb shell:
  889. # d.shell(['pm', 'grant', 'io.appium.android.apis', 'android.permission.READ_CONTACTS'])
  890. # Open URL scheme
  891. d.open_url("appname://appnamehost")
  892. # same as
  893. # adb shell am start -a android.intent.action.VIEW -d "appname://appnamehost"
  894. ```
  895. ### Session (Beta)
  896. Session represents an app lifecycle. Can be used to start app, detect app crash.
  897. * Launch and close app
  898. ```python
  899. sess = d.session("com.netease.cloudmusic") # Starts NetEase Cloud Music
  900. # ... perform operations within the session context ...
  901. # sess(text="Play").click()
  902. sess.close() # Stops NetEase Cloud Music
  903. # sess.restart() # Cold starts NetEase Cloud Music (stops then starts)
  904. ```
  905. * Use python `with` to launch and close app
  906. ```python
  907. with d.session("com.netease.cloudmusic") as sess:
  908. # sess(text="Play").click()
  909. # App will be closed automatically when exiting the 'with' block
  910. pass
  911. ```
  912. * Attach to the running app
  913. ```python
  914. # Launch app if not running, skip launch if already running
  915. sess = d.session("com.netease.cloudmusic", attach=True)
  916. ```
  917. * Detect app crash
  918. ```python
  919. # When app is still running
  920. # sess(text="Music").click() # operation goes normal
  921. # If app crashes or quits
  922. # sess(text="Music").click() # raises SessionBrokenError
  923. # other function calls under session will raise SessionBrokenError too
  924. ```
  925. ```python
  926. # check if session is ok.
  927. # Warning: function name may change in the future
  928. if sess.running(): # True or False
  929. print("Session is active")
  930. else:
  931. print("Session is not active (app might have crashed or closed)")
  932. ```
  933. ## Other APIs
  934. ### Stop Background HTTP Service
  935. Normally, when the Python program exits, the UiAutomator service on the device also exits.
  936. However, you can also stop the service via an API call.
  937. ```python
  938. d.uiautomator.stop() # Stops the uiautomator service on the device
  939. # or d.service("uiautomator").stop()
  940. ```
  941. ### Enable Debugging
  942. Print out the HTTP request information behind the code.
  943. ```python
  944. >>> d.debug = True # This enables logging for uiautomator2 library
  945. >>> print(d.info)
  946. # Example output showing HTTP request/response
  947. # 12:32:47.182 $ curl -X POST -d '{"jsonrpc": "2.0", "id": "...", "method": "deviceInfo"}' 'http://127.0.0.1:PORT/jsonrpc/0'
  948. # 12:32:47.225 Response >>>
  949. # {"jsonrpc":"2.0","id":"...","result":{...}}
  950. # <<< END
  951. ```
  952. For more structured logging:
  953. ```python
  954. import logging
  955. from uiautomator2 import set_log_level
  956. set_log_level(logging.DEBUG) # or logging.INFO
  957. # Or configure manually
  958. # logger = logging.getLogger("uiautomator2")
  959. # logger.setLevel(logging.DEBUG)
  960. # # setup handler, formatter etc.
  961. ```
  962. ## Command Line Functions
  963. `$device_ip` represents the device's IP address.
  964. To specify a device, pass `--serial`, e.g., `python -m uiautomator2 --serial bff1234 <SubCommand>`. SubCommand can be `screenshot`, `current`, etc.
  965. To use a non-default uiautomator2 server port, pass `-p`/`--port` after the subcommand, e.g., `uiautomator2 screenshot -p 9009 screenshot.jpg`. The default port is `9008`.
  966. > 1.0.3 Added: `python -m uiautomator2` is equivalent to `uiautomator2`
  967. - `screenshot`: Take a screenshot
  968. ```bash
  969. uiautomator2 screenshot screenshot.jpg
  970. # With specific device
  971. uiautomator2 --serial <YOUR_DEVICE_SERIAL> screenshot screenshot.jpg
  972. ```
  973. - `copy-assets`: Copy assets/ to current directory
  974. Used for pyinstaller、nuitka
  975. - `current`: Get current package name and activity
  976. ```bash
  977. uiautomator2 current
  978. # Output example:
  979. # {
  980. # "package": "com.android.settings",
  981. # "activity": ".Settings",
  982. # "pid": 12345
  983. # }
  984. ```
  985. - `uninstall`: Uninstall app
  986. ```bash
  987. uiautomator2 uninstall <package-name> # Uninstall one package
  988. uiautomator2 uninstall <package-name-1> <package-name-2> # Uninstall multiple packages
  989. # uiautomator2 uninstall --all # Uninstall all third-party apps (Be careful!)
  990. ```
  991. - `stop`: Stop app
  992. ```bash
  993. uiautomator2 stop com.example.app # Stop one app
  994. # uiautomator2 stop --all # Stop all apps (Be careful!)
  995. ```
  996. - `doctor`: Check uiautomator2 environment
  997. ```bash
  998. uiautomator2 doctor
  999. # Example output:
  1000. # [I 2024-04-25 19:53:36,288 __main__:101 pid:15596] uiautomator2 is OK
  1001. ```
  1002. - `install`: Install APK from URL or local path
  1003. ```bash
  1004. uiautomator2 install http://example.com/app.apk
  1005. uiautomator2 install /path/to/local/app.apk
  1006. ```
  1007. - `clear`: Clear app data
  1008. ```bash
  1009. uiautomator2 clear <package-name>
  1010. ```
  1011. - `start`: Start app
  1012. ```bash
  1013. uiautomator2 start <package-name>
  1014. uiautomator2 start <package-name>/<activity-name>
  1015. ```
  1016. - `version`: Show uiautomator2 version
  1017. ```bash
  1018. uiautomator2 version
  1019. ```
  1020. # Agent CLI
  1021. `u2cli` is a lightweight command-line wrapper around common device operations, useful for agent-driven workflows that need to inspect and control a device without writing Python code.
  1022. ## Skill
  1023. This repository also ships a skill for Android device automation. After installing `uiautomator2`, you can add the bundled `uiautomator2` skill with either `npx` or `gh`:
  1024. ```sh
  1025. npx skills add https://github.com/openatx/uiautomator2 --skill uiautomator2
  1026. # or
  1027. gh skill install https://github.com/openatx/uiautomator2 skills/uiautomator2
  1028. ```
  1029. The installed skill uses `u2cli` under the hood, so make sure `pip install uiautomator2` is already available in your environment.
  1030. ```sh
  1031. u2cli device-info
  1032. u2cli screenshot screen.png
  1033. u2cli dump-hierarchy
  1034. u2cli click --text Settings
  1035. ```
  1036. The CLI talks to a local `u2cli` server. Normal commands start the server automatically when needed, and you can also manage it manually:
  1037. ```sh
  1038. u2cli start-server
  1039. u2cli server-status
  1040. u2cli kill-server
  1041. ```
  1042. The server keeps a device registry and reuses existing device connections by serial and port. This is especially useful for repeated CLI calls, because the device is connected once and then handled through the server instead of reconnecting on every command.
  1043. ## Differences between Google UiAutomator 2.0 and 1.x
  1044. Reference: https://www.cnblogs.com/insist8089/p/6898181.html (Chinese)
  1045. - **New APIs**: UiObject2, Until, By, BySelector (in UiAutomator 2.x Java library)
  1046. - **Import Style**: In 2.0, `com.android.uiautomator.core.*` is deprecated. Use `android.support.test.uiautomator.*` (now `androidx.test.uiautomator.*`).
  1047. - **Build System**: Maven and/or Ant (1.x); Gradle (2.0).
  1048. - **Test Package Format**: From zip/jar (1.x) to APK (2.0).
  1049. - **Running Tests via ADB**:
  1050. - 1.x: `adb shell uiautomator runtest UiTest.jar -c package.name.ClassName`
  1051. - 2.0: `adb shell am instrument -w -r -e debug false -e class package.name.ClassName#methodName package.name.test/androidx.test.runner.AndroidJUnitRunner`
  1052. - **Access to Android Services/APIs**: 1.x: No; 2.0: Yes.
  1053. - **Log Output**: 1.x: `System.out.print` echoes to the execution terminal; 2.0: Output to Logcat.
  1054. - **Execution**: 2.0: Test cases do not need to inherit from any parent class, method names are not restricted, uses Annotations; 1.x: Needs to inherit `UiAutomatorTestCase`, test methods must start with `test`.
  1055. (Note: uiautomator2 Python library abstracts away many of these Java-level differences, but understanding the underlying UiAutomator evolution can be helpful.)
  1056. ## Dependent Projects
  1057. - uiautomator-jsonrpc-server: <https://github.com/openatx/android-uiautomator-server/> (The core server running on the Android device)
  1058. - adbutils: <https://github.com/openatx/adbutils> (For ADB communication)
  1059. # Contributors
  1060. [contributors](../../graphs/contributors)
  1061. # Other Excellent Projects
  1062. - <https://github.com/ecnusse/Kea2>: Fusing automated UI testing with scripts for effectively fuzzing Android apps.
  1063. - <https://github.com/atinfo/awesome-test-automation>: A collection of excellent test automation frameworks.
  1064. - [google/mobly](https://github.com/google/mobly): Google's internal test framework.
  1065. - <https://github.com/zhangzhao4444/Maxim>: A monkey test tool based on UiAutomator.
  1066. - <http://www.sikulix.com/>: A well-established image-based automation framework.
  1067. - <http://airtest.netease.com/>: The predecessor of this project, later taken over and optimized by NetEase Guangzhou team. Features a good IDE. (archived)
  1068. (Order matters, additions welcome)
  1069. # LICENSE
  1070. [MIT](LICENSE)

Ratings and comments

Sign in to rate this skill.

Sign in

Free to use. If it’s helped, pass it on.