Automating Android Devices Using Python UIAutomator2
System Requirements
- Python version 3.6 or later
- Android OS version 4.4 or higher
Overview of UIAutomator2
UIAutomator2 is a Python-based library for automating Android device user interfaces. It is implemented over Google's UI Automator framework, providing capabilities to interact with and manipulate any UI element from Android applicasions displayed on-screen.
Repository
The library is hosted on GitHub:
Refer to the documantation in the repository for detailed insights.
Installation Procedure
-
Instal the UIAutomator2 package:
pip install --pre uiautomator2 pip install pillow # Required for screenshot functionality -
Deploy ATX Agent on the Device:
- Connect the Android device to your PC via USB and ensure its visibility with
adb devices. - Execute the following command to install the necessary server applications:
For installing with configurations:python -m uiautomator2 initpython -m uiautomator2 init --mirror --serial $SERIAL python -m uiautomator2 init --mirror
- Connect the Android device to your PC via USB and ensure its visibility with
Finally, verify successful initialization of the ATX agent.
-
Install Webitor:
- Installation command:
pip install -U weditor - Verification:
weditor --help
For convenience, on Windows systems, create a desktop shortcut:
weditor --shortcut - Installation command:
Opening Webitor can be achieved through various methods, such as executing weditor, using the shortcut, or calling it within Python.
Connnecting the Device
Two connection method are supported:
-
Via WiFi:
import uiautomator2 as u2 d = u2.connect('192.168.0.107') -
Through USB:
import uiautomator2 as u2 d = u2.connect('123456789F')
If there is no parameter, the library attempts to connect using the USB by default.
Example Operations
Checking Device State
# Verify daemons status
healthCheckStatus = d.healthcheck()
print(healthCheckStatus)
Retrieving Device Information
# Device basic information
deviceInfo = d.info
print(deviceInfo)
# Window size in pixels
print(d.window_size())
# Connected WiFi IP
print(d.wlan_ip)
Application Management
# Install application
apkUrl = 'http://example.com/path-to-apk-file.apk'
d.app_install(apkUrl)
# Start application
d.app_start('com.example.packageName')
# Stop application
d.app_stop('com.example.packageName')
# Retrieve app metadata
appInfo = d.app_info('com.example.packageName')
print(appInfo)
Interaction with the Device
# Screen manipulation
d.screen_on()
d.screen_off()
d.unlock()
# Gestures
d.click(x=100, y=200)
d.swipe(sx=100, sy=100, ex=200, ey=200)
# Push and pull files
fileToPush = "path-to-local-file.txt"
d.push(fileToPush, "/destination-path-on-device")
d.pull("/source-path-on-device", fileToPull)
This demonstrates fundamental automation tasks with UIAutomator2, empowering comprehensive control over Android devices during development or testing phases.