Home

Awesome

Appium Espresso Driver

Build Status

NPM version Downloads

Release

Appium's Espresso Driver is a test automation server for Android that uses Espresso as the underlying test technology. The Espresso Driver is a part of the Appium framework. The driver operates in scope of W3C WebDriver protocol with several custom extensions to cover operating-system specific scenarios.

The Espresso package consists of two main parts:

Note

Since version 2.0.0 Espresso driver has dropped the support of Appium 1, and is only compatible to Appium 2. Use the appium driver install espresso command to add it to your Appium 2 dist.

Comparison with UiAutomator2

The key difference between UiAutomator2 Driver and Espresso Driver is that UiAutomator2 is a black-box testing framework, and Espresso is a "grey-box" testing framework. The Espresso Driver itself is black-box (no internals of the code are exposed to the tester), but the Espresso framework itself has access to the internals of Android applications. This distinction has a few notable benefits. It can find elements that aren't rendered on the screen, it can identify elements by the Android View Tag, and it makes use of IdlingResource which blocks the framework from running commands until the UI thread is free. There is a limited support of out-of-app areas automation via the mobile: uiautomator command.

Requirements

On top of standard Appium requirements Espresso driver also expects the following prerequisites:

Doctor

Since driver version 2.31.0 you can automate the validation for the most of the above requirements as well as various optional ones needed by driver extensions by running the appium driver doctor espresso server command.

Scripts

Capabilities

General

Capability NameDescription
platformNameCould be set to android. Appium itself is not strict about this capability value if automationName is provided, so feel free to assign it to any supported platform name if this is needed, for example, to make Selenium Grid working.
appium:automationNameMust always be set to espresso. Values of automationName are compared case-insensitively.
appium:deviceNameThe name of the device under test (actually, it is not used to select a device under test). Consider setting udid for real devices and avd for emulators instead
appium:platformVersionThe platform version of an emulator or a real device. This capability is used for device autodetection if udid is not provided
appium:udidUDID of the device to be tested. Could ve retrieved from adb devices -l output. If unset then the driver will try to use the first connected device. Always set this capability if you run parallel tests.
appium:noResetPrevents the device to be reset before the session startup if set to true. This means that the application under test is not going to be terminated neither its data cleaned. false by default
appium:fullResetBeing set to true always enforces the application under test to be fully uninstalled before starting a new session. false by default
appium:printPageSourceOnFindFailureEnforces the server to dump the actual XML page source into the log if any error happens. false by default.

Driver/Server

Capability NameDescription
appium:systemPortThe number of the port the Espresso server is listening on. By default the first free port from 8300..8399 range is selected. It is recommended to set this value if you are running parallel tests on the same machine.
appium:skipServerInstallationSkip the Espresso Server component installation on the device under test and all the related checks if set to true. This could help to speed up the session startup if you know for sure the correct server version is installed on the device. In case the server is not installed or an incorrect version of it is installed then you may get an unexpected error later. Since driver version 3.3.0 the driver automatically verifies the compatibility with the server module on session startup by checking its /status response. An error is thrown if the returned server major version does not match to the driver's module major version or the target package name is different from the expected one. You may also skip the server version validation for a prebuilt server module by setting the VERSION constant to a non-valid semver value. false by default
appium:espressoServerLaunchTimeoutThe maximum number of milliseconds to wait util Espresso server is listening on the device. 45000 ms by default
appium:forceEspressoRebuildWhether to always enforce Espresso server rebuild (true). By default Espresso caches the already built server apk and only rebuilds it when it is necessary, because rebuilding process needs extra time. false by default
appium:espressoBuildConfigEither the full path to build config JSON on the server file system or the JSON content itself serialized to a string. This config allows to customize several important properties of Espresso server. Refer to Espresso Build Config for more information on how to properly construct such config.
appium:showGradleLogWhether to include Gradle log to the regular server logs while building Espresso server. false by default.

App

Capability NameDescription
appium:appFull path to the application to be tested (the app must be located on the same machine where the server is running). The .apk application extension is supported. Since driver version 2.1.0 .aab files are supported as well (they get converted to .apk format automatically if bundletool.jar could be found in your PATH). For older driver versions .aab files need to be converted manually to .apk format using bundletool first. Could also be an URL to a remote location. If neither of the app or appPackage capabilities are provided then the driver will fail to start a session. Also, if app capability is not provided it is expected that the app under test is already installed on the device under test and noReset is equal to true.
appium:appPackageApplication package identifier to be started. If not provided then Espresso will try to detect it automatically from the package provided by the app capability. Read How To Troubleshoot Activities Startup for more details
appium:appActivityMain application activity identifier. If not provided then Espresso will try to detect it automatically from the package provided by the app capability. Read How To Troubleshoot Activities Startup for more details
appium:appWaitActivityIdentifier of the first activity that the application invokes. If not provided then equals to appium:appActivity. Read How To Troubleshoot Activities Startup for more details
appium:appWaitPackageIdentifier of the first package that is invoked first. If not provided then equals to appium:appPackage. Read How To Troubleshoot Activities Startup for more details
appium:appWaitDurationMaximum amount of milliseconds to wait until the application under test is started (e. g. an activity returns the control to the caller). 20000 ms by default. Read How To Troubleshoot Activities Startup for more details
appium:intentOptionsThe mapping of custom options for the intent that is going to be passed to the main app activity. Check Intent Options for more details.
appium:activityOptionsThe mapping of custom options for the main app activity that is going to be started. Check Activity Options for more details.
appium:androidInstallTimeoutMaximum amount of milliseconds to wait until the application under test is installed. 90000 ms by default
appium:autoGrantPermissionsWhether to grant all the requested application permissions automatically when a test starts(true). The targetSdkVersion in the application manifest must be greater or equal to 23 and the Android version on the device under test must be greater or equal to Android 6 (API level 23) to grant permissions. Applications whose targetSdkVersion is lower than or equal to 22 must be reisntalled to grant permissions, for example, by setting the appium:fullReset capability as true for Android 6+ devices. false by default
appium:otherAppsAllows to set one or more comma-separated paths to Android packages that are going to be installed along with the main application under test. This might be useful if the tested app has dependencies
appium:uninstallOtherPackagesAllows to set one or more comma-separated package identifiers to be uninstalled from the device before a test starts
appium:allowTestPackagesIf set to true then it would be possible to use packages built with the test flag for the automated testing (literally adds -t flag to the adb install command). false by default
appium:remoteAppsCacheLimitSets the maximum amount of application packages to be cached on the device under test. This is needed for devices that don't support streamed installs (Android 7 and below), because ADB must push app packages to the device first in order to install them, which takes some time. Setting this capability to zero disables apps caching. 10 by default.
appium:enforceAppInstallIf set to true then the application under test is always reinstalled even if a newer version of it already exists on the device under test. false by default

App Localization

Capability NameDescription
appium:localeScriptCanonical name of the locale to be set for the app under test, for example Hans in zh-Hans-CN. See https://developer.android.com/reference/java/util/Locale.html for more details.
appium:languageName of the language to extract application strings for. Strings are extracted for the current system language by default. Also sets the language for the app under test. See https://developer.android.com/reference/java/util/Locale.html for more details. Example: en, ja
appium:localeSets the locale for the app under test. See https://developer.android.com/reference/java/util/Locale.html for more details. Example: EN, JA
appium:appLocaleSets the locale for the app under test. The main difference between this option and the above ones is that this option only changes the locale for the application under test and does not affect other parts of the system. Also, it only uses public APIs for its purpose. See https://github.com/libyal/libfwnt/wiki/Language-Code-identifiers to get the list of available language abbreviations. Example: {"language": "zh", "country": "CN", "variant": "Hans"}

ADB

Capability NameDescription
appium:adbPortNumber of the port where ADB is running. 5037 by default
appium:remoteAdbHostAddress of the host where ADB is running (the value of -H ADB command line option). Unset by default
appium:adbExecTimeoutMaximum number of milliseconds to wait until single ADB command is executed. 20000 ms by default
appium:clearDeviceLogsOnStartIf set to true then Espresso deletes all the existing logs in the device buffer before starting a new test
appium:buildToolsVersionThe version of Android build tools to use. By default Espresso driver uses the most recent version of build tools installed on the machine, but sometimes it might be necessary to give it a hint (let say if there is a known bug in the most recent tools version). Example: 28.0.3
appium:skipLogcatCaptureBeing set to true disables automatic logcat output collection during the test run. false by default
appium:suppressKillServerBeing set to true prevents the driver from ever killing the ADB server explicitly. Could be useful if ADB is connected wirelessly. false by default
appium:ignoreHiddenApiPolicyErrorBeing set to true ignores a failure while changing hidden API access policies to enable access to non-SDK interfaces. Could be useful on some devices, where access to these policies has been locked by its vendor. false by default.
pium:hideKeyboardBeing set to true hides the on-screen keyboard while the session is running. Use it instead of the legacy appium:unicodeKeyboard one (which will be dropped in the future). This effect is achieved by assigning a custom "artificial" input method. Only use this feature for special/exploratory cases as it violates the way your application under test is normally interacted with by a human. Setting this capability explicitly to false enforces adb shell ime reset call on session startup, which resets the currently selected/enabled IMEs to the default ones as if the device is initially booted with the current locale. undefined by default.
appium:mockLocationAppSets the package identifier of the app, which is used as a system mock location provider since Appium 1.18.0+. This capability has no effect on emulators. If the value is set to null or an empty string, then Appium will skip the mocked location provider setup procedure. Defaults to Appium Setting package identifier (io.appium.settings).
appium:logcatFormatThe log print format, where format is one of: brief process tag thread raw time threadtime long. threadtime is the default value.
appium:logcatFilterSpecsSeries of tag[:priority] where tag is a log component tag (or * for all) and priority is: V Verbose, D Debug, I Info, W Warn, E Error, F Fatal, S Silent (supress all output). '' means ':d' and tag by itself means tag:v. If not specified on the commandline, filterspec is set from ANDROID_LOG_TAGS. If no filterspec is found, filter defaults to '*:I'.
appium:allowDelayAdbBeing set to false prevents emulator to use -delay-adb feature to detect its startup. See https://github.com/appium/appium/issues/14773 for more details.

