Skip to content
Tutorials Center
My learning

Topics

Lesson 20 of 37 ยท Android and iOS Specifics

Android Automation with the UiAutomator2 Driver

Automate Android apps with Appium's UiAutomator2 driver: capabilities, UiSelector locators, mobile commands, activities, permissions and ADB tips.

Android is the platform where most people start with Appium, because an emulator is free and runs on every desktop operating system. Appium does not talk to Android itself. It delegates to a driver, and for modern Android versions that driver is UiAutomator2. The driver installs a small helper app on the device, and that helper uses Google's UiAutomator framework to find views, tap them, type text and read their state.

This lesson explains what the UiAutomator2 driver needs, which capabilities matter, how the Android-specific locator language UiSelector works, and how mobile: commands and ADB reach the things a plain tap cannot.

Appium, the Android SDK and an emulator cannot run on this site. The Appium and ADB snippets are therefore read-only. The runnable examples are small Python stand-ins that build the same strings and parse the same output, so you can experiment with the formats.

Setting up the driver

Appium 2 and later ship without any driver. You add the one you need with the Appium command line:

Terminal
npm install -g appium
appium driver install uiautomator2
appium driver list --installed
appium driver doctor uiautomator2

The doctor command checks the things the driver depends on: a Java JDK, the ANDROID_HOME (or ANDROID_SDK_ROOT) environment variable, adb on the path, and the build tools. Fix every red line before you run a test; most "session not created" errors on a new machine come from one of them.

You also need a target. Either start an emulator from Android Studio's Device Manager (or emulator -avd <name> on the command line), or plug in a phone with USB debugging enabled. adb devices must list it as device, not unauthorized or offline.

The capabilities you will use most

A new session starts with a capabilities object. For Android, a minimal set looks like this (Python client):

Python
from appium import webdriver
from appium.options.android import UiAutomator2Options

options = UiAutomator2Options()
options.platform_name = "Android"
options.device_name = "Pixel_8_API_35"
options.app = "/path/to/app-debug.apk"
options.auto_grant_permissions = True
options.new_command_timeout = 120

driver = webdriver.Remote("http://127.0.0.1:4723", options=options)

The same thing in raw W3C form shows the appium: prefix, which every non-standard key needs:

JSON
{
  "platformName": "Android",
  "appium:automationName": "UiAutomator2",
  "appium:deviceName": "Pixel_8_API_35",
  "appium:app": "/path/to/app-debug.apk",
  "appium:autoGrantPermissions": true,
  "appium:newCommandTimeout": 120
}
Capability Meaning
appium:app Path or URL of the APK to install and launch
appium:appPackage / appium:appActivity Start an app that is already installed, by package and launcher activity
appium:autoGrantPermissions Grant every runtime permission the manifest declares, so no dialogs appear
appium:noReset / appium:fullReset Keep app data between sessions, or uninstall and reinstall
appium:udid Pick one device when several are connected
appium:newCommandTimeout Seconds of silence before Appium ends the session

Capabilities get a full chapter of their own elsewhere in the course; here the point is that Android needs either app, or appPackage plus appActivity.

Stand-in: build capabilities and check them

This runnable checker is not Appium. It applies two rules from the real server so you can see why sessions fail: non-standard keys need the appium: prefix, and an Android session needs an app source.

Python Capabilities checker (stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Locating elements on Android

Appium offers several locator strategies, and the Android driver adds one of its own. The most reliable first choice is the accessibility ID, which maps to the view's content-desc attribute. Developers set it for screen readers, which makes it stable across layout changes and shared with iOS:

Python
from appium.webdriver.common.appiumby import AppiumBy

driver.find_element(AppiumBy.ACCESSIBILITY_ID, "Add to cart").click()
driver.find_element(AppiumBy.ID, "com.example.shop:id/search_box").send_keys("shoes")

Resource IDs are written with the package name before the colon. If the developers did not give a view an ID or description, ask them to; it is cheaper than a long XPath.

When you need logic, use UiSelector through the -android uiautomator strategy. It is a Java-like expression passed as a string:

Python
driver.find_element(
    AppiumBy.ANDROID_UIAUTOMATOR,
    'new UiSelector().text("Sign in").className("android.widget.Button")',
)

# scroll a list until a row is visible, then return it
driver.find_element(
    AppiumBy.ANDROID_UIAUTOMATOR,
    'new UiScrollable(new UiSelector().scrollable(true))'
    '.scrollIntoView(new UiSelector().textContains("Settings"))',
)

Common selector methods are text, textContains, textStartsWith, textMatches (regular expression), resourceId, description, className, checked, enabled, clickable, scrollable and instance(n) to pick the nth match.

Stand-in: a UiSelector builder

Typing quotes inside quotes causes bugs. This stand-in builds a selector string and escapes values the way you must in your own code.

Python UiSelector builder (stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Mobile commands and activities

The standard WebDriver protocol has no word for "press the Back button" or "grant a permission". Appium fills the gap with mobile: commands, called through execute_script:

Python
driver.execute_script("mobile: clickGesture", {"x": 540, "y": 1200})
driver.execute_script("mobile: deepLink", {
    "url": "myshop://product/42",
    "package": "com.example.shop",
})
driver.execute_script("mobile: shell", {"command": "pm", "args": ["list", "packages"]})

mobile: shell runs ADB shell commands and is disabled by default, because it can do anything on the device. You switch it on deliberately when starting the server: appium --allow-insecure=uiautomator2:adb_shell. Never enable insecure features on a server other people can reach.

Handy built-in helpers include driver.press_keycode(4) (Back), driver.activate_app(package), driver.terminate_app(package), driver.current_activity, driver.get_clipboard_text() and driver.hide_keyboard().

Understanding ADB output

Many Android problems are solved faster in a terminal than in a test. These commands are worth knowing:

Terminal
adb devices -l
adb shell dumpsys window | grep mCurrentFocus
adb logcat -s AndroidRuntime:E
adb install -r app-debug.apk
adb shell pm clear com.example.shop
Python Parse 'adb devices' output (stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Common mistakes

  • Using //* XPath for everything. XPath on Android walks the whole hierarchy and is the slowest strategy. Prefer accessibility ID or resource ID.
  • Forgetting that noReset keeps the previous login. Tests that pass alone and fail in a suite often share state.
  • Running on a phone that locks its screen or shows a system update dialog. Disable lock screen and animations on test devices.
  • Mixing up appium:app (a file to install) with appium:appPackage (an installed app to launch).

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Which driver does Appium use to automate modern Android apps?

    UiAutomator2 is the Android driver. XCUITest is for iOS, and ChromeDriver is only used inside web views.
  2. 2. A capability named deviceName is sent without a prefix. What happens on an Appium 2 or 3 server?

    W3C only defines a few standard keys. Everything else must carry a vendor prefix such as appium:.
  3. 3. Which locator is usually the most stable and works on both Android and iOS?

    Accessibility IDs are set deliberately by developers and survive layout and language changes.
  4. 4. Why is mobile: shell disabled by default?

    Insecure features are opt-in per driver and feature, for example uiautomator2:adb_shell.

Summary

  • UiAutomator2 is the Appium driver for Android; install it with appium driver install uiautomator2 and check it with appium driver doctor.
  • Android sessions need appium:app, or appium:appPackage plus appium:appActivity.
  • Prefer accessibility ID and resource ID; use UiSelector and UiScrollable when you need conditions or scrolling.
  • mobile: commands and ADB reach features the standard protocol lacks; insecure ones need an explicit server flag.
  • adb devices should show device before you start a test run.

Next: iOS Automation with XCUITest and WebDriverAgent