xref: /aosp_15_r20/external/mobly-snippet-lib/examples/ex4_uiautomator/README.md (revision ae5b1ec8a57d9cd6259556f14d3f2bb4f9fb3a85)
1*ae5b1ec8SZiwei Zhang# UIAutomator Snippet Example
2*ae5b1ec8SZiwei Zhang
3*ae5b1ec8SZiwei ZhangThe UiAutomator API, which allows developers to automate UI interactions on an
4*ae5b1ec8SZiwei ZhangAndroid device, is now available in Python on
5*ae5b1ec8SZiwei Zhang[google/snippet-uiautomator](https://github.com/google/snippet-uiautomator).
6*ae5b1ec8SZiwei ZhangThis makes it possible for developers to use UiAutomator in Mobly tests without
7*ae5b1ec8SZiwei Zhanghaving to write Java.
8*ae5b1ec8SZiwei Zhang
9*ae5b1ec8SZiwei ZhangThe `snippet-uiautomator` package is a wrapper around the AndroidX UiAutomator
10*ae5b1ec8SZiwei ZhangAPIs. It provides a Pythonic interface for interacting with Android UI elements,
11*ae5b1ec8SZiwei Zhangsuch as finding and clicking on buttons, entering text into fields, and
12*ae5b1ec8SZiwei Zhangscrolling through lists.
13*ae5b1ec8SZiwei Zhang
14*ae5b1ec8SZiwei ZhangTo use the `snippet-uiautomator` package, developers simply need to install it
15*ae5b1ec8SZiwei Zhangfrom PyPI and import it into their Python code. Once imported, they can use the
16*ae5b1ec8SZiwei Zhangpackage's API to automate any UI interaction.
17*ae5b1ec8SZiwei Zhang
18*ae5b1ec8SZiwei ZhangHere is an example of how to use the `snippet-uiautomator` package to automate a
19*ae5b1ec8SZiwei Zhangsimple UI interaction:
20*ae5b1ec8SZiwei Zhang
21*ae5b1ec8SZiwei Zhang```Python
22*ae5b1ec8SZiwei Zhangfrom mobly.controllers import android_device
23*ae5b1ec8SZiwei Zhangfrom snippet_uiautomator import uiautomator
24*ae5b1ec8SZiwei Zhang
25*ae5b1ec8SZiwei Zhang# Connect to an Android device.
26*ae5b1ec8SZiwei Zhangad = android_device.AndroidDevice(serial)
27*ae5b1ec8SZiwei Zhang
28*ae5b1ec8SZiwei Zhang# Load UiAutomator service.
29*ae5b1ec8SZiwei Zhanguiautomator.load_uiautomator_service(ad)
30*ae5b1ec8SZiwei Zhang
31*ae5b1ec8SZiwei Zhang# Find the "Login" button.
32*ae5b1ec8SZiwei Zhangbutton = ad.ui(res='com.example.app:id/login_button')
33*ae5b1ec8SZiwei Zhang
34*ae5b1ec8SZiwei Zhang# Click on the button.
35*ae5b1ec8SZiwei Zhangbutton.click()
36*ae5b1ec8SZiwei Zhang```
37