Emulator (Android Virtual Device)

Capability NameDescription
appium:avdThe name of Android emulator to run the test on. The names of currently installed emulators could be listed using avdmanager list avd command. If the emulator with the given name is not running then it is going to be started before a test
appium:avdLaunchTimeoutMaximum number of milliseconds to wait until Android Emulator is started. 60000 ms by default
appium:avdReadyTimeoutMaximum number of milliseconds to wait until Android Emulator is fully booted and is ready for usage. 60000 ms by default
appium:avdArgsEither a string or an array of emulator command line arguments.
appium:avdEnvMapping of emulator environment variables.
appium:networkSpeedSets the desired network speed limit for the emulator. It is only applied if the emulator is not running before the test starts. See emulator command line arguments description for more details.
appium:gpsEnabledSets whether to enable (true) or disable (false) GPS service in the Emulator. Unset by default, which means to not change the current value
appium:isHeadlessIf set to true then emulator starts in headless mode (e.g. no UI is shown). It is only applied if the emulator is not running before the test starts. false by default.
appium:injectedImagePropertiesAllows adjusting of injected image properties, like size, position or rotation. The image itself is expected to be injected by mobile: injectEmulatorCameraImage extension. It is also mandatory to provide this capability if you are going to use the injection feature on a newly created/resetted emulator as it enforces emulator restart, so it could properly reload the modified image properties. The value itself is a map, where possible keys are size, position and rotation. All of them are optional. If any of values is not provided then the following defaults are used: {size: {scaleX: 1, scaleY: 1}, position: {x: 0, y: 0, z: -1.5}, rotation: {x: 0, y: 0, z: 0}}. The size value contains scale multipliers for X and Y axes. The position contains normalized coefficients for X/Y/Z axes, where 0 means it should be centered in the viewport. Values in the rotation are measured in degrees respectively for X, Y and Z axis. The capability is available since the driver version 2.43.0.

App Signing

Capability NameDescription
appium:useKeystoreWhether to use a custom keystore to sign the app under test. false by default, which means apps are always signed with the default Appium debug certificate (unless canceled by noSign capability). This capability is used in combination with keystorePath, keystorePassword, keyAlias and keyPassword capabilities.
appium:keystorePathThe full path to the keystore file on the server filesystem. This capability is used in combination with useKeystore, keystorePath, keystorePassword, keyAlias and keyPassword capabilities. Unset by default
appium:keystorePasswordThe password to the keystore file provided in keystorePath capability. This capability is used in combination with useKeystore, keystorePath, keystorePassword, keyAlias and keyPassword capabilities. Unset by default
appium:keyAliasThe alias of the key in the keystore file provided in keystorePath capability. This capability is used in combination with useKeystore, keystorePath, keystorePassword, keyAlias and keyPassword capabilities. Unset by default
appium:keyPasswordThe password of the key in the keystore file provided in keystorePath capability. This capability is used in combination with useKeystore, keystorePath, keystorePassword, keyAlias and keyPassword capabilities. Unset by default
appium:noSignSet it to true in order to skip application signing. By default all apps are always signed with the default Appium debug signature. This capability cancels all the signing checks and makes the driver to use the application package as is. This capability does not affect .apks packages as these are expected to be already signed. Make sure that the server package is signed with the same signature as the application under test before disabling this capability.

Device Locking

Capability NameDescription
appium:skipUnlockWhether to skip the check for lock screen presence (true). By default Espresso driver tries to detect if the device's screen is locked before starting the test and to unlock that (which sometimes might be unstable). Note, that this operation takes some time, so it is recommended to set this capability to false and disable screen locking on devices under test. Read the Unlock tutorial for more details.
appium:unlockTypeSet one of the possible types of Android lock screens to unlock. Read the Unlock tutorial for more details.
appium:unlockKeyAllows to set an unlock key. Read the Unlock tutorial for more details.
appium:unlockSuccessTimeoutMaximum number of milliseconds to wait until the device is unlocked. 2000 ms by default. Read the Unlock tutorial for more details.

Web Context

Capability NameDescription
appium:autoWebviewIf set to true then Espresso driver will try to switch to the first available web view after the session is started. false by default.
appium:webviewDevtoolsPortThe local port number to use for devtools communication. By default the first free port from 10900..11000 range is selected. Consider setting the custom value if you are running parallel tests.
appium:ensureWebviewsHavePagesWhether to skip web views that have no pages from being shown in getContexts output. The driver uses devtools connection to retrieve the information about existing pages. true by default since Appium 1.19.0, false if lower than 1.19.0.
appium:enableWebviewDetailsCollectionWhether to retrieve extended web views information using devtools protocol. Enabling this capability helps to detect the necessary chromedriver version more precisely. true by default since Appium 1.22.0, false if lower than 1.22.0.
appium:chromedriverPortThe port number to use for Chromedriver communication. Any free port number is selected by default if unset.
appium:chromedriverPortsArray of possible port numbers to assign for Chromedriver communication. If none of the port in this array is free then an error is thrown.
appium:chromedriverArgsArray of chromedriver command line arguments. Note, that not all command line arguments that are available for the desktop browser are also available for the mobile one.
appium:chromedriverExecutableFull path to the chromedriver executable on the server file system.
appium:chromedriverExecutableDirFull path to the folder where chromedriver executables are located. This folder is used then to store the downloaded chromedriver executables if automatic download is enabled. Read Automatic Chromedriver Discovery article for more details.
appium:chromedriverChromeMappingFileFull path to the chromedrivers mapping file. This file is used to statically map webview/browser versions to the chromedriver versions that are capable of automating them. Read Automatic Chromedriver Discovery article for more details.
appium:chromedriverUseSystemExecutableSet it to true in order to enforce the usage of chromedriver, which gets downloaded by Appium automatically upon installation. This driver might not be compatible with the destination browser or a web view. false by default.
appium:chromedriverDisableBuildCheckBeing set to true disables the compatibility validation between the current chromedriver and the destination browser/web view. Use it with care.
appium:autoWebviewTimeoutSet the maximum number of milliseconds to wait until a web view is available if autoWebview capability is set to true. 2000 ms by default
appium:recreateChromeDriverSessionsIf this capability is set to true then chromedriver session is always going to be killed and then recreated instead of just suspending it on context switching. false by default
appium:nativeWebScreenshotWhether to use screenshoting endpoint provided by Espresso framework (true) rather than the one provided by chromedriver (false, the default value). Use it when you experience issues with the latter.
appium:extractChromeAndroidPackageFromContextNameIf set to true, tell chromedriver to attach to the android package we have associated with the context name, rather than the package of the application under test. false by default.
appium:showChromedriverLogIf set to true then all the output from chromedriver binary will be forwarded to the Appium server log. false by default.
pageLoadStrategyOne of the available page load strategies. See https://www.w3.org/TR/webdriver/#capabilities
appium:chromeOptionsA mapping, that allows to customize chromedriver options. See https://chromedriver.chromium.org/capabilities for the list of available entries.

Other

Capability NameDescription
appium:disableSuppressAccessibilityServiceBeing set to true tells the instrumentation process to not suppress accessibility services during the automated test. This might be useful if your automated test needs these services. false by default
appium:disableWindowAnimationTo avoid flakiness google recommends to disable the window animation of the Android device under test when running espresso test. Animation state is restored automatically after the session is stopped if it was enabled before it has started. The restore method may not work if the session ends unexpectedly. true by default
appium:timeZoneOverrides the current device's time zone since the driver version 2.38.0. This change is preserved until the next override. The time zone identifier must be a valid name from the list of available time zone identifiers, for example Europe/Kyiv

Settings API

Espresso driver supports Appium Settings API. Along with the common settings the following driver-specific settings are currently available:

NameTypeDescription
driver'compose' or 'espresso'The name of the subdriver to use for elements interactions. The default value is espresso. Switching the value to compose enables interactions with Jetpack Compose-based application user interfaces. Read Jetpack Compose Support for more details.

Jetpack Compose Support

Jetpack Compose is Android’s modern toolkit for building native UI. Espresso driver supports basic interactions with Compose-based applications since version 1.46.0.

Appium UiAutomator2 driver allows to interact with Jetpack Compose elements via the accessibility layer by providing testTag modifier attribute or the displayed text, but this Espresso driver allows you to access Jetpack Compose elements directly.

Interaction With Compose Elements

Espresso driver has the concept of subdrivers. This works quite similarly to the concept of contexts, while contexts are used to switch between native and web, and subdrivers are still under the native one. Each subdriver operates its own elements cache, so it is not be possible to mix Espresso and Compose elements.

In order to change between subdrivers use the driver setting. Setting its value to compose modifies driver behavior in the way it interacts with Compose elements rather that with classic Android views. It is possible to switch between espresso and compose modes at any point of time. When compose mode is active the the following webdriver commands behave differently (as of driver version 1.50.0):

Calling other driver element-specific APIs not listed above would most likely throw an exception as Compose and Espresso elements are being stored in completely separated internal caches and must not be mixed.

You could also check end-to-end tests for more examples on how to setup test capabilities and on the Compose usage in general:

Espresso Build Config

Espresso server is in tight connection with the application under test. That is why it is important that the server uses the same versions of common dependencies and there are no conflicts. Espresso driver allows to configure several build options via espressoBuildConfig capability. The configuration JSON supports the following entries:

toolsVersions

This entry allows to explicitly set the versions of different server components. The following map entries are supported:

