uiautomator2 is a Python wrapper for Google's UiAutomator test framework, enabling robust UI automation for Android devices. It simplifies interacting with Android applications, performing actions like clicking, typing, scrolling, and getting device information. The current stable version is 3.5.0, with frequent patch releases addressing bug fixes and minor enhancements. It requires Python 3.8 to 3.11.
pip install uiautomator2Verified import paths — ran on the pinned version, not inferred.
This quickstart demonstrates how to connect to an Android device using `uiautomator2`, retrieve device information, take a screenshot, press the home button, and dump the UI hierarchy. Remember to run `u2 init` on your device first to set up the necessary server applications.
Run `python -m uiautomator2 init` (or `u2 init` if installed as a command-line tool) from your terminal. This command installs the necessary APKs and starts the server on the connected device.
Always install/upgrade `uiautomator2` using `pip install uiautomator2 --upgrade`. This ensures compatible `adbutils` versions are installed. If issues arise, try reinstalling `uiautomator2` from scratch or checking its GitHub releases for specific `adbutils` compatibility notes.
Review scripts using `d.send_keys()` and remove any redundant `d.hide_keyboard()` calls that follow directly. Test carefully, as behavior can vary slightly across Android versions.
Prioritize `resourceId` for element identification. If `resourceId` is not stable or unique, consider using a combination of attributes or relative positioning. Avoid complex or deeply nested XPath expressions for better performance and maintainability.
Run `python -m uiautomator2 init` (or `u2 init`) in your terminal. Ensure your device is connected via ADB and has granted debugging permissions. This command will install and start the necessary server.
1. Ensure the device is physically connected (if using USB). 2. Verify 'USB debugging' is enabled in Developer Options. 3. Check for 'Allow USB debugging?' prompt on the device and accept it. 4. Run `adb devices` in your terminal to confirm the device is listed. 5. If connecting wirelessly, ensure the IP address is correct and ADB is connected (`adb connect <ip>`).
Install the package using pip: `pip install uiautomator2`.
Ensure the `UiObject` you're targeting is indeed a scrollable element (e.g., a RecyclerView or ScrollView). If not, you might need to find its parent scrollable container or use general device-level scrolling methods like `d.scroll()` or `d.swipe()`.