NameDescriptionExample
gradleThe Gradle version to use for Espresso server building.'6.3'
androidGradlePluginThe Gradle plugin version to use for Espresso server building. By default the version from the build.gradle.kts is used'4.1.1'
compileSdkAndroid SDK version to compile the server for. By default the version from the app build.gradle.kts is used28
buildToolsTarget Android build tools version to compile the server with. By default the version from the app build.gradle.kts is used'28.0.3'
minSdkMinimum Android SDK version to compile the server for. By default the version from the app build.gradle.kts is used18
targetSdkTarget Android SDK version to compile the server for. By default the version from the app build.gradle.kts is used28
kotlinKotlin version to compile the server for. By default the version from the build.gradle.kts is used'1.3.72'
composeVersionThe version for the Jetpack Compose dependencies to use for Espresso server building. By default the version from the build.gradle.kts is used'1.1.1'
espressoVersionThe version for the Espresso dependencies to use for Espresso server building. By default the version from the build.gradle.kts is used'3.5.0'
sourceCompatibilityThe minimum version of JVM the project sources are compatible with. The default value is VERSION_1_8VERSION_12
targetCompatibilityThe target version of JVM the project sources are compatible with. The default value is VERSION_1_8VERSION_12
jvmTargetTarget version of the generated JVM bytecode as a string. The default value is 1_81_10
annotationVersionThe target version of androidx.annotation:annotation pakage. By default the version from the app build.gradle.kts is used'1.2.0'

additionalAppDependencies

The value of this entry must be a non empty array of dependent module names with their versions. The scripts adds all these items as api lines of dependencies category in the library build.gradle.kts script. Example: ["xerces.xercesImpl:2.8.0", "xerces.xmlParserAPIs:2.6.2"]

additionalAndroidTestDependencies

The value of this entry must be a non empty array of dependent module names with their versions. The scripts adds all these items as androidTestImplementation lines of dependencies category in the app build.gradle.kts script. Example: ["xerces.xercesImpl:2.8.0", "xerces.xmlParserAPIs:2.6.2"]

Full JSON Example

{
  "toolsVersions": {
    "androidGradlePlugin": "4.0.0"
  },
  "additionalAndroidTestDependencies": ["xerces.xercesImpl:2.8.0", "xerces.xmlParserAPIs:2.6.2"]
}

Intent Options

By default Espresso creates the following intent to start the app activity:

{
  "action": "ACTION_MAIN",
  "flags": "ACTIVITY_NEW_TASK",
  "className": "<fullyQualifiedAppActivity>"
}

Although, it is possible to fully customize these options by providing the intentOptions capability. Read Intent documentation for more details on this topic. The value of this capability is expected to be a map with the following entries:

NameTypeDescriptionExample
actionstringAn action name. Application-specific actions should be prefixed with the vendor's package name.ACTION_MAIN
datastringIntent data URIcontent://contacts/people/1
typestringIntent MIME typeimage/png
categoriesstringOne or more comma-separated Intent categoriesandroid.intent.category.APP_CONTACTS
componentstringComponent name with package name prefix to create an explicit intentcom.example.app/.ExampleActivity
intFlagsstringSingle string value, which represents intent flags set encoded into an integer. Could also be provided in hexadecimal format. Check setFlags method documentation for more details.0x0F
flagsComma-separated string of intent flag names'FLAG_GRANT_READ_URI_PERMISSION, ACTIVITY_CLEAR_TASK' (the 'FLAG_' prefix could be omitted)
classNameThe name of a class inside of the application package that will be used as the component for this Intentcom.example.app.MainActivity
e or esMap<string, string>Intent string parameters{'foo': 'bar'}
esnArray<string>Intent null parameters['foo', 'bar']
ezMap<string, boolean>Intent boolean parameters{'foo': true, 'bar': false}
eiMap<string, int>Intent integer parameters{'foo': 1, 'bar': 2}
elMap<string, long>Intent long integer parameters{'foo': 1L, 'bar': 2L}
efMap<string, float>Intent float parameters{'foo': 1.ff, 'bar': 2.2f}
euMap<string, string>Intent URI-data parameters{'foo': 'content://contacts/people/1'}
ecnMap<string, string>Intent component name parameters{'foo': 'com.example.app/.ExampleActivity'}
esaMap<string, List<string>>Intent string array parameters{'foo': ['bar1','bar2','bar3','bar4']}
eiaMap<string, string>Intent integer array parameters{'foo': '1,2,3,4'}
elaMap<string, string>Intent long array parameters{'foo': '1L,2L,3L,4L'}
efaMap<string, string>Intent float array parameters{'foo': '1.1,2.2,3.2,4.4'}

Activity Options

Espresso driver allows to customize several activity startup options using activityOptions capability. The capability value is expected to be a map with the following entries:

NameTypeDescriptionExample
launchDisplayIdstring or intDisplay id which you want to assign to launch the main app activity on. This might be useful if the device under test supports multiple displays1

Espresso Element Attributes

Espresso driver supports the following element attributes in espresso subdriver:

NameDescriptionExample
checkableWhether the element is checkable or not'true'
checkedWhether the element is checked. Always false if the element is not checkable'false'
classThe full name of the element's class. Could be null for some elements'android.view.View'
clickableWhether the element could be clicked'false'
content-descThe content-description attribute of the accessible element'foo'
enabledWhether the element could be clicked'true'
focusableWhether the element could be focused'true'
focusedWhether the element could is focused. Always false if the element is not focusable'false'
long-clickableWhether the element accepts long clicks'false'
packageIdentifier of the package the element belongs to'com.mycompany'
passwordWhether the element is a password input field'true'
resource-idElement's resource identifier. Could be null'com.mycompany:id/resId'
scrollableWhether the element is scrollable'true'
selectedWhether the element is selected'false'
textThe element's text. It never equals to null'my text'
hintThe element's hint. Could be null'my hint text'
boundsThe element's visible frame ([left, top][right, bottom])[0,0][100,100]
no-multiline-buttonsWhether the element's view hierarchy does not contain multiline buttons'true'
no-overlapsWhether element's descendant objects assignable to TextView or ImageView do not overlap each other'true'
no-ellipsized-textWhether the element's view hierarchy does not contain ellipsized or cut off text views'false'
visibleWhether the element is visible to the user'true'
view-tagThe tag value assigned to the element. Could be null'my tag'

Compose Element Attributes

Espresso driver supports the following element attributes in compose subdriver:

NameDescriptionExample
boundsThe element's visible frame ([left, top][right, bottom])[0,0][100,100]
checkedWhether the element is checked. Always false if the element is not checkable'false'
classThe full name of the element's class. Could be ComposeNode for some elements'ComposeNode'
clickableWhether the element could be clicked'false'
content-descThe content-description attribute of the accessible element'foo'
enabledWhether the element could be clicked'true'
focusedWhether the element could is focused. Always false if the element is not focusable'false'
indexElement's index in the tree hierarchy0
passwordWhether the element is a password input field'true'
resource-idElement's resource identifier. Could be null'com.mycompany:id/resId'
scrollableWhether the element is scrollable'true'
selectedWhether the element is selected'false'
textThe element's text'my text'
view-tagThe testTag element's value. Could be null'my tag'

Espresso Elements Location

Espresso driver supports the following location strategies in espresso subdriver:

NameDescriptionSpeed RankingExample
idThis strategy is mapped to the native Espresso withId matcher (exact match of element's resource id). Package identifier prefix is added automatically if unset and is equal to the identifier of the current application under test.⭐⭐⭐⭐⭐'com.mycompany:id/resourceId'
accessibility idThis strategy is mapped to the native Espresso withContentDescription matcher (exact match of element's content description).⭐⭐⭐⭐⭐'my description'
class nameThis strategy is mapped to the native Espresso withClassName matcher (exact match of element's class name).⭐⭐⭐⭐⭐'android.view.View'
textThis strategy is mapped to the native Espresso withText matcher (exact match of element's text).⭐⭐⭐⭐⭐'my text'
-android viewtag or tag nameThis strategy is mapped to the native Espresso withTagValue matcher (exact match of element's tag value).⭐⭐⭐⭐⭐'my tag'
-android datamatcherThis strategy allows to create Espresso data interaction selectors which can quickly and reliably scroll to the necessary elements. Read Espresso DataMatcher Selector to know more on how to construct these locators. Also check the Unlocking New Testing Capabilities with Espresso Driver by Daniel Graham presentation video from Appium Conf 2019.⭐⭐⭐⭐{"name": "hasEntry", "args": ["title", "WebView3"]}
-android viewmatcherThis strategy allows constructing of Espresso view matchers based on the given JSON representation of them. The representation is expected to contain the following fields: name: mandatory matcher function name; args: optional matcher function arguments, each argument could also be a function; class: optional full qualified class name of the corresponding matcher (if not provided then org.hamcrest.Matchers one is used), scope (since Espresso driver 2.11.0): optional JSON representation of a RootMatchers method. Check unit tests for more examples.⭐⭐⭐⭐{"name": "withText", "args": [{"name": "containsString", "args": "getExternalStoragePublicDirectory", "class": "org.hamcrest.Matchers"}], "class": "androidx.test.espresso.matcher.ViewMatchers"}
xpathFor elements lookup Xpath strategy the driver uses the same XML tree that is generated by page source API. Only Xpath 1.0 is supported.⭐⭐⭐By.xpath("//android.view.View[@text="Regular" and @checkable="true"]")

Compose Elements Location

Espresso driver supports the following location strategies in compose subdriver:

NameDescriptionSpeed RankingExample
accessibility idThis strategy is mapped to the native Espresso hasContentDescription matcher (exact match of element's content description).⭐⭐⭐⭐⭐'my description'
-android viewtag or tag nameThis strategy is mapped to the native Compose hasTestTag matcher (exact match of element's tag value).⭐⭐⭐⭐⭐'my tag'
text or link textThis strategy is mapped to the native Compose hasText matcher (exact match of element's text).⭐⭐⭐⭐⭐'my text'
xpathFor elements lookup Xpath strategy the driver uses the same XML tree that is generated by page source API. Only Xpath 1.0 is supported.⭐⭐⭐By.xpath("//ComposeNode[@text="Regular" and @selected="true"]")

Platform-Specific Extensions

Beside of standard W3C APIs the driver provides the below custom command extensions to execute platform specific scenarios. Use the following source code examples in order to invoke them from your client code:

// Java 11+
var result = driver.executeScript("mobile: <methodName>", Map.of(
    "arg1", "value1",
    "arg2", "value2"
    // you may add more pairs if needed or skip providing the map completely
    // if all arguments are defined as optional
));
// WebdriverIO
const result = await driver.executeScript('mobile: <methodName>', [{
    arg1: "value1",
    arg2: "value2",
}]);
# Python
result = driver.execute_script('mobile: <methodName>', {
    'arg1': 'value1',
    'arg2': 'value2',
})
# Ruby
result = @driver.execute_script 'mobile: <methodName>', {
    arg1: 'value1',
    arg2: 'value2',
}
// Dotnet
object result = driver.ExecuteScript("mobile: <methodName>", new Dictionary<string, object>() {
    {"arg1", "value1"},
    {"arg2", "value2"}
});

mobile: shell

Executes the given shell command on the device under test via ADB connection. This extension exposes a potential security risk and thus is only enabled when explicitly activated by the adb_shell server command line feature specifier

Arguments

NameTypeRequiredDescriptionExample
commandstringyesShell command name to execute, for example echo or rmecho
argsArray<string>noArray of command arguments['-f', '/sdcard/myfile.txt']
timeoutnumbernoCommand timeout in milliseconds. If the command blocks for longer than this timeout then an exception is going to be thrown. The default timeout is 20000 ms100000
includeStderrbooleannoWhether to include stderr stream into the returned result. false by defaulttrue

Returns

Depending on the includeStderr value this API could either return a string, which is equal to the stdout stream content of the given command or a dictionary whose elements are stdout and stderr and values are contents of the corresponding outgoing streams. If the command exits with a non-zero return code then an exception is going to be thrown. The exception message will be equal to the command stderr.

mobile: execEmuConsoleCommand

Executes a command through emulator telnet console interface and returns its output. The emulator_console server feature must be enabled in order to use this method.

Arguments

NameTypeRequiredDescriptionExample
commandstringyesThe actual command to execute. See Android Emulator Console Guide for more details on available commandshelp-verbose
execTimeoutnumbernoTimeout used to wait for a server reply to the given command in milliseconds. 60000 ms by default100000
connTimeoutbooleannoConsole connection timeout in milliseconds. 5000 ms by default10000
initTimeoutbooleannoTelnet console initialization timeout in milliseconds (the time between the connection happens and the command prompt). 5000 ms by default10000

Returns

The actual command output. An error is thrown if command execution fails.

mobile: performEditorAction

Performs IME action on the currently focused edit element.

Very often Android developers use onEditorAction callback with actionId argument to implement actions handling, for example, when Search or Done button is pressed on the on-screen keyboard. This mobile extension is supposed to emulate the invokation of such callback on the focused element.

Arguments

NameTypeRequiredDescriptionExample
actionstringyesThe name or an integer code of the editor action to be executed. The following action names are supported: normal, unspecified, none, go, search, send, next, done, previous. Read EditorInfo for more details on this topic.search

Examples

// Java
driver.executeScript("mobile: performEditorAction", ImmutableMap.of("action", "Go"));
# Python
driver.execute_script('mobile: performEditorAction', {'action': 'previous'})

mobile: changePermissions

Changes package permissions in runtime.

Arguments

NameTypeRequiredDescriptionExample
permissionsstring or Array<string>yesThe full name of the permission to be changed or a list of permissions. Mandatory argument.['android.permission.ACCESS_FINE_LOCATION', 'android.permission.BROADCAST_SMS']
appPackagestringnoThe application package to set change permissions on. Defaults to the package name under testcom.mycompany.myapp
actionstringnoEither grant (the default action) or revokegrant

mobile: getPermissions

Gets runtime permissions list for the given application package.

Arguments

NameTypeRequiredDescriptionExample
typestringnoOne of possible permission types to get. Can be one of: denied, granted or requested (the default value).granted
appPackagestringnoThe application package to get permissions from. Defaults to the package name under testcom.mycompany.myapp

Returns

Array of strings, where each string is a permission name. the array could be empty.

mobile: startScreenStreaming

Starts device screen broadcast by creating MJPEG server. Multiple calls to this method have no effect unless the previous streaming session is stopped. This method only works if the adb_screen_streaming feature is enabled on the server side. It is also required that GStreamer with gst-plugins-base, gst-plugins-good and gst-plugins-bad packages is installed and available in PATH on the server machine.

Arguments

NameTypeRequiredDescriptionExample
widthnumbernoThe scaled width of the device's screen. If unset then the script will assign it to the actual screen width measured in pixels.768
heightnumbernoThe scaled height of the device's screen. If unset then the script will assign it to the actual screen height measured in pixels.1024
bitRatenumbernoThe video bit rate for the video, in bits per second. The default value is 4000000 (4 Mb/s). You can increase the bit rate to improve video quality, but doing so results in larger movie files.1024000
hoststringnoThe IP address/host name to start the MJPEG server on. You can set it to 0.0.0.0 to trigger the broadcast on all available network interfaces. 127.0.0.1 by default0.0.0.0
pathnamestringnoThe HTTP request path the MJPEG server should be available on. If unset then any pathname on the given host/port combination will work. Note that the value should always start with a single slash: //myserver
tcpPortnumbernoThe port number to start the internal TCP MJPEG broadcast on. This type of broadcast always starts on the loopback interface (127.0.0.1). 8094 by default5024
portnumbernoThe port number to start the MJPEG server on. 8093 by default5023
qualitynumbernoThe quality value for the streamed JPEG images. This number should be in range [1, 100], where 100 is the best quality. 70 by default80
considerRotationbooleannoIf set to true then GStreamer pipeline will increase the dimensions of the resulting images to properly fit images in both landscape and portrait orientations. Set it to true if the device rotation is not going to be the same during the broadcasting session. false by defaultfalse
logPipelineDetailsbooleannoWhether to log GStreamer pipeline events into the standard log output. Might be useful for debugging purposes. false by defaulttrue

mobile: stopScreenStreaming

Stop the previously started screen streaming. If no screen streaming server has been started then nothing is done.

mobile: deviceInfo

Retrieves the information about the device under test, like the device model, serial number, network connectivity info, etc.

Returns

The extension returns a dictionary whose entries are the device properties. Check https://github.com/appium/appium-espresso-driver/blob/master/espresso-server/app/src/androidTest/java/io/appium/espressoserver/lib/handlers/GetDeviceInfo.kt to get the full list of returned keys and their corresponding values.

mobile: swipe

Perform swipe action. Invokes Espresso swipe action under the hood.

Arguments

NameTypeRequiredDescriptionExample
elementId (element before v2.29)stringyesThe UDID of the element to perform the swipe on.123456-7890-3453-24234243
directionstringnoSwipe direction. Either this argument or swiper must be provided, but not both. The following values are supported: up, down, left, rightdown
swiperstringnoSwipe speed. Either this argument or direction must be provided, but not both. Either FAST (Swipes quickly between the co-ordinates) or SLOW (Swipes deliberately slowly between the co-ordinates, to aid in visual debugging)SLOW
startCoordinatesstringnoThe starting coordinates for the action. The following values are supported: TOP_LEFT, TOP_CENTER, TOP_RIGHT, CENTER_LEFT, CENTER, CENTER_RIGHT, BOTTOM_LEFT, BOTTOM_CENTER (the default value), BOTTOM_RIGHT, VISIBLE_CENTERCENTER_LEFT
endCoordinatesstringnoThe ending coordinates for the action. The following values are supported: TOP_LEFT, TOP_CENTER (the default value), TOP_RIGHT, CENTER_LEFT, CENTER, CENTER_RIGHT, BOTTOM_LEFT, BOTTOM_CENTER, BOTTOM_RIGHT, VISIBLE_CENTERTOP_LEFT
precisionDescriberstringnoDefines the actual swipe precision. The following values are supported: PINPOINT (1px), FINGER (average width of the index finger is 16 – 20 mm), THUMB (average width of an adult thumb is 25 mm or 1 inch, the default value)FINGER

mobile: isToastVisible

Checks whether a toast notification with the given text is currently visible.

Arguments

NameTypeRequiredDescriptionExample
textstringyesThe actual toast test or a part of it'toast text'
isRegexpbooleannoWhether the text value should be parsed as a regular expression (true) or as a raw text (false, the default value)false

Returns

Either true or false

mobile: openDrawer

Opens the DrawerLayout drawer with the gravity. This method blocks until the drawer is fully open. No operation if the drawer is already open.

Arguments

NameTypeRequiredDescriptionExample
elementId (element before v2.29)stringyesUDID of the element to perform the action on.123456-7890-3453-24234243
gravityintnoSee GravityCompat and Gravity classes documentation0x00800000 <bitwise_or> 0x00000003

mobile: closeDrawer

Closes the DrawerLayout drawer with the gravity. This method blocks until the drawer is fully closed. No operation if the drawer is already closed.

Arguments

NameTypeRequiredDescriptionExample
elementId (element before v2.29)stringyesUDID of the element to perform the action on.123456-7890-3453-24234243
gravityintnoSee GravityCompat and Gravity classes documentation0x00800000 <bitwise_or> 0x00000005

mobile: scrollToPage

Perform scrolling to the given page. Invokes one of the ViewPagerActions under the hood. Which action is invoked depends on the given arguments.

Arguments

NameTypeRequiredDescriptionExample
elementId (element before v2.29)stringyesUDID of the element to perform the action on.123456-7890-3453-24234243
scrollTostringno if scrollToPage is providedShifts ViewPager to the given page. Supported values are: first, last, left, rightlast
scrollToPageintno if scrollTo is providedMoves ViewPager to a specific page number (numbering starts from zero).1
smoothScrollbooleannoWhether to perform smooth (but slower) scrolling (true). The default value is falsetrue

mobile: navigateTo

Invokes navigateTo action under the hood.

Arguments

NameTypeRequiredDescriptionExample
elementId (element before v2.29)stringyesUDID of the element to perform the action on. View constraints: View must be a child of a DrawerLayout; View must be of type NavigationView; View must be visible on screen; View must be displayed on screen123456-7890-3453-24234243
menuItemIdintyesThe resource id of the destination menu item123

mobile: clickAction

Perform general click action.

Arguments

NameTypeRequiredDescriptionExample
elementId (element before v2.29)stringyesThe UDID of the element to perform the click on.123456-7890-3453-24234243
tapperstringnoTapper type. Supported types are: SINGLE (the default value), LONG, DOUBLELONG
coordinatesProviderstringnoThe coordinates for the action. The following values are supported: TOP_LEFT, TOP_CENTER, TOP_RIGHT, CENTER_LEFT, CENTER, CENTER_RIGHT, BOTTOM_LEFT, BOTTOM_CENTER, BOTTOM_RIGHT, VISIBLE_CENTER (the default value)CENTER_LEFT
precisionDescriberstringnoDefines the actual click precision. The following values are supported: PINPOINT (1px), FINGER (average width of the index finger is 16 – 20 mm, the default value), THUMB (average width of an adult thumb is 25 mm or 1 inch)PINPOINT
inputDeviceintnoInput device identifier, 0 by default1
buttonStateintnoButton state id, 0 by default1

mobile: getContexts

Retrieves a WebViews mapping based on CDP endpoints

Arguments

NameTypeRequiredDescriptionExample
waitForWebviewMsnumbernoTells Espresso driver for how long (in milliseconds) to wait for web view(s) to appear since Espresso driver v2.30.0. If a Chrome process running on the device under test fails to create a connection to the devtools socket, then the chromedriver will rise an error similar to failed to connect to socket 'localabstract:chrome_devtools_remote' in Espresso driver. It could cause no WebViews found result, although a couple of retrials may fix it. This argument helps to keep trying to get WebView(s) up to the given time milliseconds as one command call. This issue tends to occur Chrome v115 and over so far. issues#19251 contains more details. If set to 0ms (the default value), then Espresso driver only checks the WebView(s) availability once.10000

Returns

The following json demonstrates the example of WebviewsMapping object. Note that description in page can be an empty string most likely when it comes to Mobile Chrome)

 {
   "proc": "@webview_devtools_remote_22138",
   "webview": "WEBVIEW_22138",
   "info": {
     "Android-Package": "io.appium.settings",
     "Browser": "Chrome/74.0.3729.185",
     "Protocol-Version": "1.3",
     "User-Agent": "Mozilla/5.0 (Linux; Android 10; Android SDK built for x86 Build/QSR1.190920.001; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/74.0.3729.185 Mobile Safari/537.36",
     "V8-Version": "7.4.288.28",
     "WebKit-Version": "537.36 (@22955682f94ce09336197bfb8dffea991fa32f0d)",
     "webSocketDebuggerUrl": "ws://127.0.0.1:10900/devtools/browser"
   },
   "pages": [
     {
       "description": "{\"attached\":true,\"empty\":false,\"height\":1458,\"screenX\":0,\"screenY\":336,\"visible\":true,\"width\":1080}",
       "devtoolsFrontendUrl": "http://chrome-devtools-frontend.appspot.com/serve_rev/@22955682f94ce09336197bfb8dffea991fa32f0d/inspector.html?ws=127.0.0.1:10900/devtools/page/27325CC50B600D31B233F45E09487B1F",
       "id": "27325CC50B600D31B233F45E09487B1F",
       "title": "Releases · appium/appium · GitHub",
       "type": "page",
       "url": "https://github.com/appium/appium/releases",
       "webSocketDebuggerUrl": "ws://127.0.0.1:10900/devtools/page/27325CC50B600D31B233F45E09487B1F"
     }
   ],
   "webviewName": "WEBVIEW_com.io.appium.setting"
 }

mobile: getNotifications

Retrieves Android notifications via Appium Settings helper. Appium Settings app itself must be manually granted to access notifications under device Settings in order to make this feature working. Appium Settings helper keeps all the active notifications plus notifications that appeared while it was running in the internal buffer, but no more than 100 items altogether. Newly appeared notifications are always added to the head of the notifications array. The isRemoved flag is set to true for notifications that have been removed. See https://developer.android.com/reference/android/service/notification/StatusBarNotification and https://developer.android.com/reference/android/app/Notification.html for more information on available notification properties and their values.

Returns

The example output is:

{
   "statusBarNotifications":[
     {
       "isGroup":false,
       "packageName":"io.appium.settings",
       "isClearable":false,
       "isOngoing":true,
       "id":1,
       "tag":null,
       "notification":{
         "title":null,
         "bigTitle":"Appium Settings",
         "text":null,
         "bigText":"Keep this service running, so Appium for Android can properly interact with several system APIs",
         "tickerText":null,
         "subText":null,
         "infoText":null,
         "template":"android.app.Notification$BigTextStyle"
       },
       "userHandle":0,
       "groupKey":"0|io.appium.settings|1|null|10133",
       "overrideGroupKey":null,
       "postTime":1576853518850,
       "key":"0|io.appium.settings|1|null|10133",
       "isRemoved":false
     }
   ]
}

mobile: listSms

Retrieves the list of the most recent SMS properties list via Appium Settings helper. Messages are sorted by date in descending order.

Arguments

NameTypeRequiredDescriptionExample
maxnumbernoThe maximum count of recent messages to retrieve. 100 by default10

Returns

The example output is:

 {
   "items":[
     {
       "id":"2",
       "address":"+123456789",
       "person":null,
       "date":"1581936422203",
       "read":"0",
       "status":"-1",
       "type":"1",
       "subject":null,
       "body":"\"text message2\"",
       "serviceCenter":null
     },
     {
       "id":"1",
       "address":"+123456789",
       "person":null,
       "date":"1581936382740",
       "read":"0",
       "status":"-1",
       "type":"1",
       "subject":null,
       "body":"\"text message\"",
       "serviceCenter":null
     }
   ],
   "total":2
 }

mobile: sensorSet

Emulate changing of sensor values on the connected emulator. This extension does not work on real devices.

Arguments

NameTypeRequiredDescriptionExample
sensorTypestringyesThe set of all supported sensor types could be found in adb-emu-commands.js (look for SENSORS object values). Check the output of sensor status command in the emulator console to see more details on the available sensor typeslight
valuestringyesCheck the output of sensor get <sensorType> command in the emulator console to see the acceptable value format for the given sensor type50

mobile: refreshGpsCache

Sends a request to refresh the GPS cache on the device under test. By default the location tracking is configured for low battery consumption, so you might need to call this extension periodically to get the updated geo location if the actual (or mocked) device location is changed too frequently. The feature only works if the device under test has Google Play Services installed. In case the vanilla LocationManager is used the device API level must be at version 30 (Android R) or higher.

Arguments

NameTypeRequiredDescriptionExample
timeoutMsnumbernoThe maximum number of milliseconds to block until GPS cache is refreshed. If the API call does not receive a confirmation about successful cache refresh within this timeout then an error is thrown. Providing zero or a negative value to it skips waiting completely and does not check for any errors. 20000 ms by default.60000

mobile: setGeolocation

Sets emulated geolocation coordinates on the device under test.

Arguments

NameTypeRequiredDescriptionExample
latitudenumberyesLatitude value32.456
longitudenumberyeslongitude value32.456
altitudenumbernoAltitude value. Zero by default5.678

mobile: getGeolocation

Retrieves current geolocation coordinates from the device under test. If coordinates are mocked/emulated then these coordinates would be returned.

Returned Result

A map with the following entries:

NameTypeDescriptionExample
latitudenumberLatitude value32.456
longitudenumberlongitude value32.456
altitudenumberAltitude value5.678

mobile: resetGeolocation

Resets mocked geolocation provider to the default/system one. Only works for real devices.

mobile: pullFile

Pulls a remote file from the device.

Arguments

NameTypeRequiredDescriptionExample
remotePathstringyesThe full path to the remote file or a specially formatted path, which points to an item inside an app bundle, for example @my.app.id/my/path. It is mandatory for the app bundle to have debugging enabled in order to use the latter remotePath format. If the file with the given name does not exist then an exception will be thrown./sdcard/foo.bar

Returned Result

Base64-encoded string, which represents the content of the remote file.

mobile: pushFile

Pushes a local file to the device.

Arguments

NameTypeRequiredDescriptionExample
remotePathstringyesThe path on the device to where the payload should be written. The value format is similar to the one used in pullFile extension. If the file with the same name already exists then it will be silently overridden./sdcard/foo.bar
payloadstringyesBase64-encoded content of the file to be pushed.QXBwaXVt

mobile: pullFolder

Pulls a remote folder from the device.

Arguments

NameTypeRequiredDescriptionExample
remotePathstringyesSame as for pullFile extension, but should be pointing to a remote folder/sdcard/yolo/

Returned Result

Base64-encoded string, which represents the zipped content of the remote folder.

mobile: deleteFile

Deletes a file on the remote device.

Arguments

NameTypeRequiredDescriptionExample
remotePathstringyesThe full path to the remote file or a file inside an application bundle/sdcard/myfile.txt or @my.app.id/path/in/bundle

mobile: isAppInstalled

Verify whether an application is installed on the device under test.

Arguments

NameTypeRequiredDescriptionExample
appIdstringyesThe identifier of the application package to be checkedmy.app.id
usernumber or stringnoThe user ID for which the package is installed.. The current user is used by default1006

Returned Result

True or false

mobile: queryAppState

Queries the current state of the app.

Arguments

NameTypeRequiredDescriptionExample
appIdstringyesThe identifier of the application package to be checkedmy.app.id

Returned Result

The following numbers could returned:

mobile: activateApp

Activates the given application or launches it if necessary. The action literally simulates clicking the corresponding application icon on the dashboard.

Arguments

NameTypeRequiredDescriptionExample
appIdstringyesThe identifier of the application package to be activatedmy.app.id

mobile: removeApp

Remove the corresponding application if is installed. The call is ignored if the app is not installed.

Arguments

NameTypeRequiredDescriptionExample
appIdstringyesThe identifier of the application package to be removedmy.app.id
timeoutnumbernoThe count of milliseconds to wait until the app is terminated. 20000ms by default.1500, 0
keepDatabooleannoSet to true in order to keep the application data and cache folders after uninstall.true

Returned Result

True is the app has been found on the device and successfully removed. Otherwise false.

mobile: terminateApp

Terminates the app and waits until the app is terminated up to the given timeout by checking the app state to ensure if the app process is actually stopped.

The app state check can be skipped if the given timeout is lower or equal to zero since Espresso driver 2.13.0. The skip helps when you want to terminate the app process but do not want to check the process existence because the app under test may, for example, restart it automatically.

Arguments

NameTypeRequiredDescriptionExample
appIdstringyesThe identifier of the application package to be terminatedmy.app.id
timeoutnumbernoThe count of milliseconds to wait until the app is terminated. 500ms by default.1500, 0

Returned Result

True if the app has been successfully terminated.

mobile: installApp

Installs the given application package to the device under test. It might raise the INSTALL_FAILED_VERSION_DOWNGRADE error if the installation was a version downgrade.

Arguments

NameTypeRequiredDescriptionExample
appPathstringyesThe local .apk(s) path on the server filesystem or a remote url./app/path.apk
timeoutnumbernoThe count of milliseconds to wait until the app is installed.. 6000ms by default.120000
allowTestPackagesbooleannoSet to true in order to allow test packages installation. false by defaulttrue
useSdcardbooleannoSet to true to install the app on sdcard instead of the device memory. false by defaulttrue
grantPermissionsbooleannoSet to true in order to grant all the permissions requested in the application's manifest automatically after the installation is completed under Android 6+. The targetSdkVersion in the application manifest must be greater or equal to 23 and the Android version on the device under test must be greater or equal to Android 6 (API level 23) to grant permissions. Applications whose targetSdkVersion is lower than or equal to 22 must be reisntalled to grant permissions for Android 6+ devices. false by defaulttrue
replacebooleannoSet it to false if you don't want the application to be upgraded/reinstalled if it is already present on the device, but throw an error instead. true by defaultfalse
checkVersionbooleannoSet to true, in order to skip the application installation if the device under test has a greater or equal to the application version. It may help to avoid INSTALL_FAILED_VERSION_DOWNGRADE error and unnecessary installation.true

mobile: clearApp

Deletes all data associated with a package. Calls adb shell pm clear under the hood. The app should be accessible, should not be running, and should exist on the device under test for this extension to work properly.

Arguments

NameTypeRequiredDescriptionExample
appIdstringyesThe identifier of the application package to be clearedmy.app.id

Returned Result

Stdout of the corresponding adb command.

mobile: startActivity

Starts the given activity with intent options, activity options and locale. Activity could only be executed in scope of the current app package.

Arguments

NameTypeRequiredDescriptionExample
appActivitystringyesApplicaiton acitivity identifier to startcom.myapp.myacitivty
localeobjectnoSets the locale for the app under test. It only uses public APIs for its purpose. See https://github.com/libyal/libfwnt/wiki/Language-Code-identifiers to get the list of available language abbreviations.{"language": "zh", "country": "CN", "variant": "Hans"}
optionalIntentArgumentsobjectnoThe mapping of custom options for the intent that is going to be passed to the main app activity. Check Intent Options for more details.{ 'flags': 'ACTIVITY_NEW_TASK', 'action': '<intent_action>', 'className': '<fullyQualifiedAppActivity>', 'es': {'foo': 'bar'} }
optionalActivityArgumentsobjectnoThe mapping of custom options for the main app activity that is going to be started. Check Activity Options for more details.{ 'launchDisplayId': 1 }

mobile: startService

Starts the given service intent.

Arguments

NameTypeRequiredDescriptionExample
intentstringyesThe name of the service intent to start. Only services in the app's under test scope could be started.com.some.package.name/.YourServiceSubClassName
usernumber or stringnoThe user ID for which the service is started. The current user id is used by default1006
foregroundbooleannoSet it to true if your service must be started as foreground service.false

mobile: stopService

Stops the given service intent.

Arguments

NameTypeRequiredDescriptionExample
intentstringyesThe name of the service intent to stop. Only services in the app's under test scope could be stopped.com.some.package.name/.YourServiceSubClassName
usernumber or stringnoThe user ID for which the service is started. The current user id is used by default1006

mobile: broadcast

Send a broadcast Intent. Invokes am broadcast command under the hood.

Arguments

NameTypeRequiredDescriptionExample
intentstringnoThe full name of the intent to broadcastcom.some.package.name/.YourIntentClassName
usernumber or stringnoSpecify which user to send to; if not specified then send to all users. Possible values are all/current/<numeric user id>current
receiverPermissionstringnoRequire receiver to hold the given permissionandroid.permission.READ_PROFILE
allowBackgroundActivityStartsbooleannoThe receiver may start activities even if in the background if set to truefalse
actionstringnoAction name. The actual value for the Activity Manager's -a argument.android.intent.action.MAIN
uristringnoUnified resource identifier. The actual value for the Activity Manager's -d argument.https://appium.io
mimeTypestringnoMime type. The actual value for the Activity Manager's -t argument.application/json
identifierstringnoOptional identifier. The actual value for the Activity Manager's -i argument.my_identifier
categoriesstring or Array<string>noOne or more category names. The actual value(s) for the Activity Manager's -c argument.android.intent.category.LAUNCHER
componentstringnoComponent name. The actual value for the Activity Manager's -n argument.com.myapp/com.myapp.SplashActivity
packagestringnoPackage name. The actual value for the Activity Manager's -p argument.com.myapp
extrasArray<Array<string>>noOptional intent arguments. Must be represented as an array of arrays, where each subarray item contains two (only in case it no value is required for the given type) or three string items: value type, key (variable name) and the value itself. Supported value types are: s: string. Value must be a valid string; sn: null. Value is ignored for this type; z: boolean. Value must be either true or false; i: integer. Value must be a valid 4-byte integer number; l: long. Value must be a valid 8-byte long number; f: float: Value must be a valid float number; u: uri. Value must be a valid uniform resource identifier string; cn: component name. Value must be a valid component name string; ia: Integer[]. Value must be a string of comma-separated integers; ial: List<Integer>. Value must be a string of comma-separated integers; la: Long[]. Value must be a string of comma-separated long numbers; lal: List<Long>. Value must be a string of comma-separated long numbers; fa: Float[]. Value must be a string of comma-separated float numbers; fal: List<Float>. Value must be a string of comma-separated float numbers; sa: String[]. Value must be comma-separated strings. To embed a comma into a string escape it using ","; sal: List<String>. Value must be comma-separated strings. To embed a comma into a string, escape it using ","[['s', 'varName1', 'My String1'], ['s', 'varName2', 'My String2'], ['ia', 'arrName', '1,2,3,4']]
flagsstringnoIntent startup-specific flags as a hexadecimal string. Check Intent documentation for the list of available flag values (constants starting with FLAG_ACTIVITY_). Flag values could be merged using the logical 'or' operation.0x10200000 is the combination of two flags: 0x10000000 FLAG_ACTIVITY_NEW_TASK `

Returned Result

The actual stdout of the downstream am command.

mobile: getDeviceTime

Retrieves the current device's timestamp.

Arguments

NameTypeRequiredDescriptionExample
formatstringnoThe set of format specifiers. Read https://momentjs.com/docs/ to get the full list of supported datetime format specifiers. The default format is YYYY-MM-DDTHH:mm:ssZ, which complies to ISO-8601YYYY-MM-DDTHH:mm:ssZ

Returns

The device timestamp string formatted according to the given specifiers

mobile: setDate

Set the given date for a picker control. Invokes https://developer.android.com/reference/androidx/test/espresso/contrib/PickerActions#setdate under the hood.

Arguments

NameTypeRequiredDescriptionExample
yearintyesThe year to set2020
monthOfYearintyesThe number of the month to set3
dayOfMonthintyesThe number of the day to set20

mobile: setTime

Set the given time for a picker control. Invokes https://developer.android.com/reference/androidx/test/espresso/contrib/PickerActions#settime under the hood.

Arguments

NameTypeRequiredDescriptionExample
hoursintyesHour to set in range 0..2314
minutesintyesMinute to set in range 0..5915

mobile: flashElement

Highlights the given element in the UI by adding flashing to it

Arguments

NameTypeRequiredDescriptionExample
elementId (element before v2.29)stringyesUDID of the element to perform the action on.123456-7890-3453-24234243
durationMillisintnoDuration of single flashing sequence, 30 ms by default50
repeatCountintnoCount of repeats, 15 times by default10

mobile: dismissAutofill

Dismisses autofill picker if it is visible on the screen.

mobile: backdoor

Gives a possibility to invoke methods from your application under test.

Arguments

NameTypeRequiredDescriptionExample
elementIdstringyes if target is set to elementUDID of the element to perform the action on.123456-7890-3453-24234243
targetstringyesSelect a target for the backdoor mathod execution: activity, application, elementactivity
methodsArray<Map>yesMethods chain to executeSee Backdoor Extension Usage

Returns

The result of the last method in the chain

mobile: uiautomator

Allows to execute a limited set of UiAutomator commands to allow out-of-app interactions with accessibility elements.

Arguments

NameTypeRequiredDescriptionExample
strategystringyesUiAutomator element location strategy. The following strategies are supported: "clazz", "res", "text", "textContains", "textEndsWith", "textStartsWith", "desc", "descContains", "descEndsWith", "descStartsWith", "pkg"desc
locatorstringyesValid UiObject2 locator value for the given strategy'my description'
actionstringyesThe action name to perform on the found element. The following actions are supported: "click", "longClick", "getText", "getContentDescription", "getClassName", "getResourceName", "getVisibleBounds", "getVisibleCenter", "getApplicationPackage", "getChildCount", "clear", "isCheckable", "isChecked", "isClickable", "isEnabled", "isFocusable", "isFocused", "isLongClickable", "isScrollable", "isSelected"isEnabled
indexintnoIf the given locator matches multiple elements then only the element located by this index will be selected for the interaction, otherwise the method will be applied to all found elements. Indexing starts from zero1

Returns

The result of the selected action applied to found elements. If index is provided then the array will only contain one item. If the index is greater than the count of found elements then an exception will be thrown.

mobile: uiautomatorPageSource

Allows to retrieve accessibility elements hierarchy tree with UiAutomator framework. The extension calls dumpWindowHierarchy under the hood.

Returns

The UI accessibility hierarchy represented as XML document.

mobile: webAtoms

Allows to run a chain of Espresso web atoms on a web view element.

Arguments

NameTypeRequiredDescriptionExample
webviewElstringyesThe UDID of the destination web view element123456-7890-3453-24234243
forceJavascriptEnabledbooleanyesIf webview disables javascript then webatoms won't work. Setting this argument to true enforces javascript to be enabled.true
methodChainArray<Map>yesChain of atoms to execute. Each item in the chain must have the following properties: name (must be one of WebInteraction action names) and atom. atom is a map with two entries: name (must be one of DriverAtoms method names) and args (must be an array of the corresponding method values).[{"name": "methodName", "atom": {"name": "atomName", "args": ["arg1", "arg2", ...]}}, ...]

Returns

Chain items are executed sequentially and the next item is executed on the result of the previous item. The final result is returned to the caller.

mobile: registerIdlingResources

Registers one or more idling resources.

Arguments

NameTypeRequiredDescriptionExample
classNamesstringyesComma-separated list of idling resources class names. Each name must be a full-qualified java class name. Each class in the app source must implement a singleton pattern and have a static getInstance() method returning the class instance, which implements androidx.test.espresso.IdlingResource interface. Read Integrate Espresso Idling Resources in your app to build flexible UI tests for more details on how to design and use idling resources concept in Espresso.io.appium.espressoserver.lib.MyIdlingResource

mobile: unregisterIdlingResources

Unregisters one or more idling resources.

Arguments

NameTypeRequiredDescriptionExample
classNamesstringyesComma-separated list of idling resources class names. Each name must be a full-qualified java class name. Each class in the app source must implement a singleton pattern and have a static getInstance() method returning the class instance, which implements androidx.test.espresso.IdlingResource interface. Read Integrate Espresso Idling Resources in your app to build flexible UI tests for more details on how to design and use idling resources concept in Espresso.io.appium.espressoserver.lib.MyIdlingResource

mobile: listIdlingResources

Lists all the previously registered idling resources.

Returns

List of fully qualified class names of currently registered idling resources or an empty list if no resources have been registered yet.

mobile: waitForUIThread

mobile: unlock

Unlocks the device if it is locked. Noop if the device's screen is not locked.

Arguments

NameTypeRequiredDescriptionExample
keystringyesThe unlock key. See the documentation on appium:unlockKey capability for more details12345
typestringyesThe unlock type. See the documentation on appium:unlockType capability for more detailspassword
timeoutMsnumbernoUnlock timeout. See the documentation on appium:unlockSuccessTimeout capability for more details5000

mobile: isLocked

Determine whether the device is locked.

Returned Result

Either true or false

mobile: lock

Lock the device (and optionally unlock it after a certain amount of time). Only simple (e.g. without a password) locks are supported.

Arguments

NameTypeRequiredDescriptionExample
secondsnumberstringnoThe number of seconds after which to unlock the device. Set to 0 or leave it empty to require manual unlock (e.g. do not block and automatically unlock afterwards).

mobile: startMediaProjectionRecording

Starts a new recording of the device activity using Media Projection API. This API is available since Android 10 (API level 29) and allows to record device screen and audio in high quality. Video and audio encoding is done by Android itself. The recording is done by Appium Settings helper.

Arguments

NameTypeRequiredDescriptionExample
resolutionstringnoThe resolution of the resulting video, which usually equals to Full HD 1920x1080 on most phones, however you could change it to one of the following supported resolutions: "1920x1080", "1280x720", "720x480", "320x240", "176x144"1280x720
maxDurationSecnumbernoThe maximum number of seconds allowed for the recording to run. 900 seconds by default (15 minutes)300
prioritystringnoRecording thread priority is set to maximum (high) by default. However if you face performance drops during testing with recording enabled, you could reduce the recording priority to normal or low.low
filenamestringnoYou can type recording video file name as you want, but recording currently supports only "mp4" format so your filename must end with ".mp4". An invalid file name will fail to start the recording. If not provided then the current timestamp will be used as file name.screen.mp4

Returned Result

true if a new recording has successfully started. false if another recording is currently running.

mobile: isMediaProjectionRecordingRunning

Check if a media projection recording is currently running

Returned Result

true if a recording is running.

mobile: stopMediaProjectionRecording

Stops a recording and retrieves the recently recorded media. If no recording has been started before then an error is thrown. If the recording has been already finished before this API has been called then the most recent recorded media is returned.

Arguments

NameTypeRequiredDescriptionExample
remotePathstringnoThe path to the remote location, where the resulting video should be uploaded. The following protocols are supported: http/https, ftp. Null or empty string value (the default setting) means the content of resulting file should be encoded as Base64 and passed as the endpoont response value. An exception will be thrown if the generated media file is too big to fit into the available process memory.https://myserver.com/upload
userstringnoThe name of the user for the remote authentication.admin
passstringnoThe password for the remote authentication.pa$$w0rd
methodstringnoThe http multipart upload method name. The 'PUT' one is used by default.POST
headersMap<string, string>noAdditional headers mapping for multipart http(s) uploads{'Agent': '007'}
fileFieldNamestringnoThe name of the form field, where the file content BLOB should be stored for http(s) uploads. file by defaultblob
formFieldsMap<string, string> or Array<Pair>noAdditional form fields for multipart http(s) uploads.{'name': 'yolo.mp4'}

Returned Result

Base64-encoded content of the recorded media file if remotePath argument is falsy or an empty string.

mobile: getClipboard

Retrieves the plaintext content of the device's clipboard. Available since driver version 2.44

Returned Result

Base64-encoded content of the clipboard or an empty string if the clipboard is empty.

mobile: setClipboard

Allows to set the plain text content of the device's clipboard. Available since driver version 2.44

Arguments

NameTypeRequiredDescriptionExample
contentstringyesBase64-encoded clipboard payload.YXBwaXVt
contentTypestringnoThe only supported and the default value is plaintextplaintext
lablestringnoOptinal label to identify the current clipboard payload.yolo

mobile: hideKeyboard

Tries to hide the on-screen keyboard. Throws an exception if the keyboard cannot be hidden. Does nothing if the keyboard is already hidden.

Returned Result

true if the keyboard was successfully hidden or false if it was already invisible.

mobile: isKeyboardShown

Checks if the system on-screen keyboard is visible.

Returned Result

true if the keyboard is visible

mobile: pressKey

Emulates single key press on the key with the given code. Available since driver version 2.23

Arguments

NameTypeRequiredDescriptionExample
keycodenumberyesA valid Android key code. See KeyEvent documentation for the list of available key codes0x00000099 (which is KEYCODE_NUMPAD_9)
metastatenumbernoAn integer in which each bit set to 1 represents a pressed meta key. See KeyEvent documentation for more details.0x00000010 (which is META_ALT_LEFT_ON)
flagsnumbernoFlags for the particular key event. See KeyEvent documentation for more details.0x00000001 (which is FLAG_WOKE_HERE)
isLongPressbooleannoWhether to emulate long key press. false by default.true

mobile: getConnectivity

Returns connectivity states for different services

Arguments

NameTypeRequiredDescriptionExample
servicesstring or string[]noOne or more services to get the connectivity for. Supported service names are: wifi, data, airplaneMode. If no service names are provided then all supported names are assumed by default.[wifi, data]

Returned Result

A map is returned containing the following possible items (depending on which values have been passed to services argument):

NameTypeDescription
wifibooleanTrue if wifi is enabled
databooleanTrue if mobile data connection is enabled
airplaneModebooleanTrue if Airplane Mode is enabled

mobile: setConnectivity

Set the connectivity state for different services. At least one valid service name must be provided in arguments. Missing values tell the driver to not change the corresponding service's state.

Note

Switching Wi-Fi and mobile data states reliably work on emulators for all Android versions. Real devices support proper state switching only since Android 11.

Note

Espresso REST server app is running on the device under test and might be terminated/disconnected by Android thus failing the driver session as a result of using this API. The only way to restore the session would be to quit it after the network state is changed and then reopen it with noReset capability being set to true when the connectivity is restored.

Arguments

NameTypeRequiredDescriptionExample
wifiboooleannoEither to enable or disable Wi-Fi.false
databoooleannoEither to enable or disable mobile data.false
airplaneModeboooleannoEither to enable or disable Airplane Mode.false

mobile: getAppStrings

Retrieves string resources for the given app language. An error is thrown if strings cannot be fetched or no strings exist for the given language abbreviation. Available since driver version 2.23

Arguments

NameTypeRequiredDescriptionExample
languagestringnoThe language abbreviation to fetch app strings mapping for. If no language is provided then strings for the default language on the device under test would be returnedfr

Returned Result

App strings map, where keys are resource identifiers.

mobile: backgroundApp

Puts the app to the background and waits the given number of seconds. Then restores the app if necessary. The call is blocking. Available since driver version 2.23

Arguments

NameTypeRequiredDescriptionExample
secondsnumbernoThe amount of seconds to wait between putting the app to background and restoring it. Any negative value means to not restore the app after putting it to background (the default behavior).5

mobile: getCurrentActivity

Returns the name of the currently focused app activity. Available since driver version 2.23

Returned Result

The activity class name. Could be null

mobile: getCurrentPackage

Returns the name of the currently focused app package identifier. Available since driver version 2.23

Returned Result

The package class name. Could be null

mobile: getDisplayDensity

Returns the display density value measured in DPI. Available since driver version 2.23

Returned Result

The actual DPI value as integer number

mobile: getSystemBars

Returns properties of various system bars. Available since driver version 2.23

Returned Result

A dictionary whose entries are:

Values are dictionaries with the following properties:

mobile: fingerprint

Emulate fingerprint on Android Emulator. Only works on API 23+. Available since driver version 2.23

Arguments

NameTypeRequiredDescriptionExample
fingerprintIdnumberyesThe value is the id for the finger that was "scanned". It is a unique integer that you assign for each virtual fingerprint. When the app is running you can run this same command each time the emulator prompts you for a fingerprint, you can run the adb command and pass it the fingerprintId to simulate the fingerprint scan.1

mobile: sendSms

Emulate sending an SMS to the given phone number. Only works on emulators. Available since driver version 2.23

Arguments

NameTypeRequiredDescriptionExample
phoneNumberstringyesThe phone number to send SMS to0123456789
messagestringyesThe SMS message payloadHello

mobile: gsmCall

Emulate a GSM call to the given phone number. Only works on emulators. Available since driver version 2.23

Arguments

NameTypeRequiredDescriptionExample
phoneNumberstringyesThe phone number to call to0123456789
actioncall or accept or cancel or holdyesOne of possible actions to takeaccept

mobile: gsmSignal

Emulate GSM signal strength change event. Only works on emulators. Available since driver version 2.23

Arguments

NameTypeRequiredDescriptionExample
strength0 or 1 or 2 or 3 or 4yesOne of possible signal strength values, where 4 is the best signal.3

mobile: gsmVoice

Emulate GSM voice state change event. Only works on emulators. Available since driver version 2.23

Arguments

NameTypeRequiredDescriptionExample
stateon or off or denied or searching or roaming or home or unregisteredyesVoice stateoff

mobile: powerAC

Emulate AC power state change. Only works on emulators. Available since driver version 2.23

Arguments

NameTypeRequiredDescriptionExample
stateon or offyesAC Power stateoff

mobile: powerCapacity

Emulate power capacity change. Only works on emulators. Available since driver version 2.23

Arguments

NameTypeRequiredDescriptionExample
percent0 to 100yesPercentage value in range [0, 100]50

mobile: networkSpeed

Emulate different network connection speed modes. Only works on emulators. Available since driver version 2.23

Arguments

NameTypeRequiredDescriptionExample
speedgsm or scsd or gprs or edge or umts or hsdpa or lte or evdo or fullyesMobile network speed mode nameedge

mobile: replaceElementValue

Sends a text to the given element by replacing its previous content. Available since driver version 2.23

Arguments

NameTypeRequiredDescriptionExample
elementIdstringyesHexadecimal identifier of the destination text input123456-3456-3435-3453453
textstringyesThe text to enter. It could also contain Unicode characters. If the text ends with \\n (the backslash must be escaped, so the char is NOT translated into 0x0A) then the Enter key press is going to be emulated after it is entered (the \\n substring itself will be cut off from the typed text).yolo

mobile: toggleGps

Switches GPS setting state. This API only works reliably since Android 12 (API 31). Available since driver version 2.23

mobile: isGpsEnabled

Returns true if GPS is enabled on the device under test. Available since driver version 2.23

mobile: getPerformanceDataTypes

Fetches the list of supported perfomance data types that could be used as dataType argument value to mobile: getPerformanceData extension. Available since driver version 2.23

Returned Result

List of strings, where each item is data type name.

mobile: getPerformanceData

Retrieves performance data about the given Android subsystem. The data is parsed from the output of the dumpsys utility. Available since driver version 2.23

Arguments

NameTypeRequiredDescriptionExample
packageNamestringyesThe name of the package identifier to fetch the data forcom.myapp
dataTypestringyesOne of supported subsystem names. The full list of supported values is returned by mobile: getPerformanceDataTypes extension.batteryinfo or cpuinfo or memoryinfo or networkinfo

Returned Result

The output depends on the selected subsystem. It is organized into a table, where the first row represents column names and the following rows represent the sampled data for each column. Example output for different data types:

[
  [power],
  [23]
]
[
  [totalPrivateDirty, nativePrivateDirty, dalvikPrivateDirty, eglPrivateDirty, glPrivateDirty, totalPss, nativePss, dalvikPss, eglPss, glPss, nativeHeapAllocatedSize, nativeHeapSize],
  [18360, 8296, 6132, null, null, 42588, 8406, 7024, null, null, 26519, 10344]
]
// emulator
[
  [bucketStart, activeTime, rxBytes, rxPackets, txBytes, txPackets, operations, bucketDuration],
  [1478091600000, null, 1099075, 610947, 928, 114362, 769, 0, 3600000],
  [1478095200000, null, 1306300, 405997, 509, 46359, 370, 0, 3600000]
]
// real devices
[
  [st, activeTime, rb, rp, tb, tp, op, bucketDuration],
  [1478088000, null, null, 32115296, 34291, 2956805, 25705, 0, 3600],
  [1478091600, null, null, 2714683, 11821, 1420564, 12650, 0, 3600],
  [1478095200, null, null, 10079213, 19962, 2487705, 20015, 0, 3600],
  [1478098800, null, null, 4444433, 10227, 1430356, 10493, 0, 3600]
]
[
  [user, kernel],
  [0.9, 1.3]
]

mobile: screenshots

Retrieves a screenshot of each display available to Android. This functionality is only supported since Android 10.

Arguments

NameTypeRequiredDescriptionExample
displayIdnumber or stringnoDisplay identifier to take a screenshot for. If not provided then all display screenshots are going to be returned. If no matches were found then an error is thrown. Actual display identifiers could be retrived from the adb shell dumpsys SurfaceFlinger --display-id command output.1

Returns

A dictionary where each key is the diplay identifier and the value has the following keys:

mobile: statusBar

Performs commands on the system status bar. A thin wrapper over adb shell cmd statusbar CLI. Works on Android 8 (Oreo) and newer. Available since driver version 2.23

Arguments

NameTypeRequiredDescriptionExample
commandstringyesOne of supported status bar commands.expandNotifications
componentstringnoThe name of the tile component. It is only required for (add|remove|click)Tile commands.com.package.name/.service.QuickSettingsTileComponent

Status Bar Commands

Returned Result

The actual downstream command output. It depends on the selected command and might be empty.

mobile: setUiMode

Set the device UI appearance. A thin wrapper over adb shell cmd uimode CLI. Works on Android 10 and newer. Available since driver version 2.29

Arguments

NameTypeRequiredDescriptionExample
modestringyesOne of the supported UI mode names: night or car.night
valuestringyesThe actual mode value to set. Supported values for different UI modes are: night: yes,no,auto,custom_schedule,custom_bedtime, car: yes,no. For example, to switch the device UI to the dark mode you should set mode to night and value to yes, or to no in order to switch back to the light mode.yes

mobile: getUiMode

Gets the device UI appearance for the given mode. A thin wrapper over adb shell cmd uimode CLI. Works on Android 10 and newer. Available since driver version 2.29

Arguments

NameTypeRequiredDescriptionExample
modestringyesOne of the supported UI mode names: night or car.night

mobile: startLogsBroadcast

Starts Android logcat broadcast websocket on the same host and port where Appium server is running at /ws/session/:sessionId:/appium/logcat endpoint. The method will return immediately if the web socket is already listening. Each connected webcoket listener will receive logcat log lines as soon as they are visible to Appium. Read Using Mobile Execution Commands to Continuously Stream Device Logs with Appium for more details.

mobile: stopLogsBroadcast

Stops the previously started logcat broadcasting websocket server. This method will return immediately if no server is running. Read Using Mobile Execution Commands to Continuously Stream Device Logs with Appium for more details.

mobile: injectEmulatorCameraImage

Simulates an image injection into the VirtualScene emulator camera background. Calls to this extension should seamlessly change the foreground picture in the VirtualScene emulator camera view to the supplied one. This extension could, for example, be useful if you need to verify QR codes scanning by the application under test. Available since driver version 2.43.0

Arguments

NameTypeRequiredDescriptionExample
payloadstringyesA valid base64-encoded .PNG image payload. Other image formats are not supported. This image will be shown on the virtual scene foreground as soon as you open a camera client app.iVBORw0KGgoAAAANSUh...

Required Preconditions

This feature only works on Android emulators. It is mandatory to provide a value (it could also be an empty map to use defaults) to the appium:injectedImageProperties capability in order to prepare the emulator for image injection if this extension is used on a newly created or resetted device.

There is also a possiblity to perform a manual configuration of the necessary preconditions if you don't want to restart the emulator on session startup. For that replace the content of the Toren1BD.posters file located in $ANDROID_HOME/emulator/resources folder with the following text:

poster wall
size 2 2
position -0.807 0.320 5.316
rotation 0 -150 0
default poster.png

poster table
size 1 1
position 0 0 -1.5
rotation 0 0 0

Save the changed file and re(start) the emulator to pick up the changes. You may also customize values for different image properties under poster table in the above text snippet.

Backdoor Extension Usage

Espresso driver allows to directly invoke a method from your application under test using mobile: backdoor extension. If target is set to application then methods will be invoked on the application class. If target is set to activity then methods will be invoked on the current application activity. If target is set to element then methods will be invoked on the selected view element. Only 'public' methods can be invoked ('open' modifier is necessary in Kotlin). The following primitive types are supported for method arguments: "int", "boolean", "byte", "short", "long", "float", "char". Object wrappers over primitive types with fully qualified names "java.lang.*" are also supported: "java.lang.CharSequence", "java.lang.String", "java.lang.Integer", "java.lang.Float", "java.lang.Double", "java.lang.Boolean", "java.lang.Long", "java.lang.Short", "java.lang.Character", etc.

For example, in the following arguments map

{
   "target": "activity",
   "methods":
   [
     {
       "name": "someMethod",
     },
     {
       "name": "anotherMethod",
       "args": [
         {"value": "foo", "type": "java.lang.CharSequence"},
         {"value": 1, "type": "int"}
       ]
     }
   ]
}

the anotherMethod will be called on the object returned by someMethod, which has no arguments and which was executed on the current activity instance. Also anotherMethod accepts to arguments of type java.lang.CharSequence and int. The result of anotherMethod will be serialized and returned to the client.

Parallel Tests

It is possible to execute tests in parallel using Espresso driver. Appium allows to do this on per-process (multiple server processes running on different ports managing single session) or per-request basis (single server process managing multiple sessions, more preferable, uses less resources and ensures better control over running sessions). Check Parallel Android Tests article for more details.

Note If you are not going to run your tests in parallel then consider enabling the --session-override Appium server argument. It forces the server to close all pending sessions before a new one could be opened, which allows you to avoid possible issues with such sessions silently running/expiring in the background.

Troubleshooting

Contributing

Contents of Repo

Running

Tests