Documente Academic
Documente Profesional
Documente Cultură
In this document
1. Project and File Structure
2. Android Build System
3. Debug and Performance
4. Installation, Setup, and Update Management
5. Other Highlights
See also
1. IntelliJ FAQ on migrating to IntelliJ IDEA
Android Studio is the official IDE for Android application development, based on IntelliJ
IDEA. On top of the capabilities you expect from IntelliJ, Android Studio offers:
If you're new to Android Studio or the IntelliJ IDEA interface, this page provides an
introduction to some key Android Studio features.
For specific Android Studio how-to documentation, see the pages in the Workflow section,
such as Managing Projects from Android Studio and Building and Running from Android
Studio.
By default, Android Studio displays your profile files in the Android project view. This view
shows a flattened version of your project's structure that provides quick access to the key
source files of Android projects and helps you work with the new Gradle-based build system.
The Android project view:
Groups the build files for all modules at the top level of the project hierarchy.
Shows the most important source directories at the top level of the module hierarchy.
Groups all the manifest files for each module.
Shows resource files from all Gradle source sets.
Groups resource files for different locales, orientations, and screen types in a single
group per resource type.
The Android project view shows all the build files at the top level of the project hierarchy
under Gradle Scripts. Each project module appears as a folder at the top level of the project
hierarchy and contains these three elements at the top level:
Note: The project structure on disk differs from this flattened representation. To switch to
back the segregated project view, select Project from the Project
When you use the Project view of a new project in Android Studio, you should notice that the
project structure appears different than you may be used to in Eclipse. Each instance of
Android Studio contains a project with one or more application modules. Each application
module folder contains the complete source sets for that module, including src/main and
src/androidTest directories, resources, build file and the Android manifest. For the most
part, you will need to modify the files under each module's src/main directory for source
code updates, the gradle.build file for build specification and the files under
src/androidTest directory for test case creation.
For more information, see IntelliJ project organization and Managing Projects.
You can quickly add new code and resource files by clicking the appropriate directory in the
Project pane and pressing ALT + INSERT on Windows and Linux or COMMAND + N on Mac.
Based on the type of directory selected, Android Studio offers to create the appropriate file
type.
For example, if you select a layout directory, press ALT + INSERT on Windows, and select
Layout resource file, a dialog opens so you can name the file (you can exclude the .xml
suffix) and choose a root view element. The editor then switches to the layout design editor
so you can begin designing your layout.
The Android build system is the toolkit you use to build, test, run and package your apps.
This build system replaces the Ant system used with Eclipse ADT. It can run as an integrated
tool from the Android Studio menu and independently from the command line. You can use
the features of the build system to:
The flexibility of the Android build system enables you to achieve all of this without
modifying your app's core source files. To build an Android Studio project, see Building and
Running from Android Studio. To configure custom build settings in an Android Studio
project, see Configuring Gradle Builds.
With the Android build system, the applicationId attribute is used to uniquely identify
application packages for publishing. The application ID is set in the android section of the
build.gradle file.
android {
compileSdkVersion 19
buildToolsVersion "19.1"
defaultConfig {
applicationId "com.example.my.app"
minSdkVersion 15
targetSdkVersion 19
versionCode 1
versionName "1.0"
}
...
Note: The applicationId is specified only in your build.gradle file, and not in the
AndroidManifest.xml file.
When using build variants, the build system enables you to to uniquely identify different
packages for each product flavors and build types. The application ID in the build type is
added as a suffix to those specified for the product flavors.
productFlavors {
pro {
applicationId = "com.example.my.pkg.pro"
}
free {
applicationId = "com.example.my.pkg.free"
}
}
buildTypes {
debug {
applicationIdSuffix ".debug"
}
}
....
The package name must still be specified in the manifest file. It is used in your source code to
refer to your R class and to resolve any relative activity/service registrations.
package="com.example.app">
Note: If you have multiple manifests (for exmample, a product flavor specific manifest
and a build type manifest), the package name is optional in those manifests. If it is
specified in those manifests, the package name must be identical to the package name
specified in the manifest in the src/main/ folder.
For more information about the build files and process, see Build System Overview.
AVD Manager has updated screens with links to help you select the most popular device
configurations, screen sizes and resolutions for your app previews.
Click the Android Virtual Device Manager in the toolbar to open it and create new
virtual devices for running your app in the emulator.
The AVD Manager comes with emulators for Nexus 6 and Nexus 9 devices and also
supports creating custom Android device skins based on specific emulator properties
and assigning those skins to hardware profiles. Android Studio installs the Intel® x86
Hardware Accelerated Execution Manager (HAXM) emulator accelerator and creates a
default emulator for quick app prototyping.
Memory Monitor
Android Studio provides a memory monitor view so you can more easily monitor your
app's memory usage to find deallocated objects, locate memory leaks and track the
amount of memory the connected device is using. With your app running on a device or
emulator, click the Memory Monitor tab in the lower right corner to launch the
memory monitor.
Figure 4. Memory Monitor
Hovering over a Lint error displays the full issue explanation inline for easy error
resolution. There is also a helpful hyperlink at the end of the error message for
additional error information.
With Android Studio, you can run Lint for a specific build variant, or for all build
variants. You can configure Lint by adding a lintOptions property to the Android
settings in the build.gradle file.
android {
lintOptions {
// set to true to turn off analysis progress reporting by lint
quiet true
// if true, stop the gradle build if errors are found
abortOnError false
// if true, only report errors
ignoreWarnings true
Easily select and preview layout changes for different device images, display densities,
UI modes, locales, and Android versions (multi-API version rendering).
Figure 7. API Version Rendering
From the Design View, you can drag and drop elements from the Palette to the Preview
or Component Tree. The Text View allows you to directly edit the XML settings, while
previewing the device display.
Log messages
When you build and run your app with Android Studio, you can view adb and device
log messages (logcat) in the DDMS pane by clicking Android at the bottom of the
window.
If you want to debug your app with the Android Debug Monitor, you can launch it by
clicking Monitor in the toolbar. The Debug Monitor is where you can find the
complete set of DDMS tools for profiling your app, controlling device behaviors, and
more. It also includes the Hierarchy Viewer tools to help optimize your layouts.
An updated installation and setup wizards walk you through a step-by-step installation and
setup process as the wizard checks for system requirements, such as the Java Development
Kit (JDK) and available RAM, and then prompts for optional installation options, such as the
Intel® HAXM emulator accelerator.
An updated setup wizard walks you through the setup processes as the wizard updates your
system image and emulation requirements, such GPU, and then creates an optimized default
Android Virtual Device (AVD) based on Android 5 (Lollipop) for speedy and reliable
emulation.
Android Studio supports new templates for Google Services and expands the availabe device
types.
For easy cross-platform development, the Project Wizard provides new templates for creating
your apps for Android Wear and TV.
Figure 9. New Form Factors
During app creation, the Project Wizard also displays an API Level dialog to help you choose
the best minSdkVersion for your project.
Quick cloud integration. Using Google App Engine to connect to the Google cloud and create
a cloud end-point is as easy as selecting File > New Module > App Engine Java Servlet
Module and specifying the module, package, and client names.
Figure 10. Setup Wizard
Update channels
Android Studio provides four update channels to keep Android Studio up-to-date based on
your code-level preference:
Canary channel: Canary builds provide bleeding edge releases, updated about weekly. While
these builds do get tested, they are still subject to bugs, as we want people to see what's
new as soon as possible. This is not recommended for production.
Dev channel: Dev builds are hand-picked older canary builds that survived the test of time.
They are updated roughly bi-weekly or monthly.
Beta channel: Beta builds are used for beta-quality releases before a production release.
Stable channel: Used for stable, production-ready versions.
By default, Android Studio uses the Stable channel. Use File > Settings > Updates to change
your channel setting.
Other Highlights
Translation Editor
Multi-language support is enhanced with the Translation Editor plugin so you can easily add
locales to the app's translation file. Color codes indicate whether a locale is complete or still
missing string translations. Also, you can use the plugin to export your strings to the Google
Play Developer Console for translation, then download and import your translations back into
your project.
To access the Translation Editor, open a strings.xml file and click the Open Editor link.
Android Studio supports the new Material Design themes, widgets, and graphics, such as
shadow layers and API version rendering (showing the layout across different UI versions).
Also, the new drawable XML tags and attributes, such as <ripple> and <animated-selector>,
are supported.
Clicking Import Samples from the File menu or Welcome page provides seamless access to
Google code samples on GitHub.
Figure 12. Code Sample Access
Except as noted, this content is licensed under Creative Commons Attribution 2.5. For details and
restrictions, see the Content License.
See also
1. Download Android Studio
2. IntelliJ IDEA Android Tutorials
3. IntelliJ FAQ on migrating to IntelliJ IDEA
If you're unfamiliar with using Android Studio and the IntelliJ IDEA interface, this page
provides some tips to help you get started with some of the most common tasks and
productivity enhancements.
Productivity Features
Android Studio includes a number of features to help you be more productive in your coding.
This section notes a few of the key features to help you work quickly and efficiently.
Smart Rendering
With smart rendering, Android Studio displays links for quick fixes to rendering errors. For
example, if you add a button to the layout without specifying the width and height atttributes,
Android Studio displays the rendering message Automatically add all missing attributs.
Clicking the message adds the missing attributes to the layout.
While debugging, you can now right-click on bitmap variables in your app and invoke View
Bitmap. This fetches the associated data from the debugged process and renders the bitmap in
the debugger.
Figure 1. Bitmap Rendering
When checking build results, you can filter messages by message type to quickly locate
messages of interest.
Creating layouts
Android Studio offers an advanced layout editor that allows you to drag-and-drop widgets
into your layout and preview your layout while editing the XML.
While editing in the Text view, you can preview the layout on devices by opening the
Preview pane available on the right side of the window. Within the Preview pane, you can
modify the preview by changing various options at the top of the pane, including the preview
device, layout theme, platform version and more. To preview the layout on multiple devices
simultaneously, select Preview All Screen Sizes from the device drop-down.
You can switch to the graphical editor by clicking Design at the bottom of the window.
While editing in the Design view, you can show and hide the widgets available to drag-and-
drop by clicking Palette on the left side of the window. Clicking Designer on the right side
of the window reveals a panel with a layout hierarchy and a list of properties for each view in
the layout.
Working with IntelliJ
This section list just a few of the code editing practices you should consider using when
creating Android Studio apps.
For complete user documentation for the IntelliJ IDEA interface (upon which Android Studio
is based), refer to the IntelliJ IDEA documentation.
External annotations
Specify annotations within the code or from an external annotation file. The Android Studio
IDE keeps track of the restrictions and validates compliance, for example setting the data
type of a string as not null.
For quick fixes to coding errors, the IntelliJ powered IDE implements the Alt + Enter key
binding to fix errors (missing imports, variable assignments, missing references, etc) when
possible, and if not, suggest the most probable solution.
The Ctrl + D key binding is great for quickly duplicating code lines or fragments. Simply
select the desired line or fragment and enter this key binding.
Navigate menu
In case you're not familiar with an API class, file or symbol, the Navigate menu lets you jump
directly to the class of a method or field name without having to search through individual
classes.
Inspection scopes
Scopes set the color of code segments for easy code identification and location. For example,
you can set a scope to identify all code related to a specific action bar.
External annotations
Specify annotations within the code or from an external annotation file. The Android Studio
IDE keeps track of the restrictions and validates compliance, for example setting the data
type of a string as not null.
Injecting languages
With language injection, the Android Studio IDE allows you to work with islands of different
languages embedded in the source code. This extends the syntax, error highlighting and
coding assistance to the embedded language. This can be especially useful for checking
regular expression values inline, and validating XML and SQL statments.
Code folding
This allows you to selectively hide and display sections of the code for readability. For
example, resource expressions or code for a nested class can be folded or hidden in to one
line to make the outer class structure easier to read. The inner clas can be later expanded for
updates.
When referencing images and icons in your code, a preview of the image or icon appears (in
actual size at different densities) in the code margin to help you verify the image or icon
reference. Pressing F1 with the preview image or icon selected displays resource asset details,
such as the dp settings.
Quick F1 documentation
You can now inspect theme attributes using View > Quick Documentation (F1), see the
theme inheritance hierarchy, and resolve values for the various attributes.
If you invoke View > Quick Documentation (usually bound to F1) on the theme attribute
?android:textAppearanceLarge, you will see the theme inheritance hierarchy and resolved
values for the various attributes that are pulled in.
You can now inspect theme attributes using View > Quick Documentation F1, see the theme
inheritance hierarchy, and resolved values for the various attributes.
Keyboard Commands
Note: This section lists Android Studio keyboard shortcuts for the default keymap. To change
the default keymap on Windows and Linux, go to File > Settings > Keymap. To change the
default keymap on Mac OS X, go to Android Studio > Preferences > Keymap.
Note: If you're using Mac OS X, update your keymap to use the Mac OS X 10.5+ version
keymaps under Android Studio > Preferences > Keymap.
Table 1. Programming key commands
For a complete keymap reference guide, see the IntelliJ IDEA documentation.
Except as noted, this content is licensed under Creative Commons Attribution 2.5. For details
and restrictions, see the Content License.
However, you may choose to develop with another IDE or a simple text editor and invoke the
tools on the command line or with scripts. This is a less streamlined way to develop because
you will sometimes have to call command line tools manually, but you will have access to the
same number of features that you would have in Android Studio.
Figure 1. The development process for Android applications.
App Workflow
The basic steps for developing applications (with or without Android Studio) are shown in
figure 1. The development steps encompass four development phases, which include:
Environment Setup
During this phase you install and set up your development environment. You also
create Android Virtual Devices (AVDs) and connect hardware devices on which you
can install your applications.
See Managing Virtual Devices and Using Hardware Devices for more information.
During this phase you set up and develop your Android Studio project and application
modules, which contain all of the source code and resource files for your application.
For more information, see Create an Android project.
During this phase you build your project into a debuggable .apk package(s) that you
can install and run on the emulator or an Android-powered device. Android Studio
uses a build system based on Gradle that provides flexibility, customized build
variants, dependency resolution, and much more. If you're using another IDE, you can
build your project using Gradle and install it on a device using adb. For more
information, see Build and run your application.
Next, with Android Studio you debug your application using the Android Debug
Monitor and device log messages (logact) along with the IntelliJ IDEA intelligent
coding features. You can also use a JDWP-compliant debugger along with the
debugging and logging tools that are provided with the Android SDK. For more
information see Debug your application with the SDK debugging and logging tools.
Last, you test your application using various Android SDK testing tools. For more
information, see Test your application with the Testing and Instrumentation
framework.
Publishing
During this phase you configure and build your application for release and distribute
your application to users. For more information, see Publishing Overview.
When developing in IDEs or editors other than Android Studio, be familiar with all of the
tools below, because you will have to run them from the command line or script.
android
Create and update Android projects and create, move, and delete AVDs.
Android Emulator
Run your Android applications on an emulated Android platform.
Android Debug Bridge
Interface with your emulator or connected device (install apps, shell the device, issue
commands, etc.).
In addition to the above tools that are included with the SDK, you need the following open
source and third-party tools:
Gradle
To compile and build your Android project into an installable .apk file(s).
Keytool
To generate a keystore and private key, used to sign your .apk file. Keytool is part of
the JDK.
Jarsigner (or similar signing tool)
To sign your .apk file with a private key generated by Keytool. Jarsigner is part of the
JDK.
If you are using Android Studio, tools such as adb and android are automatically called by
Android Studio so you don't have to manually invoke these tools. You need to be familiar
with adb, however, because certain functions are not accessible from Android Studio, such as
the adb shell commands. You might also need to call Keytool and Jarsigner to sign your
applications, but you can set up Android Studio to do this automatically as well.
For more information on the tools provided with the Android SDK, see the Tools section of
the documentation.
Except as noted, this content is licensed under Creative Commons Attribution 2.5. For details
and restrictions, see the Content License.
The easiest way to create an AVD is to use the graphical AVD Manager, which you launch
from Eclipse by clicking Window > AVD Manager. You can also start the AVD Manager
from the command line by calling the android tool with the avd options, from the
<sdk>/tools/ directory.
You can also create AVDs on the command line by passing the android tool options. For
more information on how to create AVDs in this manner, see Managing Virtual Devices from
the Command Line.
A hardware profile: Defines the hardware features of the virtual device. For example,
you can define whether the device has a camera, whether it uses a physical QWERTY
keyboard or a dialing pad, how much memory it has, and so on.
A mapping to a system image: You can define what version of the Android platform
will run on the virtual device. You can choose a version of the standard Android
platform or the system image packaged with an SDK add-on.
Other options: You can specify the emulator skin you want to use with the AVD,
which lets you control the screen dimensions, appearance, and so on. You can also
specify the emulated SD card to use with the AVD.
A dedicated storage area on your development machine: the device's user data
(installed applications, settings, and so on) and emulated SD card are stored in this
area.
You can create as many AVDs as you need, based on the types of device you want to model.
To thoroughly test your application, you should create an AVD for each general device
configuration (for example, different screen sizes and platform versions) with which your
application is compatible and test your application on each one.
Keep these points in mind when you are selecting a system image target for your AVD:
The API Level of the target is important, because your application will not be able to
run on a system image whose API Level is less than that required by your application,
as specified in the minSdkVersion attribute of the application's manifest file. For
more information about the relationship between system API Level and application
minSdkVersion, see Specifying Minimum System API Version.
You should create at least one AVD that uses a target whose API Level is greater than
that required by your application, because it allows you to test the forward-
compatibility of your application. Forward-compatibility testing ensures that, when
users who have downloaded your application receive a system update, your
application will continue to function normally.
If your application declares a uses-library element in its manifest file, the
application can only run on a system image in which that external library is present. If
you want to run your application on an emulator, create an AVD that includes the
required library. Usually, you must create such an AVD using an Add-on component
for the AVD's platform (for example, the Google APIs Add-on contains the Google
Maps library).
To learn how to manage AVDs using a graphical tool, read Managing AVDs with AVD
Manager. To learn how to manage AVDs on the command line, read Managing AVDs from
the Command Line.
The AVD Manager is a tool you can use to create and manage Android virtual devices
(AVDs), which define device configurations for the Android Emulator.
In Android Studio, select Tools > Android > AVD Manager, or click the AVD
$ android avd
The AVD Manager main screen shows your current virtual devices, as shown in figure 1.
Figure 1. The AVD Manager main screen shows your current virtual devices.
Note: If you launch the AVD Manager from the command line, the UI is different than how it
appears in Android Studio, as documented here. Most of the same functionality is available,
but the command-line version of the AVD Manager is currently not documented.
Creating an AVD
You can create as many AVDs as you would like to use with the Android Emulator. To
effectively test your app, you should create an AVD that models each device type for which
you have designed your app to support. For instance, you should create an AVD for each API
level equal to and higher than the minimum version you've specified in your manifest <uses-
sdk> tag.
1. From the main screen (figure 1), click Create Virtual Device.
2. In the Select Hardware window, select a device configuration, such as Nexus 6, then
click Next.
3. Select the desired system version for the AVD and click Next.
4. Verify the configuration settings, then click Finish.
If necessary, click Show Advanced Settings to select a custom skin for the hardware
profile and adjust other hardware settings.
To launch the AVD in the Android Emulator, click the launch button in the list of
AVDs.
Creating a device definition
In case the available device definitions do not match the device type you'd like to emulate,
you can create a custom device definition for your AVD:
1. From the main screen (figure 1), click Create Virtual Device.
2. To begin you custom device by using an existing device profile as a template, select a
device profile then click Clone Device.
3. The following Configure Hardware Profile window (figure 3) allows you to specify
various configurations such as the screen size, memory options, input type, and
sensors.
4. Your custom device configuration is now available in the list of device definitions
(shown after you click Create Virtual Device). To continue preparing an AVD with
your custom device configuration, select the new configuration and follow the
instructions above to create an AVD with an existing device definition (and select
your new definition).
Hardware options
If you are creating a new AVD, you can specify the following hardware options for the AVD
to emulate:
A hardware.ini file
Layout files for supported orientations (landscape, portrait) and physical configuration
Image files for display elements, such as background, keys and buttons
1. Create a new directory where you will save your skin configuration files.
2. Define the visual appearance of the skin in a text file named layout. This file defines
many characteristics of the skin, such as the size and image assets for specific buttons.
For example:
parts {
device {
display {
width 320
height 480
x 0
y 0
}
}
portrait {
background {
image background_port.png
}
buttons {
power {
image button_vertical.png
x 1229
y 616
}
}
}
...
}
3. Add the bitmap files of the device images in the same directory.
4. Specify additional hardware-specific device configurations an hardware.ini file for
the device settings, such as hw.keyboard and hw.lcd.density.
5. Archive the files in the skin folder and select the archive file as a custom skin.
For more detailed information about creating emulator skins, see the Android Emulator Skin
File Specification in the tools source code.
Managing AVDs from the Command Line
In this document
1. Listing Targets
2. Creating AVDs
1. Customize the device resolution or density
2. Default location of AVD files
3. Setting hardware emulation options
3. Moving an AVD
4. Updating an AVD
5. Deleting an AVD
See also
1. Building and Running from the Command Line
2. Using the Android Emulator
The android tool lets you manage AVDs on the command line. For a complete reference of
the command line options that you can use, see the reference for the android tool.
Listing Targets
The android tool scans the <sdk>/platforms/ and <sdk>/add-ons/ directories looking for
valid system images and then generates the list of targets. Here's an example of the command
output:
Creating AVDs
In addition to creating AVDs with the AVD Manager user interface, you can also create them
by passing in command line arguments to the android tool.
To create each AVD, you issue the command android create avd, with options that
specify a name for the new AVD and the system image you want to run on the emulator when
the AVD is invoked. You can specify other options on the command line also, such as the
emulated SD card size, the emulator skin, or a custom location for the user data files.
You can use any name you want for the AVD, but since you are likely to be creating multiple
AVDs, you should choose a name that lets you recognize the general characteristics offered
by the AVD. The target ID is an integer assigned by the android tool. The target ID is not
derived from the system image name, version, or API Level, or other attribute, so you need to
run the android list targets command to list the target ID of each system image. You
should do this before you run the android create avd command. See the android tool
documentation for more information on the command line options.
When you've selected the target you want to use and made a note of its ID, use the android
create avd command to create the AVD, supplying the target ID as the -t argument. Here's
an example that creates an AVD with name "my_android1.5" and target ID "2" (the standard
Android 1.5 system image in the list above):
If the target you selected was a standard Android system image ("Type: platform"), the
android tool next asks you whether you want to create a custom hardware profile.
Note: If you are creating an AVD whose target is an SDK add-on, the android tool does not
allow you to set hardware emulation options. It assumes that the provider of the add-on has
set emulation options appropriately for the device that the add-on is modeling, and so
prevents you from resetting the options.
When testing your application, we recommend that you test your application in several
different AVDs, using different screen configurations (different combinations of size and
density). In addition, you should set up the AVDs to run at a physical size that closely
matches an actual device.
To set up your AVDs for a specific resolution or density, follow these steps:
1. Use the create avd command to create a new AVD, specifying the --skin option
with a value that references either a default skin name (such as "WVGA800") or a
custom skin resolution (such as 240x432). Here's an example:
2. To specify a custom density for the skin, answer "yes" when asked whether you want
to create a custom hardware profile for the new AVD.
3. Continue through the various profile settings until the tool asks you to specify
"Abstracted LCD density" (hw.lcd.density). Enter an appropriate value, such as "120"
for a low-density screen, "160" for a medium density screen, or "240" for a high-
density screen.
4. Set any other hardware options and complete the AVD creation.
In the example above (WVGA medium density), the new AVD will emulate a 5.8" WVGA
screen.
As an alternative to adjusting the emulator skin configuration, you can use the emulator skin's
default density and add the -dpi-device option to the emulator command line when starting
the AVD. For example:
When you create an AVD, the android tool creates a dedicated directory for it on your
development computer. The directory contains the AVD configuration file, the user data
image and SD card image (if available), and any other files associated with the device. Note
that the directory does not contain a system image — instead, the AVD configuration file
contains a mapping to the system image, which it loads when the AVD is launched.
The android tool also creates an <AVD_name>.ini file for the AVD at the root of the
.android/avd/ directory on your computer. The file specifies the location of the AVD
directory and always remains at the root the .android directory.
By default, the android tool creates the AVD directory inside ~/.android/avd/ (on
Linux/Mac), C:\Documents and Settings\<user>\.android\ on Windows XP, and
C:\Users\<user>\.android\ on Windows 7 and Vista. If you want to use a custom
location for the AVD directory, you can do so by using the -p <path> option when you
create the AVD:
If the .android directory is hosted on a network drive, we recommend using the -p option to
place the AVD directory in another location. The AVD's .ini file remains in the .android
directory on the network drive, regardless of the location of the AVD directory.
When you are creating a new AVD that uses a standard Android system image ("Type:
platform"), the android tool lets you set hardware emulation options for virtual device. The
table below lists the options available and the default values, as well as the names of
properties that store the emulated hardware options in the AVD's configuration file (the
config.ini file in the AVD's local directory).
Table 1. Available hardware profile options for AVDs and the default values
Moving an AVD
If you want to move or rename an AVD, you can do so using this command:
Updating an AVD
If, for any reason, the platform/add-on root folder has its name changed (maybe because the
user has installed an update of the platform/add-on) then the AVD will not be able to load the
system image that it is mapped to. In this case, the android list targets command will
produce this output:
To fix this error, use the android update avd command to recompute the path to the system
images.
Deleting an AVD
You can use the android tool to delete an AVD. Here is the command usage:
When you issue the command, the android tool looks for an AVD matching the specified
name deletes the AVD's directory and files.
The Android SDK includes a virtual mobile device emulator that runs on your computer. The
emulator lets you prototype, develop and test Android applications without using a physical
device.
The Android emulator mimics all of the hardware and software features of a typical mobile
device, except that it cannot place actual phone calls. It provides a variety of navigation and
control keys, which you can "press" using your mouse or keyboard to generate events for
your application. It also provides a screen in which your application is displayed, together
with any other active Android applications.
To let you model and test your application more easily, the emulator utilizes Android Virtual
Device (AVD) configurations. AVDs let you define certain hardware aspects of your
emulated phone and allow you to create many configurations to test many Android platforms
and hardware permutations. Once your application is running on the emulator, it can use the
services of the Android platform to invoke other applications, access the network, play audio
and video, store and retrieve data, notify the user, and render graphical transitions and
themes.
The emulator also includes a variety of debug capabilities, such as a console from which you
can log kernel output, simulate application interrupts (such as arriving SMS messages or
phone calls), and simulate latency effects and dropouts on the data network.
Overview
The Android emulator is an application that provides a virtual mobile device on which you
can run your Android applications. It runs a full Android system stack, down to the kernel
level, that includes a set of preinstalled applications (such as the dialer) that you can access
from your applications. You can choose what version of the Android system you want to run
in the emulator by configuring AVDs, and you can also customize the mobile device skin and
key mappings. When launching the emulator and at runtime, you can use a variety of
commands and options to control its behavior.
The Android system images available through the Android SDK Manager contain code for
the Android Linux kernel, the native libraries, the Dalvik VM, and the various Android
packages (such as the Android framework and preinstalled applications). The emulator
provides dynamic binary translation of device machine code to the OS and processor
architecture of your development machine.
The Android emulator supports many hardware features likely to be found on mobile devices,
including:
The following sections describe the emulator and its use for development of Android
applications in more detail.
To use the emulator, you first must create one or more AVD configurations. In each
configuration, you specify an Android platform to run in the emulator and the set of hardware
options and emulator skin you want to use. Then, when you launch the emulator, you specify
the AVD configuration that you want to load.
Each AVD functions as an independent device, with its own private storage for user data, SD
card, and so on. When you launch the emulator with an AVD configuration, it automatically
loads the user data and SD card data from the AVD directory. By default, the emulator stores
the user data, SD card data, and cache in the AVD directory.
To create and manage AVDs you use the AVD Manager UI or the android tool that is
included in the SDK. For complete information about how to set up AVDs, see Managing
Virtual Devices.
You can run your application on a single instance of the emulator or, depending on your
needs, you can start multiple emulator instances and run your application in more than one
emulated device. You can use the emulator's built-in commands to simulate GSM phone
calling or SMS between emulator instances, and you can set up network redirection that
allows emulators to send data to one another. For more information, see Telephony
Emulation, SMS Emulation, and Emulator Networking
To start an instance of the emulator from the command line, navigate to the tools/ folder of
the SDK. Enter emulator command like this:
This initializes the emulator, loads an AVD configuration and displays the emulator window.
For more information about command line options for the emulator, see the Android
Emulator tool reference.
Note: You can run multiple instances of the emulator concurrently, each with its own AVD
configuration and storage area for user data, SD card, and so on.
When you run your app from Android Studio, it installs and launches the app on your
connected device or emulator (launching the emulator, if necessary). You can specify
emulator startup options in the Run/Debug dialog, in the Target tab. When the emulator is
running, you can issue console commands as described later in this document.
If you are not working in Android Studio, see Installing Applications on the Emulator for
information about how to install your application.
For a reference of the emulator's startup commands and keyboard mapping, see the Android
Emulator tool reference.
If you don't have access to Android Studio, you can install your application on the emulator
using the adb utility. Before installing the application, you need to build and package it into
an .apk as described in Building and Running Apps. Once the application is installed, you
can start the emulator from the command line as described previously, using any startup
options necessary. When the emulator is running, you can also connect to the emulator
instance's console to issue commands as needed.
As you update your code, you periodically package and install it on the emulator. The
emulator preserves the application and its state data across restarts, in a user-data disk
partition. To ensure that the application runs properly as you update it, you may need to
delete the emulator's user-data partition. To do so, start the emulator with the -wipe-data
option. For more information about the user-data partition and other emulator storage, see
Working with Emulator Disk Images.
In order to make the Android emulator run faster and be more responsive, you can configure
it to take advantage of hardware acceleration, using a combination of configuration options,
specific Android system images and hardware drivers.
Caution: As of SDK Tools Revision 17, the graphics acceleration feature for the emulator is
experimental; be alert for incompatibilities and errors when using this feature.
Graphics acceleration for the emulator takes advantage of your development computer's
graphics hardware, specifically its graphics processing unit (GPU), to make screen drawing
faster. To use the graphics acceleration feature, you must have the following versions of the
Android development tools installed:
Note: Not all applications are compatible with graphics hardware acceleration. In particular,
the Browser application and applications using the WebView component are not compatible
with graphics acceleration.
1. Make sure you have the required SDK components installed (listed above).
2. Start the AVD Manager and create a new AVD with the Target value of Android 4.0.3 (API
Level 15), revision 3 or higher.
3. If you want to have graphics acceleration enabled by default for this AVD, in the Hardware
section, click New, select GPU emulation and set the value to Yes.
Note: You can also enable graphics acceleration when you start an emulator using
command line options as describe in the next section.
4. Name the AVD instance and select any other configuration options.
Caution: Do not select the Snapshot: Enabled option. Snapshots are not supported
for emulators with graphics acceleration enabled.
5. Click Create AVD to save the emulator configuration.
If you set GPU emulation to Yes for your AVD, then graphics acceleration is automatically
enabled when you run it. If you did not enable GPU emulation when you created the AVD,
you can still enable it at runtime.
If you are running the emulator from the command line, just include the -gpu on option:
Note: You must specify an AVD configuration that uses Android 4.0.3 (API Level
15, revision 3) or higher system image target. Graphics acceleration is not available
for earlier system images.
If you are running the emulator from Android Studio, run your Android application using an
AVD with the -gpu on option enabled:
1. In Android Studio, click your Android application module folder and then select Run
> Edit Configurations...
2. In the left panel of the Run/Debug Configurations dialog, select your Android run
configuration or create a new configuration.
3. Under the Target Device options, select the AVD you created in the previous
procedure.
4. In the Emulator tab, in the Additional command line options field, enter:
-gpu on
5. Run your Android project using this run configuration.
Caution: As of SDK Tools Revision 17, the virtual machine acceleration feature for the
emulator is experimental; be alert for incompatibilities and errors when using this feature.
Many modern CPUs provide extensions for running virtual machines (VMs) more efficiently.
Taking advantage of these extensions with the Android emulator requires some additional
configuration of your development system, but can significantly improve the execution
speed. Before attempting to use this type of acceleration, you should first determine if your
development system’s CPU supports one of the following virtualization extensions
technologies:
The specifications from the manufacturer of your CPU should indicate if it supports
virtualization extensions. If your CPU does not support one of these virtualization
technologies, then you cannot use virtual machine acceleration.
Note: Virtualization extensions are typically enabled through your computer's BIOS and are
frequently turned off by default. Check the documentation for your system's motherboard to
find out how to enable virtualization extensions.
Once you have determined that your CPU supports virtualization extensions, make sure you
can work within these additional requirements of running an emulator inside an accelerated
virtual machine:
x86 AVD Only - You must use an AVD that is uses an x86 system image target. AVDs that use
ARM-based system images cannot be accelerated using the emulator configurations
described here.
Not Inside a VM - You cannot run a VM-accelerated emulator inside another virtual
machine, such as a VirtualBox or VMWare-hosted virtual machine. You must run the
emulator directly on your system hardware.
Other VM Drivers - If you are running another virtualization technology on your system such
as VirtualBox or VMWare, you may need to unload the driver for that virtual machine
hosting software before running an accelerated emulator.
OpenGL® Graphics - Emulation of OpenGL ES graphics may not perform at the same level as
an actual device.
To use virtual machine acceleration with the emulator, you need the following version of
Android development tools. Use the Android SDK Manager to install these components:
If your development environment meets all of the requirements for running a VM-accelerated
emulator, you can use the AVD Manager to create an x86-based AVD configuration:
1. In the Android SDK Manager, make sure you have an x86-based System Image installed for
your target Android version. If you do not have an x86 System Image installed, select one in
the Android SDK Manager and install it.
Tip: System images are listed under each API Level in the SDK Manager. An x86
system image may not be available for all API levels.
2. Start the AVD Manager and create a new AVD with an x86 value for the CPU/ABI field. You
may need to select a specific Target value, or select a Target value and then select a specific
CPU/ABI option.
3. Name the emulator instance and select any other configuration options.
4. Click Create AVD to save the emulator configuration.
Virtual machine acceleration for Windows requires the installation of the Intel Hardware
Accelerated Execution Manager (Intel HAXM). The software requires an Intel CPU with
Virtualization Technology (VT) support and one of the following operating systems:
Windows 7 (32/64-bit)
Windows Vista (32/64-bit)
Windows XP (32-bit only)
sc query intelhaxm
SERVICE_NAME: intelhaxm
...
STATE : 4 RUNNING
...
If you are running the emulator from the command line, just specify an x86-based AVD:
If you are running the emulator from Android Studio, run your Android application with an
x86-based AVD:
1. In Android Studio, click your Android project folder and then select Run > Edit
Configurations...
2. In the left panel of the Run/Debug Configurations dialog, select your Android run
configuration or create a new configuration.
3. Under the Target Device options, select the x86-based AVD you created previously.
4. Run your Android project using this run configuration.
You can adjust the amount of memory available to the Intel HAXM kernel extension by re-
running its installer.
You can stop using the virtualization driver by uninstalling it. Re-run the installer or use the
Control Panel to remove the software.
Virtual machine acceleration on a Mac requires the installation of the Intel Hardware
Accelerated Execution Manager (Intel HAXM) kernel extension to allow the Android
emulator to make use of CPU virtualization extensions. The kernel extension is compatible
with Mac OS X Snow Leopard (version 10.6.0) and higher.
You should see a status message containing the following extension name, indicating
that the kernel extension is loaded:
com.intel.kext.intelhaxm
If you are running the emulator from the command line, just specify an x86-based AVD:
If you are running the emulator from Andriod Studio, run your Android application with an
x86-based AVD:
1. In Android Studio, click your Android module folder and then select Run > Edit
Configurations...
2. In the left panel of the Run/Debug Configurations dialog, select your Android run
configuration or create a new configuration.
3. Under the Target Device options, select the x86-based AVD you created previously.
4. Run your Android project using this run configuration.
You can adjust the amount of memory available to the Intel HAXM kernel extension by re-
running the installer.
You can stop using the virtualization kernel driver by uninstalling it. Before removing it, shut
down any running x86 emulators. To unload the virtualization kernel driver, run the
following command in a terminal window:
sudo
/System/Library/Extensions/intelhaxm.kext/Contents/Resources/uninstall.sh
Linux-based systems support virtual machine acceleration through the KVM software
package. Follow instructions for installing KVM on your Linux system, and verify that KVM
is enabled. In addition to following the installation instructions, be aware of these
configuration requirements:
Running KVM requires specific user permissions, make sure you have sufficient permissions
according to the KVM installation instructions.
If you use another virtualization technology in your Linux platform, unload its kernel driver
before running the x86 emulator. For example, the VirtualBox driver program is vboxdrv.
If you are running the emulator from the command line, start the emulator with an x86-
based AVD and include the KVM options:
If you are running the emulator from Android Studio, run your Android application with an
x86-based AVD and include the KVM options:
1. In Android Studio, click your Android module folder and then select Run > Edit
Configurations...
2. In the left panel of the Run/Debug Configurations dialog, select your Android run
configuration or create a new configuration.
3. Under the Target Device options, select the x86-based AVD you created previously.
4. In the Emulator tab, in the Additional command line options field, enter:
Important: When using the -qemu command line option, make sure it is the last parameter in
your command. All subsequent options are interpreted as qemu-specific parameters.
SD Card Emulation
You can create a disk image and then load it to the emulator at startup, to simulate the
presence of a user's SD card in the device. To do this, you can specify an SD card image
when you create an AVD, or you can use the mksdcard utility included in the SDK.
The following sections describe how to create an SD card disk image, how to copy files to it,
and how to load it in the emulator at startup.
Note that you can only load a disk image at emulator startup. Similarly, you can not remove a
simulated SD card from a running emulator. However, you can browse, send files to, and
copy/remove files from a simulated SD card either with adb or the emulator.
The emulator supports emulated SDHC cards, so you can create an SD card image of any size
up to 128 gigabytes.
The -c option can also be used to to specify a path to an SD card image for the new AVD.
For more information, see Managing Virtual Devices from the Command Line.
You can also use the mksdcard tool, included in the SDK, to create a FAT32 disk image that
you can load in the emulator at startup. You can access mksdcard in the tools/ directory of the
SDK and create a disk image like this:
For example:
Once you have created the disk image, you can copy files to it prior to loading it in the
emulator. To copy files, you can mount the image as a loop device and then copy the files to
it, or you can use a utility such as mtools to copy the files directly to the image. The mtools
package is available for Linux, Mac, and Windows.
Alternatively, you can use the adb push command to move files onto an SD card image
while it is loaded in an emulator. For more information see the adb push documentation.
By default, the emulator loads the SD card image that is stored with the active AVD (see the
-avd startup option).
Alternatively, you can start the emulator with the -sdcard flag and specify the name and path
of your image (relative to the current working directory):
The emulator uses mountable disk images stored on your development machine to simulate
flash (or similar) partitions on an actual device. For example, it uses a disk image containing
an emulator-specific kernel, the Android system, a ramdisk image, and writeable images for
user data and simulated SD card.
To run properly, the emulator requires access to a specific set of disk image files. By default,
the Emulator always looks for the disk images in the private storage area of the AVD in use.
If no images exist there when the Emulator is launched, it creates the images in the AVD
directory based on default versions stored in the SDK.
Note: The default storage location for AVDs is in ~/.android/avd on OS X and Linux,
C:\Documents and Settings\<user>\.android\ on Windows XP, and
C:\Users\<user>\.android\ on Windows Vista.
To let you use alternate or custom versions of the image files, the emulator provides startup
options that override the default locations and filenames of the image files. When you use one
of these options, the emulator searches for the image file under the image name or location
that you specify; if it can not locate the image, it reverts to using the default names and
location.
The emulator uses three types of image files: default image files, runtime image files, and
temporary image files. The sections below describe how to override the location/name of
each type of file.
When the emulator launches, but does not find an existing user data image in the active
AVD's storage area, it creates a new one from a default version included in the SDK. The
default user data image is read-only. The image files are read-only.
The emulator provides the -system <dir> startup option to let you override the location
where the emulator looks for the default user data image.
The emulator also provides a startup option that lets you override the name of the default user
data image, as described in the following table. When you use the option, the emulator looks
in the default directory, or in a custom location (if you specified -system <dir>).
At runtime, the emulator reads and writes data to two disk images: a user-data image and
(optionally) an SD card image. These images emulate the user-data partition and removable
storage media on actual device.
The emulator provides a default user-data disk image. At startup, the emulator creates the
default image as a copy of the system user-data image (user-data.img), described above. The
emulator stores the new image with the files of the active AVD.
The emulator provides startup options to let you override the actual names and storage
locations of the runtime images to load, as described in the following table. When you use
one of these options, the emulator looks for the specified file(s) in the current working
directory, in the AVD directory, or in a custom location (if you specified a path with the
filename).
User-Data Image
Each emulator instance uses a writeable user-data image to store user- and session-specific
data. For example, it uses the image to store a unique user's installed application data,
settings, databases, and files.
At startup, the emulator attempts to load a user-data image stored during a previous session.
It looks for the file in the current working directory, in the AVD directory described in a
previous section and at the custom location/name that you specified at startup.
If it finds a user-data image, it mounts the image and makes it available to the system for
reading and writing of user data.
If it does not find one, it creates an image by copying the system user-data image
(userdata.img), described above. At device power-off, the system persists the user data to
the image, so that it will be available in the next session. Note that the emulator stores the
new disk image at the location/name that you specify in -data startup option.
Note: Because of the AVD configurations used in the emulator, each emulator instance gets
its own dedicated storage. There is no longer a need to use the -d option to specify an
instance-specific storage area.
SD Card
Optionally, you can create a writeable disk image that the emulator can use to simulate
removeable storage in an actual device. For information about how to create an emulated SD
card and load it in the emulator, see SD Card Emulation
You can also use the android tool to automatically create an SD Card image for you, when
creating an AVD. For more information, see Managing Virtual Devices with AVD Manager.
Temporary Images
The emulator creates two writeable images at startup that it deletes at device power-off. The
images are:
The emulator does not permit renaming the temporary system image or persisting it at device
power-off.
The /cache partition image is initially empty, and is used by the browser to cache
downloaded web pages and images. The emulator provides an -cache <file>, which
specifies the name of the file in which to persist the /cache image at device power-off. If
<file> does not exist, the emulator creates it as an empty file.
You can also disable the use of the cache partition by specifying the -nocache option at
startup.
Emulator Networking
The emulator provides versatile networking capabilities that you can use to set up complex
modeling and testing environments for your application. The sections below introduce the
emulator's network architecture and capabilities.
Each instance of the emulator runs behind a virtual router/firewall service that isolates it from
your development machine's network interfaces and settings and from the internet. An
emulated device can not see your development machine or other emulator instances on the
network. Instead, it sees only that it is connected through Ethernet to a router/firewall.
The virtual router for each instance manages the 10.0.2/24 network address space — all
addresses managed by the router are in the form of 10.0.2.<xx>, where <xx> is a number.
Addresses within this space are pre-allocated by the emulator/router as follows:
10.0.2.4 / 10.0.2.5 /
Optional second, third and fourth DNS server (if any)
10.0.2.6
Note that the same address assignments are used by all running emulator instances. That
means that if you have two instances running concurrently on your machine, each will have
its own router and, behind that, each will have an IP address of 10.0.2.15. The instances are
isolated by a router and can not see each other on the same network. For information about
how to let emulator instances communicate over TCP/UDP, see Connecting Emulator
Instances.
Also note that the address 127.0.0.1 on your development machine corresponds to the
emulator's own loopback interface. If you want to access services running on your
development machine's loopback interface (a.k.a. 127.0.0.1 on your machine), you should use
the special address 10.0.2.2 instead.
Finally, note that each emulated device's pre-allocated addresses are specific to the Android
emulator and will probably be very different on real devices (which are also very likely to be
NAT-ed, i.e., behind a router/firewall)
Android applications running in an emulator can connect to the network available on your
workstation. However, they connect through the emulator, not directly to hardware, and the
emulator acts like a normal application on your workstation. This means that the emulator,
and thus your Android applications, are subject to some limitations:
Communication with the emulated device may be blocked by a firewall program running on
your machine.
Communication with the emulated device may be blocked by another (physical)
firewall/router to which your machine is connected.
The emulator's virtual router should be able to handle all outbound TCP and UDP
connections/messages on behalf of the emulated device, provided your development
machine's network environment allows it to do so. There are no built-in limitations on port
numbers or ranges except the one imposed by your host operating system and network.
Depending on the environment, the emulator may not be able to support other protocols (such
as ICMP, used for "ping") might not be supported. Currently, the emulator does not support
IGMP or multicast.
To communicate with an emulator instance behind its virtual router, you need to set up
network redirection on the virtual router. Clients can then connect to a specified guest port on
the router, while the router directs traffic to/from that port to the emulated device's host port.
To set up the network redirection, you create a mapping of host and guest ports/addresses on
the emulator instance. There are two ways to set up network redirection: using emulator
console commands and using the ADB tool, as described below.
Each emulator instance provides a control console the you can connect to, to issue commands
that are specific to that instance. You can use the redir console command to set up
redirection as needed for an emulator instance.
First, determine the console port number for the target emulator instance. For example, the
console port number for the first emulator instance launched is 5554. Next, connect to the
console of the target emulator instance, specifying its console port number, as follows:
Once connected, use the redir command to work with redirection. To add a redirection, use:
add <protocol>:<host-port>:<guest-port>
where <protocol> is either tcp or udp, and <host-port> and <guest-port> sets the
mapping between your own machine and the emulated system, respectively.
For example, the following command sets up a redirection that handles all incoming TCP
connections to your host (development) machine on 127.0.0.1:5000 and will pass them
through to the emulated system's 10.0.2.15:6000.:
To delete a redirection, you can use the redir del command. To list all redirection for a
specific instance, you can use redir list. For more information about these and other
console commands, see Using the Emulator Console.
Note that port numbers are restricted by your local environment. this typically means that you
cannot use host port numbers under 1024 without special administrator privileges. Also, you
won't be able to set up a redirection for a host port that is already in use by another process on
your machine. In that case, redir generates an error message to that effect.
Setting Up Redirection through ADB
The Android Debug Bridge (ADB) tool provides port forwarding, an alternate way for you to
set up network redirection. For more information, see Forwarding Ports in the ADB
documentation.
Note that ADB does not currently offer any way to remove a redirection, except by killing the
ADB server.
At startup, the emulator reads the list of DNS servers that your system is currently using. It
then stores the IP addresses of up to four servers on this list and sets up aliases to them on the
emulated addresses 10.0.2.3, 10.0.2.4, 10.0.2.5 and 10.0.2.6 as needed.
On Linux and OS X, the emulator obtains the DNS server addresses by parsing the file
/etc/resolv.conf. On Windows, the emulator obtains the addresses by calling the
GetNetworkParams() API. Note that this usually means that the emulator ignores the content
of your "hosts" file (/etc/hosts on Linux/OS X, %WINDOWS%/system32/HOSTS on
Windows).
When starting the emulator at the command line, you can also use the -dns-server
<serverList> option to manually specify the addresses of DNS servers to use, where
<serverList> is a comma-separated list of server names or IP addresses. You might find this
option useful if you encounter DNS resolution problems in the emulated network (for
example, an "Unknown Host error" message that appears when using the web browser).
If your emulator must access the Internet through a proxy server, you can use the -http-
proxy <proxy> option when starting the emulator, to set up the appropriate redirection. In
this case, you specify proxy information in <proxy> in one of these formats:
http://<machineName>:<port>
or
http://<username>:<password>@<machineName>:<port>
The -http-proxy option forces the emulator to use the specified HTTP/HTTPS proxy for all
outgoing TCP connections. Redirection for UDP is not currently supported.
Alternatively, you can define the environment variable http_proxy to the value you want to
use for <proxy>. In this case, you do not need to specify a value for <proxy> in the -http-
proxy command — the emulator checks the value of the http_proxy environment variable
at startup and uses its value automatically, if defined.
You can use the -verbose-proxy option to diagnose proxy connection problems.
Interconnecting Emulator Instances
To allow one emulator instance to communicate with another, you must set up the necessary
network redirection as illustrated below.
and you want to run a server on B, to which C will connect, here is how you could set it up:
For example, if you wanted to run an HTTP server, you can select <serverPort> as 80 and
<localPort> as 8080:
B listens on 10.0.2.15:80
On B's console, issue redir add tcp:8080:80
C connects to 10.0.2.2:8080
The emulator automatically forwards simulated voice calls and SMS messages from one
instance to another. To send a voice call or SMS, use the dialer application or SMS
application, respectively, from one of the emulators.
To send an SMS message to another emulator instance, launch the SMS application (if
available). Specify the console port number of the target emulator instance as as the SMS
address, enter the message text, and send the message. The message is delivered to the target
emulator instance.
You can also connect to an emulator instance's console to simulate an incoming voice call or
SMS. For more information, see Telephony Emulation and SMS Emulation.
To connect to the console of any running emulator instance at any time, use this command:
An emulator instance occupies a pair of adjacent ports: a console port and an adb port. The
port numbers differ by 1, with the adb port having the higher port number. The console of the
first emulator instance running on a given machine uses console port 5554 and adb port 5555.
Subsequent instances use port numbers increasing by two — for example, 5556/5557,
5558/5559, and so on. Up to 16 concurrent emulator instances can run a console facility.
To connect to the emulator console, you must specify a valid console port. If multiple
emulator instances are running, you need to determine the console port of the emulator
instance you want to connect to. You can find the instance's console port listed in the title of
the instance window. For example, here's the window title for an instance whose console port
is 5554:
Alternatively, you can use the adb devices command, which prints a list of running
emulator instances and their console port numbers. For more information, see Querying for
Emulator/Device Instances in the adb documentation.
Note: The emulator listens for connections on ports 5554-5587 and accepts connections only
from localhost.
Once you are connected to the console, you can then enter help [command] to see a list of
console commands and learn about specific commands.
The following sections below describe the major functional areas of the console.
Port Redirection
You can use the console to add and remove port redirection while the emulator is running.
After you connect to the console, manage port redirection by entering the following
command:
redir <list|add|del>
The redir command supports the subcommands listed in the table below.
You can use the console to set the geographic location reported to the applications running
inside an emulator. Use the geo command to send a simple GPS fix to the emulator, with or
without NMEA 1083 formatting:
geo <fix|nmea>
The geo command supports the subcommands listed in the table below.
You can issue the geo command as soon as an emulator instance is running. The emulator
sets the location you enter by creating a mock location provider. This provider responds to
location listeners set by applications, and also supplies the location to the LocationManager.
Any application can query the location manager to obtain the current GPS fix for the
emulated device by calling:
LocationManager.getLastKnownLocation("gps")
event <send|types|codes|text>
The event command supports the subcommands listed in the table below.
send
Send one or more events to the You can use text names or integers for
<type>:<code>:<value>
[...] Android kernel. <type> and <value>.
The power command controls the power state reported by the emulator to applications. The
syntax for this command is as follows:
power <display|ac|status|present|health|capacity>
The event command supports the subcommands listed in the table below.
Display
display battery and
charger state.
Set AC
ac <on|off> charging state
to on or off.
Change
status <unknown|charging|discharging|not-
battery status
charging|full>
as specified.
Set battery
present <true|false> presence
state.
Set remaining
battery
capacity <percent>
capacity state
(0-100).
Network Status
You can use the console to check the network status and current delay and speed
characteristics. To do so, connect to the console and use the netstatus command. Here's an
example of the command and its output.
network status
The emulator lets you simulate various network latency levels, so that you can test your
application in an environment more typical of the actual conditions in which it will run. You
can set a latency level or range at emulator startup or you can use the console to change the
latency, while the application is running in the emulator.
To set latency at emulator startup, use the -netdelay emulator option with a supported
<delay> value, as listed in the table below. Here are some examples:
To make changes to network delay while the emulator is running, connect to the console and
use the netdelay command with a supported <delay> value from the table below.
The format of network <delay> is one of the following (numbers are milliseconds):
The emulator also lets you simulate various network transfer rates. You can set a transfer rate
or range at emulator startup or you can use the console to change the rate, while the
application is running in the emulator.
To set the network speed at emulator startup, use the -netspeed emulator option with a
supported <speed> value, as listed in the table below. Here are some examples:
To make changes to network speed while the emulator is running, connect to the console and
use the netspeed command with a supported <speed> value from the table below.
The format of network <speed> is one of the following (numbers are kilobits/sec):
Telephony Emulation
The Android emulator includes its own GSM emulated modem that lets you simulate
telephony functions in the emulator. For example, you can simulate inbound phone calls,
establish data connections and terminate them. The Android system handles simulated calls
exactly as it would actual calls. The emulator does not support call audio.
You can use the gsm command to access the emulator's telephony functions after connecting
to the console. The syntax for this command is as follows:
gsm <call|accept|busy|cancel|data|hold|list|voice|status>
The gsm command supports the subcommands listed in the table below.
Simulate an inbound
call
phone call from
<phonenumber>
<phonenumber>.
Terminate an inbound
cancel or outbound phone call
<phonenumber> to/from
<phonenumber>.
Change the state of a You can change a call's state to "held" only if its
hold
call to "held". current state is "active" or "waiting".
Report the current GSM Values are those described for the voice and data
status
voice/data state. commands.
SMS Emulation
The Android emulator console lets you generate an SMS message and direct it to an emulator
instance. Once you connect to an emulator instance, you can generate an emulated incoming
SMS using the following command:
The console forwards the SMS message to the Android framework, which passes it through
to an application that handles that message type.
VM State
You can use the vm command to control the VM on an emulator instance. The syntax for this
command is as follows:
vm <start|stop|status>
Emulator Window
You can use the window command to manage the emulator window. The syntax for this
command is as follows:
window <scale>
You can terminate an emulator instance through the console, using the kill command.
Emulator Limitations
No support for placing or receiving actual phone calls. You can simulate phone calls (placed
and received) through the emulator console, however.
No support for USB connections
No support for device-attached headphones
No support for determining network connected state
No support for determining battery charge level and AC charging state
No support for determining SD card insert/eject
No support for Bluetooth
For emulators running on Mac OS X, if you see an error Warning: No DNS servers found
when starting the emulator, check to see whether you have an /etc/resolv.conf file. If not,
please run the following line in a command window:
ln -s /private/var/run/resolv.conf /etc/resolv.conf
See also
1. Google USB Driver
2. OEM USB Drivers
When building a mobile application, it's important that you always test your application on a
real device before releasing it to users. This page describes how to set up your development
environment and Android-powered device for testing and debugging on the device.
You can use any Android-powered device as an environment for running, debugging, and
testing your applications. The tools included in the SDK make it easy to install and run your
application on the device each time you compile. You can install your application on the
device directly from Android Studio or from the command line with ADB. If you don't yet
have a device, check with the service providers in your area to determine which Android-
powered devices are available.
If you want a SIM-unlocked phone, then you might consider a Nexus phone. To purchase a
Nexus phone, visit the Google Play store.
Note: When developing on a device, keep in mind that you should still use the Android
emulator to test your application on configurations that are not equivalent to those of your
real device. Although the emulator does not allow you to test every device feature (such as
the accelerometer), it does allow you to verify that your application functions properly on
different versions of the Android platform, in different screen sizes and orientations, and
more.
To access these settings, open the Developer options in the system Settings. On Android 4.2
and higher, the Developer options screen is hidden by default. To make it visible, go to
Settings > About phone and tap Build number seven times. Return to the previous screen to
find Developer options at the bottom.
With an Android-powered device, you can develop and debug your Android applications just
as you would on the emulator. Before you can start, there are just a few things to do:
In the build file, make sure the debuggable property in the debug build type is set to
true. The build type property overrides the manifest setting.
android {
buildTypes {
debug {
debuggable true
}
In the AndroidManifest.xml file, add android:debuggable="true" to the
<application> element.
Note: If you manually enable debugging in the manifest file, be sure to disable it in
your release build (your published application should usually not be debuggable).
b. Now execute:
chmod a+r /etc/udev/rules.d/51-android.rules
Note: When you connect a device running Android 4.2.2 or higher to your computer, the
system shows a dialog asking whether to accept an RSA key that allows debugging through
this computer. This security mechanism protects user devices because it ensures that USB
debugging and other adb commands cannot be executed unless you're able to unlock the
device and acknowledge the dialog. This requires that you have adb version 1.0.31 (available
with SDK Platform-tools r16.0.1 and higher) in order to debug on a device running Android
4.2.2 or higher.
When plugged in over USB, you can verify that your device is connected by executing adb
devices from your SDK platform-tools/ directory. If connected, you'll see the device
name listed as a "device."
If using Android Studio, run or debug your application as usual. You will be presented with a
Device Chooser dialog that lists the available emulator(s) and connected device(s). Select the
device upon which you want to install and run the application.
If using the Android Debug Bridge (adb), you can issue commands with the -d flag to target
your connected device.
This table provides a reference to the vendor IDs needed in order to add USB device support
on Linux. The USB Vendor ID is the value given to the ATTR{idVendor} property in the
rules file, as described above.
See also
1. Using Hardware Devices
2. Google USB Driver
If you are developing on Windows and would like to connect an Android-powered device to
test your applications, then you need to install the appropriate USB driver. This document
provides links to the web sites for several original equipment manufacturers (OEMs), where
you can download the appropriate USB driver for your device. However, this list is not
exhaustive for all available Android-powered devices.
If you're developing on Mac OS X or Linux, then you probably don't need to install a USB
driver. To start developing with your device, read Using Hardware Devices.
Note: If your device is one of the Android Developer Phones (ADP), a Nexus One, or a
Nexus S, then you need the Google USB Driver, instead of an OEM driver. The Galaxy
Nexus driver, however, is distributed by Samsung (listed as model SCH-I515).
First, find the appropriate driver for your device from the OEM drivers table below.
Once you've downloaded your USB driver, follow the instructions below to install or upgrade
the driver, based on your version of Windows and whether you're installing for the first time
or upgrading an existing driver.
Tip: When you finish the USB driver installation, see Using Hardware Devices for other
important information about using an Android-powered device for development.
1. Windows 7
2. Windows Vista
Caution: You may make changes to android_winusb.inf file found inside usb_driver\
(for example, to add support for other devices), however, this will lead to security warnings
when you install or upgrade the driver. Making any other changes to the driver files may
break the installation process.
Windows 7
To install the Android USB driver on Windows 7 for the first time:
Or, to upgrade an existing Android USB driver on Windows 7 with the new driver:
Windows Vista
To install the Android USB driver on Windows Vista for the first time:
1. Connect your Android-powered device to your computer's USB port. Windows will
detect the device and launch the Found New Hardware wizard.
2. Select Locate and install driver software.
3. Select Don't search online.
4. Select I don't have the disk. Show me other options.
5. Select Browse my computer for driver software.
6. Click Browse and locate the USB driver folder. (The Google USB Driver is located in
<sdk>\extras\google\usb_driver\.) As long as you specified the exact location of
the installation package, you may leave Include subfolders checked or unchecked—
it doesn't matter.
7. Click Next. Vista may prompt you to confirm the privilege elevation required for
driver installation. Confirm it.
8. When Vista asks if you'd like to install the Google ADB Interface device, click Install
to install the driver.
Or, to upgrade an existing Android USB driver on Windows Vista with the new driver:
OEM Drivers
Note: If your device is one of the Android Developer Phones (purchased from the Google
Play Developer Console), a Nexus One, or a Nexus S, then you need the Google USB Driver,
instead of an OEM driver. The Galaxy Nexus driver, however, is distributed by Samsung
(listed as model SCH-I515).
An Android project contains everything that defines your Android app, from app source code
to build configurations and test code. The SDK tools require that your projects follow a
specific structure so it can compile and package your application correctly. If you're using
Android Studio, it takes care of all this for you.
A module is the first level of containment within a project that encapsulates specific types of
source code files and resources. There are several types of modules with a project:
When you use the Android development tools to create a new project and the module, the
essential files and folders will be created for you. There are only a handful of files and folders
generated for you, and some of them depend on whether you use Android Studio or the
android tool to generate your module. As your application grows in complexity, you might
require new kinds of resources, directories, and files.
Note: Project folders and files apply across the entire Android project and override similar
module file settings.
Android Studio project files and settings provide project-wide settings that apply across all
modules in the project.
.idea
Directory for IntelliJ IDEA settings.
app
Application module directories and files.
build
This directory stories the build output for all project modules.
gradle
Contains the gradler-wrapper files.
.gitignore
Specifies the untracked files that Git should ignore.
build.gradle
Customizable properties for the build system. You can edit this file to specify the
default build settings used by the application modules and also set the location of your
keystore and key alias so that the build tools can sign your application when building
in release mode. This file is integral to the project, so maintain it in a source revision
control system.
gradle.properties
Project-wide Gradle settings.
gradlew
Gradle startup script for Unix.
gradlew.bat
Gradle startup script for Windows.
local.properties
Customizable computer-specific properties for the build system, such as the path to
the SDK installation. Because the content of the file is specific to the local installation
of the SDK, the local.properties should not be maintained in a source revision
control system.
.iml
Module file created by the IntelliJ IDEA to store module information.
settings.gradle
Specifies the sub-projects to build.
Android Application Modules are the modules that eventually get built into the .apk files
based on your build settings. They contain things such as application source code and
resource files. Most code and resource files are generated for you by default, while others
should be created if required. The following directories and files comprise an Android
application module:
build/
Contains build folders for the specified build variants. Stored in the main application
module.
libs/
Contains private libraries. Stored in the main application module.
src/
Contains your stub Activity file, which is stored at
src/main/java//ActivityName>.java. All other source code files (such as .java
or .aidl files) go here as well.
androidTest/
Contains the instrumentation tests. For more information, see the Android Test
documentation.
main/java/com.>project<.>app<
Contains Java code source for the app activities.
main/jni/
Contains native code using the Java Native Interface (JNI). For more information, see
the Android NDK documentation.
main/gen/
Contains the Java files generated by Android Studio, such as your R.java file and
interfaces created from AIDL files.
main/assets/
This is empty. You can use it to store raw asset files. Files that you save here are
compiled into an .apk file as-is, and the original filename is preserved. You can
navigate this directory in the same way as a typical file system using URIs and read
files as a stream of bytes using the AssetManager. For example, this is a good
location for textures and game data.
main/res/
Contains application resources, such as drawable files, layout files, and string values
in the following directories. See Application Resources for more information.
anim/
For XML files that are compiled into animation objects. See the Animation resource
type.
color/
For XML files that describe colors. See the Color Values resource type.
drawable/
For bitmap files (PNG, JPEG, or GIF), 9-Patch image files, and XML files that
describe Drawable shapes or Drawable objects that contain multiple states (normal,
pressed, or focused). See the Drawable resource type.
layout/
XML files that are compiled into screen layouts (or part of a screen). See the Layout
resource type.
menu/
For XML files that define application menus. See the Menus resource type.
raw/
For arbitrary raw asset files. Saving asset files here is essentially the same as saving
them in the assets/ directory. The only difference is how you access them. These
files are processed by aapt and must be referenced from the application using a
resource identifier in the R class. For example, this is a good place for media, such as
MP3 or Ogg files.
values/
For XML files that define resources by XML element type. Unlike other resources in
the res/ directory, resources written to XML files in this folder are not referenced by
the file name. Instead, the XML element type controls how the resources defined
within the XML files are placed into the R class.
xml/
For miscellaneous XML files that configure application components. For example, an
XML file that defines a PreferenceScreen, AppWidgetProviderInfo, or
Searchability Metadata. See Application Resources for more information about
configuring these application components.
AndroidManifest.xml
The control file that describes the nature of the application and each of its
components. For instance, it describes: certain qualities about the activities, services,
intent receivers, and content providers; what permissions are requested; what external
libraries are needed; what device features are required, what API Levels are supported
or required; and others. See the AndroidManifest.xml documentation for more
information
.gitignore/
Specifies the untracked files ignored by git.
app.iml/
IntelliJ IDEA module
build.gradle
Customizable properties for the build system. You can edit this file to override default
build settings used by the manifest file and also set the location of your keystore and
key alias so that the build tools can sign your application when building in release
mode. This file is integral to the project, so maintain it in a source revision control
system.
proguard-rules.pro
ProGuard settings file.
Library Module
To download the sample applications and run them as modules in your environment, use the
Android SDK Manager to download the "Samples for SDK API 8" (or later) module into
your SDK.
For more information and to browse the code of the samples, see the TicTacToeMain
application.
An Android library module is a development module that holds shared Android source code
and resources. Other Android application modules can reference the library module and, at
build time, include its compiled sources in their .apk files. Multiple application modules can
reference the same library module and any single application module can reference multiple
library modules.
Note: You need SDK Tools r14 or newer to use the new library module feature that generates
each library module into its own JAR file. You can download the tools and platforms using
the Android SDK Manager, as described in Exploring the SDK.
If you have source code and resources that are common to multiple Android projects, you can
move them to a library module so that it is easier to maintain across applications and
versions. Here are some common scenarios in which you could make use of library modules:
If you are developing multiple related applications that use some of the same
components, you move the redundant components out of their respective application
module and create a single, reusable set of the same components in a library module.
If you are creating an application that exists in both free and paid versions. You move
the part of the application that is common to both versions into a library module. The
two dependent modules, with their different package names, will reference the library
module and provide only the difference between the two application versions.
However, a library module differs from a standard Android application module in that you
cannot compile it directly to its own .apk and run it on an Android device. Similarly, you
cannot export the library module to a self-contained JAR file, as you would do for a true
library. Instead, you must compile the library indirectly, by referencing the library in the
dependent application and building that application.
When you build an application that depends on a library module, the SDK tools compile the
library into a temporary JAR file and use it in the main module, then uses the result to
generate the .apk. In cases where a resource ID is defined in both the application and the
library, the tools ensure that the resource declared in the application gets priority and that the
resource in the library module is not compiled into the application .apk. This gives your
application the flexibility to either use or redefine any resource behaviors or values that are
defined in any library.
To organize your code further, your application can add references to multiple library
modules, then specify the relative priority of the resources in each library. This lets you build
up the resources actually used in your application in a cumulative manner. When two
libraries referenced from an application define the same resource ID, the tools select the
resource from the library with higher priority and discard the other.
Once you have added references to library modules to your Android application module, you
can set their relative priority. At build time, the libraries are merged with the application one
at a time, starting from the lowest priority to the highest.
Library modules can reference other library modules and can import an external library
(JAR) in the normal way.
Development considerations
As you develop your library modules and dependent applications, keep the points listed
below in mind:
Resource conflicts
Since the tools merge the resources of a library module with those of a dependent
application module, a given resource ID might be defined in both modules. In this
case, the tools select the resource from the application, or the library with highest
priority, and discard the other resource. As you develop your applications, be aware
that common resource IDs are likely to be defined in more than one project and will
be merged, with the resource from the application or highest-priority library taking
precedence.
To avoid resource conflicts for common resource IDs, consider using a prefix or other
consistent naming scheme that is unique to the module (or is unique across all project
modules).
A library cannot be distributed as a binary file (such as a JAR file). This will be added
in a future version of the SDK Tools.
You can develop a library module that itself includes a JAR library; however you
need to manually edit the dependent application modules's build path and add a path
to the JAR file.
You can develop a library module that depends on an external library (for example,
the Maps external library). In this case, the dependent application must build against a
target that includes the external library (for example, the Google APIs Add-On). Note
also that both the library module and the dependent application must declare the
external library in their manifest files, in a <uses-library> element.
The tools do not support the use of raw asset files (saved in the assets/ directory) in
a library module. Any asset resources used by an application must be stored in the
assets/ directory of the application module itself. However, resource files saved in
the res/ directory are supported.
A library is compiled as part of the dependent application module, so the API used in
the library module must be compatible with the version of the Android library used to
compile the application module. In general, the library module should use an API
level that is the same as — or lower than — that used by the application. If the library
module uses an API level that is higher than that of the application, the application
module will not compile. It is perfectly acceptable to have a library that uses the
Android 1.5 API (API level 3) and that is used in an Android 1.6 (API level 4) or
Android 2.1 (API level 7) module, for instance.
There is no requirement for the package name of a library to be the same as that of
applications that use it.
When you build the dependent application modules, library modules are compiled and
merged with the application module. Each library has its own R class, named
according to the library's package name. The R class generated from main module and
the library module is created in all the packages that are needed including the main
module's package and the libraries' packages.
There are no specific requirements on where you should store a library module,
relative to a dependent application module, as long as the application module can
reference the library module by a relative link. What is important is that the main
module can reference the library module through a relative link.
Test Projects
Test projects contain Android applications that you write using the Testing and
Instrumentation framework. The framework is an extension of the JUnit test framework and
adds access to Android system objects.
The test projects are now automatically part of the app source folder. When a new application
module is created, Android Studio creates the src/androidTest source set. This source set
contains tests for the default configuration and is combined with the debug build type to
generate a test application.
Figure 1. androidTest Folder.
Note: The src/androidTest source set may not be created for every type of available
module template. If this source set is not created, you can just create it for that module.
For each product flavor, create a test folder specific to that product flavor.
src/main/
src/androidTest/
src/productFlavor1/
src/testproductFlavor1/
src/productFlavor2/
src/testproductFlavor2/
The test manifests are always generated so a manifest in a test source set is optional.
The test applications run against the debug build type. This can be configured using the
testBuildType property in the build file.
There are two recommended ways of setting up testing on code and resources in a library
module:
You can set up a test module that instruments an application module that depends on
the library module. You can then add tests to the module for library-specific features.
You can set up a standard application module that depends on the library and put the
instrumentation in that module. This lets you create a self-contained module that
contains both the tests/instrumentations and the code to test.
Android Studio provides graphical tools for creating and managing Android projects, which
contain everything that define your Android apps, from app source code to build
configurations and test code. Each project contains one or more different types of modules,
such as application modules, library modules, and test modules.
This guide explains how to create Android projects and different modules using Android
Studio. For more information about the Android project structure and module types, read
Managing Projects Overview.
Android Studio makes it easy to create Android apps for several form factors, such as phone,
tablet, TV, Wear, and Google Glass. The New Project wizard lets you choose the form
factors for your app and populates the project structure with everything you need to get
started.
If you didn't have a project opened, Android Studio shows the Welcome screen. To create a
new project, click New Project.
If you had a project opened, Android Studio shows the development environment. To create a
new project, click File > New Project.
The next window lets you configure the name of your app, the package name, and the
location of your project.
Figure 1. Choose a name for your project.
The next window lets you select the form factors supported by your app, such as phone,
tablet, TV, Wear, and Google Glass. The selected form factors become the application
modules witin the project. For each form factor, you can also select the API Level for that
app. To get more information, click Help me choose.
Figure 2. Select the API Level.
The API Level window shows the distribution of mobile devices running each version of
Android, as shown in figure 3. Click on an API level to see a list of features introduced in the
corresponding version of Android. This helps you choose the minimum API Level that has all
the features that your apps needs, so you can reach as many devices as possible. Then click
OK.
Figure 3. Choose form factors for your app.
The next screen lets you select an activity type to add to your app, as shown in figure 4. This
screen displays a different set of activities for each of the form factors you selected earlier.
Figure 4. Add an activity to your app.
Note: If you choose "Add No Activity", click Finish to create the project.
The next screen lets you configure the activity to add to your app, as shown in figure 5.
Figure 5. Choose a name for your activity.
Enter the activity name, the layout name, and the activity title. Then click Finish.
Android Studio creates the default structure for your project and opens the development
environment. If your app supports more than one form factor, Android Studio creates a
module folder with complete source files for each of them as shown in figure 6.
Figure 6. The default project structure for a mobile app.
Now you are ready to develop your app. For more information, see the following links:
Training Lessons
Building Apps for Wearables
Android TV
Google Glass
To create a new module, select File > New > Module. Select the desire module type then
click Next to enter the basic module settings:
Enter an Application Name. This name is used as the title of your application
launcher icon when it is installed on a device.
Enter a Module Name. This text is used as the name of the folder where your Java-
based activity files are stored.
Enter a Package Name and Package Location. This class package namespace creates
the initial package structure for your applications code files and is added as the
package attribute in your application's Android manifest file. This manifest value
serves as the unique identifier for your application app when you distribute it to users.
The package name must follow the same rules as packages in the Java programming
language.
Select the Minimum required SDK. This setting indicates the lowest version of the
Android platform that your application supports for the selected form factor. This
value sets the minSdkVersion attribute in the build.gradle file.
Note: You can manually change the minimum and target SDK for your module at any
time: Double-click the module's build.gradle in the Project Explorer, set the
targetSdkVersion and targetSdkVersion in the defaultConfig section.
Select a Target SDK. This setting indicates the highest version of Android with
which you have tested with your application and sets the targetSdkVersion attribute
in your application's' build.gradle file.
Select a Compile With API version. This setting specifies what version of the SDK
to compile your project against. We strongly recommend using the most recent
version of the API.
Select a Language Level API version. This setting specifies what version of the SDK
to compile your project against. We strongly recommend using the most recent
version of the API.
Select a Theme. This setting specifies which standard Android visual style is applied
to your application. Select activity template. For more information about Android
code templates, see Using Code TemplatesLeave the Create activity option checked
so you can start your application with some essential components.
Click the check box for the required Support Libraries then click Next.
In the Configure Launcher Icon page, create an icon and options, then click Next.
In the Create Activity page, select activity template then click Next. For more
information about Android code templates, see Using Code Templates.
Review the new module settings then click Finish.
The wizard creates a new Android application module according to the options you have
chosen.
A library module is a standard Android module, so you can create a new one in the same way
as you would a new application module, using the New Module wizard and selecting Android
Library as the module type. The created library module will appear in your project view
along with the other modules.
You can easily change an existing application module to a library module by changing the
plugin assignment in the build.gradle file to com.android.libary.
android {...}
apply plugin: 'com.android.library'
android {...}
The library dependency can be declared in the module's manifest file or in the
<strong<build.gradle< strong=""> file. </strong<build.gradle<>
A library modules's manifest file must declare all of the shared components that it includes,
just as would a standard Android application. For more information, see the documentation
for AndroidManifest.xml.
For example, the TicTacToeLib example library project declares the activity GameActivity:
<manifest>
...
<application>
...
<activity android:name="GameActivity" />
...
</application>
</manifest>
To add the dependency declaration to the build file, edit the build file for the app module
(app/build.gradle) and add a dependency on the lib module:
...
dependencies {
...
compile project(":lib")
}
In this example, the lib module can still be built and tested independently, and the build
system creates an AAR package for it that you could reuse in other projects.
Note: The library settings in the app/build.gradle file will override any shared library
resources declared in the manifest file.
If you are developing an application and want to include the shared code or resources from a
library module, you can also do so easily by adding a reference to the library module in the
module's dependency page.
1. Make sure that both the module library and the application module that depends on it
are in your proejct. If one of the modules is missing, import it into your project.
2. In the project view, right-click the dependent module and select Open > Module
Settings.
3. Right-click the plus icon to add a new dependencies.
If you are adding references to multiple libraries, you can set their relative priority
(and merge order) by selecting a library and using the Up and Down controls. The
tools merge the referenced libraries with your application starting from lowest priority
(bottom of the list) to highest (top of the list). If more than one library defines the
same resource ID, the tools select the resource from the library with higher priority.
The application itself has highest priority and its resources are always used in
preference to identical resource IDs defined in libraries.
4. Use the Scope drop-down to select how the dependency will be applied.
5. Click Apply to create the dependency and OK to close the Project Structure
window.
Android Studio rebuilds the module, including the contents of the library module the next
time the project or module is built.
In the manifest file of the application module, you must add declarations of all components
that the application will use that are imported from a library module. For example, you must
declare any <activity>, <service>, <receiver>, <provider>, and so on, as well as
<permission>, <uses-library>, and similar elements.
Declarations should reference the library components by their fully-qualified package names,
where appropriate.
For example, the TicTacToeMain example application declares the library activity
GameActivity like this:
<manifest>
...
<application>
...
<activity
android:name="com.example.android.tictactoe.library.GameActivity" />
...
</application>
</manifest>
For more information about the manifest file, see the documentation for
AndroidManifest.xml.
The Android project view in Android Studio shows a flattened version of your project's
structure that provides quick access to the key source files of Android projects and helps you
work with the new Gradle-based build system. The Android project view:
Groups the build files for all modules at the top level of the project hierarchy.
Shows the most important source directories at the top level of the module hierarchy.
Groups all the manifest files for each module.
Shows resource files from all Gradle source sets.
Groups resource files for different locales, orientations, and screen types in a single
group per resource type.
The Android project view is not yet enabled by default. To show the Android project view,
click Project and select Android, as shown in figure 9.
The Android project view shows all the build files at the top level of the project hierarchy
under Gradle Scripts. Each project module appears as a folder at the top level of the project
hierarchy and contains these three elements at the top level:
Figure 10 shows how the Android project view groups all the instances of the
ic_launcher.png resource for different screen densities under the same element.
Note: The Android project view shows a hierarchy that helps you work with Android projects
by providing a flattened structure that highlights the most commonly used files while
developing Android applications. However, the project structure on disk differs from this
representation.
Figure 10: The traditional project view (left) and the Android project view (right).
See also
1. Testing from Other IDEs
The android tool provides you with commands to create all three types of projects. An
Android project contains all of the files and resources that are needed to build a project into
an .apk file for installation.
An Android project contains all of the files and resources that are needed to build a
project into an .apk file for installation. You need to create an Android project for any
application that you want to eventually install on a device.
You can also designate an Android project as a library project, which allows it to be
shared with other projects that depend on it. Once an Android project is designated as
a library project, it cannot be installed onto a device.
Test projects extend JUnit test functionality to include Android specific functionality.
For more information on creating a test project, see Testing from other IDEs.
To create an Android project, you must use the android tool. When you create a new project
with android, it will generate a project directory with some default application files, stub
files, configuration files and a build file.
To create a new Android project, open a command-line, navigate to the tools/ directory of
your SDK and run:
Here's an example:
Once you've created your project, you're ready to begin development. You can move your
project folder wherever you want for development, but keep in mind that you must use the
Android Debug Bridge (adb) — located in the SDK platform-tools/ directory — to send
your application to the emulator (discussed later). So you need access between your project
solution and the platform-tools/ folder.
Tip: Add the platform-tools/ as well as the tools/ directory to your PATH environment
variable.
Caution: You should refrain from moving the location of the SDK directory, because this
will break the SDK location property located in local.properties. If you need to update
the SDK location, use the android update project command. See Updating a Project for
more information.
Updating a Project
If you're up grading a project from an older version of the Android SDK or want to create a
new project from existing code, use the android update project command to update the
project to the new development environment. You can also use this command to revise the
build target of an existing project (with the --target option) and the project name (with the
--name option). The android tool will generate any files and folders (listed in the previous
section) that are either missing or need to be updated, as needed for the Android project.
To update an existing Android project, open a command-line and navigate to the tools/
directory of your SDK. Now run:
Here's an example:
To create a new library project, navigate to the <sdk>/tools/ directory and use this
command:
The create lib-project command creates a standard project structure that includes preset
property that indicates to the build system that the project is a library. It does this by adding
this line to the project's project.properties file:
android.library=true
Once the command completes, the library project is created and you can begin moving source
code and resources into it, as described in the sections below.
If you want to convert an existing application project to a library project, so that other
applications can use it, you can do so by adding a the android.library=true property to
the application's project.properties file.
A library project's manifest file must declare all of the shared components that it includes,
just as would a standard Android application. For more information, see the documentation
for AndroidManifest.xml.
For example, the TicTacToeLib example library project declares the Activity GameActivity:
<manifest>
...
<application>
...
<activity android:name="GameActivity" />
...
</application>
</manifest>
If you want to update the build properties (build target, location) of the library project, use
this command:
To add a reference to a library project, navigate to the <sdk>/tools/ directory and use this
command:
This command updates the application project's build properties to include a reference to the
library project. Specifically, it adds an android.library.reference.n property to the
project's project.properties file. For example:
android.library.reference.1=path/to/library_projectA
If you are adding references to multiple libraries, note that you can set their relative priority
(and merge order) by manually editing the project.properties file and adjusting the each
reference's .n index as appropriate. For example, assume these references:
android.library.reference.1=path/to/library_projectA
android.library.reference.2=path/to/library_projectB
android.library.reference.3=path/to/library_projectC
You can reorder the references to give highest priority to library_projectC in this way:
android.library.reference.2=path/to/library_projectA
android.library.reference.3=path/to/library_projectB
android.library.reference.1=path/to/library_projectC
Note that the .n index in the references must begin at "1" and increase uniformly without
"holes". References appearing in the index after a hole are ignored.
At build time, the libraries are merged with the application one at a time, starting from the
lowest priority to the highest. Note that a library cannot itself reference another library and
that, at build time, libraries are not merged with each other before being merged with the
application.
In the manifest file of the application project, you must add declarations of all components
that the application will use that are imported from a library project. For example, you must
declare any <activity>, <service>, <receiver>, <provider>, and so on, as well as
<permission>, <uses-library>, and similar elements.
Declarations should reference the library components by their fully-qualified package names,
where appropriate.
For example, the TicTacToeMain example application declares the library Activity
GameActivity like this:
<manifest>
...
<application>
...
<activity
android:name="com.example.android.tictactoe.library.GameActivity" />
...
</application>
</manifest>
For more information about the manifest file, see the documentation for
AndroidManifest.xml.
To build an application project that depends on one or more library projects, you can use the
standard Gradle build commands and compile modes, as described in Building and Running.
The tools compile and merge all libraries referenced by the application as part of compiling
the dependent application project. No additional commands or steps are necessary.
The SDK tools provide templates for quickly creating Android application projects with the
basic structure or for adding components to your existing application modules. The code
templates provided by the Android SDK follow the Android design and development
guidelines to get you on the right track to creating a beautiful, functional application.
There are several types of Android code templates, which can create anything from an entire
application down to specific application components. The main categories of code templates
are as follows:
Application Templates
Activity Templates
Other Templates
Application Templates
Application templates create basic Android application modules that you can immediately
run and test on your Android device. These templates are available when you create a new
Android module, though you can also use these templates to add new activities to an existing
module.
Note: The other activity template options also create applications, however these applications
require further modification before they can be launched on an Android device.
Example Description
Example Description
Activity Templates
Android activity templates provide options to add new activities to your existing application.
1. Right click the project folder of the Android application where you want to add an
activity.
2. Select New > Other...
3. Select Android > Android Activity, then click Next.
4. Select an activity template, then follow the instructions to add it to your existing
application.
o LoginActivity
o SettingsActivity
o BlankActivity
o FullScreenActivity
o MasterDetailFlow
These templates create the same type of activity as they do when used as an application
template, however the following templates create activities which are specifically intended to
be used as part of an existing application.
Example Description
Other Templates
Android object templates provide options to add new components to your existing
application, including the previously mentioned activities as well as the following additional
items:
1. Right-click the module folder of the Android application where you want to add a
code component.
2. Select New
3. Select the object type and template, then follow the instructions to add it to your
existing application.
o AIDL
o Activity
o Folder
o Fragment
o Google
o Other
o Service
o UI Component
o Wear
o Widget
o XML
Building and Running Overview
See also
1. Building Your Project from Android Studio
2. Building Your Project from the Command Line
3. Build System
The Android build process provides project and module build settings so that your Android
modules are compiled and packaged into .apk files, the containers for your application
binaries, based on your build settings. The apk file for each app contains all of the
information necessary to run your application on a device or emulator, such as compiled .dex
files (.class files converted to Dalvik byte code), a binary version of the
AndroidManifest.xml file, compiled resources (resources.arsc) and uncompiled resource
files for your application.
To run an application on an emulator or device, the application must be signed using debug
or release mode. You typically want to sign your application in debug mode when you
develop and test your application, because the build system uses a debug key with a known
password so you do not have to enter it every time you build. When you are ready to release
the application to Google Play, you must sign the application in release mode, using your
own private key.
If you are using Android development tools, the build system can sign the application for you
when build your app for debugging. You must obtain a certificate to sign your app when you
build and app for release. For more information on signing applications, see Signing Your
Applications.
The following diagram depicts the components involved in building and running an
application:
See also
1. Build System
2. Managing AVDs with AVD Manager
3. Using the Android Emulator
4. Signing Your Applications
This document shows you how to use Android Studio to build an application .apk for testing
or release and how to run your application on an emulator or a real device.
To build the project on Android Studio, click Build and select Make Project. The status bar
at the bottom of the window shows the current progress of the build:
Click on the bottom right part of the window to show the Gradle Console,
as shown in figure 2.
The Gradle Console shows the build tasks and subtasks that the build system runs for
Android Studio. If the build fails, you can find more details on the console. To hide the
Gradle Console, click again.
If your project uses product flavors, Android Studio invokes the task for the selected build
variant. For more information, see the Build System guide.
To view the list of all available build tasks in Android Studio, click Gradle on the right side
of the IDE window. The Gradle tasks panel appears as shown in figure 3. Double-click any
build task to run it in Android Studio. To hide the Gradle tasks panel, click Gradle again.
You can now build the release version of your application for distribution. To build it from
Android Studio:
You can use this procedure to invoke any build task from Android Studio.
The build generates an APK for each build variant: the app/build/apk/ directory contains
packages named app-<flavor>-<buildtype>.apk; for example, app-full-release.apk
and app-demo-debug.apk.
This section shows you how to run your application on an emulator or a real device from
Android Studio—all of which is done using the debug version of your application. For more
information about how to sign your application with a private key for release, see Signing
Your Applications
The run configuration specifies the module to run, package to deploy, Activity to start, target
device, emulator settings, and Logcat options. Run configuration can be set at the project,
default, and module levels. When you first run a module as an Android Application, Android
Studio will automatically create a run configuration. The default run configuration will
launch the default project Activity and use automatic target mode for device selection (with
no preferred AVD). If the default settings don't suit your project or module, you can
customize the run configuration or even create a new one.
The following steps highlight the important things you need to do for an Android project:
By default, a run configuration uses the automatic target mode in order to select an AVD. In
this mode, Android Studio will select an AVD for the application in the following manner:
1. If there's a device or emulator already running and its AVD configuration meets the
requirements of the application's build target, the application is installed and run upon
it.
2. If there's more than one device or emulator running, each of which meets the
requirements of the build target, a device chooser is shown to let you select which
device to use.
3. If there are no devices or emulators running that meet the requirements of the build
target, Android Studio looks at the available AVDs. If there is an AVD that matches
the build target of the project, Android Studio chooses that AVD. If the AVD versions
are newer than the build target of the project, Android Studio chooses the oldest
possible version of an AVD that meets the project or module build target requirement.
4. If there are no suitable AVDs, the application is not installed and a console error
warning tells you that there is no existing AVD that meets the build target
requirements.
However, if a "preferred" AVD is selected in the run configuration, then the application will
always be deployed to that AVD. If it's not already running, then a new emulator will be
launched.
If your run configuration uses manual mode, then the "device chooser" is presented every
time that your application is run, so that you can select which AVD to use.
Before you can run your application on the Android Emulator, you verify the default AVD or
create an AVD.
To run (or debug) your application, select Run > Run (or Run > debug) from the Android
Studio menu bar. Android Studio automatically creates a default run configuration for the
project. Android Studio will then perform the following:
1. Compile the project (if there have been changes since the last build).
2. Create a default run configuration (if one does not already exist for the project).
3. Install and start the application on an emulator (or device), based on the Deployment
Target defined by the run configuration.
By default, Android run configurations use an "automatic target" mode for selecting a
device target. For information on how automatic target mode selects a deployment
target, see Automatic and manual target modes above.
If you run the application with Debug, the Choose a Device option appears so you can select
an attached device or emulator. Once the device or emulator is selected, Android Studio
opens the Debug console and starts the application's main activity. Otherwise, if you run the
application with the normal Run command, Android Studio installs the application on the
device and launches the main activity.
To set or change the run configuration used for your project or module, select Run > Edit
Configurations. See the section below about Creating a Run Configuration for more
information.
Be certain to create multiple AVDs upon which to test your application. You should have one
AVD for each platform and screen type with which your application is compatible. For
instance, if your application compiles against the Android 4.0 (API Level 14) platform, you
should create an AVD for each platform equal to and greater than 4.0 and an AVD for each
screen type you support, then test your application on each one.
Running on a device
Before you can run your application on a device, you must perform some basic setup for your
device:
Ensure that your application is debuggable by setting the android:debuggable
attribute of the <application> element to true in the build.gradle file.
Enable USB debugging on your device.
o On most devices running Android 3.2 or older, you can find the option under
Settings > Applications > Development.
o On Android 4.0 and newer, it's in Settings > Developer options.
Ensure that your development computer can detect your device when connected via
USB
Once set up and your device is connected via USB, install your application on the device by
selecting Run > Run (or Run > Debug) from the Android Studio menu bar.
See also
1. Build System
2. Managing AVDs from the Command Line
3. Using the Android Emulator
4. Signing Your Applications
By default, there are two build types to build your application using the gradle.build settings:
one for debugging your application — debug — and one for building your final package for
release — release mode. Regardless of which way you build type your modules use, the app
must be signed before it can install on an emulator or device—with a debug key when
building in debug mode and with your own private key when building in release mode.
Whether you're building with the debug or release build type, you need to run and build your
module. This will create the .apk file that you can install on an emulator or device. When you
build using the debug build type, the .apk file is automatically signed by the SDK tools with a
debug key based on the debuggable true setting in the module's gradle.build file, so it's
instantly ready for installation onto an emulator or attached development device. You cannot
distribute an application that is signed with a debug key. When you build using the release
build type, the .apk file is unsigned, so you must manually sign it with your own private key,
using Keytool and Jarsigner settings in the module's gradle.build file.
It's important that you read and understand Signing Your Applications, particularly once
you're ready to release your application and share it with end-users. That document describes
the procedure for generating a private key and then using it to sign your .apk file. If you're
just getting started, however, you can quickly run your applications on an emulator or your
own development device by building in debug mode.
If you don't have Gradle, you can obtain it from the Gradle home page. Install it and make
sure it is in your executable PATH. Before calling Ant, you need to declare the
JAVA_HOME environment variable to specify the path to where the JDK is installed.
Note: When installing JDK on Windows, the default is to install in the "Program Files"
directory. This location will cause ant to fail, because of the space. To fix the problem, you
can specify the JAVA_HOME variable like this:
set JAVA_HOME=c:\Progra~1\Java\<jdkdir>
The easiest solution, however, is to install JDK in a non-space directory, for example:
c:\java\jdk1.7
For immediate application testing and debugging, you can build your application in debug
mode and immediately install it on an emulator. In debug mode, the build tools automatically
sign your application with a debug key and optimize the package with zipalign.
To build in debug mode, open a command-line and navigate to the root of your project
directory. Use Gradle to build your project in debug mode, invoke the assembleDebug build
task using the Gradle wrapper script (gradlew assembleRelease).
This creates your debug .apk file inside the module build/ directory, named
<your_module_name>-debug.apk. The file is already signed with the debug key and has
been aligned with zipalign.
The first command (chmod) adds the execution permission to the Gradle wrapper script and is
only necessary the first time you build this project from the command line.
After you build the project, the output APK for the app module is located in
app/build/outputs/apk/, and the output AAR for any lib modules is located in
lib/build/outputs/libs/.
To see a list of all available build tasks for your project, type this command:
$ ./gradlew tasks
Each time you change a source file or resource, you must run Gradle again in order to
package up the latest version of the application.
To install and run your application on an emulator, see the section about Running on the
Emulator.
When you're ready to release and distribute your application to end-users, you must build
your application in release mode. Once you have built in release mode, it's a good idea to
perform additional testing and debugging with the final .apk.
Before you start building your application in release mode, be aware that you must sign the
resulting application package with your private key, and should then align it using the
zipalign tool. There are two approaches to building in release mode: build an unsigned
package in release mode and then manually sign and align the package, or allow the build
script to sign and align the package for you.
Build unsigned
If you build your application unsigned, then you will need to manually sign and align the
package.
To build an unsigned .apk in release mode, open a command-line and navigate to the root of
your module directory. Invoke the assembleRelease build task.
$ ./gradlew assembleRelease
This creates your Android application .apk file inside the project bin/ directory, named
<your_module_name>-unsigned.apk.
Note: The .apk file is unsigned at this point and can't be installed until signed with your
private key.
Once you have created the unsigned .apk, your next step is to sign the .apk with your private
key and then align it with zipalign. To complete this procedure, read Signing Your
Applications.
When your .apk has been signed and aligned, it's ready to be distributed to end-users. You
should test the final build on different devices or AVDs to ensure that it runs properly on
different platforms.
If you would like, you can configure the Android build script to automatically sign and align
your application package. To do so, you must provide the path to your keystore and the name
of your key alias in your modules's build.gradle file. With this information provided, the
build will prompt you for your keystore and alias password when you build using the release
build type and produce your final application package, which will be ready for distribution.
To specify your keystore and alias, open the module gradle.build file (found in the root of the
module directory) and add entries for storeFile, storePassword, keyAlias and
keyPassword. For example:
storeFile file("myreleasekey.keystore")
keyAlias "MyReleaseKey"
Save your changes. Now you can build a signed .apk in release mode:
...
android {
...
defaultConfig { ... }
signingConfigs {
release {
storeFile file("myreleasekey.keystore")
storePassword "password"
keyAlias "MyReleaseKey"
keyPassword "password"
}
}
buildTypes {
release {
...
signingConfig signingConfigs.release
}
}
}
...
3. When prompted, enter you keystore and alias passwords.
This creates your Android application .apk file inside the module build/ directory, named
<your_module_name>-release.apk. This .apk file has been signed with the private key
specified in gradle.build file and aligned with zipalign. It's ready for installation and
distribution.
Once you have signed your application with a private key, you can install and run it on an
emulator or device. You can also try installing it onto a device from a web server. Simply
upload the signed .apk to a web site, then load the .apk URL in your Android web browser to
download the application and begin installation. (On your device, be sure you have enabled
Settings > Applications > Unknown sources.)
Before you can run your application on the Android Emulator, you must create an AVD.
From your SDK's platform-tools/ directory, execute the android tool with the avd
options:
android avd
From your SDK's tools/ directory, install the .apk on the emulator:
Your .apk file (signed with either a release or debug key) is in your module build/
directory after you build your application.
If there is more than one emulator running, you must specify the emulator upon which
to install the application, by its serial number, with the -s option. For example:
Be certain to create multiple AVDs upon which to test your application. You should have one
AVD for each platform and screen type with which your application is compatible. For
instance, if your application compiles against the Android 4.0 (API Level 14) platform, you
should create an AVD for each platform equal to and greater than 4.0 and an AVD for each
screen type you support, then test your application on each one.
Tip: If you have only one emulator running, you can build your application and install it on
the emulator in one simple step. Navigate to the root of your project directory and use Ant to
compile the project with install mode: ant install. This will build your application, sign it
with the debug key, and install it on the currently running emulator.
Running on a Device
Before you can run your application on a device, you must perform some basic setup for your
device:
Ensure that your development computer can detect your device when connected via
USB
Once your device is set up and connected via USB, navigate to your SDK's platform-
tools/ directory and install the .apk on the device:
The -d flag specifies that you want to use the attached device (in case you also have an
emulator running).
For more information on the tools used above, please see the following documents:
android Tool
Android Emulator
Android Debug Bridge (ADB)
Application Signing
As you begin developing Android applications, understand that all Android applications must
be digitally signed before the system will install them on an emulator or device. There are
two ways to do this: with a debug key (for immediate testing on an emulator or development
device) or with a private key (for application distribution).
The Android build tools help you get started by automatically signing your .apk files with a
debug key at build time. This means that you can build your application and install it on the
emulator without having to generate your own private key. However, please note that if you
intend to publish your application, you must sign the application with your own private key,
rather than the debug key generated by the SDK tools.
Android Studio helps you get started quickly by signing your .apk files with a debug key,
prior to installing them on an emulator or development device. This means that you can
quickly run your application from Android Studio without having to generate your own
private key. No specific action on your part is needed, provided ADT has access to Keytool.
However, please note that if you intend to publish your application, you must sign the
application with your own private key, rather than the debug key generated by the SDK tools.
Please read Signing Your Applications, which provides a thorough guide to application
signing on Android and what it means to you as an Android application developer. The
document also includes a guide to publishing and signing your application.
See the Gradle Build Language Reference for a complete list and description of the Gradle
Domain Specific Language (DSL) and declarative language elements.
Testing
The Android framework includes an integrated testing framework that helps you test all
aspects of your application and the SDK tools include tools for setting up and running test
applications. Whether you are working in Eclipse with ADT or working from the command
line, the SDK tools help you set up and run your tests within an emulator or the device you
are targeting.
If you aren't yet familiar with the Android testing framework, start by reading Testing
Fundamentals. For a step-by-step introduction to Android testing, try the Activity Testing
Tutorial.
Blog Articles
StrictMode is a new API in Gingerbread which primarily lets you set a policy on a thread
declaring what you’re not allowed to do on that thread, and what the penalty is if you violate
the policy. Implementation-wise, this policy is simply a thread-local integer bitmask.
I recently took my first serious look at Traceview, and it occurred to me, first, that there are
probably a few other Android developers who haven’t used it and, second, that this is an
opportunity to lecture sternly on one of my favorite subjects: performance improvement and
profiling.
Testing Fundamentals
In this document
1. Test Structure
2. Test Projects
3. The Testing API
1. JUnit
2. Instrumentation
3. Test case classes
4. Assertion classes
5. Mock object classes
4. Running Tests
5. Seeing Test Results
6. monkey and monkeyrunner
7. Working With Package Names
8. What To Test
9. Next Steps
Key classes
1. InstrumentationTestRunner
2. android.test
3. android.test.mock
4. junit.framework
Related tutorials
1. Activity Testing Tutorial
See also
1. Testing from Eclipse with ADT
2. Testing from Other IDEs
3. monkeyrunner
4. UI/Application Exerciser Monkey
The Android testing framework, an integral part of the development environment, provides
an architecture and powerful tools that help you test every aspect of your application at every
level from unit to framework.
Android test suites are based on JUnit. You can use plain JUnit to test a class that doesn't call
the Android API, or Android's JUnit extensions to test Android components. If you're new to
Android testing, you can start with general-purpose test case classes such as
AndroidTestCase and then go on to use more sophisticated classes.
The Android JUnit extensions provide component-specific test case classes. These classes
provide helper methods for creating mock objects and methods that help you control the
lifecycle of a component.
Test suites are contained in test packages that are similar to main application packages, so
you don't need to learn a new set of tools or techniques for designing and building tests.
The SDK tools for building and tests are available in Eclipse with ADT, and also in command-
line form for use with other IDEs. These tools get information from the project of the
application under test and use this information to automatically create the build files,
manifest file, and directory structure for the test package.
The SDK also provides monkeyrunner, an API for testing devices with Python programs, and
UI/Application Exerciser Monkey, a command-line tool for stress-testing UIs by sending
pseudo-random events to a device.
This document describes the fundamentals of the Android testing framework, including the
structure of tests, the APIs that you use to develop tests, and the tools that you use to run tests
and view results. The document assumes you have a basic knowledge of Android application
programming and JUnit testing methodology.
The following diagram summarizes the testing framework:
Test Structure
Android's build and test tools assume that test projects are organized into a standard structure
of tests, test case classes, test packages, and test projects.
Android testing is based on JUnit. In general, a JUnit test is a method whose statements test a
part of the application under test. You organize test methods into classes called test cases (or
test suites). Each test is an isolated test of an individual module in the application under test.
Each class is a container for related test methods, although it often provides helper methods
as well.
In JUnit, you build one or more test source files into a class file. Similarly, in Android you
use the SDK's build tools to build one or more test source files into class files in an Android
test package. In JUnit, you use a test runner to execute test classes. In Android, you use test
tools to load the test package and the application under test, and the tools then execute an
Android-specific test runner.
Test Projects
A test project is a directory or Eclipse project in which you create the source code, manifest
file, and other files for a test package. The Android SDK contains tools for Eclipse with ADT
and for the command line that create and update test projects for you. The tools create the
directories you use for source code and resources and the manifest file for the test package.
The command-line tools also create the Ant build files you need.
You should always use Android tools to create a test project. Among other benefits, the tools:
You can create a test project anywhere in your file system, but the best approach is to add the
test project so that its root directory tests/ is at the same level as the src/ directory of the
main application's project. This helps you find the tests associated with an application. For
example, if your application project's root directory is MyProject, then you should use the
following directory structure:
MyProject/
AndroidManifest.xml
res/
... (resources for main application)
src/
... (source code for main application) ...
tests/
AndroidManifest.xml
res/
... (resources for tests)
src/
... (source code for tests)
The Android testing API is based on the JUnit API and extended with a instrumentation
framework and Android-specific testing classes.
JUnit
You can use the JUnit TestCase class to do unit testing on a class that doesn't call Android
APIs. TestCase is also the base class for AndroidTestCase, which you can use to test
Android-dependent objects. Besides providing the JUnit framework, AndroidTestCase offers
Android-specific setup, teardown, and helper methods.
You use the JUnit Assert class to display test results. The assert methods compare values
you expect from a test to the actual results and throw an exception if the comparison fails.
Android also provides a class of assertions that extend the possible types of comparisons, and
another class of assertions for testing the UI. These are described in more detail in the section
Assertion classes
To learn more about JUnit, you can read the documentation on the junit.org home page. Note
that the Android testing API supports JUnit 3 code style, but not JUnit 4. Also, you must use
Android's instrumented test runner InstrumentationTestRunner to run your test case
classes. This test runner is described in the section Running Tests.
Instrumentation
Android instrumentation is a set of control methods or "hooks" in the Android system. These
hooks control an Android component independently of its normal lifecycle. They also control
how Android loads applications.
Normally, an Android component runs in a lifecycle determined by the system. For example,
an Activity object's lifecycle starts when the Activity is activated by an Intent. The object's
onCreate() method is called, followed by onResume(). When the user starts another
application, the onPause() method is called. If the Activity code calls the finish() method,
the onDestroy() method is called. The Android framework API does not provide a way for
your code to invoke these callback methods directly, but you can do so using instrumentation.
Also, the system runs all the components of an application into the same process. You can
allow some components, such as content providers, to run in a separate process, but you can't
force an application to run in the same process as another application that is already running.
With Android instrumentation, though, you can invoke callback methods in your test code.
This allows you to run through the lifecycle of a component step by step, as if you were
debugging the component. The following test code snippet demonstrates how to use this to
test that an Activity saves and restores its state:
// Stop the activity - The onDestroy() method should save the state of
the Spinner
mActivity.finish();
// Re-start the Activity - the onResume() method should restore the
state of the Spinner
mActivity = getActivity();
The key method used here is getActivity(), which is a part of the instrumentation API. The
Activity under test is not started until you call this method. You can set up the test fixture in
advance, and then call this method to start the Activity.
Also, instrumentation can load both a test package and the application under test into the
same process. Since the application components and their tests are in the same process, the
tests can invoke methods in the components, and modify and examine fields in the
components.
Android provides several test case classes that extend TestCase and Assert with Android-
specific setup, teardown, and helper methods.
AndroidTestCase
A useful general test case class, especially if you are just starting out with Android testing, is
AndroidTestCase. It extends both TestCase and Assert. It provides the JUnit-standard
setUp() and tearDown() methods, as well as all of JUnit's Assert methods. In addition, it
provides methods for testing permissions, and a method that guards against memory leaks by
clearing out certain class references.
A key feature of the Android testing framework is its component-specific test case classes.
These address specific component testing needs with methods for fixture setup and teardown
and component lifecycle control. They also provide methods for setting up mock objects.
These classes are described in the component-specific testing topics:
Activity Testing
Content Provider Testing
Service Testing
Android does not provide a separate test case class for BroadcastReceiver. Instead, test a
BroadcastReceiver by testing the component that sends it Intent objects, to verify that the
BroadcastReceiver responds correctly.
ApplicationTestCase
You use the ApplicationTestCase test case class to test the setup and teardown of
Application objects. These objects maintain the global state of information that applies to
all the components in an application package. The test case can be useful in verifying that the
<application> element in the manifest file is correctly set up. Note, however, that this test
case does not allow you to control testing of the components within your application package.
InstrumentationTestCase
If you want to use instrumentation methods in a test case class, you must use
InstrumentationTestCase or one of its subclasses. The Activity test cases extend this
base class with other functionality that assists in Activity testing.
Assertion classes
Because Android test case classes extend JUnit, you can use assertion methods to display the
results of tests. An assertion method compares an actual value returned by a test to an
expected value, and throws an AssertionException if the comparison test fails. Using
assertions is more convenient than doing logging, and provides better test performance.
Besides the JUnit Assert class methods, the testing API also provides the MoreAsserts and
ViewAsserts classes:
To facilitate dependency injection in testing, Android provides classes that create mock
system objects such as Context objects, ContentProvider objects, ContentResolver
objects, and Service objects. Some test cases also provide mock Intent objects. You use
these mocks both to isolate tests from the rest of the system and to facilitate dependency
injection for testing. These classes are found in the packages android.test and
android.test.mock.
Mock objects isolate tests from a running system by stubbing out or overriding normal
operations. For example, a MockContentResolver replaces the normal resolver framework
with its own local framework, which is isolated from the rest of the system.
MockContentResolver also stubs out the notifyChange(Uri, ContentObserver,
boolean) method so that observer objects outside the test environment are not accidentally
triggered.
Mock object classes also facilitate dependency injection by providing a subclass of the
normal object that is non-functional except for overrides you define. For example, the
MockResources object provides a subclass of Resources in which all the methods throw
Exceptions when called. To use it, you override only those methods that must provide
information.
With this feature, you can associate a mock content provider with an authority. You can
create an instance of a real provider but use test data in it. You can even set the provider for
an authority to null. In effect, a MockContentResolver object isolates your test from
providers that contain real data. You can control the function of the provider, and you can
prevent your test from affecting real data.
Android provides two Context classes that are useful for testing:
This class allows you to test an application's data operations without affecting real
data that may be present on the device.
This object provides a quick way to set up an isolated area for data operations, while
keeping normal functionality for all other Context operations.
Running Tests
Test cases are run by a test runner class that loads the test case class, set ups, runs, and tears
down each test. An Android test runner must also be instrumented, so that the system utility
for starting applications can control how the test package loads test cases and the application
under test. You tell the Android platform which instrumented test runner to use by setting a
value in the test package's manifest file.
InstrumentationTestRunner is the primary Android test runner class. It extends the JUnit
test runner framework and is also instrumented. It can run any of the test case classes
provided by Android and supports all possible types of testing.
Note: If you use a test runner other than InstrumentationTestRunner, you must change the
<instrumentation> element to point to the class you want to use.
The system classes load and start the test package, kill any processes that are running an
instance of the application under test, and then load a new instance of the application under
test. They then pass control to InstrumentationTestRunner, which runs each test case class
in the test package. You can also control which test cases and methods are run using settings
in Eclipse with ADT, or using flags with the command-line tools.
Neither the system classes nor InstrumentationTestRunner run the application under test.
Instead, the test case does this directly. It either calls methods in the application under test, or
it calls its own methods that trigger lifecycle events in the application under test. The
application is under the complete control of the test case, which allows it to set up the test
environment (the test fixture) before running a test. This is demonstrated in the previous code
snippet that tests an Activity that displays a Spinner widget.
To learn more about running tests, please read the topics Testing from Eclipse with ADT or
Testing from Other IDEs.
The Android testing framework returns test results back to the tool that started the test. If you
run a test in Eclipse with ADT, the results are displayed in a new JUnit view pane. If you run
a test from the command line, the results are displayed in STDOUT. In both cases, you see a
test summary that displays the name of each test case and method that was run. You also see
all the assertion failures that occurred. These include pointers to the line in the test code
where the failure occurred. Assertion failures also list the expected value and actual value.
The test results have a format that is specific to the IDE that you are using. The test results
format for Eclipse with ADT is described in Testing from Eclipse with ADT. The test results
format for tests run from the command line is described in Testing from Other IDEs.
The UI/Application Exerciser Monkey, usually called "monkey", is a command-line tool that
sends pseudo-random streams of keystrokes, touches, and gestures to a device. You run it
with the Android Debug Bridge (adb) tool. You use it to stress-test your application and
report back errors that are encountered. You can repeat a stream of events by running the
tool each time with the same random number seed.
The monkeyrunner tool is an API and execution environment for test programs written in
Python. The API includes functions for connecting to a device, installing and uninstalling
packages, taking screenshots, comparing two images, and running a test package against an
application. Using the API, you can write a wide range of large, powerful, and complex tests.
You run programs that use the API with the monkeyrunner command-line tool.
In the test environment, you work with both Android application package names and Java
package identifiers. Both use the same naming format, but they represent substantially
different entities. You need to know the difference to set up your tests correctly.
An Android package name is a unique system name for a .apk file, set by the
"android:package" attribute of the <manifest> element in the package's manifest. The
Android package name of your test package must be different from the Android package
name of the application under test. By default, Android tools create the test package name by
appending ".test" to the package name of the application under test.
The test package also uses an Android package name to target the application package it tests.
This is set in the "android:targetPackage" attribute of the <instrumentation> element in the
test package's manifest.
A Java package identifier applies to a source file. This package name reflects the directory
path of the source file. It also affects the visibility of classes and members to each other.
Android tools that create test projects set up an Android test package name for you. From
your input, the tools set up the test package name and the target package name for the
application under test. For these tools to work, the application project must already exist.
By default, these tools set the Java package identifier for the test class to be the same as the
Android package identifier. You may want to change this if you want to expose members in
the application under test by giving them package visibility. If you do this, change only the
Java package identifier, not the Android package names, and change only the test case source
files. Do not change the Java package name of the generated R.java class in your test
package, because it will then conflict with the R.java class in the application under test. Do
not change the Android package name of your test package to be the same as the application
it tests, because then their names will no longer be unique in the system.
What to Test
The topic What To Test describes the key functionality you should test in an Android
application, and the key situations that might affect that functionality.
Most unit testing is specific to the Android component you are testing. The topics Activity
Testing, Content Provider Testing, and Service Testing each have a section entitled "What To
Test" that lists possible testing areas.
When possible, you should run these tests on an actual device. If this is not possible, you can
use the Android Emulator with Android Virtual Devices configured for the hardware,
screens, and versions you want to test.
Next Steps
To learn how to set up and run tests in Eclipse, please refer to Testing from Eclipse with
ADT. If you're not working in Eclipse, refer to Testing from Other IDEs.
If you want a step-by-step introduction to Android testing, try the Activity Testing Tutorial.
This topic explains how create and run tests of Android applications in Eclipse with ADT.
Before you read this topic, you should read about how to create an Android application with
the basic processes for creating and running applications with ADT, as described in
Managing Projects from Eclipse and Building and Running from Eclipse. You may also want
to read Testing Fundamentals, which provides an overview of the Android testing framework.
ADT provides several features that help you set up and manage your testing environment
effectively:
It lets you quickly create a test project and link it to the application under test. When it
creates the test project, it automatically inserts the necessary <instrumentation>
element in the test package's manifest file.
It lets you quickly import the classes of the application under test, so that your tests
can inspect them.
It lets you create run configurations for your test package and include in them flags
that are passed to the Android testing framework.
It lets you run your test package without leaving Eclipse. ADT builds both the
application under test and the test package automatically, installs them if necessary to
your device or emulator, runs the test package, and displays the results in a separate
window in Eclipse.
If you are not developing in Eclipse or you want to learn how to create and run tests from the
command line, see Testing from Other IDEs.
To set up a test environment for your Android application, you must first create a separate
project that holds the test code. The new project follows the directory structure used for any
Android application. It includes the same types of content and files, such as source code,
resources, a manifest file, and so forth. The test package you create is connected to the
application under test by an <instrumentation> element in its manifest file.
The New Android Test Project dialog makes it easy for you to generate a new test project that
has the proper structure, including the <instrumentation> element in the manifest file. You
can use the New Android Test Project dialog to generate the test project at any time. The
dialog appears just after you create a new Android main application project, but you can also
run it to create a test project for a project that you created previously.
1. In Eclipse, select File > New > Other. This opens the Select a Wizard dialog.
2. In the dialog, in the Wizards drop-down list, find the entry for Android, then click the
toggle to the left. Select Android Test Project, then at the bottom of the dialog click
Next. The New Android Test Project wizard appears.
3. Next to Test Project Name, enter a name for the project. You may use any name, but
you may want to associate the name with the project name for the application under
test. One way to do this is to take the application's project name, append the string
"Test" to it, and then use this as the test package project name.
The name becomes part of the suggested project path, but you can change this in the
next step.
4. In the Content panel, examine the suggested path to the project. If Use default
location is set, then the wizard will suggest a path that is a concatenation of the
workspace path and the project name you entered. For example, if your workspace
path is /usr/local/workspace and your project name is MyTestApp, then the wizard
will suggest /usr/local/workspace/MyTestApp. To enter your own choice for a
path, unselect Use default location, then enter or browse to the path where you want
your project.
To learn more about choosing the location of test projects, please read Testing
Fundamentals.
5. In the Test Target panel, set An Existing Android Project, click Browse, then select
your Android application from the list. You now see that the wizard has completed
the Test Target Package, Application Name, and Package Name fields for you (the
latter two are in the Properties panel).
6. In the Build Target panel, select the Android SDK platform that the application under
test uses.
7. Click Finish to complete the wizard. If Finish is disabled, look for error messages at
the top of the wizard dialog, and then fix any problems.
Once you have created a test project, you populate it with a test package. This package does
not require an Activity, although you can define one if you wish. Although your test package
can combine Activity classes, test case classes, or ordinary classes, your main test case
should extend one of the Android test case classes or JUnit classes, because these provide the
best testing features.
Test packages do not need to have an Android GUI. When you run the package in Eclipse
with ADT, its results appear in the JUnit view. Running tests and seeing the results is
described in more detail in the section Running Tests.
To create a test package, start with one of Android's test case classes defined in
android.test. These extend the JUnit TestCase class. The Android test classes for Activity
objects also provide instrumentation for testing an Activity. To learn more about test case
classes, please read the topic Testing Fundamentals.
Before you create your test package, you choose the Java package identifier you want to use
for your test case classes and the Android package name you want to use. To learn more
about this, please read Testing Fundamentals.
1. In the Project Explorer tab, open your test project, then open the src folder.
2. Find the Java package identifier set by the projection creation wizard. If you haven't
added classes yet, this node won't have any children, and its icon will not be filled in.
If you want to change the identifier value, right-click the identifier and select
Refactor > Rename, then enter the new name.
3. When you are ready, right-click the Java package identifier again and select New >
Class. This displays the New Java Class dialog, with the Source folder and Package
values already set.
4. In the Name field, enter a name for the test case class. One way to choose a class
name is to append the string "Test" to the class of the component you are testing. For
example, if you are testing the class MyAppActivity, your test case class name would
be MyAppActivityTest. Leave the modifiers set to public.
5. In the Superclass field, enter the name of the Android test case class you are
extending. You can also browse the available classes.
6. In Which method stubs would you like to create?, unset all the options, then click
Finish. You will set up the constructor manually.
7. Your new class appears in a new Java editor pane.
You now have to ensure that the constructor is set up correctly. Create a constructor for your
class that has no arguments; this is required by JUnit. As the first statement in this
constructor, add a call to the base class' constructor. Each base test case class has its own
constructor signature. Refer to the class documentation in the documentation for
android.test for more information.
To control your test environment, you will want to override the setUp() and tearDown()
methods:
setUp(): This method is invoked before any of the test methods in the class. Use it to
set up the environment for the test (the test fixture. You can use setUp() to instantiate
a new Intent with the action ACTION_MAIN. You can then use this intent to start the
Activity under test.
tearDown(): This method is invoked after all the test methods in the class. Use it to
do garbage collection and to reset the test fixture.
Another useful convention is to add the method testPreconditions() to your test class.
Use this method to test that the application under test is initialized correctly. If this test fails,
you know that that the initial conditions were in error. When this happens, further test results
are suspect, regardless of whether or not the tests succeeded.
The Resources tab contains an Activity Testing tutorial with more information about creating
test classes and methods.
Running Tests
To run tests created in Eclipse with ADT with command-line tools, you must first install
additional files into the test project using the android tool's "create test-project" option. To
see how to do this, read Testing in Other IDEs.
When you run a test package in Eclipse with ADT, the output appears in the Eclipse JUnit
view. You can run the entire test package or one test case class. To do run tests, Eclipse runs
the adb command for running a test package, and displays the output, so there is no
difference between running tests inside Eclipse and running them from the command line.
As with any other package, to run a test package in Eclipse with ADT you must either attach
a device to your computer or use the Android emulator. If you use the emulator, you must
have an Android Virtual Device (AVD) that uses the same target as the test package.
Run a test just as you run an application, by selecting Run As... > Android JUnit
Test from the project's context menu or from the main menu's Run item.
Create an Eclipse run configuration for your test project. This is useful if you want
multiple test suites, each consisting of selected tests from the project. To run a test
suite, you run the test configuration.
1. In the Package Explorer, select the test project, then from the main menu, select Run
> Run Configurations.... The Run Configurations dialog appears.
2. In the left-hand pane, find the Android JUnit Test entry. In the right-hand pane, click
the Test tab. The Name: text box shows the name of your project. The Test class:
dropdown box shows one of the test classes in your project.
3. To run one test class, click Run a single test, then enter your project name in the
Project: text box and the class name in the Test class: text box.
To run all the test classes, click Run all tests in the selected project or package, then
enter the project or package name in the text box.
Note: Although you can run the test immediately by clicking Run, you should save
the test first and then run it by selecting it from the Eclipse standard toolbar.
9. On the Eclipse standard toolbar, click the down arrow next to the green Run arrow.
This displays a menu of saved Run and Debug configurations.
10. Select the test run configuration you just created. The test starts.
The progress of your test appears in the Console view as a series of messages. Each message
is preceded by a timestamp and the .apk filename to which it applies. For example, this
message appears when you run a test to the emulator, and the emulator is not yet started:
Message Examples
The examples shown in this section come from the SpinnerTest sample test package, which
tests the Spinner sample application. This test package is also featured in the Activity Testing
tutorial.
In the following description of these messages, devicename is the name of the device or
emulator you are using to run the test, and port is the port number for the device. The name
and port number are in the format used by the adb devices command. Also, testfile is the
.apk filename of the test package you are running, and appfile is the filename of the
application under test.
If you are using an emulator and you have not yet started it, then Eclipse first starts
the emulator. When this is complete, you see the message:
If you have not already installed your test package, then you see the message:
Next, if you have not yet installed the application under test to the device or emulator,
you see the message
followed by
Finally, you see the message Running tests, which indicates that your tests are
running. At this point, you should start seeing the test results in the JUnit view. When
the tests are finished, you see the console message Test run complete. This
indicates that your tests are finished.
The test results appear in the JUnit view. This is divided into an upper summary pane, and a
lower stack trace pane.
The upper pane contains test information. In the pane's header, you see the following
information:
Total time elapsed for the test package (labeled Finished after x seconds).
Number of runs (Runs:) - the number of tests in the entire test class.
Number of errors (Errors:) - the number of program errors and exceptions
encountered during the test run.
Number of failures (Failures:) - the number of test failures encountered during the test
run. This is the number of assertion failures. A test can fail even if the program does
not encounter an error.
A progress bar. The progress bar extends from left to right as the tests run. If all the
tests succeed, the bar remains green. If a test fails, the bar turns from green to red.
The body of the upper pane contains the details of the test run. For each test case class that
was run, you see a line with the class name. To look at the results for the individual test
methods in that class, you click the left arrow to expand the line. You now see a line for each
test method in the class, and to its right the time it took to run. If you double-click the method
name, Eclipse opens the test class source in an editor view pane and moves the focus to the
first line of the test method.
The lower pane is for stack traces. If you highlight a failed test in the upper pane, the lower
pane contains a stack trace for the test. If a line corresponds to a point in your test code, you
can double-click it to display the code in an editor view pane, with the line highlighted. For a
successful test, the lower pane is empty.
See Also
1. Testing Fundamentals
2. Android Debug Bridge
This document describes how to create and run tests directly from the command line. You
can use the techniques described here if you are developing in an IDE other than Eclipse or if
you prefer to work from the command line. This document assumes that you already know
how to create a Android application in your programming environment. Before you start this
document, you should read the topic Testing Fundamentals, which provides an overview of
Android testing.
If you are developing in Eclipse with ADT, you can set up and run your tests directly in
Eclipse. For more information, please read Testing from Eclipse with ADT.
You use the android tool to create test projects. You also use android to convert existing
test code into an Android test project, or to add the test Ant target to an existing Android
test project. These operations are described in more detail in the section Updating a test
project. The test target is described in Quick build and run with Ant.
You must supply all the flags. The following table explains them in detail:
Directory in which you The android tool creates the test project files and directory
-p, -
want to create the new structure in this directory. If the directory does not exist,
-path
test project. android creates it.
If the operation is successful, android lists to STDOUT the names of the files and directories
it has created.
This creates a new test project with the appropriate directories and build files. The directory
structure and build file contents are identical to those in a regular Android application project.
They are described in detail in the topic Managing Projects.
For example, suppose you create a project in the directory ~/source/HelloAndroid, with
the package name com.example.helloandroid, and the activity name HelloAndroid. You
can to create the test for this in ~/source/HelloAndroidTest. To do so, you enter:
$ cd ~/source
$ android create test-project -m ../HelloAndroid -n HelloAndroidTest -p
HelloAndroidTest
This creates a directory called ~/src/HelloAndroidTest. In the new directory you see the
file AndroidManifest.xml. This file contains the following instrumentation-related elements
and attributes:
You use the android tool when you need to change the path to the project of the application
under test. If you are changing an existing test project created in Eclipse with ADT so that
you can also build and run it from the command line, you must use the "create" operation.
See the section Creating a test project.
Note: If you change the Android package name of the application under test, you must
manually change the value of the <android:targetPackage> attribute within the
AndroidManifest.xml file of the test package. Running android update test-project
does not do this.
If the operation is successful, android lists to STDOUT the names of the files and directories
it has created.
Once you have created a test project, you populate it with a test package. The application
does not require an Activity, although you can define one if you wish. Although your test
package can combine Activities, Android test class extensions, JUnit extensions, or ordinary
classes, you should extend one of the Android test classes or JUnit classes, because these
provide the best testing features.
If you run your tests with InstrumentationTestRunner (or a related test runner), then it
will run all the methods in each class. You can modify this behavior by using the TestSuite
class.
To create a test package, start with one of Android's test classes in the Java package
android.test. These extend the JUnit TestCase class. With a few exceptions, the Android
test classes also provide instrumentation for testing.
For test classes that extend TestCase, you probably want to override the setUp() and
tearDown() methods:
setUp(): This method is invoked before any of the test methods in the class. Use it to set
up the environment for the test. You can use setUp() to instantiate a new Intent object
with the action ACTION_MAIN. You can then use this intent to start the Activity under test.
Note: If you override this method, call super.setUp() as the first statement in your
code.
tearDown(): This method is invoked after all the test methods in the class. Use it to do
garbage collection and re-setting before moving on to the next set of tests.
Note: If you override this method, you must call super.tearDown() as the last
statement in your code.
Another useful convention is to add the method testPreConditions() to your test class.
Use this method to test that the application under test is initialized correctly. If this test fails,
you know that that the initial conditions were in error. When this happens, further test results
are suspect, regardless of whether or not the tests succeeded.
To learn more about creating test packages, see the topic Testing Fundamentals, which
provides an overview of Android testing. If you prefer to follow a tutorial, try the Activity
Testing tutorial, which leads you through the creation of tests for an actual Android
application.
Running Tests
You run tests from the command line, either with Ant or with an Android Debug Bridge
(adb) shell.
You can use Ant to run all the tests in your test project, using the target test, which is
created automatically when you create a test project with the android tool.
This target re-builds your main project and test project if necessary, installs the test
application to the current AVD or device, and then runs all the test classes in the test
application. The results are directed to STDOUT.
You can update an existing test project to use this feature. To do this, use the android tool
with the update test-project option. This is described in the section Updating a test
project.
When you run tests from the command line with Android Debug Bridge (adb), you get more
options for choosing the tests to run than with any other method. You can select individual
test methods, filter tests according to their annotation, or specify testing options. Since the
test run is controlled entirely from a command line, you can customize your testing with shell
scripts in various ways.
To run a test from the command line, you run adb shell to start a command-line shell on
your device or emulator, and then in the shell run the am instrument command. You control
am and your tests with command-line flags.
As a shortcut, you can start an adb shell, call am instrument, and specify command-line
flags all on one input line. The shell opens on the device or emulator, runs your tests,
produces output, and then returns to the command line on your computer.
This operation starts an adb shell, then runs am instrument with the specified parameters.
This particular form of the command will run all of the tests in your test package. You can
control this behavior with flags that you pass to am instrument. These flags are described in
the next section.
The main input parameters to am instrument are described in the following table:
am instrument options
-e <key> <value>
Some keys accept multiple values. You specify multiple values in a comma-separated list.
For example, this invocation of InstrumentationTestRunner provides multiple values for
the package key:
The following table describes the key-value pairs and their result. Please review the Usage
Notes following the table.
The fully-qualified Java class name for one of the test case
<class_name>
classes. Only this test case class is executed.
class
A fully-qualified test case class name, and one of its
<class_name>#method
methods. Only this method is executed. Note the hash
name
mark (#) between the class name and the method name.
Runs all test classes that extend
func true
InstrumentationTestCase.
[small | medium | Runs a test method annotated by size. The annotations are
size
large] @SmallTest, @MediumTest, and @LargeTest.
Loads and logs all specified tests, but does not run them.
log true The test information appears in STDOUT. Use this to verify
combinations of other filters and test specifications.
Usage examples
The following sections provide examples of using am instrument to run tests. They are
based on the following structure:
The test package has the Android package name com.android.demo.app.tests
There are three test classes:
o UnitTests, which contains the methods testPermissions and
testSaveState.
o FunctionTests, which contains the methods testCamera, testXVGA, and
testHardKeyboard.
o IntegrationTests, which contains the method testActivityProvider.
The test runner is InstrumentationTestRunner.
am instrument gets the value of the -e flag, detects the class keyword, and runs all the
methods in the UnitTests class.
To run all of the tests in UnitTests, and the testCamera method in FunctionTests, enter:
You can find more examples of the command in the documentation for
InstrumentationTestRunner.
Activity Testing
In this document
1. The Activity Testing API
1. ActivityInstrumentationTestCase2
2. ActivityUnitTestCase
3. SingleLaunchActivityTestCase
4. Mock objects and activity testing
5. Assertions for activity testing
2. What to Test
3. Next Steps
4. Appendix: UI Testing Notes
1. Testing on the UI thread
2. Turning off touch mode
3. Unlocking the Emulator or Device
4. Troubleshooting UI tests
Key Classes
1. InstrumentationTestRunner
2. ActivityInstrumentationTestCase2
3. ActivityUnitTestCase
Related Tutorials
1. Activity Testing Tutorial
See Also
1. Testing from Eclipse with ADT
2. Testing from Other IDEs
This document describes how to test activities using instrumentation and other test facilities.
The document assumes you have already read Testing Fundamentals, the introduction to the
Android testing and instrumentation framework.
Lifecycle control: With instrumentation, you can start the activity under test, pause it,
and destroy it, using methods provided by the test case classes.
Dependency injection: Instrumentation allows you to create mock system objects such
as Contexts or Applications and use them to run the activity under test. This helps you
control the test environment and isolate it from production systems. You can also set
up customized Intents and start an activity with them.
User interface interaction: You use instrumentation to send keystrokes or touch events
directly to the UI of the activity under test.
The activity testing classes also provide the JUnit framework by extending TestCase and
Assert.
ActivityInstrumentationTestCase2
ActivityUnitTestCase
The ActivityUnitTestCase test case class tests a single activity in isolation. Before you
start the activity, you can inject a mock Context or Application, or both. You use it to run
activity tests in isolation, and to do unit testing of methods that do not interact with Android.
You can not send mock Intents to the activity under test, although you can call
Activity.startActivity(Intent) and then look at arguments that were received.
SingleLaunchActivityTestCase
This test case is useful for testing an activity that runs in a mode other than standard. It
ensures that the test fixture is not reset between tests. You can then test that the activity
handles multiple calls correctly.
This section contains notes about the use of the mock objects defined in android.test.mock
with activity tests.
The mock object MockApplication is only available for activity testing if you use the
ActivityUnitTestCase test case class. By default, ActivityUnitTestCase, creates a
hidden MockApplication object that is used as the application under test. You can inject
your own object using setApplication().
What To Test
Input validation: Test that an activity responds correctly to input values in an EditText
View. Set up a keystroke sequence, send it to the activity, and then use
findViewById(int) to examine the state of the View. You can verify that a valid
keystroke sequence enables an OK button, while an invalid one leaves the button
disabled. You can also verify that the Activity responds to invalid input by setting
error messages in the View.
Lifecycle events: Test that each of your application's activities handles lifecycle
events correctly. In general, lifecycle events are actions, either from the system or
from the user, that trigger a callback method such as onCreate() or onClick(). For
example, an activity should respond to pause or destroy events by saving its state.
Remember that even a change in screen orientation causes the current activity to be
destroyed, so you should test that accidental device movements don't accidentally lose
the application state.
Intents: Test that each activity correctly handles the intents listed in the intent filter
specified in its manifest. You can use ActivityInstrumentationTestCase2 to send
mock Intents to the activity under test.
Runtime configuration changes: Test that each activity responds correctly to the
possible changes in the device's configuration while your application is running.
These include a change to the device's orientation, a change to the current language,
and so forth. Handling these changes is described in detail in the topic Handling
Runtime Changes.
Screen sizes and resolutions: Before you publish your application, make sure to test it
on all of the screen sizes and densities on which you want it to run. You can test the
application on multiple sizes and densities using AVDs, or you can test your
application directly on the devices that you are targeting. For more information, see
the topic Supporting Multiple Screens.
Next Steps
To learn how to set up and run tests in Eclipse, please refer to Testing from Eclipse with
ADT. If you're not working in Eclipse, refer to Testing from Other IDEs.
If you want a step-by-step introduction to testing activities, try the Activity Testing Tutorial,
which guides you through a testing scenario that you develop against an activity-oriented
application.
An application's activities run on the application's UI thread. Once the UI is instantiated, for
example in the activity's onCreate() method, then all interactions with the UI must run in
the UI thread. When you run the application normally, it has access to the thread and does not
have to do anything special.
This changes when you run tests against the application. With instrumentation-based classes,
you can invoke methods against the UI of the application under test. The other test classes
don't allow this. To run an entire test method on the UI thread, you can annotate the thread
with @UIThreadTest. Notice that this will run all of the method statements on the UI thread.
Methods that do not interact with the UI are not allowed; for example, you can't invoke
Instrumentation.waitForIdleSync().
To run a subset of a test method on the UI thread, create an anonymous class of type
Runnable, put the statements you want in the run() method, and instantiate a new instance
of the class as a parameter to the method appActivity.runOnUiThread(), where
appActivity is the instance of the application you are testing.
For example, this code instantiates an activity to test, requests focus (a UI action) for the
Spinner displayed by the activity, and then sends a key to it. Notice that the calls to
waitForIdleSync and sendKeys aren't allowed to run on the UI thread:
...
/*
* Get a reference to the main widget of the app under test, a
Spinner
*/
mSpinner = (Spinner)
mActivity.findViewById(com.android.demo.myactivity.R.id.Spinner01);
...
mInstrumentation.waitForIdleSync();
this.sendKeys(KeyEvent.KEYCODE_DPAD_CENTER);
To control the emulator or a device with key events you send from your tests, you must turn
off touch mode. If you do not do this, the key events are ignored.
You may find that UI tests don't work if the emulator's or device's home screen is disabled
with the keyguard pattern. This is because the application under test can't receive key events
sent by sendKeys(). The best way to avoid this is to start your emulator or device first and
then disable the keyguard for the home screen.
You can also explicitly disable the keyguard. To do this, you need to add a permission in the
manifest file (AndroidManifest.xml) and then disable the keyguard in your application
under test. Note, though, that you either have to remove this before you publish your
application, or you have to disable it with code in the published application.
Troubleshooting UI tests
This section lists some of the common test failures you may encounter in UI testing, and their
causes:
WrongThreadException
Problem:
For a failed test, the Failure Trace contains the following error message:
android.view.ViewRoot$CalledFromWrongThreadException: Only the
original thread that created a view hierarchy can touch its views.
Probable Cause:
This error is common if you tried to send UI events to the UI thread from outside the
UI thread. This commonly happens if you send UI events from the test application,
but you don't use the @UIThread annotation or the runOnUiThread() method. The
test method tried to interact with the UI outside the UI thread.
Suggested Resolution:
Run the interaction on the UI thread. Use a test class that provides instrumentation.
See the previous section Testing on the UI Thread for more details.
java.lang.RuntimeException
Problem:
For a failed test, the Failure Trace contains the following error message:
java.lang.RuntimeException: This method can not be called from the
main application thread
Probable Cause:
This error is common if your test method is annotated with @UiThreadTest but then
tries to do something outside the UI thread or tries to invoke runOnUiThread().
Suggested Resolution:
Service Testing
In this document
1. Service Design and Testing
2. ServiceTestCase
3. Mock object classes
4. What to Test
Key Classes
1. InstrumentationTestRunner
2. ServiceTestCase
3. MockApplication
4. RenamingDelegatingContext
Related Tutorials
1. Activity Testing Tutorial
See Also
1. Testing From Eclipse with ADT
2. Testing From Other IDEs
Android provides a testing framework for Service objects that can run them in isolation and
provides mock objects. The test case class for Service objects is ServiceTestCase. Since the
Service class assumes that it is separate from its clients, you can test a Service object without
using instrumentation.
This document describes techniques for testing Service objects. If you aren't familiar with the
Service class, please read the Services document. If you aren't familiar with Android testing,
please read Testing Fundamentals, the introduction to the Android testing and
instrumentation framework.
When you design a Service, you should consider how your tests can examine the various
states of the Service lifecycle. If the lifecycle methods that start up your Service, such as
onCreate() or onStartCommand() do not normally set a global variable to indicate that they
were successful, you may want to provide such a variable for testing purposes.
Most other testing is facilitated by the methods in the ServiceTestCase test case class. For
example, the getService() method returns a handle to the Service under test, which you can
test to confirm that the Service is running even at the end of your tests.
ServiceTestCase
ServiceTestCase extends the JUnit TestCase class with with methods for testing
application permissions and for controlling the application and Service under test. It also
provides mock application and Context objects that isolate your test from the rest of the
system.
The setUp() method for ServiceTestCase is called before each test. It sets up the test
fixture by making a copy of the current system Context before any test methods touch it. You
can retrieve this Context by calling getSystemContext(). If you override this method, you
must call super.setUp() as the first statement in the override.
ServiceTestCase assumes that you will use a mock Context or mock Application (or both)
for the test environment. These objects isolate the test environment from the rest of the
system. If you don't provide your own instances of these objects before you start the Service,
then ServiceTestCase will create its own internal instances and inject them into the Service.
You can override this behavior by creating and injecting your own instances before starting
the Service
To inject a mock Application object into the Service under test, first create a subclass of
MockApplication. MockApplication is a subclass of Application in which all the
methods throw an Exception, so to use it effectively you subclass it and override the methods
you need. You then inject it into the Service with the setApplication() method. This mock
object allows you to control the application values that the Service sees, and isolates it from
the real system. In addition, any hidden dependencies your Service has on its application
reveal themselves as exceptions when you run the test.
You inject a mock Context into the Service under test with the setContext() method. The
mock Context classes you can use are described in more detail in Testing Fundamentals.
What to Test
The topic What To Test lists general considerations for testing Android components. Here are
some specific guidelines for testing a Service:
Test any business logic that your Service implements. Business logic includes
checking for invalid values, financial and arithmetic calculations, and so forth.
Key Classes
1. InstrumentationTestRunner
2. ProviderTestCase2
3. IsolatedContext
4. MockContentResolver
Related Tutorials
1. Activity Testing Tutorial
See Also
1. Testing Fundamentals
2. Testing From Eclipse with ADT
3. Testing From Other IDEs
Content providers, which store and retrieve data and make it accessible across applications,
are a key part of the Android API. As an application developer you're allowed to provide
your own public providers for use by other applications. If you do, then you should test them
using the API you publish.
This document describes how to test public content providers, although the information is
also applicable to providers that you keep private to your own application. If you aren't
familiar with content providers or the Android testing framework, please read Content
Providers, the guide to developing content providers, and Testing Fundamentals, the
introduction to the Android testing and instrumentation framework.
In Android, content providers are viewed externally as data APIs that provide tables of data,
with their internals hidden from view. A content provider may have many public constants,
but it usually has few if any public methods and no public variables. This suggests that you
should write your tests based only on the provider's public members. A content provider that
is designed like this is offering a contract between itself and its users.
The base test case class for content providers, ProviderTestCase2, allows you to test your
content provider in an isolated environment. Android mock objects such as
IsolatedContext and MockContentResolver also help provide an isolated test
environment.
As with other Android tests, provider test packages are run under the control of the test
runner InstrumentationTestRunner. The section Running Tests With
InstrumentationTestRunner describes the test runner in more detail. The topic Testing From
Eclipse with ADT shows you how to run a test package in Eclipse, and the topic Testing
From Other IDEs shows you how to run a test package from the command line.
The main focus of the provider testing API is to provide an isolated testing environment. This
ensures that tests always run against data dependencies set explicitly in the test case. It also
prevents tests from modifying actual user data. For example, you want to avoid writing a test
that fails because there was data left over from a previous test, and you want to avoid adding
or deleting contact information in a actual provider.
The test case class and mock object classes for provider testing set up this isolated testing
environment for you.
ProviderTestCase2
You test a provider with a subclass of ProviderTestCase2. This base class extends
AndroidTestCase, so it provides the JUnit testing framework as well as Android-specific
methods for testing application permissions. The most important feature of this class is its
initialization, which creates the isolated test environment.
The initialization is done in the constructor for ProviderTestCase2, which subclasses call in
their own constructors. The ProviderTestCase2 constructor creates an IsolatedContext
object that allows file and database operations but stubs out other interactions with the
Android system. The file and database operations themselves take place in a directory that is
local to the device or emulator and has a special prefix.
The constructor then creates a MockContentResolver to use as the resolver for the test. The
MockContentResolver class is described in detail in the section Mock object classes.
Lastly, the constructor creates an instance of the provider under test. This is a normal
ContentProvider object, but it takes all of its environment information from the
IsolatedContext, so it is restricted to working in the isolated test environment. All of the
tests done in the test case class run against this isolated object.
What To Test
The topic What To Test lists general considerations for testing Android components. Here are
some specific guidelines for testing content providers.
Test with resolver methods: Even though you can instantiate a provider object in
ProviderTestCase2, you should always test with a resolver object using the
appropriate URI. This ensures that you are testing the provider using the same
interaction that a regular application would use.
Test a public provider as a contract: If you intent your provider to be public and
available to other applications, you should test it as a contract. This includes the
following ideas:
o Test with constants that your provider publicly exposes. For example, look for
constants that refer to column names in one of the provider's data tables. These
should always be constants publicly defined by the provider.
o Test all the URIs offered by your provider. Your provider may offer several
URIs, each one referring to a different aspect of the data. The Note Pad
sample, for example, features a provider that offers one URI for retrieving a
list of notes, another for retrieving an individual note by it's database ID, and a
third for displaying notes in a live folder.
o Test invalid URIs: Your unit tests should deliberately call the provider with an
invalid URI, and look for errors. Good provider design is to throw an
IllegalArgumentException for invalid URIs.
Test the standard provider interactions: Most providers offer six access methods:
query, insert, delete, update, getType, and onCreate(). Your tests should verify that all
of these methods work. These are described in more detail in the topic Content
Providers.
Test business logic: Don't forget to test the business logic that your provider should
enforce. Business logic includes handling of invalid values, financial or arithmetic
calculations, elimination or combining of duplicates, and so forth. A content provider
does not have to have business logic, because it may be implemented by activities that
modify the data. If the provider does implement business logic, you should test it.
Next Steps
To learn how to set up and run tests in Eclipse, please refer to Testing from Eclipse with
ADT. If you're not working in Eclipse, refer to Testing From Other IDEs.
If you want a step-by-step introduction to testing activities, try the Activity Testing Tutorial,
which guides you through a testing scenario that you develop against an activity-oriented
application.
See Also
1. Accessibility Developer Checklist
2. Android Design: Accessibility
3. Making Applications Accessible
Testing is an important part of making your application accessible to users with varying
abilities. Following design and development guidelines for accessibility are important steps
toward that goal, but testing for accessibility can uncover problems with user interaction that
are not obvious during design and development.
This accessibility testing checklist guides you through the important aspects of accessibility
testing, including overall goals, required testing steps, recommended testing and special
considerations. This document also discusses how to enable accessibility features on Android
devices for testing purposes.
Testing Goals
Your accessibility testing should have the following, high level goals:
The following tests must be completed in order to ensure a minimum level of application
accessibility.
1. Directional controls: Verify that the application can be operated without the use of a touch
screen. Attempt to use only directional controls to accomplish the primary tasks in the
application. Use the keyboard and directional-pad (D-Pad) controls in the Android Emulator
or use gesture navigation on devices with Android 4.1 (API Level 16) or higher.
Note: Keyboards and D-pads provide different navigation paths than accessibility
gestures. While gestures allow users to focus on nearly any on-screen content,
keyboard and D-pad navigation only allow focus on input fields and buttons.
2. TalkBack audio prompts: Verify that user interface controls that provide information
(graphics or text) or allow user action have clear and accurate audio descriptions when
TalkBack is enabled and controls are focused. Use directional controls to move focus
between application layout elements.
3. Explore by Touch prompts: Verify that user interface controls that provide information
(graphics or text) or allow user action have appropriate audio descriptions when Explore by
Touch is enabled. There should be no regions where contents or controls do not provide an
audio description.
4. Touchable control sizes: All controls where a user can select or take an action must be a
minimum of 48 dp (approximately 9mm) in length and width, as recommended by Android
Design.
5. Gestures work with TalkBack enabled: Verify that app-specific gestures, such as zooming
images, scrolling lists, swiping between pages or navigating carousel controls continue to
work when TalkBack is enabled. If these gestures do not function, then an alternative
interface for these actions must be provided.
6. No audio-only feedback: Audio feedback must always have a secondary feedback
mechanism to support users who are deaf or hard of hearing, for example: A sound alert for
the arrival of a message should also be accompanied by a system Notification, haptic
feedback (if available) or another visual alert.
Testing Recommendations
The following tests are recommended for ensuring the accessibility of your application. If
you do not test these items, it may impact the overall accessibility and quality of your
application.
1. Repetitive audio prompting: Check that closely related controls (such as items with multiple
components in a list) do not simply repeat the same audio prompt. For example, in a
contacts list that contains a contact picture, written name and title, the prompts should not
simply repeat “Bob Smith” for each item.
2. Audio prompt overloading or underloading: Check that closely related controls provide an
appropriate level of audio information that enables users to understand and act on a screen
element. Too little or too much prompting can make it difficult to understand and use a
control.
Special Cases and Considerations
The following list describes specific situations that should be tested to ensure an accessible
app. Some, none or all of the cases described here may apply to your application. Be sure to
review this list to find out if these special cases apply and take appropriate action.
1. Review developer special cases and considerations: Review the list of special cases for
accessibility development and test your application for the cases that apply.
2. Prompts for controls that change function: Buttons or other controls that change function
due to application context or workflow must provide audio prompts appropriate to their
current function. For example, a button that changes function from play video to pause
video should provide an audio prompt which is appropriate to its current state.
3. Video playback and captioning: If the application provides video playback, verify that it
supports captioning and subtitles to assist users who are deaf or hard of hearing. The video
playback controls must clearly indicate if captioning is available for a video and provide a
clear way of enabling captions.
Audible accessibility feedback features on Android devices provide audio prompts that
speaks the screen content as you move around an application. By enabling these features on
an Android device, you can test the experience of users with blindness or low-vision using
your application.
The TalkBack accessibility service works by speaking the contents of user interface controls
as the user moves focus onto controls. This service should be enabled as part of testing focus
navigation and audible prompts.
The Explore by Touch system feature is available on devices running Android 4.0 and later,
and works by enabling a special accessibility mode that allows users to drag a finger around
the interface of an application and hear the contents of the screen spoken. This feature does
not require screen elements to be focused using an directional controller, but listens for hover
events over user interface controls.
Note: On Android 4.1 (API Level 16) and higher, the system provides a popup
message to enable Explore by Touch. On older versions, you must follow the step
below.
4. Return to the Accessibility category and select Explore by Touch to enable it.
Note: You must turn on TalkBack first, otherwise this option is not available.
For more information about using the Explore by Touch features, see Touch Exploration.
Focus navigation is the use of directional controls to navigate between the individual user
interface elements of an application in order to operate it. Users with limited vision or limited
manual dexterity often use this mode of navigation instead of touch navigation. As part of
accessibility testing, you should verify that your application can be operated using only
directional controls.
You can test navigation of your application using only focus controls, even if your test
devices does not have a directional controller. The Android Emulator provides a simulated
directional controller that you can use to test navigation. You can also use a software-based
directional controller, such as the one provided by the Eyes-Free Keyboard to simulate use of
a D-pad on a test device that does not have a physical D-pad.
Gesture navigation is an accessibility navigation mode that allows users to navigate Android
devices and applications using specific gestures. This navigation mode is available on
Android 4.1 (API Level 16) and higher.
Note: Accessibility gestures provide a different navigation path than keyboards and D-pads.
While gestures allow users to focus on nearly any on-screen content, keyboard and D-pad
navigation only allow focus on input fields and buttons.
Enable both TalkBack and the Explore by Touch feature as described in the Testing with
Explore by Touch. When both of these features are enabled, accessibility gestures are
automatically enabled.
You can change gesture settings using Settings > Accessibility > TalkBack > Settings >
Manage shortcut gestures.
For more information about using Explore by Touch accessibility gestures, see Touch
Exploration.
Note: Accessibility services other than TalkBack may map accessibility gestures to different
user actions. If gestures are not producing the expected actions during testing, try disabling
other accessibility services before proceeding.
UI Testing
In this document
1. Overview
o Workflow
2. Analyzing Your UI
3. Preparing to Test
o Load the App
o Identify UI Components
o Ensure Accessibility
o Configure Development Environment
4. Creating Tests
o uiautomator API
o Sample Test Case
5. Building and Deploying Tests
6. Running Tests
7. Best Practices
Key classes
1. IAutomationSupport
2. UiAutomatorTestCase
3. UiCollection
4. UiDevice
5. UiObject
6. UiScrollable
7. UiSelector
See Also
1. uiautomator (reference)
In addition to unit testing the individual components that make up your Android application
(such as activities, services, and content providers), it is also important that you test the
behavior of your application’s user interface (UI) when it is running on a device. UI testing
ensures that your application returns the correct UI output in response to a sequence of user
actions on a device, such as entering keyboard input or pressing toolbars, menus, dialogs,
images, and other UI controls.
Functional or black-box UI testing does not require testers to know the internal
implementation details of the app, only its expected output when a user performs a specific
action or enters a specific input. This approach allows for better separation of development
and testing roles in your organization.
One common approach to UI testing is to run tests manually and verify that the app is
behaving as expected. However, this approach can be time-consuming, tedious, and error-
prone. A more efficient and reliable approach is to automate the UI testing with a software
testing framework. Automated testing involves creating programs to perform testing tasks
(test cases) to cover specific usage scenarios, and then using the testing framework to run the
test cases automatically and in a repeatable manner.
Overview
The Android SDK provides the following tools to support automated, functional UI testing on
your application:
To use these tools, you must have the following versions of the Android development tools
installed:
1. Prepare to test by installing the app on a test device, analyzing the app’s UI
components, and ensuring that your application is accessible by the test automation
framework.
2. Create automated tests to simulate specific user interactions on your application.
3. Compile your test cases into a JAR file and install it on your test device along with
your app.
4. Run the tests and view the test results.
5. Correct any bugs or defects discovered in testing.
Before you start writing your test cases, it's helpful to familiarize yourself with the UI
components (including the views and controls) of the targeted application. You can use the
uiautomatorviewer tool to take a snapshot of the foreground UI screen on any Android
device that is connected to your development machine. The uiautomatorviewer tool
provides a convenient visual interface to inspect the layout hierarchy and view the properties
of the individual UI components that are displayed on the test device. Using this information,
you can later create uiautomator tests with selector objects that target specific UI
components to test.
Figure 1. The uiautomatorviewer showing the captured interface of a test device.
$ uiautomatorviewer
4. To capture a screen for analysis, click the Device Screenshot button in the GUI of the
uiautomatorviewer tool.
Note: If you have more than one device connected, specify the device for screen
capture by setting the ANDROID_SERIAL environment variable:
a. Find the serial numbers for your connected devices by running this command:
$ adb devices
In UNIX:
If you are connected to only a single device, you do not need to set the
ANDROID_SERIAL environment variable.
Preparing to Test
Before using the uiautomator testing framework, complete these pre-flight tasks:
If you are reading this document, chances are that the Android application that you want to
test has not been published yet. If you have a copy of the APK file, you can install the APK
onto a test device by using the adb tool. To learn how to install an APK file using the adb
tool, see the adb documentation.
Before writing your uiautomator tests, first identify the UI components in the application
that you want to test. Typically, good candidates for testing are UI components that are
visible and that users can interact with. The UI components should also have visible text
labels, android:contentDescription values, or both.
You can inspect the visible screen objects in an application conveniently by using the
uiautomatorviewer tool. For more information about how to analyze an application screen
with this tool, see the section Analyzing Your Application’s UI. For more information about
the common types of UI components provided by Android, see User Interface.
This step is required because the uiautomator tool depends on the accessibility features of
the Android framework to execute your functional UI tests. You should include these
minimum optimizations to support the uiautomator tool:
For more information about implementing and testing accessibility, see Making Applications
Accessible.
Note: To identify the non-accessible components in the UI, click on the Toggle NAF Nodes
option in the uiautomatorviewer tool.
Generally, Android application developers get accessibility support for free, courtesy of the
View and ViewGroup classes. However, some applications use custom view components to
provide a richer user experience. Such custom components won't get the accessibility support
that is provided by the standard Android UI components. If this applies to your application,
ensure that the application developer exposes the custom drawn UI components to Android
accessibility services, by implementing the AccessibilityNodeProvider class. For more
information about making custom view components accessible, see Making Applications
Accessible.
If you're developing in Eclipse, the Android SDK provides additional tools that help you
write test cases using uiautomator and buiild your JAR file. In order to set up Eclipse to
assist you, you need to create a project that includes the uiautomator client library, along
with the Android SDK library. To configure Eclipse:
1. Create a new Java project in Eclipse, and give your project a name that is relevant to
the tests you’re about to create (for example, "MyAppNameTests"). In the project,
you will create the test cases that are specific to the application that you want to test.
2. From the Project Explorer, right-click on the new project that you created, then
select Properties > Java Build Path, and do the following:
a. Click Add Library > JUnit then select JUnit3 to add JUnit support.
b. Click Add External JARs... and navigate to the SDK directory. Under the
platforms directory, select the latest SDK version and add both the
uiautomator.jar and android.jar files.
If you did not configure Eclipse as your development environment, make sure that the
uiautomator.jar and android.jar files from the <android-sdk>/platforms/<sdk>
directory are in your Java class path.
Once you have completed these prerequisite tasks, you're almost ready to start creating your
uiautomator tests.
To build a test that runs in the uiautomator framework, create a test case that extends the
UiAutomatorTestCase class. In Eclipse, the test case file goes under the src directory in
your project. Later, you will build the test case as a JAR file, then copy this file to the test
device. The test JAR file is not an APK file and resides separately from the application that
you want to test on the device.
The first thing your test case should do is access the device that contains the target app. It’s
also good practice to start the test from the Home screen of the device. From the Home screen
(or some other starting location you’ve chosen in the target app), you can use the classes
provided by the uiautomator API to simulate user actions and to test specific UI
components. For an example of how to put together a uiautomator test case, see the sample
test case.
uiautomator API
The uiautomator API is bundled in the uiautomator.jar file under the <android-
sdk>/platforms/ directory. The API includes these key classes that allow you to capture
and manipulate UI components on the target app:
UiDevice
Represents the device state. In your tests, you can call methods on the UiDevice
instance to check for the state of various properties, such as current orientation or
display size. Your tests also can use the UiDevice instance to perform device level
actions, such as forcing the device into a specific rotation, pressing the d-pad
hardware button, or pressing the Home and Menu buttons.
getUiDevice().pressHome();
UiSelector
Represents a search criteria to query and get a handle on specific elements in the
currently displayed UI. If more than one matching element is found, the first matching
element in the layout hierarchy is returned as the target UiObject. When constructing
a UiSelector, you can chain together multiple properties to refine your search. If no
matching UI element is found, a UiAutomatorObjectNotFoundException is thrown.
You can use the childSelector() method to nest multiple UiSelector instances.
For example, the following code example shows how to specify a search to find the
first ListView in the currently displayed UI, then search within that ListView to find
a UI element with the text property Apps.
UiObject appItem = new UiObject(new UiSelector()
.className("android.widget.ListView").instance(1)
.childSelector(new UiSelector().text("Apps")));
UiObject
Represents a UI element. To create a UiObject instance, use a UiSelector that
describes how to search for, or select, the UI element.
The following code example shows how to construct UiObject instances that
represent a Cancel button and a OK button in your application.
You can reuse the UiObject instances that you have created in other parts of your app
testing, as needed. Note that the uiautomator test framework searches the current
display for a match every time your test uses a UiObject instance to click on a UI
element or query a property.
In the following code example, the uiautomator test framework searches for a UI
element with the text property OK. If a match is found and if the element is enabled,
the framework simulates a user click action on the element.
You can also restrict the search to find only elements of a specific class. For example,
to find matches of the Button class:
If the videos are listed within a LinearLayout view, and you want to to retrieve the
number of videos in this collection:
If you want to find a specific video that is labeled with the text element Cute Baby
Laughing from the collection and simulate a user-click on the video:
Similarly, you can simulate other user actions on the UI object. For example, if you
want to simulate selecting a checkbox that is associated with the video:
For example, the following code shows how to simulate scrolling down the Settings
menu and clicking on an About tablet option:
For more information about these APIs, see the uiautomator reference.
The following code example shows a simple test case which simulates a user bringing up the
Settings app in a stock Android device. The test case mimics all the steps that a user would
typically take to perform this task, including opening the Home screen, launching the All
Apps screen, scrolling to the Settings app icon, and clicking on the icon to enter the Settings
app.
package com.uia.example.my;
1. Create the required build configuration files to build the output JAR. To generate the
build configuration files, open a terminal and run the following command:
The <name> is the name of the project that contains your uiautomator test source
files, and the <path> is the path to the corresponding project directory.
set ANDROID_HOME=<path_to_your_sdk>
o In UNIX:
export ANDROID_HOME=<path_to_your_sdk>
3. Go to the project directory where your build.xml file is located and build your test
JAR.
ant build
4. Deploy your generated test JAR file to the test device by using the adb push
command:
Here’s an example:
Here’s an example of how to run a test that is implemented in the LaunchSettings.jar file.
The tests are bundled in the com.uia.example.my package:
To learn more about the syntax, subcommands, and options for uiautomator, see the
uiautomator reference.
Best Practices
Here are some best practices for functional UI testing with the uiautomator framework:
Ensure that you validate the same UI functions on your application across the various
types of devices that your application might run on (for example, devices with
different screen densities).
You should also test your UI against common scenarios such as in-coming phone
calls, network interruptions, and user-initiated switching to other applications on the
device.
What To Test
As you develop Android applications, knowing what to test is as important as knowing how
to test. This document lists some most common Android-related situations that you should
consider when you test, even at the unit test level. This is not an exhaustive list, and you
consult the documentation for the features that you use for more ideas. The android-
developers Google Groups site is another resource for information about testing.
The following sections are organized by behaviors or situations that you should test. Each
section contains a scenario that further illustrates the situation and the test or tests you should
do.
Change in orientation
For devices that support multiple orientations, Android detects a change in orientation when
the user turns the device so that the display is "landscape" (long edge is horizontal) instead of
"portrait" (long edge is vertical).
When Android detects a change in orientation, its default behavior is to destroy and then re-
start the foreground Activity. You should consider testing the following:
Is the screen re-drawn correctly? Any custom UI code you have should handle changes in the
orientation.
Does the application maintain its state? The Activity should not lose anything that the user
has already entered into the UI. The application should not "forget" its place in the current
transaction.
Change in configuration
A situation that is more general than a change in orientation is a change in the device's
configuration, such as a change in the availability of a keyboard or a change in system
language.
A change in configuration also triggers the default behavior of destroying and then restarting
the foreground Activity. Besides testing that the application maintains the UI and its
transaction state, you should also test that the application updates itself to respond correctly
to the new configuration.
Battery life
Mobile devices primarily run on battery power. A device has finite "battery budget", and
when it is gone, the device is useless until it is recharged. You need to write your application
to minimize battery usage, you need to test its battery performance, and you need to test the
methods that manage battery usage.
Techniques for minimizing battery usage were presented at the 2010 Google I/O conference
in the presentation Coding for Life -- Battery Life, That Is. This presentation describes the
impact on battery life of various operations, and the ways you can design your application to
minimize these impacts. When you code your application to reduce battery usage, you also
write the appropriate unit tests.
If your application depends on network access, SMS, Bluetooth, or GPS, then you should test
what happens when the resource or resources are not available.
For example, if your application uses the network,it can notify the user if access is
unavailable, or disable network-related features, or do both. For GPS, it can switch to IP-
based location awareness. It can also wait for WiFi access before doing large data transfers,
since WiFi transfers maximize battery usage compared to transfers over 3G or EDGE.
You can use the emulator to test network access and bandwidth. To learn more, please see
Network Speed Emulation. To test GPS, you can use the emulator console and
LocationManager. To learn more about the emulator console, please see Using the Emulator
Console.
Appendix
1. Installing the Completed Test Application File
2. For Users Not Developing In Eclipse
See Also
1. Testing Fundamentals
2. ActivityInstrumentationTestCase2
3. Assert
4. InstrumentationTestRunner
Android includes powerful tools for testing applications. The tools extend JUnit with
additional features, provide convenience classes for mock Android system objects, and use
instrumentation to give you control over your main application while you are testing it. The
entire Android testing environment is discussed in the document Testing Fundamentals.
This tutorial demonstrates the Android testing tools by presenting a simple Android
application and then leading you step-by-step through the creation of a test application for it.
The test application demonstrates these key points:
An Android test is itself an Android application that is linked to the application under
test by entries in its AndroidManifest.xml file.
Instead of Android components, an Android test application contains one or more test
cases. Each of these is a separate class definition.
Android test case classes extend the JUnit TestCase class.
Android test case classes for activities extend JUnit and also connect you to the
application under test with instrumentation. You can send keystroke or touch events
directly to the UI.
You choose an Android test case class based on the type of component (application,
activity, content provider, or service) you are testing.
Additional test tools in Eclipse/ADT provide integrated support for creating test
applications, running them, and viewing the results.
The test application contains methods that perform the following tests:
Initial conditions test. Tests that the application under test initializes correctly. This is
also a unit test of the application's onCreate() method. Testing initial conditions also
provides a confidence measure for subsequent tests.
UI test. Tests that the main UI operation works correctly. This test demonstrates the
instrumentation features available in activity testing. It shows that you can automate
UI tests by sending key events from the test application to the main application.
State management tests. Test the application's code for saving state. This test
demonstrates the instrumentation features of the test runner, which are available for
testing any component.
Prerequisites
During this tutorial, you will be working with sample code that is provided as part of the
downloadable Samples component of the SDK. Specifically, you will be working with a pair
of related sample applications — an application under test and a test application:
Spinner is the application under test. This tutorial focuses on the common situation of
writing tests for an application that already exists, so the main application is provided
to you.
SpinnerTest is the test application. In the tutorial, you create this application step-by-
step. If you want to run quickly through the tutorial, you can install the completed
SpinnerTest application first, and then follow the text. You may get more from the
tutorial, however, if you create the test application as you go. The instructions for
installing the completed test application are in the section Installing the Completed
Test Application File.
The sample applications are described in more detail in the Samples topic. Follow the
instructions to download the version of the samples that's appropriate for the platform you're
working with.
In this tutorial, you will use the Android emulator to run applications. The emulator needs an
Android Virtual Device (AVD) with an API level equal to or higher than the one you set for
the projects in the previous step. To find out how to check this and create the right AVD if
necessary, see Creating an AVD.
As a test of the AVD and emulator, run the SpinnerActivity application in Eclipse with ADT.
When it starts, click the large downward-pointing arrow to the right of the spinner text. You
see the spinner expand and display the title "Select a planet" at the top. Click one of the other
planets. The spinner closes, and your selection appears below it on the screen.
When you are ready to get started with the tutorial, begin by setting up Eclipse projects for
both Spinner (the application under test) and SpinnerTest (the test application).
You'll be using the Spinner application as-is, without modification, so you'll be loading it into
Eclipse as a new Android project from existing source. In the process, you'll be creating a
new test project associated with Spinner that will contain the SpinnerTest application. The
SpinnerTest application will be completely new and you'll be using the code examples in this
tutorial to add test classes and tests to it.
To install the Spinner app in a new Android project from existing source, following these
steps:
1. In Eclipse, select File > New > Project > Android > Android Project, then click
Next. The New Android Project dialog appears.
2. In the Project name text box, enter "SpinnerActivity". The Properties area is filled in
automatically.
3. In the Contents area, set "Create project from existing source".
4. For Location, click Browse, navigate to the directory
<SDK_path>/samples/android-8/Spinner, then click Open. The directory name
<SDK_path>/samples/android-8/Spinner now appears in the Location text box.
5. In the Build Target area, set a API level of 3 or higher. If you are already developing
with a particular target, and it is API level 3 or higher, then use that target.
6. In the Properties area, in the Min SDK Version:, enter "3".
7. You should now see these values:
o Project Name: "SpinnerActivity"
o Create project from existing source: set
o Location: "<SDK_path>/samples/android-8/Spinner"
o Build Target: "API level of 3 or higher" (Target Name "Android 1.5 or
higher")
o Package name: (disabled, set to "com.android.example.spinner")
o Create Activity: (disabled, set to ".SpinnerActivity")
o Min SDK Version: "3"
Note: If you set Build Target to an API level higher than "3", you will see the
warning "The API level for the selected SDK target does not match the Min SDK
version". You do not need to change the API level or the Min SDK version. The
message tells you that you are building the projects with one particular API level, but
specifying that a lower API level is required. This may occur if you have chosen not
to install the optional earlier API levels.
If you see errors listed in the Problems pane at the bottom of the Eclipse window, or
if a red error marker appears next to the entry for SpinnerActivity in the Package
Explorer, highlight the SpinnerActivity entry and then select Project > Clean. This
should fix any errors.
You now have the application under test in the SpinnerActivity project, and an empty test
project in SpinnerActivityTest. You may notice that the two projects are in different
directories, but Eclipse with ADT handles this automatically. You should have no problem in
either building or running them.
Notice that Eclipse and ADT have already done some initial setup for your test application.
Expand the SpinnerActivityTest project, and notice that it already has an Android manifest
file AndroidManifest.xml. Eclipse with ADT created this when you added the test project.
Also, the test application is already set up to use instrumentation. You can see this by
examining AndroidManifest.xml. Open it, then at the bottom of the center pane click
AndroidManifest.xml to display the XML contents:
The next step is to define the test case class. In this tutorial, you'll be creating a test case class
that includes:
Test setup. This use of the JUnit setUp() method demonstrates some of the tasks you
might perform before running an Android test.
Testing initial conditions. This test demonstrates a good testing technique. It also
demonstrates that with Android instrumentation you can look at the application under
test before the main activity starts. The test checks that the application's important
objects have been initialized. If the test fails, you then know that any other tests
against the application are unreliable, since the application was running in an
incorrect state.
Note: The purpose of testing initial conditions is not the same as using setUp(). The
JUnit setUp() runs once before each test method, and its purpose is to create a clean
test environment. The initial conditions test runs once, and its purpose is to verify that
the application under test is ready to be tested.
Testing the UI. This test shows how to control the main application's UI with
instrumentation, a powerful automation feature of Android testing.
Testing state management. This test shows some techniques for testing how well the
application maintains state in the Android environment. Remember that to provide a
satisfactory user experience, your application must never lose its current state, even if
it's interrupted by a phone call or destroyed because of memory constraints. The
Android activity lifecycle provides ways to maintain state, and the SpinnerActivity
application uses them. The test shows the techniques for verifying that they work.
Android tests are contained in a special type of Android application that contains one or more
test class definitions. Each of these contains one or more test methods that do the actual tests.
In this tutorial, you will first add a test case class, and then add tests to it.
You first choose an Android test case class to extend. You choose from the base test case
classes according to the Android component you are testing and the types of tests you are
doing. In this tutorial, the application under test has a single simple activity, so the test case
class will be for an Activity component. Android offers several, but the one that tests in the
most realistic environment is ActivityInstrumentationTestCase2, so you will use it as
the base class. Like all activity test case classes, ActivityInstrumentationTestCase2
offers convenience methods for interacting directly with the UI of the application under test.
To add ActivityInstrumentationTestCase2 as the base test case class, follow these steps:
1. In the Package Explorer, expand the test project SpinnerActivityTest if it is not open
already.
2. Within SpinnerActivityTest, expand the src/ folder and then the package marker for
com.android.example.spinner.test. Right-click on the package name and select
New > Class:
import com.android.example.spinner.SpinnerActivity;
To ensure that the test application is instantiated correctly, you must set up a constructor that
the test runner will call when it instantiates your test class. This constructor has no
parameters, and its sole purpose is to pass information to the superclass's default constructor.
To set up this constructor, enter the following code in the class:
public SpinnerActivityTest() {
super(SpinnerActivity.class);
} // end of SpinnerActivityTest constructor definition
This calls the superclass constructor with the main activity's class
(SpinnerActivity.class) for the application under test. Android uses this information to
find the application and activity to test.
You are now ready to add tests, by adding test methods to the class.
The setUp() method is invoked before every test. You use it to initialize variables and clean
up from previous tests. You can also use the JUnit tearDown() method, which runs after
every test method. The tutorial does not use it.
Add this code to the definition of SpinnerActivityTest, after the constructor definition:
@Override
protected void setUp() throws Exception {
super.setUp();
setActivityInitialTouchMode(false);
mActivity = getActivity();
mSpinner =
(Spinner) mActivity.findViewById(
com.android.example.spinner.R.id.Spinner01
);
mPlanetData = mSpinner.getAdapter();
import android.widget.Spinner;
import android.widget.SpinnerAdapter;
The initial conditions test verifies that the application under test is initialized correctly. It is
an illustration of the types of tests you can run, so it is not comprehensive. It verifies the
following:
The item select listener is initialized. This listener is called when a selection is made
from the spinner.
The adapter that provides values to the spinner is initialized.
The adapter contains the right number of entries.
The actual initialization of the application under test is done in setUp(), which the test
runner calls automatically before every test. The verifications are done with JUnit Assert
calls. As a useful convention, the method name is testPreConditions():
Now create a UI test that selects an item from the Spinner widget. The test sends key events
to the UI with key events. The test confirms that the selection matches the result you expect.
This test demonstrates the power of using instrumentation in Android testing. Only an
instrumentation-based test class allows you to send key events (or touch events) to the
application under test. With instrumentation, you can test your UI without having to take
screenshots, record the screen, or do human-controlled testing.
To work with the spinner, the test has to request focus for it and then set it to a known
position. The test uses requestFocus() and setSelection() to do this. Both of these
methods interact with a View in the application under test, so you have to call them in a
special way.
Code in a test application that interacts with a View of the application under test must run in
the main application's thread, also known as the UI thread. To do this, you use the
Activity.runOnUiThread() method. You pass the code to runOnUiThread()in an
anonymous Runnable object. To set the statements in the Runnable object, you override the
object's run() method.
To send key events to the UI of the application under test, you use the sendKeys() method.
This method does not have to run on the UI thread, since Android uses instrumentation to
pass the key events to the application under test.
The last part of the test compares the selection made by sending the key events to a pre-
determined value. This tests that the spinner is working as intended.
The following sections show you how to add the code for this test.
1. Get focus and set selection. Create a new method public void testSpinnerUI().
Add code to to request focus for the spinner and set its position to default or initial
position, "Earth". This code is run on the UI thread of the application under test:
mActivity.runOnUiThread(
new Runnable() {
public void run() {
mSpinner.requestFocus();
mSpinner.setSelection(INITIAL_POSITION);
} // end of run() method definition
} // end of anonymous Runnable object instantiation
); // end of invocation of runOnUiThread
2. Make a selection. Send key events to the spinner to select one of the items. To do this,
open the spinner by "clicking" the center keypad button (sending a DPAD_CENTER
key event) and then clicking (sending) the down arrow keypad button five times.
Finally, click the center keypad button again to highlight the desired item. Add the
following code:
this.sendKeys(KeyEvent.KEYCODE_DPAD_CENTER);
for (int i = 1; i <= TEST_POSITION; i++) {
this.sendKeys(KeyEvent.KEYCODE_DPAD_DOWN);
} // end of for loop
this.sendKeys(KeyEvent.KEYCODE_DPAD_CENTER);
This sets the final position of the spinner to "Saturn" (the spinner's backing adapter is
0-based).
3. Check the result. Query the current state of the spinner, and compare its current
selection to the expected value. Call the method getSelectedItemPosition() to
find out the current selection position, and then getItemAtPosition() to get the
object corresponding to that position (casting it to a String). Assert that this string
value matches the expected value of "Saturn":
mPos = mSpinner.getSelectedItemPosition();
mSelection = (String)mSpinner.getItemAtPosition(mPos);
TextView resultView =
(TextView) mActivity.findViewById(
com.android.example.spinner.R.id.SpinnerResult
);
assertEquals(resultText,mSelection);
import android.view.KeyEvent;
import android.widget.TextView;
Pause here to run the tests you have. The procedure for running a test application is different
from running a regular Android application. You run a test application as an Android JUnit
application. To see how to do this, see Running the Tests and Seeing the Results.
Eventually, you will see the SpinnerActivity application start, and the test application
controlling it by sending it key events. You will also see a new JUnit view in the Explorer
pane, showing the results of the test. The JUnit view is documented in a following section,
Running the Test and Seeing the Results.
Adding state management tests
You now write two tests that verify that SpinnerActivity maintains its state when it is paused
or terminated. The state, in this case, is the current selection in the spinner. When users make
a selection, pause or terminate the application, and then resume or restart it, they should see
the same selection.
Maintaining state is an important feature of an application. Users may switch from the current
application temporarily to answer the phone, and then switch back. Android may decide to
terminate and restart an activity to change the screen orientation, or terminate an unused
activity to regain storage. In each case, users are best served by having the UI return to its
previous state (except where the logic of the application dictates otherwise).
Activity is hidden. When the spinner screen (the activity) is running but hidden by
some other screen, it stores the spinner's position and value in a form that persists
while the application is running.
Application is terminated. When the activity is terminated, it stores the spinner's
position and value in a permanent form. The activity can read the position and value
when it restarts, and restore the spinner to its previous state.
Activity re-appears. When the user returns to the spinner screen, the previous
selection is restored.
Application is restarted. When the user starts the application again, the previous
selection is restored.
Note: An application can manage its state in other ways as well, but these are not covered in
this tutorial.
Note: If you would like to learn more about the difference between losing focus/pausing and
killing an application, read about the activity lifecycle.
The first test verifies that the spinner selection is maintained after the entire application is
shut down and then restarted. The test uses instrumentation to set the spinner's variables
outside of the UI. It then terminates the activity by calling Activity.finish(), and restarts
it using the instrumentation method getActivity(). The test then asserts that the current
spinner state matches the test values.
The second test verifies that the spinner selection is maintained after the activity is paused
and then resumed. The test uses instrumentation to set the spinner's variables outside of the
UI and then force calls to the onPause() and onResume() methods. The test then asserts that
the current spinner state matches the test values.
Notice that these tests make limited assumptions about the mechanism by which the activity
manages state. The tests use the activity's getters and setters to control the spinner. The first
test also knows that hiding an activity calls onPause(), and bringing it back to the
foreground calls onResume(). Other than this, the tests treat the activity as a "black box".
To add the code for testing state management across shutdown and restart, follow these steps:
1. Add the test method testStateDestroy(), then set the spinner selection to a test
value:
mActivity.finish();
mActivity = this.getActivity();
assertEquals(TEST_STATE_DESTROY_POSITION, currentPosition);
assertEquals(TEST_STATE_DESTROY_SELECTION, currentSelection);
} // end of testStateDestroy() method definition
To add the code for testing state management across a pause and resume, follow these steps:
@UiThreadTest
public void testStatePause() {
The @UiThreadTest annotation tells Android to build this method so that it runs on
the UI thread. This allows the method to change the state of the spinner widget in the
application under test. This use of @UiThreadTest shows that, if necessary, you can
run an entire method on the UI thread.
mInstr.callActivityOnPause(mActivity);
mActivity.setSpinnerPosition(0);
mActivity.setSpinnerSelection("");
This ensures that resuming the activity actually restores the spinner's state rather than
simply leaving it as it was.
mInstr.callActivityOnResume(mActivity);
assertEquals(TEST_STATE_PAUSE_POSITION,currentPosition);
assertEquals(TEST_STATE_PAUSE_SELECTION,currentSelection);
} // end of testStatePause() method definition
import android.app.Instrumentation;
import android.test.UiThreadTest;
1. In the Package Explorer, right-click the project SpinnerActivityTest at the top level,
and then select Run As > Android JUnit Test:
2. You will see the emulator start. When the unlock option is displayed (its appearance
depends on the API level you specified for the AVD), unlock the home screen.
3. The test application starts. You see a new tab for the JUnit view, next to the Package
Explorer tab:
This view contains two sub-panes. The top pane summarizes the tests that were run, and the
bottom pane shows failure traces for highlighted tests.
At the conclusion of a successful test run, this is the view's appearance:
Total time elapsed for the test application(labeled Finished after <x> seconds).
Number of runs (Runs:) - the number of tests in the entire test class.
Number of errors (Errors:) - the number of program errors and exceptions
encountered during the test run.
Number of failures (Failures:) - the number of test failures encountered during the
test run. This is the number of assertion failures. A test can fail even if the program
does not encounter an error.
A progress bar. The progress bar extends from left to right as the tests run.
If all the tests succeed, the bar remains green. If a test fails, the bar turns from green
to red.
A test method summary. Below the bar, you see a line for each class in the test
application. To look at the results for the individual methods in a test, click the arrow
at the left to expand the line. You see the name of each test method. To the right of
the name, you see the time taken by the test. You can look at the test's code by
double-clicking its name.
The lower pane contains the failure trace. If all the tests are successful, this pane is empty. If
some tests fail, then if you highlight a failed test in the upper pane, the lower view contains a
stack trace for the test. This is demonstrated in the next section.
Note: If you run the test application and nothing seems to happen, look for the JUnit view. If
you do not see it, you may have run the test application as a regular Android application.
Remember that you need to run it as an Android JUnit application.
A test is as useful when it fails as when it succeeds. This section shows what happens in
Eclipse with ADT when a test fails. You can quickly see that a test class has failed, find the
method or methods that failed, and then use a failure trace to find the exact problem.
The example application SpinnerActivity that you downloaded passes all the tests in the test
application SpinnerActivityTest. To force the test to fail, you must modify the example
application. You change a line of setup code in the application under test. This causes the
testPreConditions() and testTextView() test methods to fail.
1. In Eclipse with ADT, go to the SpinnerActivity project and open the file
SpinnerActivity.java.
2. At the top of SpinnerActivity.java, at the end of the onCreate() method, find the
following line:
// mySpinner.setOnItemSelectedListener(null);
Remove the forward slash characters at the beginning of the line to uncomment the
line. This sets the listener callback to null:
mySpinner.setOnItemSelectedListener(null);
The JUnit view is either created or updated with the results of the test. Now, however, the
progress bar is red, the number of failures is 2, and small "x" icons appear in the list icons
next to the testPreConditions and TestSpinnerUI tests. This indicates that the tests have
failed. The display is similar to this:
You now want to look at the failures to see exactly where they occurred.
1. Click the testPreconditions entry. In the lower pane entitled Failure Trace, you see a
stack trace of the calls that led to the failure. This trace is similar to the following
screenshot:
2. The first line of the trace tells you the error. In this case, a JUnit assertion failed. To
look at the assertion in the test code, double-click the next line (the first line of the
trace). In the center pane a new tabbed window opens, containing the code for the test
application SpinnerActivityTest. The failed assertion is highlighted in the middle
of the window.
The assertion failed because you modified the main application to set the
getOnItemSelectedListener callback to null.
You can look at the failure in testTextView if you want. Remember, though, that
testPreConditions is meant to verify the initial setup of the application under test. If
testPreConditions() fails, then succeeding tests can't be trusted. The best strategy to follow is
to fix the problem and re-run all the tests.
Next Steps
This example test application has shown you how to create a test project and link it to the
application you want to test, how to choose and add a test case class, how to write UI and
state management tests, and how to run the tests against the application under test. Now that
you are familiar with the basics of testing Android applications, here are some suggested next
steps:
If you haven't done so already, read the Testing Fundamentals document in the Dev
Guide. It provides an overview of how testing on Android works. If you are just
getting started with Android testing, reading that document will help you understand
the tools available to you, so that you can develop effective tests.
ActivityInstrumentationTestCase2
ActivityUnitTestCase
ProviderTestCase2
ServiceTestCase
Appendix
The recommended approach to this tutorial is to follow the instructions step-by-step and write
the test code as you go. However, if you want to do this tutorial quickly, you can install the
entire file for the test application into the test project.
To do this, you first create a test project with the necessary structure and files by using the
automated tools in Eclipse. Then you exit Eclipse and copy the test application's file from the
SpinnerTest sample project into your test project. The SpinnerTest sample project is part of
the Samples component of the SDK.
The result is a complete test application, ready to run against the Spinner sample application.
1. Set up the projects for the application under test and the test application, as described
in the section section Setting Up the Projects.
2. Set up the emulator, as described in the section Setting Up the Emulator.
3. Add the test case class, as described in the section Adding the test case class file.
4. Close Eclipse with ADT.
5. Copy the file <SDK_path>/samples/android-
8/SpinnerTest/src/com/android/example/spinner/test/SpinnerActivityTes
t.java to the directory
workspace/SpinnerActivityTest/src/com/android/example/spinner/test/.
6. Restart Eclipse with ADT.
7. In Eclipse with ADT, re-build the project SpinnerActivityTest by selecting it in
the Package Explorer, right-clicking, and selecting Project > Clean.
8. The complete, working test application should now be in the SpinnerActivityTest
project.
You can now continue with the tutorial, starting at the section Adding the test case
constructor and following along in the text.
If you are not developing in Eclipse, you can still do this tutorial. Android provides tools for
creating test applications using a code editor and command-line tools. You use the following
tools:
adb - Installs and uninstalls applications and test applications to a device or the
emulator. You also use this tool to run the test application from the command line.
android - Manages projects and test projects. This tool also manages AVDs and
Android platforms.
You use the emulator tool to run the emulator from the command line.
Here are the general steps for doing this tutorial using an editor and the command line:
1. As described in the section Installing the Tutorial Sample Code, get the sample code.
You will then have a directory <SDK_path>/samples/android-8, containing (among
others) the directories Spinner and SpinnerTest:
o Spinner contains the main application, also known as the application under
test. This tutorial focuses on the common situation of writing tests for an
application that already exists, so the main application is provided to you.
o SpinnerTest contains all the code for the test application. If you want to run
quickly through the tutorial, you can install the test code and then follow the
text. You may get more from the tutorial, however, if you write the code as
you go. The instructions for installing the test code are in the section
Appendix: Installing the Completed Test Application File.
2. Navigate to the directory <SDK_path>/samples/android-8.
3. Create a new Android application project using android create project:
The value of <APItarget> should be "3" (API level 3) or higher. If you are already
developing with a particular API level, and it is higher than 3, then use that API level.
This a new Android project SpinnerActivity in the existing Spinner directory. The
existing source and resource files are not touched, but the android tool adds the
necessary build files.
This will create a new Android test project in the new directory
SpinnerActivityTest. You do this so that the solution to the tutorial that is in
SpinnerTest is left untouched. If you want to use the solution code instead of
entering it as you read through the tutorial, refer to the section Appendix: Installing
the Completed Test Application File.
Note: Running android create test-project will automatically create the file
AndroidManifest.xml with the correct <instrumentation> element.
5. Build the sample application. If you are building with Ant, then it is easiest to use the
command ant debug to build a debug version, since the SDK comes with a debug
signing key. The result will be the file Spinner/bin/SpinnerActivity-debug.apk.
You can install this to your device or emulator. Attach your device or start the
emulator if you haven't already, and run the command:
9. In your device or emulator, check that both the main application SpinnerActivity
and the test application SpinnerActivityTest are installed.
10. To run the test application, enter the following at the command line:
com.android.example.spinner.test.SpinnerActivityTest:....
Test results for InstrumentationTestRunner=....
Time: 10.098
OK (4 tests)
If you force the test to fail, as described in the previous section Forcing Some Tests to
Fail, then the output looks like this:
com.android.example.spinner.test.SpinnerActivityTest:
Failure in testPreConditions:
junit.framework.AssertionFailedError
at
com.android.example.spinner.test.SpinnerActivityTest.testPreConditions(Spin
nerActivityTest.java:104)
at java.lang.reflect.Method.invokeNative(Native Method)
at
android.test.InstrumentationTestCase.runMethod(InstrumentationTestCase.java
:205)
at
android.test.InstrumentationTestCase.runTest(InstrumentationTestCase.java:1
95)
at
android.test.ActivityInstrumentationTestCase2.runTest(ActivityInstrumentati
onTestCase2.java:175)
at android.test.AndroidTestRunner.runTest(AndroidTestRunner.java:169)
at android.test.AndroidTestRunner.runTest(AndroidTestRunner.java:154)
at
android.test.InstrumentationTestRunner.onStart(InstrumentationTestRunner.ja
va:430)
at
android.app.Instrumentation$InstrumentationThread.run(Instrumentation.java:
1447)
Failure in testSpinnerUI:
junit.framework.ComparisonFailure: expected:<Result> but was:<Saturn>
at
com.android.example.spinner.test.SpinnerActivityTest.testSpinnerUI(SpinnerA
ctivityTest.java:153)
at java.lang.reflect.Method.invokeNative(Native Method)
at
android.test.InstrumentationTestCase.runMethod(InstrumentationTestCase.java
:205)
at
android.test.InstrumentationTestCase.runTest(InstrumentationTestCase.java:1
95)
at
android.test.ActivityInstrumentationTestCase2.runTest(ActivityInstrumentati
onTestCase2.java:175)
at android.test.AndroidTestRunner.runTest(AndroidTestRunner.java:169)
at android.test.AndroidTestRunner.runTest(AndroidTestRunner.java:154)
at
android.test.InstrumentationTestRunner.onStart(InstrumentationTestRunner.ja
va:430)
at
android.app.Instrumentation$InstrumentationThread.run(Instrumentation.java:
1447)
..
Test results for InstrumentationTestRunner=.F.F..
Time: 9.377
FAILURES!!!
Tests run: 4, Failures: 2, Errors: 0
Except as noted, this content is licensed under Creative Commons Attribution 2.5. For details
and restrictions, see the Content License.
The Android SDK provides most of the tools that you need to debug your applications. You
need a JDWP-compliant debugger if you want to be able to do things such as step through
code, view variable values, and pause execution of an application. If you are using Android
Studio, a JDWP-compliant debugger is already included and there is no setup required. If you
are using another IDE, you can use the debugger that comes with it and attach the debugger
to a special port so it can communicate with the application VMs on your devices. The main
components that comprise a typical Android debugging environment are:
adb
adb acts as a middleman between a device and your development system. It provides
various device management capabilities, including moving and syncing files to the
emulator, running a UNIX shell on the device or emulator, and providing a general
means to communicate with connected emulators and devices.
Dalvik Debug Monitor Server
DDMS is a graphical program that communicates with your devices through adb.
DDMS can capture screenshots, gather thread and stack information, spoof incoming
calls and SMS messages, and has many other features.
Device or Android Virtual Device
Your application must run in a device or in an AVD so that it can be debugged. An
adb device daemon runs on the device or emulator and provides a means for the adb
host daemon to communicate with the device or emulator.
JDWP debugger
The Dalvik VM (Virtual Machine) supports the JDWP protocol to allow debuggers to
attach to a VM. Each application runs in a VM and exposes a unique port that you can
attach a debugger to via DDMS. If you want to debug multiple applications, attaching
to each port might become tedious, so DDMS provides a port forwarding feature that
can forward a specific VM's debugging port to port 8700. You can switch freely from
application to application by highlighting it in the Devices tab of DDMS. DDMS
forwards the appropriate port to port 8700. Most modern Java IDEs include a JDWP
debugger, or you can use a command line debugger such as jdb.
Debugging Environment
Figure 1 shows how the various debugging tools work together in a typical debugging
environment.
Additional Debugging Tools
In addition to the main debugging tools, the Android SDK provides additional tools to help
you debug and profile your applications:
Debugging Tips
While debugging, keep these helpful tips in mind to help you figure out common problems
with your applications:
See also
Android Studio Tips and Tricks
Debugging
Device Monitor
Using DDMS
Android Studio enables you to debug apps running on the emulator or on an Android device.
With Android Studio, you can:
To debug your app, Android Studio builds a debuggable version of your app, connects to a
device or to the emulator, installs the app and runs it. The IDE shows the system log while
your app is running and provides debugging tools to filter log messages, work with
breakpoints, and control the execution flow.
Figure 1. The Choose Device window enables you to select a physical Android device or a
virtual device to debug your app.
To run your app in debug mode, you build an APK signed with a debug key and install it on a
physical Android device or on the Android emulator. To set up an Android device for
development, see Using Hardware Devices. For more information about the emulator
provided by the Android SDK, see Using the Emulator.
Figure 1 shows the Choose Device window. The list shows all the Android devices connected
to your computer. Select Launch Emulator to use an Android virtual device instead. Click
the ellipsis to open the Android Virtual Device Manager.
Android Studio opens the Debug tool window when you debug your app. To open the Debug
window manually, click Debug . This window shows threads and variables in
the Debugger tab, the device status in the Console tab, and the system log in the Logcat tab.
The Debug tool window also provides other debugging tools covered in the following
sections.
Figure 2. The Debug tool window in Android Studio showing the current thread and the
object tree for a variable.
You don't always have to restart your app to debug it. To debug an app that you're already
running:
The system log shows system messages while you debug your app. These messages include
information from apps running on the device. If you want to use the system log to debug your
app, make sure your code writes log messages and prints the stack trace for exceptions while
your app is in the development phase.
To write log messages in your code, use the Log class. Log messages help you understand the
execution flow by collecting the system debug output while you interact with your app. Log
messages can tell you what part of your application failed. For more information about
logging, see Reading and Writing Logs.
The following example shows how you might add log messages to determine if previous state
information is available when your activity starts:
import android.util.Log;
...
public class MyActivity extends Activity {
private static final String TAG = MyActivity.class.getSimpleName();
...
@Override
public void onCreate(Bundle savedInstanceState) {
if (savedInstanceState != null) {
Log.d(TAG, "onCreate() Restoring previous state");
/* restore state */
} else {
Log.d(TAG, "onCreate() No saved state available");
/* initialize app */
}
}
}
During development, your code can also catch exceptions and write the stack trace to the
system log:
void someOtherMethod() {
try {
...
} catch (SomeException e) {
Log.d(TAG, "someOtherMethod()", e);
}
}
Note: Remove debug log messages and stack trace print calls from your code when you are
ready to publish your app. You could do this by setting a DEBUG flag and placing debug log
messages inside conditional statements.
Both the Android DDMS (Dalvik Debug Monitor Server) and the Debug tool windows show
the system log; however, the Android DDMS tool window lets you view only log messages
for a particular process. To view the system log on the Android DDMS tool window:
The Android DDMS tool window gives you access to some DDMS features from Android
Studio. For more information about DDMS, see Using DDMS.
The system log shows messages from Android services and other Android apps. To filter the
log messages to view only the ones you are interested in, use the tools in the Android DDMS
window:
To show only log messages for a particular process, select the process in the Devices
view and then click Only Show Logcat from Selected Process . If the Devices
view is not available, click Restore Devices View on the right of the Android
DDMS tool window. This button is only visible when you hide the Devices window.
To filter log messages by log level, select a level under Log Level on the top of the
Android DDMS window.
To show only log messages that contain a particular string, enter the string in the
search box and press Enter.
Breakpoints enable you to pause the execution of your app at a particular line of code,
examine variables, evaluate expressions, and continue the execution line by line. Use
breakpoints to determine the causes of run-time errors that you can't fix by looking at your
code only. To debug your app using breakpoints:
Figure 5. A red dot appears next to the line when you set a breakpoint.
To view all the breakpoints and configure breakpoint settings, click View Breakpoints
on the left side of the Debug tool window. The Breakpoints window appears, as shown in
figure 6.
Figure 6. The Breakpoints window lists all the current breakpoints and includes behavior
settings for each.
The Breakpoints window lets you enable or disable each breakpoint from the list on the left.
If a breakpoint is disabled, Android Studio does not pause your app when it hits that
breakpoint. Select a breakpoint from the list to configure its settings. You can configure a
breakpoint to be disabled at first and have the system enable it after a different breakpoint is
hit. You can also configure whether a breakpoint should be disabled after it is hit. To set a
breakpoint for any exception, select Exception Breakpoints in the list of breakpoints.
After you set breakpoints in your code, click Rerun to start the app again. When a
breakpoint is hit, Android Studio pauses the app and highlights the breakpoint in the source
code. The Debug tool window lets you examine variables and control the execution step by
step:
To examine the object tree for a variable, expand it in the Variables view. If the
Variables view is not visible, click Restore Variables View .
To evaluate an expression at the current execution point, click Evaluate Expression
.
To advance to the next line in the code (without entering a method), click Step Over
To advance to the first line inside a method call, click Step Into .
To advance to the next line outside the current method, click Step Out .
Android Studio lets you track objects that are being allocated on the Java heap and see which
classes and threads are allocating these objects. This allows you to see the list of objects
allocated during a period of interest. This information is valuable for assessing memory usage
that can affect application performance.
Allocation order
Allocated class
Allocation size
Thread ID
Allocation method, class, and line number
Stack trace at the point of allocation
Even if your application does not generate runtime errors, this does not mean it is free of
problems. You should also consider the following issues:
The Android Device Monitor is a stand-alone tool with a graphical user interface for serveral
Android application debugging and analysis tools, including the Dalvik Debug Monitor
Server (DDMS). You can use the Android Device Monitor to analyze memory usage, profile
methods, monitor network traffic and simulate incoming calls and messages.
To open the Android Device Monitor from Android Studio, click Monitor on the
toolbar. The Android Device Monitor opens in a new window.
For more information about the Android Device Monitor and DDMS, see Device Monitor
and Using DDMS.
Capture Screenshots and Videos
Android Studio enables you to capture a screenshot or a short video of the device screen
while your app is running. Screenshots and videos are useful as promotional materials for
your app, and you can also attach them to bug reports that you send to your development
team.
3. Click Screen Record on the left side of the Android DDMS tool window.
4. Click Start Recording.
5. Interact with your app.
6. Click Stop Recording.
7. Enter a file name for the recording and click OK.
If you are not using Android Studio to develop, you can still take advantage of all the tools
that the Android SDK provides for debugging. A basic debugging environment consists of:
ADB
DDMS
Java Debugger
You need to obtain a JDWP-compliant Java debugger to properly debug your application.
Most Java IDEs will already have one included, or you can use a command line debugger,
such as JDB, if you are using a simple text editor to develop applications.
Starting a debugging environment
A Java Debugger assists you in finding problems with your code by letting you set
breakpoints, step through execution of your application, and examine variable values. Since
you are not using Android Studio, you have to manually start up the debugging environment
yourself by running a few tools that are provided in the Android SDK. To begin debugging
your application, follow these general steps:
1. Load an AVD with the Android emulator or connect a device to your computer.
2. Start DDMS from the sdk /tools directory. This also starts ADB if it is not already
started. You should see your device appear in DDMS.
3. Install and run your .apk file on the device or emulator. In DDMS, you should see
your application running under the device that you installed it to.
4. Attach your debugger to the debugging port 8700, or to the specific port shown for the
application in DDMS.
DDMS assigns a specific debugging port to every virtual machine that it finds on the
emulator. You must either attach your IDE to that port (listed on the Info tab for that VM), or
you can use a default port 8700 to connect to whatever application is currently selected on the
list of discovered virtual machines.
Your IDE should attach to your application running on the emulator, showing you its threads
and allowing you to suspend them, inspect their state, and set breakpoints. If you selected
"Wait for debugger" in the Development settings panel the application will run when Android
Studio connects, so you will need to set any breakpoints you want before connecting.
Changing either the application being debugged or the "Wait for debugger" option causes the
system to kill the selected application if it is currently running. You can use this to kill your
application if it is in a bad state by simply going to the settings and toggling the checkbox.
Using DDMS
In this document
1. Running DDMS
2. How DDMS Interacts with a Debugger
3. Using DDMS
1. Viewing heap usage for a process
2. Tracking memory allocation of objects
3. Working with an emulator or device's file system
4. Examining thread information
5. Starting method profiling
6. Using the Network Traffic tool
7. Using LogCat
8. Emulating phone operations and location
Android ships with a debugging tool called the Dalvik Debug Monitor Server (DDMS),
which provides port-forwarding services, screen capture on the device, thread and heap
information on the device, logcat, process, and radio state information, incoming call and
SMS spoofing, location data spoofing, and more. This page provides a modest discussion of
DDMS features; it is not an exhaustive exploration of all the features and capabilities.
Running DDMS
DDMS is integrated into Eclipse and is also shipped in the tools/ directory of the SDK.
DDMS works with both the emulator and a connected device. If both are connected and
running simultaneously, DDMS defaults to the emulator.
From Eclipse: Click Window > Open Perspective > Other... > DDMS.
From the command line: Type ddms (or ./ddms on Mac/Linux) from the tools/ directory.
On Android, every application runs in its own process, each of which runs in its own virtual
machine (VM). Each VM exposes a unique port that a debugger can attach to.
DDMS assigns a debugging port to each VM on the device. Typically, DDMS assigns port
8600 for the first debuggable VM, the next on 8601, and so on. When a debugger connects to
one of these ports, all traffic is forwarded to the debugger from the associated VM. You can
only attach a single debugger to a single port, but DDMS can handle multiple, attached
debuggers.
By default, DDMS also listens on another debugging port, the DDMS "base port" (8700, by
default). The base port is a port forwarder, which can accept VM traffic from any debugging
port and forward it to the debugger on port 8700. This allows you to attach one debugger to
port 8700, and debug all the VMs on a device. The traffic that is forwarded is determined by
the currently selected process in the DDMS Devices view.
The following screenshot shows a typical DDMS screen in Eclipse. If you are starting DDMS
from the command line, the screen is slightly different, but much of the functionality is
identical. Notice that the highlighted process, com.android.email, that is running in the
emulator has the debugging port 8700 assigned to it as well as 8606. This signifies that
DDMS is currently forwarding port 8606 to the static debugging port of 8700.
Figure 1. Screenshot of DDMS
If you are not using Eclipse and ADT, read Configuring your IDE to attach to the debugging
port, for more information on attaching your debugger.
Tip: You can set a number of DDMS preferences in File > Preferences. Preferences are
saved to $HOME/.android/ddms.cfg.
Using DDMS
The following sections describe how to use DDMS and the various tabs and panes that are part of
the DDMS GUI. The Eclipse version and the command line version have minor UI differences, but the
same functionality. For information on running DDMS, see the previous section in this document,
Running DDMS.
DDMS allows you to view how much heap memory a process is using. This information is
useful in tracking heap usage at a certain point of time during the execution of your
application.
1. In the Devices tab, select the process that you want to see the heap information for.
2. Click the Update Heap button to enable heap information for the process.
3. In the Heap tab, click Cause GC to invoke garbage collection, which enables the collection of
heap data. When the operation completes, you will see a group of object types and the
memory that has been allocated for each type. You can click Cause GC again to refresh the
data.
4. Click on an object type in the list to see a bar graph that shows the number of objects
allocated for a particular memory size in bytes.
DDMS provides a feature to track objects that are being allocated to memory and to see
which classes and threads are allocating the objects. This allows you to track, in real time,
where objects are being allocated when you perform certain actions in your application. This
information is valuable for assessing memory usage that can affect application performance.
1. In the Devices tab, select the process that you want to enable allocation tracking for.
2. In the Allocation Tracker tab, click the Start Tracking button to begin allocation tracking. At
this point, anything you do in your application will be tracked.
3. Click Get Allocations to see a list of objects that have been allocated since you clicked on the
Start Tracking button. You can click on Get Allocations again to append to the list new
objects that that have been allocated.
4. To stop tracking or to clear the data and start over, click the Stop Tracking button.
5. Click on a specific row in the list to see more detailed information such as the method and
line number of the code that allocated the object.
DDMS provides a File Explorer tab that allows you to view, copy, and delete files on the
device. This feature is useful in examining files that are created by your application or if you
want to transfer files to and from the device.
1. In the Devices tab, select the emulator that you want to view the file system for.
2. To copy a file from the device, locate the file in the File Explorer and click the Pull file
button.
3. To copy a file to the device, click the Push file button on the File Explorer tab.
The Threads tab in DDMS shows you the currently running threads for a selected process.
1. In the Devices tab, select the process that you want to examine the threads for.
2. Click the Update Threads button.
3. In the Threads tab, you can view the thread information for the selected process.
Method profiling is a means to track certain metrics about a method, such as number of calls,
execution time, and time spent executing the method. If you want more granular control over
where profiling data is collected, use the startMethodTracing() and
stopMethodTracing() methods. For more information about generating trace logs, see
Profiling and Debugging UIs.
Before you start method profiling in DDMS, be aware of the following restrictions:
Android 2.1 and earlier devices must have an SD card present and your application must
have permission to write to the SD card.
Android 2.2 and later devices do not need an SD card. The trace log files are streamed
directly to your development machine.
1. On the Devices tab, select the process that you want to enable method profiling for.
2. Click the Start Method Profiling button.
3. Interact with your application to start the methods that you want to profile.
4. Click the Stop Method Profiling button. DDMS stops profiling your application and opens
Traceview with the method profiling information that was collected between the time you
clicked on Start Method Profiling and Stop Method Profiling.
These tags are shown in a stack area chart in DDMS, as shown in figure 2:
By monitoring the frequency of your data transfers, and the amount of data transferred during
each connection, you can identify areas of your application that can be made more battery-
efficient. Generally, you should look for short spikes that can be delayed, or that should cause
a later transfer to be pre-empted.
To better identify the cause of transfer spikes, the TrafficStats API allows you to tag the
data transfers occurring within a thread using setThreadStatsTag(), followed by manually
tagging (and untagging) individual sockets using tagSocket() and untagSocket(). For
example:
TrafficStats.setThreadStatsTag(0xF00D);
TrafficStats.tagSocket(outputSocket);
// Transfer data using socket
TrafficStats.untagSocket(outputSocket);
Alternatively, the Apache HttpClient and URLConnection APIs included in the platform
automatically tag sockets internally based on the active tag (as identified by
getThreadStatsTag()). These APIs correctly tag/untag sockets when recycled through
keep-alive pools. In the following example, setThreadStatsTag() sets the active tag to be
0xF00D. There can only be one active tag per thread. That is the value that will be returned by
getThreadStatsTag() and thus used by HttpClient to tag sockets. The finally statement
invokes clearThreadStatsTag() to clear the tag.
TrafficStats.setThreadStatsTag(0xF00D);
try {
// Make network request using HttpClient.execute()
} finally {
TrafficStats.clearThreadStatsTag();
}
Socket tagging is supported in Android 4.0, but real-time stats will only be displayed on
devices running Android 4.0.3 or higher.
Using LogCat
LogCat is integrated into DDMS, and outputs the messages that you print out using the Log
class along with other system messages such as stack traces when exceptions are thrown.
View the Reading and Writing Log Messages. topic for more information on how to log
messages to the LogCat.
When you have set up your logging, you can use the LogCat feature of DDMS to filter
certain messages with the following buttons:
Verbose
Debug
Info
Warn
Error
You can also setup your own custom filter to specify more details such as filtering messages
with the log tags or with the process id that generated the log message. The add filter, edit
filter, and delete filter buttons let you manage your custom filters.
The Emulator control tab lets you simulate a phone's voice and data network status. This is
useful when you want to test your application's robustness in differing network environments.
The Telephony Status section of the Emulator controls tab lets you change different aspects
of the phone's networks status, speed and latency. The following options are available to you
and are effective immediately after you set them:
The Telephony Actions section of the Emulator controls tab lets you spoof calls and
messages. This is useful when you want to to test your application's robustness in responding
to incoming calls and messages that are sent to the phone. The following actions are available
to you:
Voice - Enter a number in the Incoming number field and click Call to send a simulated call
to the emulator or phone. Click the Hang up button to terminate the call.
SMS - Enter a number in the Incoming number field and a message in the Message: field and
click the Send button to send the message.
If your application depends on the location of the phone, you can have DDMS send your
device or AVD a mock location. This is useful if you want to test different aspects of your
application's location specific features without physically moving. The following geolocation
data types are available to you:
Manual - set the location by manually specifying decimal or sexagesimal longitude and
latitude values.
GPX - GPS eXchange file
KML - Keyhole Markup Language file
For more information about providing mock location data, see Location Strategies.
The Android logging system provides a mechanism for collecting and viewing system debug
output. Logcat dumps a log of system messages, which include things such as stack traces
when the emulator throws an error and messages that you have written from your application
by using the Log class. You can run LogCat through ADB or from DDMS, which allows you
to read the messages in real time.
For example:
Log.i("MyActivity", "MyClass.getView() — get item number " + position);
Using LogCat
You can use LogCat from within DDMS or call it on an ADB shell. For more information on
how to use LogCat within DDMS, see Using DDMS. To run LogCat, through the ADB shell,
the general usage is:
You can use the logcat command from your development computer or from a remote adb
shell in an emulator/device instance. To view log output in your development computer, you
use
$ adb logcat
# logcat
Every Android log message has a tag and a priority associated with it.
The tag of a log message is a short string indicating the system component from
which the message originates (for example, "View" for the view system).
The priority is one of the following character values, ordered from lowest to highest
priority:
o V — Verbose (lowest priority)
o D — Debug
o I — Info
o W — Warning
o E — Error
o F — Fatal
o S — Silent (highest priority, on which nothing is ever printed)
You can obtain a list of tags used in the system, together with priorities, by running LogCat
and observing the first two columns of each message, given as <priority>/<tag>.
Here's an example of logcat output that shows that the message relates to priority level "I"
and tag "ActivityManager":
To reduce the log output to a manageable level, you can restrict log output using filter
expressions. Filter expressions let you indicate to the system the tags-priority combinations
that you are interested in — the system suppresses other messages for the specified tags.
A filter expression follows this format tag:priority ..., where tag indicates the tag of
interest and priority indicates the minimum level of priority to report for that tag. Messages
for that tag at or above the specified priority are written to the log. You can supply any
number of tag:priority specifications in a single filter expression. The series of
specifications is whitespace-delimited.
Here's an example of a filter expression that suppresses all log messages except those with
the tag "ActivityManager", at priority "Info" or above, and all log messages with tag
"MyApp", with priority "Debug" or above:
The final element in the above expression, *:S, sets the priority level for all tags to "silent",
thus ensuring only log messages with "View" and "MyApp" are displayed. Using *:S is an
excellent way to ensure that log output is restricted to the filters that you have explicitly
specified — it lets your filters serve as a "whitelist" for log output.
The following filter expression displays all log messages with priority level "warning" and
higher, on all tags:
If you're running LogCat from your development computer (versus running it on a remote
adb shell), you can also set a default filter expression by exporting a value for the
environment variable ANDROID_LOG_TAGS:
Note that ANDROID_LOG_TAGS filter is not exported to the emulator/device instance, if you are
running LogCat from a remote shell or using adb shell logcat.
Log messages contain a number of metadata fields, in addition to the tag and priority. You
can modify the output format for messages so that they display a specific metadata field. To
do so, you use the -v option and specify one of the supported output formats listed below.
brief — Display priority/tag and PID of the process issuing the message (the default
format).
process — Display PID only.
tag — Display the priority/tag only.
raw — Display the raw log message, with no other metadata fields.
time — Display the date, invocation time, priority/tag, and PID of the process issuing
the message.
threadtime — Display the date, invocation time, priority, tag, and the PID and TID
of the thread issuing the message.
long — Display all metadata fields and separate messages with blank lines.
When starting LogCat, you can specify the output format you want by using the -v option:
Here's an example that shows how to generate messages in thread output format:
Note that you can only specify one output format with the -v option.
The Android logging system keeps multiple circular buffers for log messages, and not all of
the log messages are sent to the default circular buffer. To see additional log messages, you
can run the logcat command with the -b option, to request viewing of an alternate circular
buffer. You can view any of these alternate buffers:
Here's an example of how to view a log buffer containing radio and telephony messages:
By default, the Android system sends stdout and stderr (System.out and System.err)
output to /dev/null. In processes that run the Dalvik VM, you can have the system write a
copy of the output to the log file. In this case, the system writes the messages to the log using
the log tags stdout and stderr, both with priority I.
To route the output in this way, you stop a running emulator/device instance and then use the
shell command setprop to enable the redirection of output. Here's how you do it:
The system retains this setting until you terminate the emulator/device instance. To use the
setting as a default on the emulator/device instance, you can add an entry to
/data/local.prop on the device.
If you're developing a web application for Android, you can debug your JavaScript using the
console JavaScript APIs, which output messages to LogCat. For more information, see
Debugging Web Apps.
In addition to testing that your Android application meets its functional requirements, it's
important to ensure that your code has no structural problems. Poorly structured code can
impact the reliability and efficiency of your Android apps and make your code harder to
maintain. For example, if your XML resource files contain unused namespaces, this takes up
space and incurs unnecessary processing. Other structural issues, such as use of deprecated
elements or API calls that are not supported by the target API versions, might lead to code
failing to run correctly.
Overview
The Android SDK provides a code scanning tool called lint that can help you to easily
identify and correct problems with the structural quality of your code, without having to
execute the app or write any test cases. Each problem detected by the tool is reported with a
description message and a severity level, so that you can quickly prioritize the critical
improvements that need to be made. You can also configure a problem's severity level to
ignore issues that are not relevant for your project, or raise the severity level. The tool has a
command-line interface, so you can easily integrate it into your automated testing process.
The lint tool checks your Android project source files for potential bugs and optimization
improvements for correctness, security, performance, usability, accessibility, and
internationalization. You can run lint from the command-line or from the Eclipse
environment.
Figure 1 shows how the lint tool processes the application source files.
The source files consist of files that make up your Android project, including Java and XML
files, icons, and ProGuard configuration files.
A configuration file that you can use to specify any lint checks that you want to exclude
and to customize problem severity levels.
A static code scanning tool that you can run on your Android project from the command-line
or from Eclipse. The lint tool checks for structural code problems that could affect the
quality and performance of your Android application. It is strongly recommended that you
correct any errors that lint detects before publishing your application.
You can view the results from lint in the console or in the Lint Warnings view in Eclipse.
Each issue is identified by the location in the source files where it occurred and a description
of the issue.
The lint tool is automatically installed as part of the Android SDK Tools revision 16 or
higher. If you want to use lint in the Eclipse environment, you must also install the Android
Development Tools (ADT) Plugin for Eclipse revision 16 or higher. For more information
about installing the SDK or the ADT Plugin for Eclipse, see Installing the SDK.
If the ADT Plugin is installed in your Eclipse environment, the lint tool runs automatically
when you perform one of these actions:
Export an APK
Edit and save an XML source file in your Android project (such as a manifest or layout file)
Use the layout editor in Eclipse to make changes
Note that when you export an APK, lint only runs an automatic check for fatal errors and
aborts the export if fatal errors are found. You can turn off this automatic checking from the
Lint Error Checking page in Eclipse Preferences.
The output is displayed in the Lint Warnings view. If the Lint Warnings view is not
showing in the workbench, you can bring it up from the Eclipse menu by clicking Window >
Show View > Other > Android > Lint Warnings.
You can also run a lint scan manually on your Android project in Eclipse by right-clicking
on the project folder in the Package Explorer > Android Tools > Run Lint: Check for
Common Errors.
For example, you can issue the following command to scan the files under the myproject
directory and its subdirectories. The issue ID MissingPrefix tells lint to only scan for
XML attributes that are missing the Android namespace prefix.
To see the full list of flags and command-line arguments supported by the tool:
lint --help
The following example shows the console output when the lint command is run against a
project called Earthquake.
$ lint Earthquake
Scanning Earthquake:
...........................................................................
....................................................
Scanning Earthquake (Phase 2): .......
AndroidManifest.xml:23: Warning: <uses-sdk> tag appears after <application>
tag [ManifestOrder]
<uses-sdk android:minSdkVersion="7" />
^
AndroidManifest.xml:23: Warning: <uses-sdk> tag should specify a target API
level (the highest verified version; when running on later versions,
compatibility behaviors may be enabled) with android:targetSdkVersion="?"
[UsesMinSdkAttributes]
<uses-sdk android:minSdkVersion="7" />
^
res/layout/preferences.xml: Warning: The resource R.layout.preferences
appears to be unused [UnusedResources]
res: Warning: Missing density variation folders in res: drawable-xhdpi
[IconMissingDensityFolder]
0 errors, 4 warnings
The output above lists four warnings and no errors in this project. Three warnings
(ManifestOrder, UsesMinSdkAttributes, and UsesMinSdkAttributes) were found in the
project's AndroidManifest.xml file. The remaining warning (IconMissingDensityFolder)
was found in the Preferences.xml layout file.
Configuring lint
By default, when you run a lint scan, the tool checks for all issues that are supported by
lint. You can also restrict the issues for lint to check and assign the severity level for those
issues. For example, you can disable lint checking for specific issues that are not relevant to
your project and configure lint to report non-critical issues at a lower severity level.
You can configure global, project-specific, and file-specific settings for lint from the
Eclipse user interface.
Global preferences
1. Open Window > Preferences > Android > Lint Error Checking.
2. Specify your preferences and click OK.
These settings are applied by default when you run lint on your Android projects in Eclipse.
1. Run the lint tool on your project by right-clicking on your project folder in the Package
Explorer and selecting Android Tools > Run Lint: Check for Common Errors. This action
brings up the Lint Warnings view which displays a list of issues that lint detected in your
project.
2. From the Lint Warnings view, use the toolbar options to configure lint preferences for
individual projects and files in Eclipse. The options you can select include:
o Suppress this error with an annotation/attribute - If the issue appears in a Java
class, the lint tool adds a @SuppressLint annotation to the method where the
issue was detected. If the issue appears in an .xml file, lint inserts a
tools:ignore attribute to disable checking for the lint issue in this file.
o Ignore in this file - Disables checking for this lint issue in this file.
o Ignore in this project - Disables checking for this lint issue in this project.
o Always ignore - Disables checking for this lint issue globally for all projects.
If you select the second or third option, the lint tool automatically generates a lint.xml file
with these configuration settings in your Android application project folder.
You can specify your lint checking preferences in the lint.xml file. If you are creating this
file manually, place it in the root directory of your Android project. If you are configuring
lint preferences in Eclipse, the lint.xml file is automatically created and added to your
Android project for you.
The lint.xml file consists of an enclosing <lint> parent tag that contains one or more
children <issue> elements. Each <issue> is identified by a unique id attribute value, which
is defined by lint.
By setting the severity attribute value in the <issue> tag, you can disable lint checking for
an issue or change the severity level for an issue.
Tip: To see the full list of issues supported by the lint tool and their corresponding issue
IDs, run the lint --list command.
You can disable lint checking from your Java and XML source files.
Tip: If you are using Eclipse, you can use the Quick Fix feature to automatically add the
annotation or attribute to disable lint checking to your Java or XML source files:
1. Open the Java or XML file that has a lint warning or error in an Eclipse editor.
2. Move your cursor to the location in the file where is lint issue is found, then press Ctrl+1
to bring up the Quick Fix pop-up.
3. From the Quick Fix pop-up, select the action to add an annotation or attribute to ignore the
lint issue.
To disable lint checking specifically for a Java class or method in your Android project, add
the @SuppressLint annotation to that Java code.
The following example shows how you can turn off lint checking for the NewApi issue in
the onCreate method. The lint tool continues to check for the NewApi issue in other
methods of this class.
@SuppressLint("NewApi")
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
The following example shows how to turn off lint checking for the ParserError issue in
the FeedProvider class:
@SuppressLint("ParserError")
public class FeedProvider extends ContentProvider {
To suppress checking for all lint issues in the Java file, use the all keyword, like this:
@SuppressLint("all")
You can use the tools:ignore attribute to disable lint checking for specific sections of
your XML files. In order for this attribute to be recognized by the lint tool, the following
namespace value must be included in your XML file:
namespace xmlns:tools="http://schemas.android.com/tools"
The following example shows how you can turn off lint checking for the UnusedResources
issue for the <LinearLayout> element of an XML layout file. The ignore attribute is
inherited by the children elements of the parent element in which the attribute is declared. In
this example, the lint check is also disabled for the child <TextView> element.
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
tools:ignore="UnusedResources" >
<TextView
android:text="@string/auto_update_prompt" />
</LinearLayout>
To disable more than one issue, list the issues to disable in a comma-separated string. For
example:
tools:ignore="NewApi,StringFormatInvalid"
To suppress checking for all lint issues in the XML element, use the all keyword, like this:
tools:ignore="all"
Optimizing Your UI
In this document
1. Using Hierarchy Viewer
1. Running Hierarchy Viewer and choosing a window
2. About the View Hierarchy window
3. Working with an individual View in Tree View
4. Debugging with View Hierarchy
5. Optimizing with View Hierarchy
2. Using Pixel Perfect
1. About the Pixel Perfect window
2. Working with Pixel Perfect overlays
3. Using lint to optimize your UI
Related videos
1.
2.
Sometimes your application's layout can slow down your application. To help debug issues in
your layout, the Android SDK provides the Hierarchy Viewer and lint tools.
The Hierarchy Viewer application allows you to debug and optimize your user interface. It
provides a visual representation of the layout's View hierarchy (the View Hierarchy window)
with performance information for each node in the layout, and a magnified view of the
display (the Pixel Perfect window) to closely examine the pixels in your layout.
Android lint is a static code scanning tool that helps you optimize the layouts and layout
hierarchies of your applications, as well as detect other common coding problems. You can
run it against your layout files or resource directories to quickly check for inefficiencies or
other types of problems that could be affecting the performance of your application.
2. If you have not done so already, install the application you want to work with.
3. Run the application, and ensure that its UI is visible.
4. From a terminal, launch hierarchyviewer from the <sdk>/tools/ directory.
5. The first window you see displays a list of devices and emulators. To expand the list
of Activity objects for a device or emulator, click the arrow on the left. This displays a
list of the Activity objects whose UI is currently visible on the device or emulator.
The objects are listed by their Android component name. The list includes both your
application Activity and system Activity objects. A screenshot of this window appears
in figure 1.
6. Select the name of your Activity from the list. You can now look at its view hierarchy
using the View Hierarchy window, or look at a magnified image of the UI using the
Pixel Perfect window.
To learn how to use the View Hierarchy window, go to About the View Hierarchy window.
To learn how to use the Pixel Perfect window, go to About the Pixel Perfect window.
Figure 1. Hierarchy Viewer device window
The View Hierarchy window displays the View objects that form the UI of the Activity that
is running on your device or emulator. You use it to look at individual View objects within
the context of the entire View tree. For each View object, the View Hierarchy window also
displays rendering performance data.
To see the View Hierarchy window, run Hierarchy Viewer as described in the section
Running Hierarchy Viewer and choosing a window. Next, click View Hierarchy at the top of
the device window.
Tree View: The left-hand pane displays the Tree View, a diagram of the Activity
object's hierarchy of views. Use Tree View to examine individual View objects and
see the relationships between View objects in your UI.
To zoom in on the pane, use the slider at the bottom of the pane, or use your mouse
scroll wheel. To move around in the pane or reveal View objects that are not currently
visible, click and drag the pane.
To highlight the nodes in the tree whose class or ID match a search string, enter the
string in the Filter by class or id: edit box at the bottom of the window. The
background of nodes that match the search string will change from gray to bright
blue.
To save a screenshot of Tree View to a PNG file, click Save As PNG at the top of the
View Hierarchy window. This displays a dialog in which you can choose a directory
and file name.
In Photoshop (or similar program that accepts .psd files), you can hide, show or edit a
layer independently of others. When you save a layered screenshot, you can examine
and modify the image of an individual View object. This helps you experiment with
design changes.
The upper right-hand pane displays the Tree Overview, a smaller map representation
of the entire Tree View window. Use Tree Overview to identify the part of the view
tree that is being displayed in Tree View.
You can also use Tree Overview to move around in the Tree View pane. Click and
drag the shaded rectangle over an area to reveal it in Tree View.
The middle right-hand pane displays the Properties View, a list of the properties for a
selected View object. With Properties View, you can examine all the properties
without having to look at your application source.
The lower right-hand pane displays the Layout View, a block representation of the
UI. Layout View is another way to navigate through your UI. When you click on a
View object in Tree View, its position in the UI is highlighted. Conversely, when you
click in an area of Layout View, the View object for that area is highlighted in Tree
View.
o Bold red: The block represents the the View that is currently selected in Tree
View.
o Light red: The block represents the parent of the block outlined in bold red.
o White: The block represents a visible View that is not a parent or child of the
View that is currently selected in Tree View.
When the UI of the current Activity changes, the View Hierarchy window is not
automatically updated. To update it, click Load View Hierarchy at the top of the window.
Also, the window is not updated if you switch to a new Activity. To update it, start by
clicking the window selection icon in the bottom left-hand corner of the window. This
navigates back to the Window Selection window. From this window, click the Android
component name of the new Activity and then click Load View Hierarchy at the top of the
window.
Each node in Tree View represents a single View. Some information is always visible.
Starting at the top of the node, you see the following:
When you select a node, additional information for the View appears in a small window
above the node. When you click one of the nodes, you see the following:
Image: The actual image of the View, as it would appear in the emulator. If the View
has children, these are also displayed.
View count: The number of View objects represented by this node. This includes the
View itself and a count of its children. For example, this value is 4 for a View that has
3 children.
Render times: The actual measure, layout, and draw times for the View rendering, in
milliseconds. These represent the same values as the performance indicators
mentioned in the preceding section.
An annotated screenshot of an individual node in the Tree View window appears in figure 3.
Figure 3. An annotated node in Tree View
The View Hierarchy window helps you debug an application by providing a static display of
the UI. The display starts with your application's opening screen. As you step through your
application, the display remains unchanged until you redraw it by invalidating and then
requesting layout for a View.
Select a View in Tree View. As you move up towards the root of the tree (to the left
in the Tree View), you see the highest-level View objects. Redrawing a high-level
object usually forces the lower-level objects to redraw as well.
Click Invalidate at the top of the window. This marks the View as invalid, and
schedules it for a redraw at the next point that a layout is requested.
Click Request Layout to request a layout. The View and its children are redrawn, as
well as any other View objects that need to be redrawn.
Manually redrawing a View allows you to watch the View object tree and examine the
properties of individual View objects one step at a time as you go through breakpoints in your
code.
View Hierarchy also helps you identify slow render performance. You start by looking at the
View nodes with red or yellow performance indicators to identify the slower View objects.
As you step through your application, you can judge if a View is consistently slow or slow
only in certain circumstances.
Remember that slow performance is not necessarily evidence of a problem, especially for
ViewGroup objects. View objects that have more children and more complex View objects
render more slowly.
The View Hierarchy window also helps you find performance issues. Just by looking at the
performance indicators (the dots) for each View node, you can see which View objects are
the slowest to measure, layout, and draw. From that, you can quickly identify the problems
you should look at first.
Pixel Perfect is a tool for examining pixel properties and laying out UIs from a design
drawing.
The Pixel Perfect window displays a magnified image of the screen that is currently visible
on the emulator or device. In it, you can examine the properties of individual pixels in the
screen image. You can also use the Pixel Perfect window to help you lay out your application
UI based on a bitmap design.
To see the Pixel Perfect window, run Hierarchy Viewer, as described in the section Running
Hierarchy Viewer and choosing a window. Next, click Inspect Screenshot at the top of the
device window. The Pixel Perfect window appears.
View Object pane: This is a hierarchical list of the View objects that are currently
visible on the device or emulator screen, including both the ones in your application
and the ones generated by the system. The objects are listed by their View class. To
see the class names of a View object's children, expand the View by clicking the
arrow to its left. When you click a View, its position is highlighted in the Pixel Perfect
pane on the right.
Pixel Perfect Loupe pane: This is the magnified screen image. It is overlaid by a grid
in which each square represents one pixel. To look at the information for a pixel, click
in its square. Its color and X,Y coordinates appear at the bottom of the pane.
The magenta crosshair in the pane corresponds to the positioning crosshair in the next
pane. It only moves when you move the crosshair in the next pane.
To zoom in or out on the image, use the Zoom slider at the bottom of the pane, or use
your mouse's scroll wheel.
When you select a pixel in the Loupe pane, you see the following information at the
bottom of the pane:
o Pixel swatch: A rectangle filled with the same color as the pixel.
o HTML color code: The hexadecimal RGB code corresponding to the pixel
color
o RGB color values: A list of the (R), green (G), and blue (B) color values of the
pixel color. Each value is in the range 0-255.
o X and Y coordinates: The pixel's coordinates, in device-specific pixel units.
The values are 0-based, with X=0 at the left of the screen and Y=0 at the top.
Pixel Perfect pane: This displays the currently visible screen as it would appear in the
emulator.
You use the cyan crosshair to do coarse positioning. Drag the crosshair in the image,
and the Loupe crosshair will move accordingly. You can also click on a point in the
Pixel Perfect pane, and the crosshair will move to that point.
The image corresponding to the View object selected in the View Object pane is
outlined in a box that indicates the View object's position on the screen. For the
selected object, the box is bold red. Sibling and parent View objects have a light red
box. View objects that are neither parents nor siblings are in white.
The layout box may have other rectangles either inside or outside it, each of which
indicates part of the View. A purple or green rectangle indicates the View bounding
box. A white or black box inside the layout box represents the padding, the defined
distance between the View object's content and its bounding box. An outer white or
black rectangle represents the margins, the distance between the View bounding box
and adjacent View objects. The padding and margin boxes are white if the layout
background is black, and vice versa.
You can save the screen image being displayed in the Pixel Perfect pane as a PNG
file. This produces a screenshot of the current screen. To do this, click Save as PNG
at the top of the window. This displays a dialog, in which you can choose a directory
and filename for the file.
The panes are not automatically refreshed when you change one of the View objects or go to
another Activity. To refresh the Pixel Perfect pane and the Loupe pane, click Refresh
Screenshot at the top of the window. This will change the panes to reflect the current screen
image. You still may need to refresh the View Object pane; to do this, click Refresh Tree at
the top of the window.
To automatically refresh the panes while you are debugging, set Auto Refresh at the top of
the window, and then set a refresh rate with the Refresh Rate slider at the bottom of the
Loupe pane.
You often construct a UI based on a design done as a bitmap image. The Pixel Perfect
window helps you match up your View layout to a bitmap image by allowing you to load the
bitmap as an overlay on the screen image.
Start your application in a device or emulator and navigate to the Activity whose UI
you want to work with.
Start Hierarchy Viewer and navigate to the Pixel Perfect window.
At the top of the window, click Load Overlay. A dialog opens, prompting for the
image file to load. Load the image file.
Pixel Perfect displays the overlay over the screen image in the Pixel Perfect pane. The
lower left corner of the bitmap image (X=0, Y=max value) is anchored on the lower
leftmost pixel (X=0, Y=max screen) of the screen.
By default, the overlay has a 50% transparency, which allows you to see the screen
image underneath. You can adjust this with the Overlay: slider at the bottom of the
Loupe pane.
Also by default, the overlay is not displayed in the Loupe pane. To display it, set
Show in Loupe at the top of the window.
The overlay is not saved as part of the screenshot when you save the screen image as a PNG
file.
The Android lint tool lets you analyze the XML files that define your application's UI to
find inefficiencies in the view hierarchy.
Note: The Android layoutopt tool has been replaced by the lint tool beginning in ADT
and SDK Tools revision 16. The lint tool reports UI layout performance issues in a similar
way as layoutopt, and detects additional problems.
For more information about using lint, see Improving Your Code with lint and the lint
reference documentation.
Traceview is a graphical viewer for execution logs that you create by using the Debug class to
log tracing information in your code. Traceview can help you debug your application and
profile its performance.
Traceview Layout
When you have a trace log file (generated by adding tracing code to your application or by
DDMS), you can load the log files in Traceview, which displays the log data in two panels:
A timeline panel -- describes when each thread and method started and stopped
A profile panel -- provides a summary of what happened inside a method
The sections below provide addition information about the traceview output panes.
Timeline Panel
Figure 1 shows a close up of the timeline panel. Each thread’s execution is shown in its own
row, with time increasing to the right. Each method is shown in another color (colors are
reused in a round-robin fashion starting with the methods that have the most inclusive time).
The thin lines underneath the first row show the extent (entry to exit) of all the calls to the
selected method.
Profile Panel
Figure 2 shows the profile pane, a summary of all the time spent in a method. The table
shows both the inclusive and exclusive times (as well as the percentage of the total time).
Exclusive time is the time spent in the method. Inclusive time is the time spent in the method
plus the time spent in any called functions. We refer to calling methods as "parents" and
called methods as "children." When a method is selected (by clicking on it), it expands to
show the parents and children. Parents are shown with a purple background and children with
a yellow background. The last column in the table shows the number of calls to this method
plus the number of recursive calls. The last column shows the number of calls out of the total
number of calls made to that method. In this view, we can see that there were 14 calls to
LoadListener.nativeFinished(); looking at the timeline panel shows that one of those
calls took an unusually long time.
Include the Debug class in your code and call its methods such as
startMethodTracing() and stopMethodTracing(), to start and stop logging of
trace information to disk. This option is very precise because you can specify exactly
where to start and stop logging trace data in your code.
Use the method profiling feature of DDMS to generate trace logs. This option is less
precise because you do not modify code, but rather specify when to start and stop
logging with DDMS. Although you have less control on exactly where logging starts
and stops, this option is useful if you don't have access to the application's code, or if
you do not need precise log timing.
Before you start generating trace logs, be aware of the following restrictions:
If you are using the Debug class, your application must have permission to write to
external storage (READ_EXTERNAL_STORAGE).
If you are using DDMS:
o Android 2.1 and earlier devices must have an SD card present and your
application must have permission to write to the SD card.
o Android 2.2 and later devices do not need an SD card. The trace log files are
streamed directly to your development machine.
This document focuses on using the Debug class to generate trace data. For more information
on using DDMS to generate trace data, see Using the Dalvik Debug Monitor Server.
To create the trace files, include the Debug class and call one of the startMethodTracing()
methods. In the call, you specify a base name for the trace files that the system generates. To
stop tracing, call stopMethodTracing(). These methods start and stop method tracing across
the entire virtual machine. For example, you could call startMethodTracing() in your
activity's onCreate() method, and call stopMethodTracing() in that activity's
onDestroy() method.
When your application calls startMethodTracing(), the system creates a file called
<trace-base-name>.trace. This contains the binary method trace data and a mapping table
with thread and method names.
The system then begins buffering the generated trace data, until your application calls
stopMethodTracing(), at which time it writes the buffered data to the output file. If the
system reaches the maximum buffer size before you call stopMethodTracing(), the system
stops tracing and sends a notification to the console.
Interpreted code runs more slowly when profiling is enabled. Don't try to generate absolute
timings from the profiler results (such as, "function X takes 2.5 seconds to run"). The times
are only useful in relation to other profile output, so you can see if changes have made the
code faster or slower relative to a previous profiling run.
After your application has run and the system has created your trace files <trace-base-
name>.trace on a device or emulator, you must copy those files to your development
computer. You can use adb pull to copy the files. Here's an example that shows how to
copy an example file, calc.trace, from the default location on the emulator to the /tmp
directory on the emulator host machine:
To run Traceview and view the trace files, enter traceview <trace-base-name>. For
example, to run Traceview on the example files copied in the previous section, use:
traceview /tmp/calc
Note: If you are trying to view the trace logs of an application that is built with ProGuard
enabled (release mode build), some method and member names might be obfuscated. You
can use the Proguard mapping.txt file to figure out the original unobfuscated names. For
more information on this file, see the Proguard documentation.
Using dmtracedump
dmtracedump is a tool that gives you an alternate way of generating graphical call-stack
diagrams from trace log files. The tool uses the Graphviz Dot utility to create the graphical
output, so you need to install Graphviz before running dmtracedump.
The dmtracedump tool generates the call stack data as a tree diagram, with each call
represented as a node. It shows call flow (from parent node to child nodes) using arrows. The
diagram below shows an example of dmtracedump output.
Figure 3. Screenshot of dmtracedump
The tool then loads trace log data from <trace-base-name>.data and <trace-base-
name>.key. The table below lists the options for dmtracedump.
Option Description
-d <trace-
base-name> Diff with this trace name
-g <outfile> Generate output to <outfile>
-h Turn on HTML output
-o Dump the trace file instead of profiling
-d <trace-
base-name> URL base to the location of the sortable javascript file
Minimum threshold for including child nodes in the graph (child's
-t <percent> inclusive time as a percentage of parent inclusive time). If this option is
not used, the default threshold is 20%.
See also
1. Systrace
After building features, eliminating bugs, and cleaning up your code, you should spend some
time looking at the performance of your application. The speed and smoothness with which
your application draws pixels and performs operations has an significant impact on your
users' experience.
Android applications operate within a shared resource environment, and the performance of
your application can be impacted by how efficiently it interacts with those resources in the
larger system. Applications also operate in a multithreaded environment, competing with
other threaded processes for resources, which can cause performance problems that are hard
to diagnose.
The Systrace tool allows you to collect and review code execution data for your application
and the Android system. You can use this data to diagnose execution problems and improve
the performance of your application.
Overview
Systrace helps you analyze how the execution of your application fits into the larger Android
environment, letting you see system and applications process execution on a common
timeline. The tool allows you to generate highly detailed, interactive reports from devices
running Android 4.1 and higher, such as the report in figure 1.
Generating Traces
In order to create a trace of your application, you must perform a few setup steps. First, you
must have a device running Android 4.1 or higher. Set up the device for debugging, connect
it to your development system, and install your application. Some types of trace information,
specifically disk activity and kernel work queues, require that you have root access to the
device. However, most Systrace log data only requires that the device be enabled for
developer debugging.
Systrace traces can be run either from a command line or from a graphical user interface.
This guide focuses on using the command line options.
Limit the amount of time covered by the trace with the -t, --time option. The
default length of a trace is 5 seconds.
Limit the size of the data collected by the trace with the -b, --buf-size option.
Specify what types of processes are traced. The types of processes that can be traced
depends on the version of Android you are running:
o Android 4.2 and lower devices: Use the --set-tags option and the --disk, -
-cpu-freq, --cpu-idle, --cpu-load options.
o Android 4.3 and higher devices: Use the --list-categories option to see
what categories are available on your test device.
1. Make sure the device is connected through a USB cable and is enabled for debugging.
2. Run the trace with the options you want, for example:
$ cd android-sdk/platform-tools/systrace
$ python systrace.py --time=10 -o mynewtrace.html sched gfx view wm
3. On the device, execute any user actions you want be included in the trace.
For more information on the available options for running Systrace, see the Systrace help
page.
To use Systrace effectively with devices running Android 4.2 and lower, you must configure
the types of processes you want to trace before running a trace. The tool can gather the
following types of process information:
General system processes such as graphics, audio and input processes (selected using
trace category tags).
Low level system information such as CPU, kernel and disk activity (selected using
options).
$ cd android-sdk/platform-tools/systrace
$ python systrace.py --set-tags=gfx,view,wm
2. Stop and restart the adb shell to enable tracing of these processes.
$ adb shell stop
$ adb shell start
To set trace tags for Systrace using the device user interface:
1. On the device connected for tracing, navigate to: Settings > Developer options >
Monitoring > Enable traces.
2. Select the categories of processes to be traced and click OK.
Note: The adb shell does not have to be stopped and restarted when selecting trace tags using
this method.
After you have configured the category tags for your trace, you can start collecting
information for analysis.
1. Make sure the device is connected through a USB cable and is enabled for debugging.
2. Run the trace with the low-level system trace options and limits you want, for
example:
3. On the device, execute any user actions you want be included in the trace.
For more information on the available options for running Systrace, see the Systrace help
page.
The Systrace tool can trace the execution of code within your application. In Android 4.3
(API level 18) and higher, you can use the methods of the Trace class to add instrumentation
to your application code and see the results in a Systrace report.
The following code example shows how to use the Trace class to track execution of an
application method, including two nested code blocks within that method.
Trace.beginSection("Processing John");
try {
// code for John task...
} finally {
Trace.endSection(); // ends "Processing John"
}
} finally {
Trace.endSection(); // ends "ProcessPeople"
}
}
Note: When you nest trace calls within each other, the endSection() method ends the most
recently called beginSection(String) method. This means that a trace started within
another trace cannot extend beyond the end of the enclosing trace, so make sure your
beginning and ending method calls are properly matched to measure your applications
processing.
Note: Traces must begin and end on the same thread. Do not call beginSection(String) on
one thread of execution and then attempt to end the trace with a call to endSection() on
another thread.
When using application-level tracing with Systrace, you must specify the package name of
your application in the user interface or specify the -a or --app= options on the command
line. For more information, see the Systrace help page.
Analyzing Traces
After you have generated a trace using Systrace, it lists the location of the output file and you
can open the report using a web browser. How you use the trace data depends on the
performance issues you are investigating. However, this section provides some general
instructions on how to analyze a trace.
The reports generated by Systrace are interactive, allowing you to zoom into and out of the
process execution details. Use the W key to zoom in, the S key to zoom out, the A key to pan
left and the D key to pan right. Select a task in timeline using your mouse to get more
information about the task. For more information about the using the keyboard navigation
shortcuts and navigation, see the Systrace reference documentation.
A well-behaved application executes many small operations quickly and with a regular
rhythm, with individual operations completing within few milliseconds, depending on the
device and the processes being performed, as shown in figure 2:
Figure 2. Excerpt from a trace of a smoothly running application with a regular execution
rhythm.
The trace excerpt in figure 2 shows a well-behaved application with a regular process rhythm
(1). The lower section of figure 2 shows a magnified section of the trace indicated by the
dotted outline, which reveals some irregularity in the process execution. In particular, one of
the wider task bars, indicated by (2), is taking slightly longer (14 milliseconds) than other,
similar tasks on this thread, which are averaging between 9 and 12 milliseconds to complete.
This particular task execution length is likely not noticeable to a user, unless it impacts
another process with specific timing, such as a screen update.
Long running processes show up as thicker than usual execution bars in a trace. These thicker
bars can indicate a problem in your application performance. When they show up in your
trace, zoom in on the process using the keyboard navigation shortcuts to identify the task
causing the problem, and click on the task to get more information. You should also look at
other processes running at the same time, looking for a thread in one process that is being
blocked by another process.
The Systrace tool is particularly useful in analyzing application display slowness, or pauses in
animations, because it shows you the execution of your application across multiple system
processes. With display execution, drawing screen frames with a regular rhythm is essential
for good performance. Having a regular rhythm for display ensures that animations and
motion are smooth on screen. If an application drops out of this rhythm, the display can
become jerky or slow from the users perspective.
If you are analyzing an application for this type of problem, examine the SurfaceFlinger
process in the Systrace report where your application is also executing to look for places
where it drops out of its regular rhythm.
Figure 3. Excerpt from a trace of an application showing interruptions in display processing.
The trace excerpt in figure 3 shows an section of a trace that indicates an interruption in the
device display. The section of the SurfaceFlinger process in top excerpt, indicated by (1),
shows that display frames are being missed. These dropped frames are potentially causing the
display to stutter or halt. Zooming into this problem area in the lower trace, shows that a
memory operation (image buffer dequeuing and allocation) in the surfaceflinger secondary
thread is taking a long time (2). This delay causes the application to miss the display update
window, indicated by the dotted line. As the developer of this application, you should
investigate other threads in your application that may also be trying to allocate memory at the
same time or otherwise blocking memory allocation with another request or task.
Note: When using Systrace to analyze display problems, make sure you activate the tracing
tags for Graphics and Views.
For more information on the command line options and keyboard controls for Systrace, see
the Systrace help page.
See Also
Managing Your App's Memory
Because Android is designed for mobile devices, you should always be careful about how
much random-access memory (RAM) your app uses. Although Android’s Dalvik virtual
machine performs routine garbage collection, this doesn’t mean you can ignore when and
where your app allocates and releases memory. In order to provide a stable user experience
that allows the system to quickly switch between apps, it’s important that your app does not
needlessly consume memory when the user is not interacting with it.
Even if you follow all the best practices for Managing Your App Memory during
development (which you should), you still might leak objects or introduce other memory
bugs. The only way to be certain your app is using as little memory as possible is to analyze
your app’s memory usage with tools. This guide shows you how to do that.
The simplest place to begin investigating your apps memory usage is the Dalvik log
messages. You'll find these log messages in logcat (the output is available in the Device
Monitor or directly in IDEs such as Eclipse and Android Studio).
Every time a garbage collection occurs, logcat prints a message with the following
information:
What triggered the garbage collection and what kind of collection it is. Reasons that may
appear include:
GC_CONCURRENT
A concurrent garbage collection that frees up memory as your heap begins to fill up.
GC_FOR_MALLOC
A garbage collection caused because your app attempted to allocate memory when your
heap was already full, so the system had to stop your app and reclaim memory.
GC_HPROF_DUMP_HEAP
A garbage collection that occurs when you create an HPROF file to analyze your heap.
GC_EXPLICIT
An explicit garbage collection, such as when you call gc() (which you should avoid calling
and instead trust the garbage collector to run when needed).
GC_EXTERNAL_ALLOC
This happens only on API level 10 and lower (newer versions allocate everything in the Dalvik
heap). A garbage collection for externally allocated memory (such as the pixel data stored in
native memory or NIO byte buffers).
Amount freed
Heap stats
Externally allocated memory on API level 10 and lower (amount of allocated memory) /
(limit at which collection will occur).
Pause time
Larger heaps will have larger pause times. Concurrent pause times show two pauses: one at
the beginning of the collection and another near the end.
For example:
As these log messages stack up, look out for increases in the heap stats (the 3571K/9991K
value in the above example). If this value continues to increase and doesn't ever seem to get
smaller, you could have a memory leak.
2. In the Debug Monitor window, select your app's process from the list on the left.
3. Click Update Heap above the process list.
4. In the right-side panel, select the Heap tab.
The Heap view shows some basic stats about your heap memory usage, updated after every
garbage collection. To see the first update, click the Cause GC button.
Figure 1. The Device Monitor tool, showing the [1] Update Heap and [2] Cause GC
buttons. The Heap tab on the right shows the heap results.
Continue interacting with your app to watch your heap allocation update with each garbage
collection. This can help you identify which actions in your app are likely causing too much
allocation and where you should try to reduce allocations and release resources.
Tracking Allocations
As you start narrowing down memory issues, you should also use the Allocation Tracker to
get a better understanding of where your memory-hogging objects are allocated. The
Allocation Tracker can be useful not only for looking at specific uses of memory, but also to
analyze critical code paths in an app such as scrolling.
For example, tracking allocations when flinging a list in your app allows you to see all the
allocations that need to be done for that behavior, what thread they are on, and where they
came from. This is extremely valuable for tightening up these paths to reduce the work they
need and improve the overall smoothness of the UI.
2. In the DDMS window, select your app's process in the left-side panel.
3. In the right-side panel, select the Allocation Tracker tab.
4. Click Start Tracking.
5. Interact with your app to execute the code paths you want to analyze.
6. Click Get Allocations every time you want to update the list of allocations.
The list shows all recent allocations, currently limited by a 512-entry ring buffer. Click on a
line to see the stack trace that led to the allocation. The trace shows you not only what type of
object was allocated, but also in which thread, in which class, in which file and at which line.
Figure 2. The Device Monitor tool, showing recent app allocations and stack traces in the
Allocation Tracker.
Note: You will always see some allocations from DdmVmInternal and else where that come
from the allocation tracker itself.
Although it's not necessary (nor possible) to remove all allocations for your performance
critical code paths, the allocation tracker can help you identify important issues in your code.
For instance, some apps might create a new Paint object on every draw. Moving that object
into a global member is a simple fix that helps improve performance.
For further analysis, you may want to observe how your app's memory is divided between
different types of RAM allocation with the following adb command:
The output lists all of your app's current allocations, measured in kilobytes.
When inspecting this information, you should be familiar with the following types of
allocation:
This is memory that is being used by only your process. This is the bulk of the RAM that the
system can reclaim when your app’s process is destroyed. Generally, the most important
portion of this is “private dirty” RAM, which is the most expensive because it is used by only
your process and its contents exist only in RAM so can’t be paged to storage (because
Android does not use swap). All Dalvik and native heap allocations you make will be private
dirty RAM; Dalvik and native allocations you share with the Zygote process are shared dirty
RAM.
This is a measurement of your app’s RAM use that takes into account sharing pages across
processes. Any RAM pages that are unique to your process directly contribute to its PSS
value, while pages that are shared with other processes contribute to the PSS value only in
proportion to the amount of sharing. For example, a page that is shared between two
processes will contribute half of its size to the PSS of each process.
A nice characteristic of the PSS measurement is that you can add up the PSS across all
processes to determine the actual memory being used by all processes. This means PSS is a
good measure for the actual RAM weight of a process and for comparison against the RAM
use of other processes and the total available RAM.
For example, below is the the output for Gmail’s process on a tablet device. There is a lot of
information here, but key points for discussion are listed below.
Note: The information you see may vary slightly from what is shown here, as some details of
the output differ across platform versions.
Objects
Views: 426 ViewRootImpl: 3(8)
AppContexts: 6(7) Activities: 2(7)
Assets: 2 AssetManagers: 2
Local Binders: 64 Proxy Binders: 34
Death Recipients: 0
OpenSSL Sockets: 1
SQL
MEMORY_USED: 1739
PAGECACHE_OVERFLOW: 1164 MALLOC_SIZE: 62
Generally, you should be concerned with only the Pss Total and Private Dirty columns.
In some cases, the Private Clean and Heap Alloc columns also offer interesting data. Here
is some more information about the different memory allocations (the rows) you should
observe:
Dalvik Heap
The RAM used by Dalvik allocations in your app. The Pss Total includes all Zygote
allocations (weighted by their sharing across processes, as described in the PSS definition
above). The Private Dirty number is the actual RAM committed to only your app’s heap,
composed of your own allocations and any Zygote allocation pages that have been modified
since forking your app’s process from Zygote.
Note: On newer platform versions that have the Dalvik Other section, the Pss
Total and Private Dirty numbers for Dalvik Heap do not include Dalvik overhead
such as the just-in-time compilation (JIT) and garbage collection (GC) bookkeeping,
whereas older versions list it all combined under Dalvik.
The Heap Alloc is the amount of memory that the Dalvik and native heap allocators
keep track of for your app. This value is larger than Pss Total and Private Dirty
because your process was forked from Zygote and it includes allocations that your
process shares with all the others.
The RAM being used for mmapped .so (native) and .dex (Dalvik) code. The Pss Total
number includes platform code shared across apps; the Private Clean is your app’s own
code. Generally, the actual mapped size will be much larger—the RAM here is only what
currently needs to be in RAM for code that has been executed by the app. However, the .so
mmap has a large private dirty, which is due to fix-ups to the native code when it was loaded
into its final address.
Unknown
Any RAM pages that the system could not classify into one of the other more specific items.
Currently, this contains mostly native allocations, which cannot be identified by the tool
when collecting this data due to Address Space Layout Randomization (ASLR). As with the
Dalvik heap, the Pss Total for Unknown takes into account sharing with Zygote, and
Private Dirty is unknown RAM dedicated to only your app.
TOTAL
The total Proportional Set Size (PSS) RAM used by your process. This is the sum of all PSS
fields above it. It indicates the overall memory weight of your process, which can be directly
compared with other processes and the total available RAM.
The Private Dirty and Private Clean are the total allocations within your
process, which are not shared with other processes. Together (especially Private
Dirty), this is the amount of RAM that will be released back to the system when your
process is destroyed. Dirty RAM is pages that have been modified and so must stay
committed to RAM (because there is no swap); clean RAM is pages that have been
mapped from a persistent file (such as code being executed) and so can be paged out
if not used for a while.
ViewRootImpl
The number of root views that are active in your process. Each root view is associated with a
window, so this can help you identify memory leaks involving dialogs or other windows.
The number of app Context and Activity objects that currently live in your process. This
can be useful to quickly identify leaked Activity objects that can’t be garbage collected
due to static references on them, which is common. These objects often have a lot of other
allocations associated with them and so are a good way to track large memory leaks.
Note: A View or Drawable object also holds a reference to the Activity that it's from, so
holding a View or Drawable object can also lead to your app leaking an Activity.
A heap dump is a snapshot of all the objects in your app's heap, stored in a binary format
called HPROF. Your app's heap dump provides information about the overall state of your
app's heap so you can track down problems you might have identified while viewing heap
updates.
2. In the DDMS window, select your app's process in the left-side panel.
3. Click Dump HPROF file, shown in figure 3.
4. In the window that appears, name your HPROF file, select the save location, then click Save.
Figure 3. The Device Monitor tool, showing the [1] Dump HPROF file button.
If you need to be more precise about when the dump is created, you can also create a heap
dump at the critical point in your app code by calling dumpHprofData().
The heap dump is provided in a format that's similar to, but not identical to one from the Java
HPROF tool. The major difference in an Android heap dump is due to the fact that there are a
large number of allocations in the Zygote process. But because the Zygote allocations are
shared across all app processes, they don’t matter very much to your own heap analysis.
To analyze your heap dump, you can use a standard tool like jhat or the Eclipse Memory
Analyzer Tool (MAT). However, first you'll need to convert the HPROF file from Android's
format to the J2SE HPROF format. You can do this using the hprof-conv tool provided in
the <sdk>/platform-tools/ directory. Simply run the hprof-conv command with two
arguments: the original HPROF file and the location to write the converted HPROF file. For
example:
Note: If you're using the version of DDMS that's integrated into Eclipse, you do not need to
perform the HPROF converstion—it performs the conversion by default.
You can now load the converted file in MAT or another heap analysis tool that understands
the J2SE HPROF format.
When analyzing your heap, you should look for memory leaks caused by:
Long-lived references to an Activity, Context, View, Drawable, and other objects that may
hold a reference to the container Activity or Context.
Non-static inner classes (such as a Runnable, which can hold the Activity instance).
Caches that hold objects longer than necessary.
Once you open your converted HPROF file in MAT, you'll see a pie chart in the Overview,
showing what your largest objects are. Below this chart, are links to couple of useful features:
The Histogram view shows a list of all classes and how many instances there are of each.
You might want to use this view to find extra instances of classes for which you know
there should be only a certain number. For example, a common source of leaks is
additional instance of your Activity class, for which you should usually have only
one instance at a time. To find a specific class instance, type the class name into the
<Regex> field at the top of the list.
When you find a class with too many instances, right-click it and select List objects >
with incoming references. In the list that appears, you can determine where an
instance is retained by right-clicking it and selecting Path To GC Roots > exclude
weak references.
The Dominator tree shows a list of objects organized by the amount of retained heap.
What you should look for is anything that's retaining a portion of heap that's roughly
equivalent to the memory size you observed leaking from the GC logs, heap updates,
or allocation tracker.
When you see something suspicious, right-click on the item and select Path To GC
Roots > exclude weak references. This opens a new tab that traces the references to
that object which is causing the alleged leak.
Note: Most apps will show an instance of Resources near the top with a good chunk
of heap, but this is usually expected when your app uses lots of resources from your
res/ directory.
Figure 4. The Eclipse Memory Analyzer Tool (MAT), showing the Histogram view and a
search for "MainActivity".
For more information about MAT, watch the Google I/O 2011 presentation, Memory
management for Android apps, which includes a walkthrough using MAT beginning at about
21:10. Also refer to the Eclipse Memory Analyzer documentation.
You may find it useful to compare your app's heap state at two different points in time in
order to inspect the changes in memory allocation. To compare two heap dumps using MAT:
While using the tools described above, you should aggressively stress your app code and try
forcing memory leaks. One way to provoke memory leaks in your app is to let it run for a
while before inspecting the heap. Leaks will trickle up to the top of the allocations in the
heap. However, the smaller the leak, the longer you need to run the app in order to see it.
You can also trigger a memory leak in one of the following ways:
1. Rotate the device from portrait to landscape and back again multiple times while in different
activity states. Rotating the device can often cause an app to leak an Activity, Context,
or View object because the system recreates the Activity and if your app holds a
reference to one of those objects somewhere else, the system can't garbage collect it.
2. Switch between your app and another app while in different activity states (navigate to the
Home screen, then return to your app).
Tip: You can also perform the above steps by using the "monkey" test framework. For more
information on running the monkey test framework, read the monkeyrunner documentation.
The Dev Tools application relies on a number of permissions that are not available for third
party applications. If you'd like to install the Dev Tools application on a real development
device, you'd have to build a system image for that device and sign the Dev Tools application
with the same key as used for the system image.
To get started, launch the Dev Tools application and select Development Settings. This will
open the Development Settings page with the following options (among others):
Debug app
Lets you select the application to debug. You do not need to set this to attach a
debugger, but setting this value has two effects:
Note: You cannot turn this feature off once it is on, without restarting the emulator.
Show background
Displays a background pattern when no activity screens are visible. This typically
does not happen, but can happen during debugging.
In this document
1. Preparing Your Application for Release
2. Releasing Your Application to Users
See also
1. Publishing on Google Play
Publishing is the general process that makes your Android applications available to users.
When you publish an Android application you perform two main tasks:
During the preparation step you build a release version of your application, which
users can download and install on their Android-powered devices.
During the release step you publicize, sell, and distribute the release version of your
application to users.
Usually, you release your application through an application marketplace, such as Google
Play. However, you can also release applications by sending them directly to users or by
letting users download them from your own website.
Figure 1 shows how the publishing process fits into the overall Android application
development process. The publishing process is typically performed after you finish testing
your application in a debug environment. Also, as a best practice, your application should
meet all of your release criteria for functionality, performance, and stability before you begin
the publishing process.
Figure 1. Publishing is the last phase of the Android application development process.
Preparing Your Application for Release
Preparing your application for release is a multi-step process that involves the following
tasks:
At a minimum you need to remove Log calls and remove the android:debuggable
attribute from your manifest file. You should also provide values for the
android:versionCode and android:versionName attributes, which are located in
the <manifest> element. You may also have to configure several other settings to
meet Google Play requirements or accomodate whatever method you're using to
release your application.
If you are using Gradle build files, you can use the release build type to set your build
settings for the published version of your app.
You can use the Gradle build files with the release build type to build and sign a
release version of your application. See Building and Running from Android Studio.
Before you distribute your application, you should thoroughly test the release version
on at least one target handset device and one target tablet device.
You need to be sure that all application resources such as multimedia files and
graphics are updated and included with your application or staged on the proper
production servers.
Preparing remote servers and services that your application depends on.
If your application depends on external servers or services, you need to be sure they
are secure and production ready.
You may have to perform several other tasks as part of the preparation process. For example,
you will need to get a private key for signing your application, and you may need to get a
Maps API release key if you are using the Google Maps external library. You will also need
to create an icon for your application, and you may want to prepare an End User License
Agreement (EULA) to protect your person, organization, and intellectual property.
When you are finished preparing your application for release you will have a signed .apk file
that you can distribute to users.
To learn how to prepare your application for release, see Preparing for Release in the Dev
Guide. This topic provides step-by-step instructions for configuring and building a release
version of your application.
You can release your Android applications several ways. Usually, you release applications
through an application marketplace such as Google Play, but you can also release
applications on your own website or by sending an application directly to a user.
If you want to distribute your apps to the broadest possible audience, releasing through an
app marketplace such as Google Play is ideal.
Google Play is the premier marketplace for Android apps and is particularly useful if you
want to distribute your applications to a large global audience. However, you can distribute
your apps through any app marketplace you want or you can use multiple marketplaces.
Google Play is a robust publishing platform that helps you publicize, sell, and distribute your
Android applications to users around the world. When you release your applications through
Google Play you have access to a suite of developer tools that let you analyze your sales,
identify market trends, and control who your applications are being distributed to. You also
have access to several revenue-enhancing features such as in-app billing and application
licensing. The rich array of tools and features, coupled with numerous end-user community
features, makes Google Play the premier marketplace for selling and buying Android
applications.
Releasing your application on Google Play is a simple process that involves three basic steps:
To fully leverage the marketing and publicity capabilities of Google Play, you need to
create promotional materials for your application, such as screenshots, videos,
graphics, and promotional text.
Google Play lets you target your application to a worldwide pool of users and devices.
By configuring various Google Play settings, you can choose the countries you want
to reach, the listing languages you want to use, and the price you want to charge in
each country. You can also configure listing details such as the application type,
category, and content rating. When you are done configuring options you can upload
your promotional materials and your application as a draft (unpublished) application.
Figure 1. Users can simply click Install when you send them an application via email.
The easiest and quickest way to release your application is to send it to a user through email.
To do this, you prepare your application for release and then attach it to an email and send it
to a user. When the user opens your email message on their Android-powered device the
Android system will recognize the APK and display an Install Now button in the email
message (see figure 1). Users can install your application by touching the button.
Note: The Install Now button shown in Figure 1 appears only if a user has configured their
device to allow installation from unknown sources and has opened your email with the native
Gmail application.
Distributing applications through email is convenient if you are sending your application to
only a few trusted users, but it provides few protections from piracy and unauthorized
distribution; that is, anyone you send your application to can simply forward it to someone
else.
If you do not want to release your app on a marketplace like Google Play, you can make the
app available for download on your own website or server, including on a private or
enterprise server. To do this, you must first prepare your application for release in the normal
way. Then all you need to do is host the release-ready APK file on your website and provide
a download link to users.
When users browse to the download link from their Android-powered devices, the file is
downloaded and Android system automatically starts installing it on the device. However, the
installation process will start automatically only if the user has configured their Settings to
allow the installation of apps from unknown sources.
Although it is relatively easy to release your application on your own website, it can be
inefficient. For example, if you want to monetize your application you will have to process
and track all financial transactions yourself and you will not be able to use Google Play's In-
app Billing service to sell in-app products. In addition, you will not be able to use the
Licensing service to help prevent unauthorized installation and use of your application.
Figure 2. Users must enable the Unknown sources setting before they can install apps not
downloaded from Google Play.
Android protects users from inadvertent download and install of apps from locations other
than Google Play (which is trusted). It blocks such installs until the user opts-in Unknown
sources in Settings > Security, shown in Figure 2. To allow the installation of applications
from other sources, users need to enable the Unknown sources setting on their devices, and
they need to make this configuration change before they download your application to their
devices.
Note that some network providers do not allow users to install applications from unknown
sources.
In this document
1. Introduction
2. Gathering Materials and Resources
3. Configuring Your Application
4. Building Your Application
5. Preparing External Servers and Resources
6. Testing Your Application for Release
See also
1. Publishing Overview
2. Signing Your Applications
3. Launch Checklist for Google Play
Before you distribute your Android application to users you need to prepare it for release.
The preparation process is a required development task for all Android applications and is the
first step in the publishing process (see figure 1).
When you prepare your application for release, you configure, build, and test a release
version of your application. The configuration tasks are straightforward, involving basic code
cleanup and code modification tasks that help optimize your application. The build process is
similar to the debug build process and can be done using JDK and Android SDK tools. The
testing tasks serve as a final check, ensuring that your application performs as expected under
real-world conditions. When you are finished preparing your application for release you have
a signed .apk file, which you can distribute directly to users or distribute through an
application marketplace such as Google Play.
This document summarizes the main tasks you need to perform to prepare your application
for release. The tasks that are described in this document apply to all Android applications
regardless how they are released or distributed to users. If you are releasing your application
through Google Play, you should also read Publishing Checklist for Google Play to be sure
your release-ready application satisfies all Google Play requirements.
Note: As a best practice, your application should meet all of your release criteria for
functionality, performance, and stability before you perform the tasks outlined in this
document.
Figure 1. Preparing for release is a required development task and is the first step in the
publishing process.
Introduction
To release your application to users you need to create a release-ready package that users can
install and run on their Android-powered devices. The release-ready package contains the
same components as the debug .apk file — compiled source code, resources, manifest file,
and so on — and it is built using the same build tools. However, unlike the debug .apk file,
the release-ready .apk file is signed with your own certificate and it is optimized with the
zipalign tool.
Figure 2. You perform five main tasks to prepare your application for release.
The signing and optimization tasks are usually seamless if you are building your application
with Android Studio. For example, you can use Android Studio with the Gradle build files to
compile, sign, and optimize your application all at once. You can also configure the Gradle
build files to do the same when you build from the command line. For more details about
using the Gradle build files, see the Build System guide.
To prepare your application for release you typically perform five main tasks (see figure 2).
Each main task may include one or more smaller tasks depending on how you are releasing
your application. For example, if you are releasing your application through Google Play you
may want to add special filtering rules to your manifest while you are configuring your
application for release. Similarly, to meet Google Play publishing guidelines you may have to
prepare screenshots and create promotional text while you are gathering materials for release.
You usually perform the tasks listed in figure 2 after you have throroughly debugged and
tested your application. The Android SDK contains several tools to help you test and debug
your Android applications. For more information, see the Debugging and Testing sections in
the Dev Guide.
To begin preparing your application for release you need to gather several supporting items.
At a minimum this includes cryptographic keys for signing your application and an
application icon. You might also want to include an end-user license agreement.
Cryptographic keys
The Android system requires that each installed application be digitally signed with a
certificate that is owned by the application's developer (that is, a certificate for which the
developer holds the private key). The Android system uses the certificate as a means of
identifying the author of an application and establishing trust relationships between
applications. The certificate that you use for signing does not need to be signed by a
certificate authority; the Android system allows you to sign your applications with a self-
signed certificate. To learn about certificate requirements, see Signing Your Applications.
Important: Your application must be signed with a cryptographic key whose validity period
ends after 22 October 2033.
You may also have to obtain other release keys if your application accesses a service or uses
a third-party library that requires you to use a key that is based on your private key. For
example, if your application uses the MapView class, which is part of the Google Maps
external library, you will need to register your application with the Google Maps service and
obtain a Maps API key. For information about getting a Maps API key, see Obtaining a Maps
API key.
Application Icon
Be sure you have an application icon and that it meets the recommended icon guidelines.
Your application's icon helps users identify your application on a device's Home screen and
in the Launcher window. It also appears in Manage Applications, My Downloads, and
elsewhere. In addition, publishing services such as Google Play display your icon to users.
Note: If you are releasing your application on Google Play, you need to create a high
resolution version of your icon. See Graphic Assets for your Application for more
information.
Consider preparing an End User License Agreement (EULA) for your application. A EULA
can help protect your person, organization, and intellectual property, and we recommend that
you provide one with your application.
Miscellaneous Materials
You might also have to prepare promotional and marketing materials to publicize your
application. For example, if you are releasing your application on Google Play you will need
to prepare some promotional text and you will need to create screenshots of your application.
For more information, see Graphic Assets for your Application
After you gather all of your supporting materials you can start configuring your application
for release. This section provides a summary of the configuration changes we recommend
that you make to your source code, resource files, and application manifest prior to releasing
your application. Although most of the configuration changes listed in this section are
optional, they are considered good coding practices and we encourage you to implement
them. In some cases, you may have already made these configuration changes as part of your
development process.
Make sure you choose a package name that is suitable over the life of your application. You
cannot change the package name after you distribute your application to users. You can set
the package name in application's manifest file. For more information, see the package
attribute documentation.
Make sure you deactivate logging and disable the debugging option before you build your
application for release. You can deactivate logging by removing calls to Log methods in your
source files. You can disable debugging by removing the android:debuggable attribute
from the <application> tag in your manifest file, or by setting the android:debuggable
attribute to false in your manifest file. Also, remove any log files or static test files that were
created in your project.
Also, you should remove all Debug tracing calls that you added to your code, such as
startMethodTracing() and stopMethodTracing() method calls.
Important: Ensure that you disable debugging for your app if using WebView to display paid
for content or if using JavaScript interfaces, since debugging allows users to inject scripts and
extract content using Chrome DevTools. To disable debugging, use the
WebView.setWebContentsDebuggingEnabled() method.
Clean up your project and make sure it conforms to the directory structure described in
Android Projects. Leaving stray or orphaned files in your project can prevent your application
from compiling and cause your application to behave unpredictably. At a minimum you
should do the following cleanup tasks:
Review the contents of your jni/, lib/, and src/ directories. The jni/ directory should
contain only source files associated with the Android NDK, such as .c, .cpp, .h, and .mk
files. The lib/ directory should contain only third-party library files or private library files,
including prebuilt shared and static libraries (for example, .so files). The src/ directory
should contain only the source files for your application (.java and .aidl files). The src/
directory should not contain any .jar files.
Check your project for private or proprietary data files that your application does not use
and remove them. For example, look in your project's res/ directory for old drawable files,
layout files, and values files that you are no longer using and delete them.
Check your lib/ directory for test libraries and remove them if they are no longer being
used by your application.
Review the contents of your assets/ directory and your res/raw/ directory for raw asset
files and static files that you need to update or remove prior to release.
Verify that the following manifest and build files items are set correctly:
<uses-permission> element
You should specify only those permissions that are relevant and required for your
application.
You must specify values for these attributes, which are located in the <application>
element.
We recommend that you specify values for these attributes, which are located in the
<manifest> element. For more information see Versioning your Application.
There are several additional manifest or build file elements that you can set if you are
releasing your application on Google Play. For example, the android:minSdkVersion and
android:targetSdkVersion attributes, which are located in the <uses-sdk> element. For
more information about these and other Google Play settings, see Filters on Google Play.
Android provides several tools and techniques to make your application compatible with a
wide range of devices. To make your application available to the largest number of users,
consider doing the following:
Make sure you meet the best practices for supporting multiple screens. By supporting
multiple screen configurations you can create an application that functions properly
and looks good on any of the screen sizes supported by Android.
If your application is designed for devices older than Android 3.0, make it compatible
with Android 3.0 devices by following the guidelines and best practices described in
Optimizing Apps for Android 3.0 .
If your application is designed for devices running Android 3.x, make your
application compatible with older versions of Android by adding the Support Library
to your application project. The Support Library provides static support libraries that
you can add to your Android application, which enables you to use APIs that are
either not available on older platform versions or use utility APIs that are not part of
the framework APIs.
If your application accesses remote servers or services, make sure you are using the
production URL or path for the server or service and not a test URL or path.
If you are releasing a paid application through Google Play, consider adding support for
Google Play Licensing. Licensing lets you control access to your application based on
whether the current user has purchased it. Using Google Play Licensing is optional even if
you are releasing your app through Google Play.
For more information about Google Play Licensing Service and how to use it in your
application, see Application Licensing.
You can use the Gradle build system, integrated with Android Studio to build a release-ready
.apk file that is signed with your private key and optimized. To learn how to setup and run
builds from Android Studio, see Building and Running from Android Studio.
The build process assumes that you have a certificate and private key suitable for signing
your application. If you do not have a suitable certificate and private key, Android Studio can
help you generate one. For more information about the signing process, see Signing Your
Applications.
If your application relies on a remote server, make sure the server is secure and that it is
configured for production use. This is particularly important if you are implementing in-app
billing in your application and you are performing the signature verification step on a remote
server.
Also, if your application fetches content from a remote server or a real-time service (such as a
content feed), be sure the content you are providing is up to date and production-ready.
Testing the release version of your application helps ensure that your application runs
properly under realistic device and network conditions. Ideally, you should test your
application on at least one handset-sized device and one tablet-sized device to verify that your
user interface elements are sized correctly and that your application's performance and battery
efficiency are acceptable.
As a starting point for testing, see What to Test. This article provides a summary of common
Android situations that you should consider when you are testing. When you are done testing
and you are satisfied that the release version of your application behaves correctly, you can
release your application to users. For more information, see Releasing Your Application to
Users. If you are publishing your application on Google Play, see Launch Checklist for
Google Play.
In this document
1. Setting Application Version
2. Specifying Your Application's System API Requirements
See also
1. Preparing to Publish Your Application
2. Launch Checklist for Google Play
3. The AndroidManifest.xml File
Users need to have specific information about the application version that is installed
on their devices and the upgrade versions available for installation.
Other applications — including other applications that you publish as a suite — need
to query the system for your application's version, to determine compatibility and
identify dependencies.
Services through which you will publish your application(s) may also need to query
your application for its version, so that they can display the version to users. A
publishing service may also need to check the application version to determine
compatibility and establish upgrade/downgrade relationships.
The Android system does not use app version information to enforce restrictions on upgrades,
downgrades, or compatibility of third-party apps. Instead, you (the developer) are responsible
for enforcing version restrictions within your application or by informing users of the version
restrictions and limitations. The Android system does, however, enforce system version
compatibility as expressed by the minSdkVersion attribute in the manifest. This attribute
allows an application to specify the minimum system API with which it is compatible. For
more information see Specifying Minimum System API Version.
To define the version information for your application, you set attributes in the application's
manifest file. Two attributes are available, and you should always define values for both of
them:
android:versionCode — An integer value that represents the version of the
application code, relative to other versions.
The value is an integer so that other applications can programmatically evaluate it, for
example to check an upgrade or downgrade relationship. You can set the value to any
integer you want, however you should make sure that each successive release of your
application uses a greater value. The system does not enforce this behavior, but
increasing the value with successive releases is normative.
Typically, you would release the first version of your application with versionCode
set to 1, then monotonically increase the value with each release, regardless whether
the release constitutes a major or minor release. This means that the
android:versionCode value does not necessarily have a strong resemblance to the
application release version that is visible to the user (see android:versionName,
below). Applications and publishing services should not display this version value to
users.
The value is a string so that you can describe the application version as a
<major>.<minor>.<point> string, or as any other type of absolute or relative version
identifier.
As with android:versionCode, the system does not use this value for any internal
purpose, other than to enable applications to display it to users. Publishing services
may also extract the android:versionName value for display to users.
You define both of these version attributes in the <manifest> element of the manifest file or
the Gradle build file. See Configuring Gradle Builds.
In this example, note that android:versionCode value indicates that the current .apk
contains the second release of the application code, which corresponds to a minor follow-on
release, as shown by the android:versionName string.
The Android framework provides an API to let applications query the system for version
information about your application. To obtain version information, applications use the
getPackageInfo(java.lang.String, int) method of PackageManager.
To specify API Level requirements, add a <uses-sdk> element in the application's manifest,
with one or more of these attributes:
When preparing to install your application, the system checks the value of this attribute and
compares it to the system version. If the android:minSdkVersion value is greater than the
system version, the system aborts the installation of the application. Similarly, the system
installs your application only if its android:maxSdkVersion is compatible with the platform
version.
If you do not specify these attributes in your manifest, the system assumes that your
application is compatible with all platform versions, with no maximum API Level.
To specify a minimum platform version for your application, add a <uses-sdk> element as a
child of <manifest>, then define the android:minSdkVersion as an attribute.
For more information, see the <uses-sdk> manifest element documentation and the API
Levels document. For Gradle build settings, see Configuring Gradle Builds.
See also
1. Versioning Your Applications
2. Preparing to Publish
Android requires that all apps be digitally signed with a certificate before they can be
installed. Android uses this certificate to identify the author of an app, and the certificate does
not need to be signed by a certificate authority. Android apps often use self-signed
certificates. The app developer holds the certificate's private key.
Signing Overview
You can sign an app in debug or release mode. You sign your app in debug mode during
development and in release mode when you are ready to distribute your app. The Android
SDK generates a certificate to sign apps in debug mode. To sign apps in release mode, you
need to generate your own certificate.
In debug mode, you sign your app with a debug certificate generated by the Android SDK
tools. This certificate has a private key with a known password, so you can run and debug
your app without typing the password every time you make a change to your project.
Android Studio signs your app in debug mode automatically when you run or debug your
project from the IDE.
You can run and debug an app signed in debug mode on the emulator and on devices
connected to your development manchine through USB, but you cannot distribute an app
signed in debug mode.
By default, the debug configuration uses a debug keystore, with a known password and a
default key with a known password. The debug keystore is located in
$HOME/.android/debug.keystore, and is created if not present. The debug build type is set to
use this debug SigningConfig automatically.
For more information about how to build and run apps in debug mode, see Building and
Running.
Signing in Release Mode
In release mode, you sign your app with your own certificate:
1. Create a keystore. A keystore is a binary file that contains a set of private keys. You
must keep your keystore in a safe and secure place.
2. Create a private key. A private key represents the entity to be identified with the app,
such as a person or a company.
3. Add the signing configuration to the build file for the app module:
...
android {
...
defaultConfig { ... }
signingConfigs {
release {
storeFile file("myreleasekey.keystore")
storePassword "password"
keyAlias "MyReleaseKey"
keyPassword "password"
}
}
buildTypes {
release {
...
signingConfig signingConfigs.release
}
}
}
...
Note: Including the passwords for your release key and keystore inside the build file is not a
good security practice. Alternatively, you can configure the build file to obtain these
passwords from environment variables or have the build process prompt you for these
passwords.
storePassword System.getenv("KSTOREPWD")
keyPassword System.getenv("KEYPWD")
To have the build process prompt you for these passwords if you are invoking the build from
the command line:
After you complete this process, you can distribute your app and publish it on Google Play.
Warning: Keep your keystore and private key in a safe and secure place, and ensure that you
have secure backups of them. If you publish an app to Google Play and then lose the key with
which you signed your app, you will not be able to publish any updates to your app, since you
must always sign all versions of your app with the same key.
The rest of this document provides detailed instructions about how to generate a private key
and sign your apps in release mode with Android Studio.
When publishing Android Wear apps, you package the wearable app inside of a handheld
app, because users cannot browse and install apps directly on the wearable. Both apps must
be signed. For more information on packaging and signing Android Wear apps, see
Packaging Wearable Apps.
To sign your app in release mode in Android Studio, follow these steps:
3. On the New Key Store window, provide the required information as shown in figure 1.
Your key should be valid for at least 25 years, so you can sign app updates with the
same key through the lifespan of your app.
Figure 1. Create a new keystore in Android Studio.
4. On the Generate Signed APK Wizard window, select a keystore, a private key, and
enter the passwords for both. Then click Next.
5. On the next window, select a destination for the signed APK and click Finish.
Figure 3. Generate a signed APK in Android Studio.
In Android Studio, you can configure your project to sign your release APK automatically
during the build process:
1. On the project browser, right click on your app and select Open Module Settings.
2. On the Project Structure window, select your app's module under Modules.
3. Click on the Signing tab.
4. Select your keystore file, enter a name for this signing configuration (as you may
create more than one), and enter the required information.
8. Click OK.
You can also specify your signing settings in Gradle configuration files. For more
information, see Configuring Gradle Builds.
Signing Considerations
You should sign all of your apps with the same certificate throughout the expected lifespan of
your applications. There are several reasons why you should do so:
App upgrade: When the system is installing an update to an app, it compares the
certificate(s) in the new version with those in the existing version. The system allows
the update if the certificates match. If you sign the new version with a different
certificate, you must assign a different package name to the application—in this case,
the user installs the new version as a completely new application.
App modularity: Android allows apps signed by the same certificate to run in the
same process, if the applications so requests, so that the system treats them as a single
application. In this way you can deploy your app in modules, and users can update
each of the modules independently.
Code/data sharing through permissions: Android provides signature-based
permissions enforcement, so that an app can expose functionality to another app that
is signed with a specified certificate. By signing multiple apps with the same
certificate and using signature-based permissions checks, your apps can share code
and data in a secure manner.
If you plan to support upgrades for an app, ensure that your key has a validity period that
exceeds the expected lifespan of that app. A validity period of 25 years or more is
recommended. When your key's validity period expires, users will no longer be able to
seamlessly upgrade to new versions of your application.
If you plan to publish your apps on Google Play, the key you use to sign these apps must
have a validity period ending after 22 October 2033. Google Play enforces this requirement
to ensure that users can seamlessly upgrade apps when new versions are available.
Maintaining the security of your private key is of critical importance, both to you and to the
user. If you allow someone to use your key, or if you leave your keystore and passwords in an
unsecured location such that a third-party could find and use them, your authoring identity
and the trust of the user are compromised.
If a third party should manage to take your key without your knowledge or permission, that
person could sign and distribute apps that maliciously replace your authentic apps or corrupt
them. Such a person could also sign and distribute apps under your identity that attack other
apps or the system itself, or corrupt or steal user data.
Your private key is required for signing all future versions of your app. If you lose or
misplace your key, you will not be able to publish updates to your existing appn. You cannot
regenerate a previously generated key.
Your reputation as a developer entity depends on your securing your private key properly, at
all times, until the key is expired. Here are some tips for keeping your key secure:
In general, if you follow common-sense precautions when generating, using, and storing your
key, it will remain secure.
The self-signed certificate used to sign your application in debug mode has an expiration date
of 365 days from its creation date. When the certificate expires, you will get a build error.
To fix this problem, simply delete the debug.keystore file. The default storage location is in
~/.android/ on OS X and Linux, in C:\Documents and Settings\<user>\.android\ on
Windows XP, and in C:\Users\<user>\.android\ on Windows Vista and Windows 7.
The next time you build, the build tools will regenerate a new keystore and debug key.
Note that, if your development machine is using a non-Gregorian locale, the build tools may
erroneously generate an already-expired debug certificate, so that you get an error when
trying to compile your application. For workaround information, see the troubleshooting
topic I can't compile my app because the build tools generated an expired debug certificate.
You do not need Android Studio to sign your app. You can sign your app from the command
line using standard tools from the Android SDK and the JDK. To sign an app in release mode
from the command line:
This example prompts you for passwords for the keystore and key, and to provide the
Distinguished Name fields for your key. It then generates the keystore as a file called
my-release-key.keystore. The keystore contains a single key, valid for 10000
days. The alias is a name that you will use later when signing your app.
This example prompts you for passwords for the keystore and key. It then modifies
the APK in-place to sign it. Note that you can sign an APK multiple times with
different keys.
zipalign ensures that all uncompressed data starts with a particular byte alignment
relative to the start of the file, which reduces the amount of RAM consumed by an
app.
Debugging Tools
adb
Android Debug Bridge (adb) is a versatile command line tool that lets you
communicate with an emulator instance or connected Android-powered device. It also
provides access to the device shell for advanced command-line operations.
uiautomator
The uiautomator testing framework lets you test your user interface (UI) efficiently
by creating automated functional UI testcases that can be run against your app on one
or more devices.
Dalvik Debug Monitor Server (ddms)
Lets you debug Android applications.
Device Monitor
Android Device Monitor is a stand-alone tool that provides a graphical user interface
for several Android application debugging and analysis tools.
dmtracedump
Generates graphical call-stack diagrams from trace log files. The tool uses the
Graphviz Dot utility to create the graphical output, so you need to install Graphviz
before running dmtracedump. For more information on using dmtracedump, see
Profiling with Traceview and dmtracedump
hprof-conv
Converts the HPROF file that is generated by the Android SDK tools to a standard
format so you can view the file in a profiling tool of your choice.
Monkey
Runs on your emulator or device and generates pseudo-random streams of user events
such as clicks, touches, or gestures, as well as a number of system-level events. You
can use the Monkey to stress-test applications that you are developing, in a random
yet repeatable manner.
MonkeyDevice
MonkeyImage
MonkeyRunner
monkeyrunner
Provides an API for writing programs that control an Android device or emulator
from outside of Android code.
Systrace
Lets you analyze the execution of your application in the context of system processes,
to help diagnose display and performance issues.
traceview
Provides a graphical viewer for execution logs saved by your application.
Systrace
Lets you analyze the execution of your application in the context of system processes,
to help diagnose display and performance issues.
Build Tools
JOBB
Allows you to build encrypted and unencrypted APK expansion files in Opaque
Binary Blob (OBB) format.
APK expansion files
ProGuard
Shrinks, optimizes, and obfuscates your code by removing unused code and renaming
classes, fields, and methods with semantically obscure names.
zipalign
Optimizes .apk files by ensuring that all uncompressed data starts with a particular
alignment relative to the start of the file. This should always be used to align .apk files
after they have been signed.
Image Tools
Draw 9-patch
Allows you to easily create a NinePatch graphic using a WYSIWYG editor. It also
previews stretched versions of the image, and highlights the area in which content is
allowed.
etc1tool
A command line utility that lets you encode PNG images to the ETC1 compression
standard and decode ETC1 compressed images back to PNG.
Tracer for OpenGL ES
Allows you to capture OpenGL ES commands and frame by frame images to help you
understand how your graphics commands are being executed.
Platform Tools
The platform tools are typically updated every time you install a new SDK platform. Each
update of the platform tools is backward compatible with older platforms. Usually, you
directly use only one of the platform tools—the Android Debug Bridge (adb). Android
Debug Bridge is a versatile tool that lets you manage the state of an emulator instance or
Android-powered device. You can also use it to install an Android application (.apk) file on a
device.
The other platform tools, such as aidl, aapt, dexdump, and dx, are typically called by the
Android build tools or Android Development Tools (ADT), so you rarely need to invoke
these tools directly. As a general rule, you should rely on the build tools or the ADT plugin to
call them as needed.
Note: The Android SDK provides additional shell tools that can be accessed through adb,
such as bmgr and logcat.
bmgr
A shell tool you can use to interact with the Backup Manager on Android devices
supporting API Level 8 or greater.
logcat
Provides a mechanism for collecting and viewing system debug output.
Android Debug Bridge (adb) is a versatile command line tool that lets you communicate with
an emulator instance or connected Android-powered device. It is a client-server program that
includes three components:
A client, which runs on your development machine. You can invoke a client from a shell by
issuing an adb command. Other Android tools such as the ADT plugin and DDMS also create
adb clients.
A server, which runs as a background process on your development machine. The server
manages communication between the client and the adb daemon running on an emulator or
device.
A daemon, which runs as a background process on each emulator or device instance.
When you start an adb client, the client first checks whether there is an adb server process
already running. If there isn't, it starts the server process. When the server starts, it binds to
local TCP port 5037 and listens for commands sent from adb clients—all adb clients use port
5037 to communicate with the adb server.
The server then sets up connections to all running emulator/device instances. It locates
emulator/device instances by scanning odd-numbered ports in the range 5555 to 5585, the
range used by emulators/devices. Where the server finds an adb daemon, it sets up a
connection to that port. Note that each emulator/device instance acquires a pair of sequential
ports — an even-numbered port for console connections and an odd-numbered port for adb
connections. For example:
As shown, the emulator instance connected to adb on port 5555 is the same as the instance
whose console listens on port 5554.
Once the server has set up connections to all emulator instances, you can use adb commands
to access those instances. Because the server manages connections to emulator/device
instances and handles commands from multiple adb clients, you can control any
emulator/device instance from any client (or from a script).
In order to use adb with a device connected over USB, you must enable USB debugging in
the device system settings, under Developer options.
On Android 4.2 and higher, the Developer options screen is hidden by default. To make it
visible, go to Settings > About phone and tap Build number seven times. Return to the
previous screen to find Developer options at the bottom.
On some devices, the Developer options screen may be located or named differently.
Note: When you connect a device running Android 4.2.2 or higher to your computer, the
system shows a dialog asking whether to accept an RSA key that allows debugging through
this computer. This security mechanism protects user devices because it ensures that USB
debugging and other adb commands cannot be executed unless you're able to unlock the
device and acknowledge the dialog. This requires that you have adb version 1.0.31 (available
with SDK Platform-tools r16.0.1 and higher) in order to debug on a device running Android
4.2.2 or higher.
For more information about connecting to a device over USB, read Using Hardware Devices.
Syntax
You can issue adb commands from a command line on your development machine or from a
script. The usage is:
If there's only one emulator running or only one device connected, the adb command is sent
to that device by default. If multiple emulators are running and/or multiple devices are
attached, you need to use the -d, -e, or -s option to specify the target device to which the
command should be directed.
Commands
The table below lists all of the supported adb commands and explains their meaning and
usage.
Returns an error if
Direct an adb command to
more than one
-e the only running emulator
emulator instance is
Target Device instance.
running.
Prints dumpsys,
dumpstate, and logcat
bugreport
data to the screen, for the
Debug purposes of bug reporting.
Pushes an Android
install <path-to- application (specified as a
Data
apk> full path to an .apk file) to
an emulator/device.
Forwards socket
tcp:<portnu
connections from a m>
forward <local> <r specified local port to a local:<UNIX
emote> specified remote port on domain
socket
the emulator/device name>
instance. dev:<charac
ter device
name>
jdwp:<pid>
adb wait-for-
device shell
getprop
Note that this
command does not
Scripting cause adb to wait until
the entire system is
Blocks execution until the fully booted. For that
device is online — that is, reason, you should not
wait-for-device
until the instance state is prepend it to other
device. commands that require
a fully booted system.
As an example, the
install requires the
Android package
manager, which is
available only after the
system is fully booted.
A command such as
adb wait-for-
device install
<app>.apk
would issue the
install command as
soon as the emulator or
device instance
connected to the adb
server, but before the
Android system was
fully booted, so it
would result in an
error.
Before issuing adb commands, it is helpful to know what emulator/device instances are
connected to the adb server. You can generate a list of attached emulators/devices using the
devices command:
adb devices
[serialNumber] [state]
Here's an example showing the devices command and its output:
adb devices
List of devices attached
emulator-5554 device
emulator-5556 device
emulator-5558 device
If multiple emulator/device instances are running, you must specify a target instance when
issuing adb commands. To do so, use the -s option in the commands. The usage for the -s
option is:
As shown, you specify the target instance for a command using its adb-assigned serial
number. You can use the devices command to obtain the serial numbers of running
emulator/device instances. For example:
Note that, if you issue a command without specifying a target emulator/device instance while
multiple devices are available, adb generates an error.
If you have multiple devices available (hardware or emulated), but only one is an emulator,
simply use the -e option to send commands to the emulator. Likewise if there's multiple
devices but only one hardware device attached, use the -d option to send commands to the
hardware device.
Installing an Application
You can use adb to copy an application from your development computer and install it on an
emulator/device instance. To do so, use the install command. With the command, you must
specify the path to the .apk file that you want to install:
For more information about how to create an .apk file that you can install on an
emulator/device instance, see Building and Running
Note that, if you are using the Eclipse IDE and have the ADT plugin installed, you do not
need to use adb (or aapt) directly to install your application on the emulator/device. Instead,
the ADT plugin handles the packaging and installation of the application for you.
Forwarding Ports
You can use the forward command to set up arbitrary port forwarding — forwarding of
requests on a specific host port to a different port on an emulator/device instance. Here's how
you would set up forwarding of host port 6100 to emulator/device port 7100:
You can also use adb to set up forwarding to named abstract UNIX domain sockets, as
illustrated here:
You can use the adb commands pull and push to copy files to and from an emulator/device
instance. Unlike the install command, which only copies an APK file to a specific location,
the pull and push commands let you copy arbitrary directories and files to any location in an
emulator/device instance.
To copy a file or directory (and its sub-directories) from the emulator or device, use
To copy a file or directory (and its sub-directories) to the emulator or device, use
In the commands, <local> and <remote> refer to the paths to the target files/directory on
your development machine (local) and on the emulator/device instance (remote). For
example:
Adb provides a Unix shell that you can use to run a variety of commands on an emulator or
connected device. The command binaries are stored in the file system of the emulator or
device, at /system/bin/...
Two of the most common command tools are activity manager (am) and package manager
(pm).
You can use the shell command to issue commands, with or without entering the adb remote
shell on the emulator/device. To issue a single command without entering a remote shell, use
the shell command like this:
adb [-d|-e|-s <serialNumber>] shell <shell_command>
When you are ready to exit the remote shell, press CTRL+D or type exit.
Within an adb shell, you can issue commands with the activity manager (am) tool to perform
various system actions, such as start an activity, force-stop a process, broadcast an intent,
modify the device screen properties, and more. While in a shell, the syntax is:
am <command>
You can also issue an activity manager command directly from adb without entering a remote
shell. For example:
Command Description
Options are:
Options are:
Options are:
instrument [options] <COMPONENT> -r: Print raw results (otherwise decode
<REPORT_KEY_STREAMRESULT>). Use with
[-e perf true] to generate raw output
for performance measurements.
-e <NAME> <VALUE>: Set argument
<NAME> to <VALUE>. For test runners a
common form is -e <testrunner_flag>
<value>[,<value>...].
-p <FILE>: Write profiling data to <FILE>.
-w: Wait for instrumentation to finish before
returning. Required for test runners.
--no-window-animation: Turn off
window animations while running.
--user <USER_ID> | current: Specify
which user instrumentation runs in; current
user if not specified.
Options are:
Options are:
set-debug-app [options] <PACKAGE>
-w: Wait for debugger when application
starts.
--persistent: Retain this value.
monitor [options]
Options are:
Example:
am display-size 1280x800
Override emulator/device display density. This
command is helpful for testing your app across
different screen densities on high-density screen
display-density <dpi> environment using a low density screen, and vice
versa.
Example:
am display-density 480
Print the given intent specification as a URI.
to-uri <INTENT>
Within an adb shell, you can issue commands with the package manager (pm) tool to perform
actions and queries on application packages installed on the device. While in a shell, the
syntax is:
pm <command>
You can also issue a package manager command directly from adb without entering a remote
shell. For example:
Command Description
Options:
Options:
list instrumentation
-f: List the APK file for the test
package.
<TARGET_PACKAGE>: List test
packages for only this app.
Options:
Options:
uninstall [options] <PACKAGE>
-k: Keep the data and cache
directories around after
package removal.
Options:
disable-user [options] <PACKAGE_OR_COMPONENT>
--user <USER_ID>: The user
to disable.
grant <PACKAGE_PERMISSION>
Grant permissions to applications. Only
optional permissions the application
has declared can be granted.
get-max-users
Prints the maximum number of users
supported by the device.
From an adb remote shell, you can use the sqlite3 command-line program to manage SQLite
databases created by Android applications. The sqlite3 tool includes many useful
commands, such as .dump to print out the contents of a table and .schema to print the SQL
CREATE statement for an existing table. The tool also gives you the ability to execute
SQLite commands on the fly.
To use sqlite3, enter a remote shell on the emulator instance, as described above, then
invoke the tool using the sqlite3 command. Optionally, when invoking sqlite3 you can
specify the full path to the database you want to explore. Emulator/device instances store
SQLite3 databases in the folder /data/data/<package_name>/databases/.
Here's an example:
Once you've invoked sqlite3, you can issue sqlite3 commands in the shell. To exit and
return to the adb remote shell, use exit or CTRL+D.
The screenrecord command is a shell utility for recording the display of devices running
Android 4.4 (API level 19) and higher. The utility records screen activity to an MPEG-4 file,
which you can then download and use as part of a video presentation. This utility is useful for
developers who want to create promotional or training videos without using a separate
recording device.
To use the screenrecord from the command line, type the following:
Stop the screen recording by pressing Ctrl-C, otherwise the recording stops automatically at
three minutes or the time limit set by --time-limit.
Here's an example recording session, using the adb shell to record the video and the pull
command to download the file from the device:
$ adb shell
shell@ $ screenrecord --verbose /sdcard/demo.mp4
(press Ctrl-C to stop)
shell@ $ exit
$ adb pull /sdcard/demo.mp4
The screenrecord utility can record at any supported resolution and bit rate you request,
while retaining the aspect ratio of the device display. The utility records at the native display
resolution and orientation by default, with a maximum length of three minutes.
There are some known limitations of the screenrecord utility that you should be aware of
when using it:
Some devices may not be able to record at their native display resolution. If you encounter
problems with screen recording, try using a lower screen resolution.
Rotation of the screen during recording is not supported. If the screen does rotate during
recording, some of the screen is cut off in the recording.
Audio is not recorded with the video file.
Options Description
Sets the video size, for example: 1280x720. The default value is the
device's main display resolution (if supported), 1280x720 if not. For
--size <WIDTHxHEIGHT>
best results, use a size supported by your device's Advanced Video
Coding (AVC) encoder.
Sets the video bit rate for the video, in megabits per second. The
default value is 4Mbps. You can increase the bit rate to improve video
--bit-rate <RATE> quality or lower it for smaller movie files. The following example sets
the recording bit rate to 6Mbps:
Displays log information on command line screen. If you do not set this
--verbose
option, the utility does not display any information while running.
The Monkey is a program that runs on your emulator or device and generates pseudo-random
streams of user events such as clicks, touches, or gestures, as well as a number of system-
level events. You can use the Monkey to stress-test applications that you are developing, in a
random yet repeatable manner.
The simplest way to use the monkey is with the following command, which launches your
application and sends 500 pseudo-random events to it.
adb shell monkey -v -p your.package.name 500
For more information about command options for Monkey, see the complete UI/Application
Exerciser Monkey documentation page.
For a list of all the available shell programs, use the following command:
Starts (restarts) an
start
emulator/device instance.
Stops execution of an
stop
emulator/device instance.
The Android logging system provides a mechanism for collecting and viewing system debug
output. Logs from various applications and portions of the system are collected in a series of
circular buffers, which then can be viewed and filtered by the logcat command.
You can use the logcat command to view and follow the contents of the system's log
buffers. The general usage is:
You can use the logcat command from your development computer or from a remote adb
shell in an emulator/device instance. To view log output in your development computer, you
use
adb logcat
logcat
See Reading and Writing Logs for complete information about logcat commend options and
filter specifications.
In some cases, you might need to terminate the adb server process and then restart it. For
example, if adb does not respond to a command, you can terminate the server and restart it
and that may resolve the problem.
To stop the adb server, use the kill-server command. You can then restart the server by
issuing any other adb command.
Wireless usage
adb is usually used over USB. However, it is also possible to use over Wi-Fi, as described
here.
1. Connect Android device and adb host computer to a common Wi-Fi network accessible to
both. We have found that not all access points are suitable; you may need to use an access
point whose firewall is configured properly to support adb.
2. Connect the device with USB cable to host.
3. Make sure adb is running in USB mode on host.
$ adb usb
restarting in USB mode
$ adb devices
List of devices attached
######## device
6. Find out the IP address of the Android device: Settings -> About tablet -> Status -> IP
address. Remember the IP address, of the form #.#.#.#.
7. Connect adb host to device:
8. Remove USB cable from device, and confirm you can still access device:
$ adb devices
List of devices attached
#.#.#.#:5555 device
1. Make sure that your host is still connected to the same Wi-Fi network your Android device
is.
2. Reconnect by executing the "adb connect" step again.
3. Or if that doesn't work, reset your adb host:
adb kill-server
android
android is an important development tool that lets you:
Create, delete, and view Android Virtual Devices (AVDs). See Managing AVDs from
the Command Line.
Create and update Android projects. See Managing Projects from the Command Line.
Update your Android SDK with new platforms, add-ons, and documentation. See
Exploring the SDK.
If you are using Eclipse, the android tool's features are integrated into ADT, so you should
not need to use this tool directly.
Note: The documentation of options below is not exhaustive and may be out of date. For the
most current list of options, execute android --help.
Syntax
android [global options] action [action options]
Global Options
-s
Silent mode: only errors are printed out
-h
Usage help
-v
Verbose mode: errors, warnings and informational messages are printed.
-a
Name for the default
Required
Activity class
-p <path>
Location of your project
Required
directory
-n <name>
The name of the project
to update
-p <path>
Location path of the
Required
project
Location path of an
-l <library path>
Android Library to add,
update
project relative to the main
project
Update any projects in
-s <subprojects> subfolders such as test
projects
-t <targetID>
Target id to set for the
project
-n <name> The name of the project
create
test- -p <path>
Location path of the
Required
project project
-m <main> The name of the project Required
update Location path of the
test- -p <path> project to test, relative to Required
project the new project
-m <main>
The main class of the
Required
project to test
-k <packageName>
(Required) Package name
Required
of the library project
create -p <path>
Location path of the
Required
lib- project
project Target ID of the library
-t <targetID> Required
project
-n <name> The name of the project Required
-p <path>
Location path of the
Required
project
Location path of an
update
lib- -l <libraryPath>
Android Library to add,
project relative to the main
project
-t <name>
Target ID of the library
project
-n <name>
The name of the UI test
project
create
uitest- -t <name>
Target ID of the UI test
Required
project project
-p <path>
Location path of the UI
Required
test project
Update actions
update adb
Updates adb to support the USB devices declared in the SDK add-ons.
update sdk
Updates the SDK by suggesting new platforms to install if available.
AVD Manager
The AVD Manager provides a graphical user interface in which you can create and manage
Android Virtual Devices (AVDs), which are required by the Android Emulator.
You can launch the AVD Manager in one of the following ways:
In Eclipse: select Window > Android Virtual Device Manager, or click the AVD
Manager icon in the toolbar.
In Android Studio: select Tools > Android > AVD Manager, or click the AVD
Manager icon in the toolbar.
In other IDEs: Navigate to your SDK's tools/ directory and execute android avd.
See also
1. Data Backup
bmgr is a shell tool you can use to interact with the Backup Manager on Android devices
supporting API Level 8 or greater. It provides commands to induce backup and restore
operations so that you don't need to repeatedly wipe data or take similar intrusive steps in
order to test your application's backup agent. These commands are accessed via the adb shell.
For information about adding support for backup in your application, read Data Backup,
which includes a guide to testing your application using bmgr.
Normally, your application must notify the Backup Manager when its data has changed, via
dataChanged(). The Backup Manager will then invoke your backup agent's onBackup()
implementation at some time in the future. However, instead of calling dataChanged(), you
can invoke a backup request from the command line by running the bmgr backup command:
<package> is the formal package name of the application you wish to schedule for backup.
When you execute this backup command, your application's backup agent will be invoked to
perform a backup operation at some time in the future (via your onBackup() method), though
there is no guarantee when it will occur. However, you can force all pending backup
operations to run immediately by using the bmgr run command:
This causes a backup pass to execute immediately, invoking the backup agents of all
applications that had previously called dataChanged() since the last backup operation, plus
any applications which had been manually scheduled for backup via bmgr backup.
Unlike backup operations, which are batched together and run on an occasional basis, restore
operations execute immediately. The Backup Manager currently provides two kinds of
restore operations. The first kind restores an entire device with the data that has been backed
up. This is typically performed only when a device is first provisioned (to replicate settings
and other saved state from the user's previous device) and is an operation that only the system
can perform. The second kind of restore operation restores a single application to its "active"
data set; that is, the application will abandon its current data and revert to the last-known-
good data that is held in the current backup image. You can invoke this second restore
operation with the requestRestore() method. The Backup Manager will then invoke your
backup agent's onRestore() implementation.
While testing your application, you can immediately invoke the restore operation (bypassing
the requestRestore() method) for your application by using the bmgr restore command:
<package> is the formal Java-style package name of the application participating in the
backup/restore mechanism, which you would like to restore. The Backup Manager will
immediately instantiate the application's backup agent and invoke it for restore. This will
happen even if your application is not currently running.
Other Commands
Wiping data
The data for a single application can be erased from the active data set on demand. This is
very useful while you're developing a backup agent, in case bugs lead you to write corrupt
data or saved state information. You can wipe an application's data with the bmgr wipe
command:
<package> is the formal package name of the application whose data you wish to erase. The
next backup operation that the application's agent processes will look as though the
application had never backed anything up before.
You can see whether the Backup Manager is operational at all with the bmgr enabled
command:
This might be useful if your application's backup agent is never being invoked for backup, to
verify whether the operating system thinks it should be performing such operations at all.
You can also directly disable or enable the Backup Manager with this command:
Warning! When backup is disabled, the current backup transport will explicitly wipe the
entire active data set from its backend storage. This is so that when a user says they do not
want their data backed up, the Backup Manager respects that wish. No further data will be
saved from the device, and no restore operations will be possible, unless the Backup Manager
is re-enabled (either through Settings or through the above bmgr command).
Device Monitor
See also
1. Investigating Your RAM Usage
Android Device Monitor is a stand-alone tool that provides a graphical user interface for
several Android application debugging and analysis tools. The Monitor tool does not require
installation of an integrated development environment, such as Eclipse, and encapsulates the
following tools:
DDMS
Tracer for OpenGL ES
Hierarchy Viewer
Systrace
Traceview
Pixel Perfect magnification viewer
Usage
To start Device Monitor, enter the following command from the SDK tools/ directory:
monitor
Start an Android emulator or connect an Android device via USB cable, and connect Device
Monitor to the device by selecting it in the Devices window.
Note: Only one debugger can be connected to your device at a time. If you're using ADT,
you may need to close the debugging tool before launching the Device Monitor in order for
the device to be fully debuggable.
dmtracedump
dmtracedump is a tool that gives you an alternate way of generating graphical call-stack
diagrams from trace log files (instead of using Traceview).
This document is a reference to the available command line options. For more information on
generating trace logs, see Profiling with Traceview and dmtracedump.
The tool then loads trace log data from <trace-base-name>.data and <trace-base-
name>.key. The table below lists the options for dmtracedump.
Option Description
-d <trace-
Diff with this trace name
base-name>
-d <trace-
URL base to the location of the sortable javascript file
base-name>
Minimum threshold for including child nodes in the graph (child's inclusive time
-t <percent> as a percentage of parent inclusive time). If this option is not used, the default
threshold is 20%.
Draw 9-patch
The Draw 9-patch tool allows you to easily create a NinePatch graphic using a WYSIWYG
editor.
For an introduction to Nine-patch graphics and how they work, please read the section about
Nine-patch in the 2D Graphics document.
Here's a quick guide to create a Nine-patch graphic using the Draw 9-patch tool. You'll need
the PNG image with which you'd like to create a NinePatch.
1. From a terminal, launch the draw9patch application from your SDK /tools
directory.
2. Drag your PNG image into the Draw 9-patch window (or File > Open 9-patch... to
locate the file). Your workspace will now open.
The left pane is your drawing area, in which you can edit the lines for the stretchable
patches and content area. The right pane is the preview area, where you can preview
your graphic when stretched.
3. Click within the 1-pixel perimeter to draw the lines that define the stretchable patches
and (optional) content area. Right-click (or hold Shift and click, on Mac) to erase
previously drawn lines.
4. When done, select File > Save 9-patch...
Note: A normal PNG file (*.png) will be loaded with an empty one-pixel border added
around the image, in which you can draw the stretchable patches and content area. A
previously saved 9-patch file (*.9.png) will be loaded as-is, with no drawing area added,
because it already exists.
Optional controls include:
Zoom: Adjust the zoom level of the graphic in the drawing area.
Patch scale: Adjust the scale of the images in the preview area.
Show lock: Visualize the non-drawable area of the graphic on mouse-over.
Show patches: Preview the stretchable patches in the drawing area (pink is a
stretchable patch).
Show content: Highlight the content area in the preview images (purple is the area in
which content is allowed).
Show bad patches: Adds a red border around patch areas that may produce artifacts
in the graphic when stretched. Visual coherence of your stretched image will be
maintained if you eliminate all bad patches.
Android Emulator
In this document
1. Keyboard Commands
2. Command Line Parameters
See also
1. Using the Android Emulator
2. Managing Virtual Devices
The Android SDK includes a mobile device emulator — a virtual mobile device that runs on
your computer. The emulator lets you develop and test Android applications without using a
physical device.
This document is a reference to the available command line options and the keyboard
mapping to device keys. For a complete guide to using the Android Emulator, see Using the
Android Emulator.
Keyboard Commands
Table 1 summarizes the mappings between the emulator keys and the keys of your keyboard.
The emulator supports a variety of options that you can specify when launching the emulator,
to control its appearance or behavior. Here's the command-line syntax of the options
available to the emulator program:
emulator -avd <avd_name> [-<option> [<value>]] ... [-<qemu args>]
-ramdisk <filepath>
Use <filepath> as
Optionally, you can specify a path
the ramdisk image.
relative to the current working
directory. For more information
on disk images, use -help-disk-
Category Option Description Comments
images.
Default value is
<system>/sdcard.img.
-sdcard <filepath>
Use <file> as the SD Optionally, you can specify a path
card image. relative to the current working
directory. For more information
on disk images, use -help-disk-
images.
Reset the current
user-data disk image
(that is, the file
specified by -
datadir and -data,
or the default file). See also -initdata.
-wipe-data
The emulator deletes
all data from the user For more information on disk
data image file, then images, use -help-disk-images.
copies the contents
of the file at -
inidata data to the
image file before
starting.
<tags> is a
Enable/disable space/comma/column-separated
-debug <tags>
debug messages for list of debug component names.
the specified debug Use -help-debug-tags to print a
tags. list of debug component names
that you can use.
Enable/disable
-debug-<tag>
debug messages for
the specified debug Use -help-debug-tags to print a
tag. list of debug component names
Disable debug that you can use in <tag>.
Debug -debug-no-<tag> messages for the
specified debug tag.
If the environment variable
ANDROID_LOG_TAGS is
-logcat <logtags>
Enable logcat output
defined and not empty, its value
with given tags.
will be used to enable logcat
output by default.
You can use this command even
Create a root shell if the adb daemon in the emulated
-shell console on the system is broken. Pressing Ctrl-c
current terminal. from the shell stops the emulator
instead of the shell.
Category Option Description Comments
<device> must be a QEMU
device type. See the
documentation for '-serial dev' at
http://wiki.qemu.org/download/qe
mu-doc.html for a list of device
types.
-shell-serial stdio is
Enable the root shell identical to -shell
(as in -shell and -shell-serial
specify the QEMU tcp::4444,server,nowa
-shell-
character device to it lets you communicate
serial <device>
use for with the shell over TCP
communication with port 4444
the shell. -shell-serial
fdpair:3:6 lets a parent
process communicate with
the shell using fds 3 (in)
and 6 (out)
-shell-serial
fdpair:0:1 uses the
normal stdin and stdout
fds, except that QEMU
won't tty-cook the data.
-show-kernel <name>
Display kernel
messages.
Enable code
-trace <name>
profiling (press F9 to
start), written to a
specified file.
Equivalent to -debug-init.
ANDROID_VERBOSE=init,modem
-audio <backend>
Use the specified
audio backend.
-audio-in <backend>
Use the specified
audio-input backend.
Use the specified
-audio-out
<backend> audio-output
backend.
Disable audio
Media -noaudio
support in the
current emulator
instance.
Redirect radio
-radio <device>
modem interface to a
host character
device.
Enable audio support
-useaudio in the current Enabled by default.
emulator instance.
The value of <servers> must be
-dns-server Use the specified a comma-separated list of up to 4
<servers> DNS server(s). DNS server names or IP
addresses.
The value of <proxy> can be one
of the following:
http://<server>:<port>
http://<username>:<password
>@<server>:<port>
Make all TCP
Network -http-proxy <proxy>
connections through The http:// prefix can be
a specified omitted. If the -http-proxy
HTTP/HTTPS proxy <proxy> command is not
supplied, the emulator looks up
the http_proxy environment
variable and automatically uses
any value matching the <proxy>
format described above.
Set network latency Default value is none. See the
-netdelay <delay> emulation to table in Network Delay Emulation
<delay>. for supported <delay> values.
Category Option Description Comments
Shortcut for -
-netfast netspeed full -
netdelay none
Default value is full. See the
Set network speed
-netspeed <speed>
table in Network Speed
emulation to
Emulation for supported <speed>
<speed>.
values.
The console port number must be
Set the console port
an even integer between 5554 and
number for this
-port <port> 5584, inclusive. <port>+1 must
emulator instance to
also be free and will be reserved
<port>.
for ADB.
<socket> must use one of these
formats:
Report the assigned tcp:<port>[,server][,max=<s
console port for this econds>]
-report-console emulator instance to unix:<port>[,server][,max=<
<socket> a remote third party seconds>]
before starting the
emulation. Use -help-report-console
etc1tool
etc1tool is a command line utility that lets you encode PNG images to the ETC1
compression standard and decode ETC1 compressed images back to PNG.
Create an ETC1 file from a PNG file. This is the default mode for the tool if
--encode
nothing is specified.
--encodeNoHeader Create a raw ETC1 data file (without a header) from a PNG file.
--showDifference Write the difference between the original and encoded image to diff-
diff-file file (only valid when encoding).
Specify the name of the output file. If outfile is not specified, the
-o outfile output file is constructed from the input filename with the appropriate
suffix (.pkm or .png).
Hierarchy Viewer
Hierarchy Viewer allows you to debug and optimize your user interface. It provides a visual
representation of the layout's View hierarchy (the Layout View) and a magnified inspector of
the display (the Pixel Perfect View).
To start Hierarchy Viewer, enter the following command from the SDK tools/ directory:
hierarchyviewer
For more information on how to use Hierarchy Viewer, see Debugging and Profiling UIs
HPROF Converter
The hprof-conv tool converts the HPROF file that is generated by the Android SDK tools to
a standard format so you can view the file in a profiling tool of your choice.
You can use "-" for <infile> or <outfile> to specify stdin or stdout.
JOBB
The jobb tool allows you to build encrypted and unencrypted APK expansion files in Opaque
Binary Blob (OBB) format. You can download and mount these expansion files in your
application using StorageManager on devices with Android 2.3 (API Level 9) or higher.
OBB files are used to provide additional file assets for Android applications (such as
graphics, sounds and video), separate from an application's APK file. For more information
on using expansion files, see APK Expansion Files.
Usage
You can use the jobb tool to create an OBB file or extract the contents of an existing OBB.
The following example command creates an OBB file from source files.
This example shows how to dump (extract) the contents of an existing OBB file:
Options
The table below lists the command line options for the jobb tool.
Option Description
Set the input directory for creating an OBB file, or the output directory when
extracting (-dump) an existing file. When creating an OBB file, the contents of
-d <directory>
the specified directory and all its sub-directories are included in the OBB file
system.
Specify the filename for the OBB file. This parameter is required when creating
-o <filename>
an OBB and extracting (dumping) its contents.
Specify the package name for the application that mounts the OBB file, which
-pn <package> corresponds to the package value specified in your application's manifest.
This parameter is required when creating an OBB file.
Set the minimum version for the application that can mount the OBB file,
-pv <version> which corresponds to the android:versionCode value in your application's
manifest. This parameter is required when creating an OBB file.
Create OBB file that is an overlay of an existing OBB file structure. This option
allows the new package contents to be mounted into the same location as a
-ov previous package and is intended for creating patch versions of previously
generated OBB files. Files within an overlay OBB file replace files that have the
same path.
-dump <filename> Extract the contents of the specified OBB file. When using this option,
you must also specify the output directory for the contents using the -d
<directory> parameter.
Note: When dumping an existing OBB file, you can omit the -d
<directory> parameter to get a listing of the directories inside the file,
without extracting the contents.
-v Set verbose output for the tool.
-about Display version and help information for the jobb tool.
lint
In this document
1. Syntax
2. Options
3. Configuring Java and XML Source Files
The Android lint tool is a static code analysis tool that checks your Android project source
files for potential bugs and optimization improvements for correctness, security,
performance, usability, accessibility, and internationalization.
For more information on running lint, see Improving Your Code with lint.
Syntax
lint [flags] <project directory>
For example, you can issue the following command to scan the Java and XML files under the
myproject directory and its subdirectories. The result is displayed on the console.
lint myproject
You can also use lint to check for a specific issue. For example, you can run the following
command to scan the files under the myproject directory and its subdirectories to check for
XML attributes missing the Android namespace prefix. The issue ID MissingPrefix tells
lint to only scan for this issue.
lint --check MissingPrefix myproject
You can create an HTML report for the issues that lint detects. For example, you can run
the following command to scan the myproject directory and its subdirectories for
accessibility issues, then generate an HTML report in the accessibility_report.html file.
lint --check Accessibility --HTML accessibility_report.html myproject
Options
To configure lint checking, you can apply the following annotation or attribute to the source
files in your Android project.
To disable lint checking for a specific Java class or method, use the @SuppressLint
annotation.
To disable lint checking for specific sections of your XML file, use the
tools:ignore attribute.
You can also specify your lint checking preferences for a specific Android project in the
lint.xml file. For more information on configuring lint, see Improving Your Code with lint.
logcat
The Android logging system provides a mechanism for collecting and viewing system debug
output. Logs from various applications and portions of the system are collected in a series of
circular buffers, which then can be viewed and filtered by the logcat command. You can use
logcat from an ADB shell to view the log messages.
For complete information about logcat options and filtering specifications, see Reading and
Writing Logs.
For more information on accessing logcat from DDMS, instead of the command line, see
Using DDMS.
Syntax
[adb] logcat [<option>] ... [<filter-spec>] ...
You can run logcat as an adb command or directly in a shell prompt of your emulator or
connected device. To view log output using adb, navigate to your SDK platform-tools/
directory and execute:
$ adb logcat
$ adb shell
# logcat
Options
Option Description
Loads an alternate log buffer for viewing, such as events or radio. The main
-b <buffer>
buffer is used by default. See Viewing Alternative Log Buffers.
-
Writes log message output to <filename>. The default is stdout.
f <filename>
Sets the maximum number of rotated logs to <count>. The default value is 4.
-n <count>
Requires the -r option.
Rotates the log file every <kbytes> of output. The default value is 16. Requires
-r <kbytes>
the -f option.
-s Sets the default filter spec to silent.
Sets the output format for log messages. The default is brief format. For a list of
-v <format>
supported formats, see Controlling Log Output Format.
mksdcard
The mksdcard tool lets you quickly create a FAT32 disk image that you can load in the
emulator, to simulate the presence of an SD card in the device. Because you can specify an
SD card while creating an AVD in the AVD Manager, you usually use that feature to create
an SD card. This tool creates an SD card that is not bundled with an AVD, so it is useful for
situations where you need to share a virtual SD card between multiple emulators.
Usage
mksdcard -l <label> <size> <file>
Options
Option Description
An integer that specifies the size (in bytes) of disk image to create. You can also specify size
size in kilobytes or megabytes, by appending a "K" or "M" to <size>. For example, 1048576K,
1024M.
Once you have created the disk image file, you can load it in the emulator at startup using the
emulator's -sdcard option. For more information, see Android Emulator.
Example
mksdcard -l mySdCard 1024M mySdCardFile.img
UI/Application Exerciser Monkey
The Monkey is a program that runs on your emulator or device and generates pseudo-random
streams of user events such as clicks, touches, or gestures, as well as a number of system-
level events. You can use the Monkey to stress-test applications that you are developing, in a
random yet repeatable manner.
Overview
The Monkey is a command-line tool that you can run on any emulator instance or on a
device. It sends a pseudo-random stream of user events into the system, which acts as a stress
test on the application software you are developing.
The Monkey includes a number of options, but they break down into four primary categories:
When the Monkey runs, it generates events and sends them to the system. It also watches the
system under test and looks for three conditions, which it treats specially:
If you have constrained the Monkey to run in one or more specific packages, it
watches for attempts to navigate to any other packages, and blocks them.
If your application crashes or receives any sort of unhandled exception, the Monkey
will stop and report the error.
If your application generates an application not responding error, the Monkey will
stop and report the error.
Depending on the verbosity level you have selected, you will also see reports on the progress
of the Monkey and the events being generated.
You can launch the Monkey using a command line on your development machine or from a
script. Because the Monkey runs in the emulator/device environment, you must launch it
from a shell in that environment. You can do this by prefacing adb shell to each command,
or by entering the shell and entering Monkey commands directly.
The table below lists all options you can include on the Monkey command line.
monkeyrunner
In this document
1. A Simple monkeyrunner Program
2. The monkeyrunner API
3. Running monkeyrunner
4. monkeyrunner Built-in Help
5. Extending monkeyrunner with Plugins
See Also
1. Testing Fundamentals
The monkeyrunner tool provides an API for writing programs that control an Android device
or emulator from outside of Android code. With monkeyrunner, you can write a Python
program that installs an Android application or test package, runs it, sends keystrokes to it,
takes screenshots of its user interface, and stores screenshots on the workstation. The
monkeyrunner tool is primarily designed to test applications and devices at the
functional/framework level and for running unit test suites, but you are free to use it for other
purposes.
The monkeyrunner tool is not related to the UI/Application Exerciser Monkey, also known as
the monkey tool. The monkey tool runs in an adb shell directly on the device or emulator and
generates pseudo-random streams of user and system events. In comparison, the
monkeyrunner tool controls devices and emulators from a workstation by sending specific
commands and events from an API.
The monkeyrunner tool provides these unique features for Android testing:
Multiple device control: The monkeyrunner API can apply one or more test suites
across multiple devices or emulators. You can physically attach all the devices or start
up all the emulators (or both) at once, connect to each one in turn programmatically,
and then run one or more tests. You can also start up an emulator configuration
programmatically, run one or more tests, and then shut down the emulator.
Functional testing: monkeyrunner can run an automated start-to-finish test of an
Android application. You provide input values with keystrokes or touch events, and
view the results as screenshots.
Regression testing - monkeyrunner can test application stability by running an
application and comparing its output screenshots to a set of screenshots that are
known to be correct.
Extensible automation - Since monkeyrunner is an API toolkit, you can develop an
entire system of Python-based modules and programs for controlling Android devices.
Besides using the monkeyrunner API itself, you can use the standard Python os and
subprocess modules to call Android tools such as Android Debug Bridge.
You can also add your own classes to the monkeyrunner API. This is described in
more detail in the section Extending monkeyrunner with plugins.
The monkeyrunner tool uses Jython, a implementation of Python that uses the Java
programming language. Jython allows the monkeyrunner API to interact easily with the
Android framework. With Jython you can use Python syntax to access the constants, classes,
and methods of the API.
# Installs the Android package. Notice that this method returns a boolean,
so you can test
# to see if the installation worked.
device.installPackage('myproject/bin/MyApplication.apk')
In a Python program, you access each class as a Python module. The monkeyrunner tool does
not import these modules automatically. To import a module, use the Python from statement:
where <module> is the class name you want to import. You can import more than one module
in the same from statement by separating the module names with commas.
Running monkeyrunner
You can either run monkeyrunner programs from a file, or enter monkeyrunner statements in
an interactive session. You do both by invoking the monkeyrunner command which is found
in the tools/ subdirectory of your SDK directory. If you provide a filename as an argument,
the monkeyrunner command runs the file's contents as a Python program; otherwise, it starts
an interactive session.
Argument Description
(Optional) Specifies a .jar file containing a plugin for
-plugin monkeyrunner. To learn more about monkeyrunner plugins, see
<plugin_jar> Extending monkeyrunner with plugins. To specify more than one file,
include the argument multiple times.
If you provide this argument, the monkeyrunner command runs the
<program_filename> contents of the file as a Python program. If the argument is not
provided, the command starts an interactive session.
<program_options> (Optional) Flags and arguments for the program in <program_file>.
<format> is either text for plain text output or html for HTML output.
<outfile> is a path-qualified name for the output file.
You can extend the monkeyrunner API with classes you write in the Java programming
language and build into one or more .jar files. You can use this feature to extend the
monkeyrunner API with your own classes or to extend the existing classes. You can also use
this feature to initialize the monkeyrunner environment.
To provide a plugin to monkeyrunner, invoke the monkeyrunner command with the -plugin
<plugin_jar> argument described in table 1.
In your plugin code, you can import and extend the the main monkeyrunner classes
MonkeyDevice, MonkeyImage, and MonkeyRunner in com.android.monkeyrunner (see The
monkeyrunner API).
Note that plugins do not give you access to the Android SDK. You can't import packages
such as com.android.app. This is because monkeyrunner interacts with the device or
emulator below the level of the framework APIs.
The .jar file for a plugin can specify a class that is instantiated before script processing
starts. To specify this class, add the key MonkeyRunnerStartupRunner to the .jar file's
manifest. The value should be the name of the class to run at startup. The following snippet
shows how you would do this within an ant build script:
<jar jarfile="myplugin" basedir="${build.dir}">
<manifest>
<attribute name="MonkeyRunnerStartupRunner" value="com.myapp.myplugin"/>
</manifest>
</jar>
To get access to monkeyrunner's runtime environment, the startup class can implement
com.google.common.base.Predicate<PythonInterpreter>. For example, this class sets
up some variables in the default namespace:
package com.android.example;
import com.google.common.base.Predicate;
import org.python.util.PythonInterpreter;
/*
* Examples of creating and initializing variables in the
monkeyrunner environment's
* namespace. During execution, the monkeyrunner program can refer
to the variables "newtest"
* and "use_emulator"
*
*/
anInterpreter.set("newtest", "enabled");
anInterpreter.set("use_emulator", 1);
return true;
}
}
Except as noted, this content is licensed under Creative Commons Attribution 2.5. For details
and restrictions, see the Content License.
MonkeyDevice
A monkeyrunner class that represents a device or emulator accessible by the workstation
running monkeyrunner.
This class is used to control an Android device or emulator. The methods send UI events,
retrieve information, install and remove applications, and run applications.
You normally do not have to create an instance of MonkeyDevice. Instead, you use
MonkeyRunner.waitForConnection() to create a new object from a connection to a device
or emulator. For example, instead of using:
newdevice = MonkeyDevice()
Summary
Constants
Methods
object Given the name of a system environment variable, returns its value for this
device. The available variable names are listed in the detailed description of
this method.
void Installs the Android application or test package contained in packageFile onto
this device. If the application or test package is already installed, it is
replaced.
startActivity (string uri, string action, string data, string mimetype, iterable
categories dictionary extras, component component, flags)
void
Starts an Activity on this device by sending an Intent constructed from the
supplied arguments.
takeSnapshot()
MonkeyImage
Captures the entire screen buffer of this device, yielding a MonkeyImage
object containing a screen capture of the current display.
void Sends the characters contained in message to this device, as if they had been
typed on the device's keyboard. This is equivalent to calling press() for each
keycode in message using the key event type DOWN_AND_UP.
wake ()
void
Wakes the screen of this device.
Constants
string DOWN
press() or touch() value. Specifies that a DOWN event type should be sent to the device,
corresponding to pressing down on a key or touching the screen.
string UP
press() or touch() value. Specifies that an UP event type should be sent to the device,
corresponding to releasing a key or lifting up from the screen.
string DOWN_AND_UP
press(), touch() or type() value. Specifies that a DOWN event type followed by an UP
event type should be sent to the device, corresponding to typing a key or clicking the screen.
Public Methods
void broadcastIntent ( string uri, string action, string data, string mimetype, iterable
categories dictionary extras, component component, iterable flags)
Broadcasts an Intent to this device, as if the Intent were coming from an application. See
Intent for more information about the arguments.
Arguments
uri The URI for the Intent. (see Intent.setData()).
An iterable data structure containing strings that define categories for this Intent (see
categories
Intent.addCategory()).
A dictionary of extra data for this Intent (see Intent.putExtra() for an example).
extras
The key for each dictionary item should be a string. The item's value can be any
simple or structured data type.
The component for this Intent (see ComponentName). Using this argument will direct
component
the Intent to a specific class within a specific Android package.
An iterable data structure containing flags that control how the Intent is handled (see
flags
Intent.setFlags()).
void drag ( tuple start, tuple end, float duration, integer steps)
Simulates a drag gesture (touch, hold, and move) on this device's screen.
Arguments
The starting point of the drag gesture, in the form of a tuple (x,y) where x and y are
start
integers.
end The end point of the drag gesture, in the form of a tuple (x,y) where x and y are integers.
duration The duration of the drag gesture in seconds. The default is 1.0 seconds.
steps The number of steps to take when interpolating points. The default is 10.
Given the name of a system environment variable, returns its value for this device.
Arguments
The name of the system environment variable. The available variable names are listed in Table
key
1. Property variable names at the end of this topic.
Returns
The value of the variable. The data format varies according to the variable requested.
Arguments
The name of the system environment variable. The available variable names are listed in Table
key
1. Property Variable Names.
Returns
The value of the variable. The data format varies according to the variable requested.
Installs the Android application or test package contained in packageFile onto this device. If
the application or test package is already installed, it is replaced.
Arguments
path The fully-qualified path and filename of the .apk file to install.
dictionary instrument ( string className, dictionary args)
Runs the specified component with Android instrumentation, and returns the results in a
dictionary whose exact format is dictated by the component being run. The component must
already be present on this device.
Use this method to start a test case that uses one of Android's test case classes. See Testing
Fundamentals to learn more about unit testing with the Android testing framework.
Arguments
The name of an Android component that is already installed on this device, in the
standard form packagename/classname, where packagename is the Android package
name of a .apk file on this device, and classname is the class name of an Android
className
component (Activity, ContentProvider, Service, or BroadcastReceiver) in that file. Both
packagename and classname must be fully qualified. See ComponentName for more
details.
A dictionary containing flags and their values. These are passed to the component as it is
args
started. If the flag does not take a value, set its dictionary value to an empty string.
Returns
A dictionary containing the component's output. The contents of the dictionary are
defined by the component itself.
Sends the key event specified by type to the key specified by keycode.
Arguments
The name of the keycode to send. See KeyEvent for a list of keycode names. Use the keycode
name
name, not its integer value.
type The type of key event to send. The allowed values are DOWN, UP, and DOWN_AND_UP.
Deletes the specified package from this device, including its data and cache.
Arguments
package The Android package name of an .apk file on this device.
Arguments
The command to execute in the adb shell. The form of these commands is described in the
cmd
topic Android Debug Bridge.
Returns
The results of the command, if any. The format of the results is determined by the
command.
void startActivity ( string uri, string action, string data, string mimetype, iterable
categories dictionary extras, component component, iterable flags)
Starts an Activity on this device by sending an Intent constructed from the supplied
arguments.
Arguments
uri The URI for the Intent. (see Intent.setData()).
An iterable data structure containing strings that define categories for the Intent (see
categories
Intent.addCategory()).
A dictionary of extra data for the Intent (see Intent.putExtra() for an example).
extras
The key for each dictionary item should be a string. The item's value can be any
simple or structured data type.
The component for the Intent (see ComponentName). Using this argument will direct
component
the Intent to a specific class within a specific Android package.
An iterable data structure containing flags that control how the Intent is handled (see
flags
Intent.setFlags()).
MonkeyImage takeSnapshot ()
Captures the entire screen buffer of this device, yielding a screen capture of the current
display.
Returns
Sends a touch event specified by type to the screen location specified by x and y.
Arguments
The horizontal position of the touch in actual device pixels, starting from the left of the screen
x
in its current orientation.
The vertical position of the touch in actual device pixels, starting from the top of the screen in
y
its current orientation.
type The type of key event to send. The allowed values are DOWN, UP, and DOWN_AND_UP.
Sends the characters contained in message to this device, as if they had been typed on the
device's keyboard. This is equivalent to calling press() for each keycode in message using
the key event type DOWN_AND_UP.
Arguments
message A string containing the characters to send.
void wake ()
Appendix
Table 1.Property variable names used with getProperty() and getSystemProperty().
Property
Property Description Notes
Group
host
user
The product/hardware
manufacturer
manufacturer.
data
The data (if any) contained in the
Intent that started the current
Activity.
Except as noted, this content is licensed under Creative Commons Attribution 2.5. For details and
restrictions, see the Content License.
MonkeyImage
A monkeyrunner class to hold an image of the device or emulator's screen. The image is
copied from the screen buffer during a screenshot. This object's methods allow you to convert
the image into various storage formats, write the image to a file, copy parts of the image, and
compare this object to other MonkeyImage objects.
newimage = MonkeyDevice.takeSnapshot()
Summary
Methods
boolean Compares this MonkeyImage object to another and returns the result of the
comparison. The percent argument specifies the percentage difference that
is allowed for the two images to be "equal".
Public Methods
Converts the current image to a particular format and returns it as a string that you can then
access as an iterable of binary bytes.
Arguments
The desired output format. All of the common raster output formats are supported. The
format
default value is "png" (Portable Network Graphics).
Returns the single pixel at the image location (x,y), as an a tuple of integer, in the form
(a,r,g,b).
Arguments
The horizontal position of the pixel, starting with 0 at the left of the screen in the orientation it had
x
when the screenshot was taken.
The vertical position of the pixel, starting with 0 at the top of the screen in the orientation it had
y
when the screenshot was taken.
Returns
A tuple of integers representing the pixel, in the form (a,r,g,b) where a is the alpha channel
value, and r, g, and b are the red, green, and blue values, respectively.
Returns the single pixel at the image location (x,y), as an an integer. Use this method to
economize on memory.
Arguments
The horizontal position of the pixel, starting with 0 at the left of the screen in the orientation it had
x
when the screenshot was taken.
The vertical position of the pixel, starting with 0 at the top of the screen in the orientation it had
y
when the screenshot was taken.
Returns
The a,r,g, and b values of the pixel as 8-bit values combined into a 32-bit integer, with a as
the leftmost 8 bits, r the next rightmost, and so forth.
Creates a new MonkeyImage object from a rectangular selection of the current image.
Arguments
A tuple (x, y, w, h) specifying the selection. x and y specify the 0-based pixel position of the
upper left-hand corner of the selection. w specifies the width of the region, and h specifies its
rect height, both in units of pixels.
The image's orientation is the same as the screen orientation at the time the screenshot
was made.
Returns
Compares this MonkeyImage object to another and returns the result of the comparison. The
percent argument specifies the percentage difference that is allowed for the two images to
be "equal".
Arguments
other Another MonkeyImage object to compare to this one.
A float in the range 0.0 to 1.0, inclusive, indicating the percentage of pixels that need to be
percent the same for the method to return true. The default is 1.0, indicating that all the pixels
must match.
Returns
Writes the current image to the file specified by filename, in the format specified by
format.
Arguments
path The fully-qualified filename and extension of the output file.
The output format to use for the file. If no format is provided, then the method tries to guess
format the format from the filename's extension. If no extension is provided and no format is
specified, then the default format of "png" (Portable Network Graphics) is used.
Except as noted, this content is licensed under Creative Commons Attribution 2.5. For details and
restrictions, see the Content License.
MonkeyRunner
A monkeyrunner class that contains static utility methods.
Summary
Methods
input (string message, string initialValue, string title, string okTitle, string
string cancelTitle)
Public Methods
Displays an alert dialog to the process running the current program. The dialog is modal, so
the program pauses until the user clicks the dialog's button.
Arguments
message The message to display in the dialog.
okTitle The text displayed in the dialog button. The default value is "OK".
Displays a dialog with a list of choices to the process running the current program. The dialog
is modal, so the program pauses until the user clicks one of the dialog's buttons.
Arguments
message The prompt message displayed in the dialog.
A Python iterable containing one or more objects that are displayed as strings. The
choices
recommended form is an array of strings.
If the user makes a selection and clicks the "OK" button, the method returns the 0-based
index of the selection within the iterable. If the user clicks the "Cancel" button, the method
returns -1.
Displays the monkeyrunner API reference in a style similar to that of Python's pydoc tool,
using the specified format.
Arguments
The markup format to use in the output. The possible values are "text" for plain text or
format
"html" for HTML.
string input (string message string initialValue, string title, string okTitle, string
cancelTitle)
Displays a dialog that accepts input and returns it to the program. The dialog is modal, so the
program pauses until the user clicks one of the dialog's buttons.
The dialog contains two buttons, one of which displays the okTitle value and the other the
cancelTitle value. If the user clicks the okTitle button, the current value of the input box is
returned. If the user clicks the cancelTitle button, an empty string is returned.
Arguments
message The prompt message displayed in the dialog.
initialValue The initial value to display in the dialog. The default is an empty string.
okTitle The text displayed in the okTitle button. The default is "OK".
cancelTitle The text displayed in the cancelTitle button. The default is "Cancel".
Returns
If the user clicks the okTitle button, then the method returns the current value of the
dialog's input box. If the user clicks the cancelTitle button, the method returns an empty
string.
Tries to make a connection between the monkeyrunner backend and the specified device or
emulator.
Arguments
timeout The number of seconds to wait for a connection. The default is to wait forever.
A regular expression that specifies the serial number of the device or emulator. See the
deviceId
topic Android Debug Bridge for a description of device and emulator serial numbers.
Returns
A MonkeyDevice instance for the device or emulator. Use this object to control and
communicate with the device or emulator.
Except as noted, this content is licensed under Creative Commons Attribution 2.5. For details and
restrictions, see the Content License.
ProGuard
In this document
1. Enabling ProGuard
2. Configuring ProGuard
3. Decoding Obfuscated Stack Traces
1. Debugging considerations for published applications
See also
1. ProGuard Manual »
2. ProGuard ReTrace Manual »
The ProGuard tool shrinks, optimizes, and obfuscates your code by removing unused code
and renaming classes, fields, and methods with semantically obscure names. The result is a
smaller sized .apk file that is more difficult to reverse engineer. Because ProGuard makes
your application harder to reverse engineer, it is important that you use it when your
application utilizes features that are sensitive to security like when you are Licensing Your
Applications.
ProGuard is integrated into the Android build system, so you do not have to invoke it
manually. ProGuard runs only when you build your application in release mode, so you do
not have to deal with obfuscated code when you build your application in debug mode.
Having ProGuard run is completely optional, but highly recommended.
This document describes how to enable and configure ProGuard as well as use the retrace
tool to decode obfuscated stack traces.
Enabling ProGuard
When you create an Android project, a proguard.cfg file is automatically generated in the
root directory of the project. This file defines how ProGuard optimizes and obfuscates your
code, so it is very important that you understand how to customize it for your needs. The
default configuration file only covers general cases, so you most likely have to edit it for your
own needs. See the following section about Configuring ProGuard for information on
customizing the ProGuard configuration file.
To enable ProGuard so that it runs as part of an Ant or Eclipse build, set the
proguard.config property in the <project_root>/project.properties file. The path
can be an absolute path or a path relative to the project's root.
Note: When using Android Studio, you must add Proguard to your gradle.build file's build
types. For more information, see the Gradle Plugin User Guide.
If you left the proguard.cfg file in its default location (the project's root directory), you can
specify its location like this:
proguard.config=proguard.cfg
You can also move the the file to anywhere you want, and specify the absolute path to it:
proguard.config=/path/to/proguard.cfg
When you build your application in release mode, either by running ant release or by
using the Export Wizard in Eclipse, the build system automatically checks to see if the
proguard.config property is set. If it is, ProGuard automatically processes the application's
bytecode before packaging everything into an .apk file. Building in debug mode does not
invoke ProGuard, because it makes debugging more cumbersome.
dump.txt
Describes the internal structure of all the class files in the .apk file
mapping.txt
Lists the mapping between the original and obfuscated class, method, and field
names. This file is important when you receive a bug report from a release build,
because it translates the obfuscated stack trace back to the original class, method, and
member names. See Decoding Obfuscated Stack Traces for more information.
seeds.txt
Lists the classes and members that are not obfuscated
usage.txt
Lists the code that was stripped from the .apk
Caution: Every time you run a build in release mode, these files are overwritten with the
latest files generated by ProGuard. Save a copy of them each time you release your
application in order to de-obfuscate bug reports from your release builds. For more
information on why saving these files is important, see Debugging considerations for
published applications.
Configuring ProGuard
For some situations, the default configurations in the proguard.cfg file will suffice.
However, many situations are hard for ProGuard to analyze correctly and it might remove
code that it thinks is not used, but your application actually needs. Some examples include:
The default proguard.cfg file tries to cover general cases, but you might encounter
exceptions such as ClassNotFoundException, which happens when ProGuard strips away
an entire class that your application calls.
You can fix errors when ProGuard strips away your code by adding a -keep line in the
proguard.cfg file. For example:
There are many options and considerations when using the -keep option, so it is highly
recommended that you read the ProGuard Manual for more information about customizing
your configuration file. The Overview of Keep options and Examples sections are particularly
helpful. The Troubleshooting section of the ProGuard Manual outlines other common
problems you might encounter when your code gets stripped away.
When your obfuscated code outputs a stack trace, the method names are obfuscated, which
makes debugging hard, if not impossible. Fortunately, whenever ProGuard runs, it outputs a
<project_root>/bin/proguard/mapping.txt file, which shows you the original class,
method, and field names mapped to their obfuscated names.
The retrace.bat script on Windows or the retrace.sh script on Linux or Mac OS X can
convert an obfuscated stack trace to a readable one. It is located in the
<sdk_root>/tools/proguard/ directory. The syntax for executing the retrace tool is:
For example:
If you do not specify a value for <stacktrace_file>, the retrace tool reads from standard
input.
Save the mapping.txt file for every release that you publish to your users. By retaining a
copy of the mapping.txt file for each release build, you ensure that you can debug a
problem if a user encounters a bug and submits an obfuscated stack trace. A project's
mapping.txt file is overwritten every time you do a release build, so you must be careful
about saving the versions that you need.
For example, say you publish an application and continue developing new features of the
application for a new version. You then do a release build using ProGuard soon after. The
build overwrites the previous mapping.txt file. A user submits a bug report containing a
stack trace from the application that is currently published. You no longer have a way of
debugging the user's stack trace, because the mapping.txt file associated with the version on
the user's device is gone. There are other situations where your mapping.txt file can be
overwritten, so ensure that you save a copy for every release that you anticipate you have to
debug.
How you save the mapping.txt file is your decision. For example, you can rename them to
include a version or build number, or you can version control them along with your source
code.
SDK Manager
The Android SDK separates tools, platforms, and other components into packages you can
download using the SDK Manager. For example, when the SDK Tools are updated or a new
version of the Android platform is released, you can use the SDK Manager to quickly
download them to your environment.
You can launch the SDK Manager in one of the following ways:
From Eclipse (with ADT), select Window > Android SDK Manager.
From Android Studio, select Tools > Android > SDK Manager.
On Windows, double-click the SDK Manager.exe file at the root of the Android SDK
directory.
On Mac or Linux, open a terminal and navigate to the tools/ directory in the
Android SDK, then execute android sdk.
You can select which packages you want to download by toggling the checkboxes on the left,
then click Install to install the selected packages.
Figure 1. The Android SDK Manager shows the SDK packages that are available, already
installed, or for which an update is available.
There are several different packages available for the Android SDK. The table below
describes most of the available packages and where they're located in your SDK directory
once you download them.
Recommended Packages
Here's an outline of the packages required and those we recommend you use:
SDK Tools
Required. Your new SDK installation already has the latest version. Make sure you
keep this up to date.
SDK Platform-tools
Required. You must install this package when you install the SDK for the first time.
SDK Platform
Required.You must download at least one platform into your environment so you're
able to compile your application. In order to provide the best user experience on the
latest devices, we recommend that you use the latest platform version as your build
target. You'll still be able to run your app on older versions, but you must build
against the latest version in order to use new features when running on devices with
the latest version of Android.
To get started, download the latest Android version, plus the lowest version you plan
to support (we recommend Android 2.2 for your lowest version).
System Image
Recommended. Although you might have one or more Android-powered devices on
which to test your app, it's unlikely you have a device for every version of Android
your app supports. It's a good practice to download system images for all versions of
Android your app supports and test your app running on them with the Android
emulator.
Android Support
Recommended. Includes a static library that allows you to use some of the latest
Android APIs (such as fragments, plus others not included in the framework at all) on
devices running a platform version as old as Android 1.6. All of the activity templates
available when creating a new project with the ADT Plugin require this. For more
information, read Support Library.
SDK Samples
Recommended. The samples give you source code that you can use to learn about
Android, load as a project and run, or reuse in your own app. Note that multiple
samples packages are available — one for each Android platform version. When you
are choosing a samples package to download, select the one whose API Level
matches the API Level of the Android platform that you plan to use.
Tip: For easy access to the SDK tools from a command line, add the location of the SDK's
tools/ and platform-tools to your PATH environment variable.
The above list is not comprehensive and you can add new sites to download additional
packages from third-parties.
In some cases, an SDK package may require a specific minimum revision of another package
or SDK tool. The development tools will notify you with warnings if there is dependency that
you need to address. The Android SDK Manager also enforces dependencies by requiring
that you download any packages that are needed by those you have selected.
By default, Available Packages displays packages available from the Android Repository
and Third party Add-ons. You can add other sites that host their own Android SDK add-ons,
then download the SDK add-ons from those sites.
For example, a mobile carrier or device manufacturer might offer additional API libraries that
are supported by their own Android-powered devices. In order to develop using their
libraries, you must install their Android SDK add-on, if it's not already available under Third
party Add-ons.
If a carrier or device manufacturer has hosted an SDK add-on repository file on their web
site, follow these steps to add their site to the Android SDK Manager:
Any SDK packages available from the site will now be listed under a new item named User
Add-ons.
Troubleshooting
If you are using the Android SDK Manager to download packages and are encountering
connection problems, try connecting over http, rather than https. To switch the protocol used
by the Android SDK Manager, follow these steps:
1. With the Android SDK Manager window open, select "Settings" in the left pane.
2. On the right, in the "Misc" section, check the checkbox labeled "Force https://...
sources to be fetched using http://..."
3. Click Save & Apply.
Systrace
The Systrace tool helps analyze the performance of your application by capturing and
displaying execution times of your applications processes and other Android system
processes. The tool combines data from the Android kernel such as the CPU scheduler, disk
activity, and application threads to generate an HTML report that shows an overall picture of
an Android device’s system processes for a given period of time.
The Systrace tool is particularly useful in diagnosing display problems where an application
is slow to draw or stutters while displaying motion or animation. For more information on
how to use Systrace, see Analyzing Display and Performance.
Requirements
In order to run Systrace, you must have Android SDK Tools 20 or later installed. You must
also have Python installed and included in your development computer's execution path. In
order to generate a trace, you must connect a device running Android 4.1 (API Level 16) or
higher to your development system using a USB debugging connection.
The Systrace tool can be run either from one of the Android SDK's graphical user interface
tools, or from the command line. The following sections describe how to run the tool using
either of these methods.
User Interface
The Systrace tool can be run from the Android Developer Tools (ADT) in Eclipse, Android
Studio, or the Android Device Monitor.
Using Eclipse
The Systrace tool has different command line options for devices running Android 4.3 (API
level 18) and higher versus devices running Android 4.2 (API level 17) and lower. The
following sections describe the different command line options for each version.
The general syntax for running Systrace from the command line is as follows.
When you use Systrace on devices running Android 4.3 and higher, you must specify at least
one trace category tag. Here is an example execution run that sets trace tags and generates a
trace from a connected device.
$ cd android-sdk/platform-tools/systrace
$ python systrace.py --time=10 -o mynewtrace.html sched gfx view wm
Tip: If you want to see the names of tasks in the trace output, you must include the sched
category in your command parameters.
The table below lists the Systrace command line options for devices running Android 4.3
(API level 18) and higher.
Option Description
-h, --help Show the help message.
-o <FILE> Write the HTML trace report to the specified file.
-t N, --time=N Trace activity for N seconds. The default value is 5 seconds.
-b N, --buf-size=N
Use a trace buffer size of N kilobytes. This option lets you
limit the total size of the data collected during a trace.
-k <KFUNCS> Trace the activity of specific kernel functions, specified in a
--ktrace=<KFUNCS> comma-separated list.
-l, --list-categories List the available tracing category tags. The available tags are:
gfx - Graphics
input - Input
view - View
webview - WebView
wm - Window Manager
am - Activity Manager
audio - Audio
video - Video
camera - Camera
hal - Hardware Modules
res - Resource Loading
dalvik - Dalvik VM
rs - RenderScript
sched - CPU Scheduling
freq - CPU Frequency
membus - Memory Bus Utilization
idle - CPU Idle
disk - Disk input and output
load - CPU Load
sync - Synchronization Manager
workq - Kernel Workqueues
Tip: If you want to see the names of tasks in the trace output,
you must include the sched category in your command
parameters.
Enable tracing for applications, specified as a comma-
-a <APP_NAME> separated list of package names. The apps must contain tracing
--app=<APP_NAME> instrumentation calls from the Trace class. For more
information, see Analyzing Display and Performance.
--link-assets
Link to the original CSS or JavaScript resources instead of
embedding them in the HTML trace report.
--from-file=<FROM_FILE>
Create the interactive Systrace report from a file, instead of
running a live trace.
Specify a directory for the trace report assets. This option is
--asset-dir=<ASSET_DIR> useful for maintaining a single set of assets for multiple
Systrace reports.
-e <DEVICE_SERIAL> Conduct the trace on a specific connected device, identified by
--serial=<DEVICE_SERIAL> its device serial number.
Using Systrace on the command line with devices running Android 4.2 and lower is typically
a two-step process. You must first set the trace tags you want to capture and then run the
trace. Here is an example execution run that sets trace tags and generates a trace from a
connected device.
$ cd android-sdk/platform-tools/systrace
$ python systrace.py --set-tags gfx,view,wm
$ adb shell stop
$ adb shell start
$ python systrace.py --disk --time=10 -o mynewtrace.html
The table below lists the Systrace command line options for devices running Android 4.2
(API level 17) and lower.
Option Description
-h, --help Show the help message.
-o <FILE> Write the HTML trace report to the specified file.
-t N, --time=N Trace activity for N seconds. The default value is 5 seconds.
-b N, --buf- Use a trace buffer size of N kilobytes. This option lets you limit the total
size=N size of the data collected during a trace.
-d, --disk
Trace disk input and output activity. This option requires root access on
the device.
Trace CPU frequency changes. Only changes to the CPU frequency are
-f, --cpu-freq logged, so the initial frequency of the CPU when tracing starts is not
shown.
-i, --cpu-idle Trace CPU idle events.
-l, --cpu-load
Trace CPU load. This value is a percentage determined by the interactive
CPU frequency governor.
-s, --no-cpu- Prevent tracing of the CPU scheduler. This option allows for longer trace
sched times by reducing the rate of data flowing into the trace buffer.
-u, --bus- Trace the bus utilization levels. This option requires root access on the
utilization device.
-w, --
workqueue Trace kernel work queues. This option requires root access on the device.
Set the enabled trace tags in a comma separated list. The available tags are:
gfx - Graphics
input - Input
view - View
webview - WebView
wm - Window Manager
--set- am - Activity Manager
tags=<TAGS> sync - Synchronization Manager
audio - Audio
video - Video
camera - Camera
Note: When setting trace tags from the command line, you must stop and
restart the framework ($ adb shell stop; adb shell start) for the
tag tracing changes to take effect.
--link-assets
Link to the original CSS or JS resources instead of embedding them in the
HTML trace report.
You can set the trace tags for Systrace on your Android 4.2 and lower device by navigating to
Settings > Developer options > Monitoring > Enable traces.
The table below lists the keyboard shortcuts that are available while viewing a Systrace trace
HTML report.
Key Description
w Zoom into the trace timeline.
s Zoom out of the trace timeline.
a Pan left on the trace timeline.
d Pan right on the trace timeline.
e Center the trace timeline on the current mouse location.
g Show grid at the start of the currently selected task.
Shift+g Show grid at the end of the currently selected task.
Right Arrow Select the next event on the currently selected timeline.
Left Arrow Select the previous event on the currently selected timeline.
Double Click Zoom into the trace timeline.
Shift+Double Click Zoom out of the trace timeline.
See also
1. Tools
Tracer is a tool for analyzing OpenGL for Embedded Systems (ES) code in your Android
application. The tool allows you to capture OpenGL ES commands and frame by frame
images to help you understand how your graphics commands are being executed.
Note: The Tracer tool requires a device running Android 4.1 (API Level 16) or higher.
Running Tracer
Tracer can be run as part of the Eclipse Android Development Tools (ADT) plugin or as part
of the Device Monitor tool.
Generating a Trace
Tracer captures OpenGL ES command execution logs and can also capture progressive
images of the frames generated by those commands to enable you to perform logical and
visual analysis of your OpenGL ES code. The Tracer tool operates by connecting to a device
running Android 4.1 (API Level 16) or higher that is running the application you want to
analyze. The Tracer tool captures trace information while the application is running and saves
it to a .gltrace file for analysis.
Figure 1. Trace capture dialog box.
1. Connect the Android device using a USB cable and make sure it is enabled for
debugging. For more information, see Using Hardware Devices.
2. In Eclipse or Device Monitor, activate the Tracer for OpenGL ES perspective.
3. On the toolbar, click the trace capture button ( ).
4. In the dialog box, select the Device to use for the trace.
5. In the Application Package field, enter the full application package name containing
the activity you want to trace, for example: com.example.android.opengl
6. In the Activity to launch field, enter the class name of the activity you want to trace,
for example: OpenGLES20Complete
Note: If you are tracing the default activity for the application, you can leave this field
blank.
Note: If you want to capture progressive frame images for each drawing call, enable
the Read back currently bound framebuffer on glDraw*() option. Be aware that
using this option can result in large trace files.
Analyzing a Trace
After you have generated a trace, you can load it for review and analysis.
Traceview
Traceview is a graphical viewer for execution logs saved by your application. Traceview can
help you debug your application and profile its performance.
To start Traceview, enter the following command from the SDK tools/ directory:
traceview
For more information on how to use Traceview, see Profiling with Traceview and
dmtracedump
uiautomator
In this document
Syntax
Options
uiautomator API
o Classes
o Interfaces
o Exceptions
The uiautomator testing framework lets you test your user interface (UI) efficiently by
creating automated functional UI testcases that can be run against your app on one or more
devices.
For more information on testing with the uiautomator framework, see UI Testing.
Syntax
To run your testcases on the target device, you can use the adb shell command to invoke
the uiautomator tool. The syntax is:
Here’s an example:
Command-line Options
The following table describes the subcommands and options for uiautomator.
package_name.class_name
package_name.class_name#method_name
events
Prints out accessibility events to the console until the
connection to the device is terminated
uiautomator API
The uiautomator API is bundled in the uiautomator.jar file under the <android-
sdk>/platforms/ directory. The API includes these key classes, interfaces, and exceptions
that allow you to capture and manipulate UI components on the target app:
Classes
Class Description
Used to enumerate a container's user
com.android.uiautomator.core.UiCollection
interface (UI) elements for the purpose of
counting, or targeting a sub elements by a
child's text or description.
com.android.uiautomator.core.UiDevice
Provides access to state information
about the device. You can also use this
class to simulate user actions on the
device, such as pressing the d-pad
hardware button or pressing the Home
and Menu buttons.
com.android.uiautomator.core.UiObject Represents a user interface (UI) element.
com.android.uiautomator.core.UiScrollable
Provides support for searching for items
in a scrollable UI container.
com.android.uiautomator.core.UiSelector
Represents a query for one or more target
UI elements on a device screen.
com.android.uiautomator.core.Configurator
Allows you to set key parameters for
running uiautomator tests.
Interfaces
Interface Description
Represents a conditional
com.android.uiautomator.core.UiWatcher watcher on the target
device.
Provides auxiliary
com.android.uiautomator.testrunner.IAutomationSupport support for running test
cases.
Defines an environment
for running multiple
com.android.uiautomator.testrunner.UiAutomatorTestCase tests. All uiautomator
test cases should extend
this class.
Exceptions
Exception Description
Indicates when a a
UiSelector could not be
com.android.uiautomator.core.UiObjectNotFoundException
matched to any UI
element displayed.
Except as noted, this content is licensed under Creative Commons Attribution 2.5. For details
and restrictions, see the Content License.
Configurator
Since API level 18
Allows you to set key parameters for running uiautomator tests. The new settings take effect
immediately and can be changed any time during a test run. To modify parameters using
Configurator, first obtain an instance by calling getInstance(). As a best practice, make
sure you always save the original value of any parameter that you are modifying. After
running your tests with the modified parameters, make sure to also restore the original
parameter values, otherwise this will impact other tests cases.
Summary
Public Methods
getActionAcknowledgmentTimeout()
long Gets the current timeout for waiting for an acknowledgment of generic
uiautomator actions, such as clicks, text setting, and menu presses.
static getInstance()
Configurator Retrieves a singleton instance of Configurator.
getKeyInjectionDelay()
long
Gets the current delay between key presses when injecting text input.
getScrollAcknowledgmentTimeout()
long Gets the timeout for waiting for an acknowledgement of an uiautomtor scroll
swipe action.
getWaitForIdleTimeout()
long Gets the current timeout used for waiting for the user interface to go into an
idle state.
getWaitForSelectorTimeout()
long Gets the current timeout for waiting for a widget to become visible in the user
interface so that it can be matched by a selector.
setActionAcknowledgmentTimeout(long timeout)
Configurator Sets the timeout for waiting for an acknowledgment of generic uiautomator
actions, such as clicks, text setting, and menu presses.
setKeyInjectionDelay(long delay)
Configurator
Sets a delay between key presses when injecting text input.
setScrollAcknowledgmentTimeout(long timeout)
Configurator
Sets the timeout for waiting for an acknowledgement of an uiautomtor scroll
swipe action.
setWaitForIdleTimeout(long timeout)
Configurator Sets the timeout for waiting for the user interface to go into an idle state before
starting a uiautomator action.
setWaitForSelectorTimeout(long timeout)
Configurator Sets the timeout for waiting for a widget to become visible in the user interface
so that it can be matched by a selector.
[Expand]
Inherited Methods
Public Methods
Gets the current timeout for waiting for an acknowledgment of generic uiautomator actions,
such as clicks, text setting, and menu presses. The acknowledgment is an AccessibilityEvent,
corresponding to an action, that lets the framework determine if the action was successful.
Generally, this timeout should not be modified. See UiObject
Returns
Since
Returns
Configurator instance
Since
Gets the current delay between key presses when injecting text input. See setText(String)
Returns
Since
Gets the timeout for waiting for an acknowledgement of an uiautomtor scroll swipe action.
The acknowledgment is an AccessibilityEvent, corresponding to the scroll action, that lets the
framework determine if the scroll action was successful. Generally, this timeout should not
be modified. See UiScrollable
Returns
Since
Gets the current timeout used for waiting for the user interface to go into an idle state. By
default, all core uiautomator objects except UiDevice will perform this wait before starting to
search for the widget specified by the object's UiSelector. Once the idle state is detected or
the timeout elapses (whichever occurs first), the object will start to wait for the selector to
find a match. See setWaitForSelectorTimeout(long)
Returns
Since
Gets the current timeout for waiting for a widget to become visible in the user interface so
that it can be matched by a selector. Because user interface content is dynamic, sometimes a
widget may not be visible immediately and won't be detected by a selector. This timeout
allows the uiautomator framework to wait for a match to be found, up until the timeout
elapses.
Returns
Since
Sets the timeout for waiting for an acknowledgment of generic uiautomator actions, such as
clicks, text setting, and menu presses. The acknowledgment is an AccessibilityEvent,
corresponding to an action, that lets the framework determine if the action was successful.
Generally, this timeout should not be modified. See UiObject
Parameters
timeout Timeout value in milliseconds
Returns
self
Since
Sets a delay between key presses when injecting text input. See setText(String)
Parameters
delay Delay value in milliseconds
Returns
self
Since
Sets the timeout for waiting for an acknowledgement of an uiautomtor scroll swipe action.
The acknowledgment is an AccessibilityEvent, corresponding to the scroll action, that lets the
framework determine if the scroll action was successful. Generally, this timeout should not
be modified. See UiScrollable
Parameters
timeout Timeout value in milliseconds
Returns
self
Since
Sets the timeout for waiting for the user interface to go into an idle state before starting a
uiautomator action. By default, all core uiautomator objects except UiDevice will perform
this wait before starting to search for the widget specified by the object's UiSelector. Once
the idle state is detected or the timeout elapses (whichever occurs first), the object will start to
wait for the selector to find a match. See setWaitForSelectorTimeout(long)
Parameters
timeout Timeout value in milliseconds
Returns
self
Since
Sets the timeout for waiting for a widget to become visible in the user interface so that it can
be matched by a selector. Because user interface content is dynamic, sometimes a widget may
not be visible immediately and won't be detected by a selector. This timeout allows the
uiautomator framework to wait for a match to be found, up until the timeout elapses.
Parameters
timeout Timeout value in milliseconds.
Returns
self
Since
IAutomationSupport
Class Overview
Summary
Public Methods
Public Methods
UiAutomatorTestCase
Class Overview
UI automation tests should extend this class. This class provides access to the following:
UiDevice instance
Bundle for command line parameters
Summary
Public Constructors
UiAutomatorTestCase()
Public Methods
getAutomationSupport()
IAutomationSupport
Provides support for running tests to report interim status
getParams()
Bundle
Get command line parameters.
getUiDevice()
UiDevice
Get current instance of UiDevice.
sleep(long ms)
void
Calls sleep(long) to sleep
[Expand]
Inherited Methods
Public Constructors
public UiAutomatorTestCase ()
Public Methods
Get command line parameters. On the command line when passing -e key value pairs, the
Bundle will have the key value pairs conveniently available to the tests.
Get current instance of UiDevice. Works similar to calling the static getInstance() from
anywhere in the test classes.
Parameters
ms is in milliseconds.
UiCollection
Used to enumerate a container's user interface (UI) elements for the purpose of counting, or
targeting a sub elements by a child's text or description.
Summary
Public Constructors
UiCollection(UiSelector selector)
Public Methods
getChildCount(UiSelector childPattern)
int
Counts child UI element instances matching the childPattern argument.
[Expand]
Inherited Methods
Public Constructors
Public Methods
Searches for child UI element within the constraints of this UiSelector selector. It looks for
any child matching the childPattern argument that has a child UI element anywhere within
its sub hierarchy that has content-description text. The returned UiObject will point at the
childPattern instance that matched the search and not at the identifying child element that
matched the content description.
Parameters
childPattern UiSelector selector of the child pattern to match and return
Returns
Throws
UiObjectNotFoundException
Searches for child UI element within the constraints of this UiSelector. It looks for any
child matching the childPattern argument that has a child UI element anywhere within its
sub hierarchy that is at the instance specified. The operation is performed only on the
visible items and no scrolling is performed in this case.
Parameters
childPattern UiSelector selector of the child pattern to match and return
Returns
Throws
UiObjectNotFoundException
Searches for child UI element within the constraints of this UiSelector selector. It looks for
any child matching the childPattern argument that has a child UI element anywhere within
its sub hierarchy that has a text attribute equal to text. The returned UiObject will point at
the childPattern instance that matched the search and not at the identifying child element
that matched the text attribute.
Parameters
childPattern UiSelector selector of the child pattern to match and return
Returns
Throws
UiObjectNotFoundException
Counts child UI element instances matching the childPattern argument. The method
returns the number of matching UI elements that are currently visible. The count does not
include items of a scrollable list that are off-screen.
Parameters
childPattern a UiSelector that represents the matching child UI elements to count
Returns
Summary
Public Methods
clearLastTraversedText()
void
Clears the text from the last UI traversal event.
click(int x, int y)
boolean
Perform a click at arbitrary coordinates specified by the user
drag(int startX, int startY, int endX, int endY, int steps)
boolean
Performs a swipe from one coordinate to another coordinate.
dumpWindowHierarchy(String fileName)
void Helper method used for debugging to dump the current window's layout
hierarchy.
freezeRotation()
void Disables the sensors and freezes the device rotation at its current rotation
state.
getCurrentActivityName()
String This method is deprecated. The results returned should be considered
unreliable
getCurrentPackageName()
String
Retrieves the name of the last package to report accessibility events.
getDisplayHeight()
int
Gets the height of the display, in pixels.
getDisplayRotation()
int
Returns the current rotation of the display, as defined in Surface
getDisplaySizeDp()
Point Returns the display size in dp (device-independent pixel) The returned
display size is adjusted per screen rotation.
getDisplayWidth()
int
Gets the width of the display, in pixels.
static getInstance()
UiDevice Retrieves a singleton instance of UiDevice
getLastTraversedText()
String
Retrieves the text from the last UI traversal event received.
getProductName()
String
Retrieves the product name of the device.
hasAnyWatcherTriggered()
boolean
Checks if any registered UiWatcher have triggered.
hasWatcherTriggered(String watcherName)
boolean
Checks if a specific registered UiWatcher has triggered.
isNaturalOrientation()
boolean
Check if the device is in its natural orientation.
isScreenOn()
boolean
Checks the power manager if the screen is ON.
openNotification()
boolean
Opens the notification shade.
openQuickSettings()
boolean
Opens the Quick Settings shade.
pressBack()
boolean
Simulates a short press on the BACK button.
pressDPadCenter()
boolean
Simulates a short press on the CENTER button.
pressDPadDown()
boolean
Simulates a short press on the DOWN button.
pressDPadLeft()
boolean
Simulates a short press on the LEFT button.
pressDPadRight()
boolean
Simulates a short press on the RIGHT button.
pressDPadUp()
boolean
Simulates a short press on the UP button.
pressDelete()
boolean
Simulates a short press on the DELETE key.
pressEnter()
boolean
Simulates a short press on the ENTER key.
pressHome()
boolean
Simulates a short press on the HOME button.
pressKeyCode(int keyCode, int metaState)
boolean
Simulates a short press using a key code.
pressKeyCode(int keyCode)
boolean
Simulates a short press using a key code.
pressMenu()
boolean
Simulates a short press on the MENU button.
pressRecentApps()
boolean
Simulates a short press on the Recent Apps button.
pressSearch()
boolean
Simulates a short press on the SEARCH button.
registerWatcher(String name, UiWatcher watcher)
void Registers a UiWatcher to run automatically when the testing framework is
unable to find a match using a UiSelector.
removeWatcher(String name)
void
Removes a previously registered UiWatcher.
resetWatcherTriggers()
void
Resets a UiWatcher that has been triggered.
runWatchers()
void
This method forces all registered watchers to run.
setCompressedLayoutHeirarchy(boolean compressed)
void
Enables or disables layout hierarchy compression.
setOrientationLeft()
void Simulates orienting the device to the left and also freezes rotation by
disabling the sensors.
setOrientationNatural()
void Simulates orienting the device into its natural orientation and also freezes
rotation by disabling the sensors.
setOrientationRight()
void Simulates orienting the device to the right and also freezes rotation by
disabling the sensors.
sleep()
void This method simply presses the power button if the screen is ON else it does
nothing if the screen is already OFF.
swipe(Point[] segments, int segmentSteps)
boolean
Performs a swipe between points in the Point array.
swipe(int startX, int startY, int endX, int endY, int steps)
boolean Performs a swipe from one coordinate to another using the number of steps
to determine smoothness and speed.
takeScreenshot(File storePath)
Take a screenshot of current window and store it as PNG Default scale of
boolean
1.0f (original size) and 90% quality is used The screenshot is adjusted per
screen rotation
takeScreenshot(File storePath, float scale, int quality)
boolean Take a screenshot of current window and store it as PNG The screenshot is
adjusted per screen rotation
unfreezeRotation()
void Re-enables the sensors and un-freezes the device rotation allowing its
contents to rotate with the device physical rotation.
waitForIdle(long timeout)
void
Waits for the current application to idle.
waitForIdle()
void
Waits for the current application to idle.
waitForWindowUpdate(String packageName, long timeout)
boolean
Waits for a window content update event to occur.
wakeUp()
void This method simulates pressing the power button if the screen is OFF else it
does nothing if the screen is already ON.
[Expand]
Inherited Methods
From class java.lang.Object
Public Methods
Parameters
x coordinate
y coordinate
Returns
public boolean drag (int startX, int startY, int endX, int endY, int steps)
Performs a swipe from one coordinate to another coordinate. You can control the smoothness
and speed of the swipe by specifying the number of steps. Each step execution is throttled to
5 milliseconds per step, so for a 100 steps, the swipe will take around 0.5 seconds to
complete.
Parameters
Returns
true if swipe is performed, false if the operation fails or the coordinates are invalid
Since
Helper method used for debugging to dump the current window's layout hierarchy. The file
root location is /data/local/tmp
Disables the sensors and freezes the device rotation at its current rotation state.
Throws
RemoteException
RemoteException
Returns
Returns
Gets the height of the display, in pixels. The size is adjusted based on the current orientation
of the display.
Returns
Since
Returns the display size in dp (device-independent pixel) The returned display size is
adjusted per screen rotation. Also this will return the actual size of the screen, rather than
adjusted per system decorations (like status bar).
Returns
Since
Android API Level 18
Gets the width of the display, in pixels. The width and height details are reported based on
the current orientation of the display.
Returns
Returns
UiDevice instance
Retrieves the text from the last UI traversal event received. You can use this method to read
the contents in a WebView container because the accessibility framework fires events as each
text is highlighted. You can write a test to perform directional arrow presses to focus on
different elements inside a WebView, and call this method to get the text from each traversed
element. If you are testing a view container that can return a reference to a Document Object
Model (DOM) object, your test should use the view's DOM instead.
Returns
Retrieves the product name of the device. This method provides information on what type of
device the test is running on. This value is the same as returned by invoking #adb shell
getprop ro.product.name.
Returns
Since
Returns
Check if the device is in its natural orientation. This is determined by checking if the
orientation is at 0 or 180 degrees.
Returns
Since
Returns
Throws
RemoteException
RemoteException
Returns
Since
Returns
Since
Returns
Returns
Returns
Returns
Returns
Returns
Returns
Returns
Returns
Parameters
Returns
Returns
Returns
Returns
Throws
RemoteException
RemoteException
Returns
Registers a UiWatcher to run automatically when the testing framework is unable to find a
match using a UiSelector. See runWatchers()
Parameters
Parameters
Parameters
Since
Simulates orienting the device to the left and also freezes rotation by disabling the sensors. If
you want to un-freeze the rotation and re-enable the sensors see unfreezeRotation().
Throws
RemoteException
RemoteException
Since
Simulates orienting the device into its natural orientation and also freezes rotation by
disabling the sensors. If you want to un-freeze the rotation and re-enable the sensors see
unfreezeRotation().
Throws
RemoteException
RemoteException
Since
Android API Level 17
Simulates orienting the device to the right and also freezes rotation by disabling the sensors.
If you want to un-freeze the rotation and re-enable the sensors see unfreezeRotation().
Throws
RemoteException
RemoteException
Since
This method simply presses the power button if the screen is ON else it does nothing if the
screen is already OFF.
Throws
RemoteException
RemoteException
Performs a swipe between points in the Point array. Each step execution is throttled to 5ms
per step. So for a 100 steps, the swipe will take about 1/2 second to complete
Parameters
Returns
true on success
public boolean swipe (int startX, int startY, int endX, int endY, int steps)
Performs a swipe from one coordinate to another using the number of steps to determine
smoothness and speed. Each step execution is throttled to 5ms per step. So for a 100 steps,
the swipe will take about 1/2 second to complete.
Parameters
Take a screenshot of current window and store it as PNG Default scale of 1.0f (original size)
and 90% quality is used The screenshot is adjusted per screen rotation
Parameters
Returns
Since
Take a screenshot of current window and store it as PNG The screenshot is adjusted per
screen rotation
Parameters
Returns
Since
Re-enables the sensors and un-freezes the device rotation allowing its contents to rotate with
the device physical rotation. During a test execution, it is best to keep the device frozen in a
specific orientation until the test case execution has completed.
Throws
RemoteException
public void waitForIdle (long timeout)
Parameters
timeout in milliseconds
Waits for the current application to idle. Default wait timeout is 10 seconds
Waits for a window content update event to occur. If a package name for the window is
specified, but the current window does not have the same package name, the function returns
immediately.
Parameters
the specified window package name (can be null). If null, a window update
packageName
from any front-end window will end the wait
timeout the timeout for the wait
Returns
true if a window update occurred, false if timeout has elapsed or if the current window
does not have the specified package name
This method simulates pressing the power button if the screen is OFF else it does nothing if
the screen is already ON. If the screen was OFF and it just got turned ON, this method will
insert a 500ms delay to allow the device time to wake up and accept input.
Throws
RemoteException
RemoteException
UiObject
A UiObject is a representation of a view. It is not in any way directly bound to a view as
an object reference. A UiObject contains information to help it locate a matching view at
runtime based on the UiSelector properties specified in its constructor. Once you create
an instance of a UiObject, it can be reused for different views that match the selector criteria.
Summary
Constants
FINGER_TOUCH_HALF_WIDT
int
H
int SWIPE_MARGIN_LIMIT
This constant is deprecated. use
lon
WAIT_FOR_EVENT_TMEOUT setScrollAcknowledgmentTimeout(l
g
ong)
lon
WAIT_FOR_SELECTOR_POLL
g
lon WAIT_FOR_SELECTOR_TIME This constant is deprecated. use
g OUT setWaitForSelectorTimeout(long)
lon WAIT_FOR_WINDOW_TMEO
g UT
Public Constructors
UiObject(UiSelector selector)
Constructs a UiObject to represent a view that matches the specified selector criteria.
Public Methods
clearTextField()
void
Clears the existing text contents in an editable field.
click()
boolean Performs a click at the center of the visible bounds of the UI element
represented by this UiObject.
clickAndWaitForNewWindow(long timeout)
boolean Performs a click at the center of the visible bounds of the UI element
represented by this UiObject and waits for window transitions.
clickAndWaitForNewWindow()
boolean Waits for window transitions that would typically take longer than the
usual default timeouts.
clickBottomRight()
boolean
Clicks the bottom and right corner of the UI element
clickTopLeft()
boolean
Clicks the top and left corner of the UI element
dragTo(UiObject destObj, int steps)
boolean
Drags this object to a destination UiObject.
dragTo(int destX, int destY, int steps)
boolean
Drags this object to arbitrary coordinates.
exists()
boolean
Check if view exists.
getBounds()
Rect
Returns the view's bounds property.
getChild(UiSelector selector)
UiObject
Creates a new UiObject for a child view that is under the present UiObject.
int getChildCount()
Counts the child views immediately under the present UiObject.
getClassName()
String
Retrieves the className property of the UI element.
getContentDescription()
String
Reads the content_desc property of the UI element
getFromParent(UiSelector selector)
UiObject Creates a new UiObject for a sibling view or a child of the sibling view,
relative to the present UiObject.
getPackageName()
String
Reads the view's package property
final getSelector()
UiSelector Debugging helper.
getText()
String
Reads the text property of the UI element
getVisibleBounds()
Rect
Returns the visible bounds of the view.
isCheckable()
boolean
Checks if the UI element's checkable property is currently true.
isChecked()
boolean
Check if the UI element's checked property is currently true
isClickable()
boolean
Checks if the UI element's clickable property is currently true.
isEnabled()
boolean
Checks if the UI element's enabled property is currently true.
isFocusable()
boolean
Check if the UI element's focusable property is currently true.
isFocused()
boolean
Check if the UI element's focused property is currently true
isLongClickable()
boolean
Check if the view's long-clickable property is currently true
isScrollable()
boolean
Check if the view's scrollable property is currently true
isSelected()
boolean
Checks if the UI element's selected property is currently true.
longClick()
boolean
Long clicks the center of the visible bounds of the UI element
longClickBottomRight()
boolean
Long clicks bottom and right corner of the UI element
longClickTopLeft()
boolean
Long clicks on the top and left corner of the UI element
performMultiPointerGesture(PointerCoords... touches)
boolean
Performs a multi-touch gesture.
performTwoPointerGesture(Point startPoint1, Point startPoint2, Point
boolean endPoint1, Point endPoint2, int steps)
Generates a two-pointer gesture with arbitrary starting and ending points.
pinchIn(int percent, int steps)
boolean Performs a two-pointer gesture, where each pointer moves diagonally
toward the other, from the edges to the center of this UiObject .
pinchOut(int percent, int steps)
Performs a two-pointer gesture, where each pointer moves diagonally
boolean
opposite across the other, from the center out towards the edges of the this
UiObject.
setText(String text)
boolean
Sets the text in an editable field, after clearing the field's content.
swipeDown(int steps)
boolean
Performs the swipe down action on the UiObject.
swipeLeft(int steps)
boolean
Performs the swipe left action on the UiObject.
swipeRight(int steps)
boolean
Performs the swipe right action on the UiObject.
swipeUp(int steps)
boolean
Performs the swipe up action on the UiObject.
waitForExists(long timeout)
boolean
Waits a specified length of time for a view to become visible.
waitUntilGone(long timeout)
boolean
Waits a specified length of time for a view to become undetectable.
Protected Methods
findAccessibilityNodeInfo(long timeout)
AccessibilityNodeInfo Finds a matching UI element in the accessibility hierarchy, by
using the selector for this UiObject.
[Expand]
Inherited Methods
From class java.lang.Object
Constants
Public Constructors
Constructs a UiObject to represent a view that matches the specified selector criteria.
Public Methods
Clears the existing text contents in an editable field. The UiSelector of this object must
reference a UI element that is editable. When you call this method, the method first sets focus
at the start edge of the field. The method then simulates a long-press to select the existing
text, and deletes the selected text. If a "Select-All" option is displayed, the method will
automatically attempt to use it to ensure full text selection. Note that it is possible that not all
the text in the field is selected; for example, if the text contains separators such as spaces,
slashes, at symbol etc. Also, not all editable fields support the long-press functionality.
Throws
UiObjectNotFoundException
Performs a click at the center of the visible bounds of the UI element represented by this
UiObject.
Returns
Throws
UiObjectNotFoundException
Performs a click at the center of the visible bounds of the UI element represented by this
UiObject and waits for window transitions. This method differ from click() only in that
this method waits for a a new window transition as a result of the click. Some examples of a
window transition:
Parameters
Returns
Throws
UiObjectNotFoundException
Waits for window transitions that would typically take longer than the usual default timeouts.
See clickAndWaitForNewWindow(long)
Returns
Throws
UiObjectNotFoundException
Returns
true on success
Throws
UiObjectNotFoundException
public boolean clickTopLeft ()
Returns
true on success
Throws
UiObjectNotFoundException
Drags this object to a destination UiObject. The number of steps specified in your input
parameter can influence the drag speed, and varying speeds may impact the results. Consider
evaluating different speeds when using this method in your tests.
Parameters
Returns
true if successful
Throws
UiObjectNotFoundException
Since
Drags this object to arbitrary coordinates. The number of steps specified in your input
parameter can influence the drag speed, and varying speeds may impact the results. Consider
evaluating different speeds when using this method in your tests.
Parameters
Returns
true if successful
Throws
UiObjectNotFoundException
Since
Returns
Returns
Rect
Throws
UiObjectNotFoundException
Creates a new UiObject for a child view that is under the present UiObject.
Parameters
Returns
Throws
UiObjectNotFoundException
Returns
Throws
UiObjectNotFoundException
Returns
Throws
Since
Returns
Throws
UiObjectNotFoundException
Creates a new UiObject for a sibling view or a child of the sibling view, relative to the
present UiObject.
Parameters
Returns
UiObjectNotFoundException
Returns
Throws
UiObjectNotFoundException
Debugging helper. A test can dump the properties of a selector as a string to its logs if
needed. getSelector().toString();
Returns
UiSelector
Returns
Throws
Returns the visible bounds of the view. If a portion of the view is visible, only the bounds of
the visible portion are reported.
Returns
Rect
Throws
UiObjectNotFoundException
See Also
getBounds()
Since
Returns
Throws
UiObjectNotFoundException
Returns
Throws
UiObjectNotFoundException
Returns
Throws
UiObjectNotFoundException
Returns
true if it is else false
Throws
UiObjectNotFoundException
Returns
Throws
UiObjectNotFoundException
Returns
Throws
UiObjectNotFoundException
Returns
Throws
UiObjectNotFoundException
Returns
UiObjectNotFoundException
Returns
Throws
UiObjectNotFoundException
Returns
Throws
UiObjectNotFoundException
Returns
Throws
UiObjectNotFoundException
Returns
Throws
UiObjectNotFoundException
Performs a multi-touch gesture. You must specify touch coordinates for at least 2 pointers.
Each pointer must have all of its touch steps defined in an array of
MotionEvent.PointerCoords. You can use this method to specify complex gestures,
like circles and irregular shapes, where each pointer may take a different path. To create a
single point on a pointer's touch path: PointerCoords p = new PointerCoords(); p.x =
stepX; p.y = stepY; p.pressure = 1; p.size = 1;
Parameters
Returns
true if all touch events for this gesture are injected successfully, false otherwise
Since
Parameters
Returns
true if all touch events for this gesture are injected successfully, false otherwise
Since
Parameters
percent percentage of the object's diagonal length for the pinch gesture
the number of steps for the gesture. Steps are injected about 5 milliseconds apart, so
steps
100 steps may take around 0.5 seconds to complete.
Returns
true if all touch events for this gesture are injected successfully, false otherwise
Throws
UiObjectNotFoundException
Since
Performs a two-pointer gesture, where each pointer moves diagonally opposite across the
other, from the center out towards the edges of the this UiObject.
Parameters
percent percentage of the object's diagonal length for the pinch gesture
the number of steps for the gesture. Steps are injected about 5 milliseconds apart, so
steps
100 steps may take around 0.5 seconds to complete.
Returns
true if all touch events for this gesture are injected successfully, false otherwise
Throws
UiObjectNotFoundException
Since
Sets the text in an editable field, after clearing the field's content. The UiSelector selector
of this object must reference a UI element that is editable. When you call this method, the
method first simulates a click() on editable field to set focus. The method then clears the
field's contents and injects your specified text into the field. If you want to capture the
original contents of the field, call getText() first. You can then modify the text and use
this method to update the field.
Parameters
Returns
Throws
UiObjectNotFoundException
Performs the swipe down action on the UiObject. The swipe gesture can be performed over
any surface. The targeted UI element does not need to be scrollable. See also:
scrollToBeginning(int)
scrollToEnd(int)
scrollBackward()
scrollForward()
Parameters
indicates the number of injected move steps into the system. Steps are injected about
steps
5ms apart. So a 100 steps may take about 1/2 second to complete.
Returns
true if successful
Throws
UiObjectNotFoundException
Performs the swipe left action on the UiObject. The swipe gesture can be performed over any
surface. The targeted UI element does not need to be scrollable. See also:
scrollToBeginning(int)
scrollToEnd(int)
scrollBackward()
scrollForward()
Parameters
indicates the number of injected move steps into the system. Steps are injected about
steps
5ms apart. So a 100 steps may take about 1/2 second to complete.
Returns
true if successful
Throws
UiObjectNotFoundException
Performs the swipe right action on the UiObject. The swipe gesture can be performed over
any surface. The targeted UI element does not need to be scrollable. See also:
scrollToBeginning(int)
scrollToEnd(int)
scrollBackward()
scrollForward()
Parameters
indicates the number of injected move steps into the system. Steps are injected about
steps
5ms apart. So a 100 steps may take about 1/2 second to complete.
Returns
true if successful
Throws
UiObjectNotFoundException
scrollToBeginning(int)
scrollToEnd(int)
scrollBackward()
scrollForward()
Parameters
indicates the number of injected move steps into the system. Steps are injected about
steps
5ms apart. So a 100 steps may take about 1/2 second to complete.
Returns
true of successful
Throws
UiObjectNotFoundException
Waits a specified length of time for a view to become visible. This method waits until the
view becomes visible on the display, or until the timeout has elapsed. You can use this
method in situations where the content that you want to select is not immediately displayed.
Parameters
Returns
true if the view is displayed, else false if timeout elapsed while waiting
Waits a specified length of time for a view to become undetectable. This method waits until a
view is no longer matchable, or until the timeout has elapsed. A view becomes undetectable
when the UiSelector of the object is unable to find a match because the element has
either changed its state or is no longer displayed. You can use this method when attempting
to wait for some long operation to compete, such as downloading a large file or connecting to
a remote server.
Parameters
Returns
true if the element is gone before timeout elapsed, else false if timeout elapsed but a
matching element is still found.
Protected Methods
Finds a matching UI element in the accessibility hierarchy, by using the selector for this
UiObject.
Parameters
timeout in milliseconds
Returns
UiObjectNotFoundException
Generated in test runs when a UiSelector selector could not be matched to any UI element
displayed.
Summary
Public Constructors
UiObjectNotFoundException(String msg)
UiObjectNotFoundException(Throwable throwable)
[Expand]
Inherited Methods
Public Constructors
UiScrollable
A UiCollection that supports searching for items in scrollable layout elements. This class
can be used with horizontally or vertically scrollable controls.
Summary
[Expand]
Inherited Constants
Public Constructors
UiScrollable(UiSelector container)
Constructor.
Public Methods
flingBackward()
boolean
Performs a backwards fling action with the default number of fling steps (5).
flingForward()
boolean
Performs a forward fling with the default number of fling steps (5).
flingToBeginning(int maxSwipes)
boolean
Performs a fling gesture to reach the beginning of a scrollable layout element.
flingToEnd(int maxSwipes)
boolean
Performs a fling gesture to reach the end of a scrollable layout element.
getMaxSearchSwipes()
int Gets the maximum number of scrolls allowed when performing a scroll action in
search of a child element.
getSwipeDeadZonePercentage()
double Returns the percentage of a widget's size that's considered as a no-touch zone
when swiping.
scrollBackward(int steps)
boolean
Performs a backward scroll.
scrollBackward()
boolean
Performs a backward scroll with the default number of scroll steps (55).
scrollDescriptionIntoView(String text)
boolean Performs a forward scroll action on the scrollable layout element until the
content-description is found, or until swipe attempts have been exhausted.
scrollForward()
boolean
Performs a forward scroll with the default number of scroll steps (55).
scrollForward(int steps)
boolean
Performs a forward scroll.
scrollIntoView(UiSelector selector)
boolean Perform a scroll forward action to move through the scrollable layout element
until a visible item that matches the selector is found.
scrollIntoView(UiObject obj)
boolean Perform a forward scroll action to move through the scrollable layout element
until a visible item that matches the UiObject is found.
scrollTextIntoView(String text)
boolean Performs a forward scroll action on the scrollable layout element until the text
you provided is visible, or until swipe attempts have been exhausted.
scrollToEnd(int maxSwipes)
boolean
Scrolls to the end of a scrollable layout element.
setAsHorizontalList()
UiScrollable
Set the direction of swipes to be horizontal when performing scroll actions.
setAsVerticalList()
UiScrollable
Set the direction of swipes to be vertical when performing scroll actions.
setMaxSearchSwipes(int swipes)
UiScrollable Sets the maximum number of scrolls allowed when performing a scroll action in
search of a child element.
setSwipeDeadZonePercentage(double swipeDeadZonePercentage)
UiScrollable Sets the percentage of a widget's size that's considered as no-touch zone when
swiping.
Protected Methods
exists(UiSelector selector)
boolean Used privately when performing swipe searches to decide if an element has become
visible or not.
[Expand]
Inherited Methods
Constructor.
Parameters
container a UiSelector selector to identify the scrollable layout element.
Public Methods
Performs a backwards fling action with the default number of fling steps (5). If the swipe
direction is set to vertical, then the swipe will be performed from top to bottom. If the swipe
direction is set to horizontal, then the swipes will be performed from left to right. Make sure
to take into account devices configured with right-to-left languages like Arabic and Hebrew.
Returns
Throws
UiObjectNotFoundException
Performs a forward fling with the default number of fling steps (5). If the swipe direction is
set to vertical, then the swipes will be performed from bottom to top. If the swipe direction is
set to horizontal, then the swipes will be performed from right to left. Make sure to take into
account devices configured with right-to-left languages like Arabic and Hebrew.
Returns
Throws
UiObjectNotFoundException
Performs a fling gesture to reach the beginning of a scrollable layout element. The beginning
can be at the top-most edge in the case of vertical controls, or the left-most edge for
horizontal controls. Make sure to take into account devices configured with right-to-left
languages like Arabic and Hebrew.
Returns
Throws
UiObjectNotFoundException
Performs a fling gesture to reach the end of a scrollable layout element. The end can be at the
bottom-most edge in the case of vertical controls, or the right-most edge for horizontal
controls. Make sure to take into account devices configured with right-to-left languages like
Arabic and Hebrew.
Returns
Throws
UiObjectNotFoundException
Searches for a child element in the present scrollable container. The search first looks for a
child element that matches the selector you provided, then looks for the content-description in
its children elements. If both search conditions are fulfilled, the method returns a {@ link
UiObject} representing the element matching the selector (not the child element in its
subhierarchy containing the content-description).
Parameters
childPattern UiSelector for a child in a scollable layout element
Returns
UiObject representing the child element that matches the search conditions
Throws
UiObjectNotFoundException
Searches for a child element in the present scrollable container. The search first looks for a
child element that matches the selector you provided, then looks for the content-description in
its children elements. If both search conditions are fulfilled, the method returns a {@ link
UiObject} representing the element matching the selector (not the child element in its
subhierarchy containing the content-description). By default, this method performs a scroll
search. See getChildByDescription(UiSelector, String, boolean)
Parameters
childPattern UiSelector for a child in a scollable layout element
Returns
UiObject representing the child element that matches the search conditions
Throws
UiObjectNotFoundException
Searches for a child element in the present scrollable container that matches the selector you
provided. The search is performed without scrolling and only on visible elements.
Parameters
childPattern UiSelector for a child in a scollable layout element
Returns
UiObject representing the child element that matches the search conditions
Throws
UiObjectNotFoundException
public UiObject getChildByText (UiSelector childPattern, String text, boolean
allowScrollSearch)
Searches for a child element in the present scrollable container. The search first looks for a
child element that matches the selector you provided, then looks for the text in its children
elements. If both search conditions are fulfilled, the method returns a {@ link UiObject}
representing the element matching the selector (not the child element in its subhierarchy
containing the text).
Parameters
childPattern UiSelector selector for a child in a scrollable layout element
Returns
UiObject representing the child element that matches the search conditions
Throws
UiObjectNotFoundException
Searches for a child element in the present scrollable container. The search first looks for a
child element that matches the selector you provided, then looks for the text in its children
elements. If both search conditions are fulfilled, the method returns a {@ link UiObject}
representing the element matching the selector (not the child element in its subhierarchy
containing the text). By default, this method performs a scroll search. See
getChildByText(UiSelector, String, boolean)
Parameters
childPattern UiSelector selector for a child in a scrollable layout element
Returns
UiObject representing the child element that matches the search conditions
Throws
UiObjectNotFoundException
public int getMaxSearchSwipes ()
Gets the maximum number of scrolls allowed when performing a scroll action in search of a
child element. See getChildByDescription(UiSelector, String) and
getChildByText(UiSelector, String).
Returns
Returns the percentage of a widget's size that's considered as a no-touch zone when swiping.
The no-touch zone is set as a percentage of a widget's total width or height, denoting a
margin around the swipable area of the widget. Swipes must start and end inside this margin.
This is important when the widget being swiped may not respond to the swipe if started at a
point too near to the edge. The default is 10% from either edge.
Returns
Performs a backward scroll. If the swipe direction is set to vertical, then the swipes will be
performed from top to bottom. If the swipe direction is set to horizontal, then the swipes will
be performed from left to right. Make sure to take into account devices configured with right-
to-left languages like Arabic and Hebrew.
Parameters
steps number of steps. Use this to control the speed of the scroll action.
Returns
Throws
UiObjectNotFoundException
Performs a backward scroll with the default number of scroll steps (55). If the swipe direction
is set to vertical, then the swipes will be performed from top to bottom. If the swipe direction
is set to horizontal, then the swipes will be performed from left to right. Make sure to take
into account devices configured with right-to-left languages like Arabic and Hebrew.
Returns
Throws
UiObjectNotFoundException
Performs a forward scroll action on the scrollable layout element until the content-description
is found, or until swipe attempts have been exhausted. See setMaxSearchSwipes(int)
Parameters
text content-description to find within the contents of this scrollable layout element.
Returns
Throws
UiObjectNotFoundException
Performs a forward scroll with the default number of scroll steps (55). If the swipe direction
is set to vertical, then the swipes will be performed from bottom to top. If the swipe direction
is set to horizontal, then the swipes will be performed from right to left. Make sure to take
into account devices configured with right-to-left languages like Arabic and Hebrew.
Returns
Throws
UiObjectNotFoundException
Performs a forward scroll. If the swipe direction is set to vertical, then the swipes will be
performed from bottom to top. If the swipe direction is set to horizontal, then the swipes will
be performed from right to left. Make sure to take into account devices configured with right-
to-left languages like Arabic and Hebrew.
Parameters
steps number of steps. Use this to control the speed of the scroll action
Returns
Throws
UiObjectNotFoundException
Perform a scroll forward action to move through the scrollable layout element until a visible
item that matches the selector is found. See scrollDescriptionIntoView(String) and
scrollTextIntoView(String).
Parameters
selector UiSelector selector
Returns
true if the item was found and now is in view; else, false
Throws
UiObjectNotFoundException
Perform a forward scroll action to move through the scrollable layout element until a visible
item that matches the UiObject is found.
Parameters
obj UiObject
Returns
true if the item was found and now is in view else false
Throws
UiObjectNotFoundException
public boolean scrollTextIntoView (String text)
Performs a forward scroll action on the scrollable layout element until the text you provided
is visible, or until swipe attempts have been exhausted. See setMaxSearchSwipes(int)
Parameters
text test to look for
Returns
Throws
UiObjectNotFoundException
Scrolls to the beginning of a scrollable layout element. The beginning can be at the top-most
edge in the case of vertical controls, or the left-most edge for horizontal controls. Make sure
to take into account devices configured with right-to-left languages like Arabic and Hebrew.
Returns
Throws
UiObjectNotFoundException
Scrolls to the beginning of a scrollable layout element. The beginning can be at the top-most
edge in the case of vertical controls, or the left-most edge for horizontal controls. Make sure
to take into account devices configured with right-to-left languages like Arabic and Hebrew.
Parameters
steps use steps to control the speed, so that it may be a scroll, or fling
Returns
Throws
UiObjectNotFoundException
public boolean scrollToEnd (int maxSwipes, int steps)
Scrolls to the end of a scrollable layout element. The end can be at the bottom-most edge in
the case of vertical controls, or the right-most edge for horizontal controls. Make sure to take
into account devices configured with right-to-left languages like Arabic and Hebrew.
Parameters
steps use steps to control the speed, so that it may be a scroll, or fling
Returns
Throws
UiObjectNotFoundException
Scrolls to the end of a scrollable layout element. The end can be at the bottom-most edge in
the case of vertical controls, or the right-most edge for horizontal controls. Make sure to take
into account devices configured with right-to-left languages like Arabic and Hebrew.
Returns
Throws
UiObjectNotFoundException
Returns
reference to itself
Returns
reference to itself
public UiScrollable setMaxSearchSwipes (int swipes)
Sets the maximum number of scrolls allowed when performing a scroll action in search of a
child element. See getChildByDescription(UiSelector, String) and
getChildByText(UiSelector, String).
Parameters
swipes the number of search swipes to perform until giving up
Returns
reference to itself
Sets the percentage of a widget's size that's considered as no-touch zone when swiping. The
no-touch zone is set as percentage of a widget's total width or height, denoting a margin
around the swipable area of the widget. Swipes must always start and end inside this margin.
This is important when the widget being swiped may not respond to the swipe if started at a
point too near to the edge. The default is 10% from either edge.
Parameters
swipeDeadZonePercentage is a value between 0 and 1
Returns
reference to itself
Protected Methods
Used privately when performing swipe searches to decide if an element has become visible or
not.
Returns
UiSelector
Specifies the elements in the layout hierarchy for tests to target, filtered by properties such as
text value, content-description, class name, and state information. You can also target an
element by its location in a layout hierarchy.
Summary
Public Constructors
UiSelector()
Public Methods
checkable(boolean val)
UiSelector
Set the search criteria to match widgets that are checkable.
checked(boolean val)
UiSelector Set the search criteria to match widgets that are currently checked (usually for
checkboxes).
childSelector(UiSelector selector)
UiSelector
Adds a child UiSelector criteria to this selector.
className(String className)
UiSelector Set the search criteria to match the class property for a widget (for example,
"android.widget.Button").
className(Class<T> type)
<T>
UiSelector Set the search criteria to match the class property for a widget (for example,
"android.widget.Button").
classNameMatches(String regex)
UiSelector Set the search criteria to match the class property for a widget, using a regular
expression.
clickable(boolean val)
UiSelector
Set the search criteria to match widgets that are clickable.
description(String desc)
UiSelector
Set the search criteria to match the content-description property for a widget.
descriptionContains(String desc)
UiSelector
Set the search criteria to match the content-description property for a widget.
descriptionMatches(String regex)
UiSelector
Set the search criteria to match the content-description property for a widget.
descriptionStartsWith(String desc)
UiSelector
Set the search criteria to match the content-description property for a widget.
enabled(boolean val)
UiSelector
Set the search criteria to match widgets that are enabled.
focusable(boolean val)
UiSelector
Set the search criteria to match widgets that are focusable.
focused(boolean val)
UiSelector
Set the search criteria to match widgets that have focus.
fromParent(UiSelector selector)
UiSelector Adds a child UiSelector criteria to this selector which is used to start search from
the parent widget.
index(int index)
UiSelector Set the search criteria to match the widget by its node index in the layout
hierarchy.
instance(int instance)
UiSelector
Set the search criteria to match the widget by its instance number.
longClickable(boolean val)
UiSelector
Set the search criteria to match widgets that are long-clickable.
packageName(String name)
UiSelector Set the search criteria to match the package name of the application that contains
the widget.
packageNameMatches(String regex)
UiSelector Set the search criteria to match the package name of the application that contains
the widget.
resourceIdMatches(String regex)
UiSelector Set the search criteria to match the resource ID of the widget, using a regular
expression.
scrollable(boolean val)
UiSelector
Set the search criteria to match widgets that are scrollable.
selected(boolean val)
UiSelector
Set the search criteria to match widgets that are currently selected.
text(String text)
UiSelector Set the search criteria to match the visible text displayed in a widget (for example,
the text label to launch an app).
textContains(String text)
UiSelector Set the search criteria to match the visible text in a widget where the visible text
must contain the string in your input argument.
textMatches(String regex)
UiSelector Set the search criteria to match the visible text displayed in a layout element,
using a regular expression.
textStartsWith(String text)
UiSelector Set the search criteria to match visible text in a widget that is prefixed by the text
parameter.
String toString()
Protected Methods
UiSelector cloneSelector()
[Expand]
Inherited Methods
Public Constructors
public UiSelector ()
Public Methods
Set the search criteria to match widgets that are checkable. Typically, using this search
criteria alone is not useful. You should also include additional criteria, such as text, content-
description, or the class name for a widget. If no other search criteria is specified, and there is
more than one matching widget, the first widget in the tree is selected.
Parameters
val Value to match
Returns
Since
Set the search criteria to match widgets that are currently checked (usually for checkboxes).
Typically, using this search criteria alone is not useful. You should also include additional
criteria, such as text, content-description, or the class name for a widget. If no other search
criteria is specified, and there is more than one matching widget, the first widget in the tree is
selected.
Parameters
val Value to match
Returns
Adds a child UiSelector criteria to this selector. Use this selector to narrow the search scope
to child widgets under a specific parent widget.
Returns
Set the search criteria to match the class property for a widget (for example,
"android.widget.Button").
Parameters
className Value to match
Returns
Since
Set the search criteria to match the class property for a widget (for example,
"android.widget.Button").
Parameters
type type
Returns
Set the search criteria to match the class property for a widget, using a regular expression.
Parameters
regex a regular expression
Returns
Since
Set the search criteria to match widgets that are clickable. Typically, using this search criteria
alone is not useful. You should also include additional criteria, such as text, content-
description, or the class name for a widget. If no other search criteria is specified, and there is
more than one matching widget, the first widget in the tree is selected.
Parameters
val Value to match
Returns
Set the search criteria to match the content-description property for a widget. The content-
description is typically used by the Android Accessibility framework to provide an audio
prompt for the widget when the widget is selected. The content-description for the widget
must match exactly with the string in your input argument. Matching is case-sensitive.
Parameters
desc Value to match
Returns
Set the search criteria to match the content-description property for a widget. The content-
description is typically used by the Android Accessibility framework to provide an audio
prompt for the widget when the widget is selected. The content-description for the widget
must contain the string in your input argument. Matching is case-insensitive.
Parameters
desc Value to match
Returns
Set the search criteria to match the content-description property for a widget. The content-
description is typically used by the Android Accessibility framework to provide an audio
prompt for the widget when the widget is selected. The content-description for the widget
must match exactly with the string in your input argument.
Parameters
regex a regular expression
Returns
Since
Set the search criteria to match the content-description property for a widget. The content-
description is typically used by the Android Accessibility framework to provide an audio
prompt for the widget when the widget is selected. The content-description for the widget
must start with the string in your input argument. Matching is case-insensitive.
Parameters
desc Value to match
Returns
Set the search criteria to match widgets that are enabled. Typically, using this search criteria
alone is not useful. You should also include additional criteria, such as text, content-
description, or the class name for a widget. If no other search criteria is specified, and there is
more than one matching widget, the first widget in the tree is selected.
Parameters
val Value to match
Returns
Set the search criteria to match widgets that are focusable. Typically, using this search criteria
alone is not useful. You should also include additional criteria, such as text, content-
description, or the class name for a widget. If no other search criteria is specified, and there is
more than one matching widget, the first widget in the tree is selected.
Parameters
val Value to match
Returns
Set the search criteria to match widgets that have focus. Typically, using this search criteria
alone is not useful. You should also include additional criteria, such as text, content-
description, or the class name for a widget. If no other search criteria is specified, and there is
more than one matching widget, the first widget in the tree is selected.
Parameters
val Value to match
Returns
Adds a child UiSelector criteria to this selector which is used to start search from the parent
widget. Use this selector to narrow the search scope to sibling widgets as well all child
widgets under a parent.
Returns
Set the search criteria to match the widget by its node index in the layout hierarchy. The
index value must be 0 or greater. Using the index can be unreliable and should only be used
as a last resort for matching. Instead, consider using the instance(int) method.
Parameters
index Value to match
Returns
Set the search criteria to match the widget by its instance number. The instance value must be
0 or greater, where the first instance is 0. For example, to simulate a user click on the third
image that is enabled in a UI screen, you could specify a a search criteria where the instance
is 2, the className(String) matches the image widget class, and enabled(boolean) is
true. The code would look like this: new
UiSelector().className("android.widget.ImageView")
.enabled(true).instance(2);
Parameters
instance Value to match
Returns
Set the search criteria to match widgets that are long-clickable. Typically, using this search
criteria alone is not useful. You should also include additional criteria, such as text, content-
description, or the class name for a widget. If no other search criteria is specified, and there is
more than one matching widget, the first widget in the tree is selected.
Parameters
val Value to match
Returns
Since
Set the search criteria to match the package name of the application that contains the widget.
Parameters
name Value to match
Returns
Set the search criteria to match the package name of the application that contains the widget.
Parameters
regex a regular expression
Returns
Since
Parameters
id Value to match
Returns
Since
Set the search criteria to match the resource ID of the widget, using a regular expression.
Parameters
regex a regular expression
Returns
Since
Set the search criteria to match widgets that are scrollable. Typically, using this search
criteria alone is not useful. You should also include additional criteria, such as text, content-
description, or the class name for a widget. If no other search criteria is specified, and there is
more than one matching widget, the first widget in the tree is selected.
Parameters
val Value to match
Returns
Set the search criteria to match widgets that are currently selected. Typically, using this
search criteria alone is not useful. You should also include additional criteria, such as text,
content-description, or the class name for a widget. If no other search criteria is specified, and
there is more than one matching widget, the first widget in the tree is selected.
Parameters
val Value to match
Returns
Set the search criteria to match the visible text displayed in a widget (for example, the text
label to launch an app). The text for the element must match exactly with the string in your
input argument. Matching is case-sensitive.
Parameters
text Value to match
Returns
Set the search criteria to match the visible text in a widget where the visible text must contain
the string in your input argument. The matching is case-sensitive.
Parameters
text Value to match
Returns
Set the search criteria to match the visible text displayed in a layout element, using a regular
expression. The text in the widget must match exactly with the string in your input argument.
Parameters
regex a regular expression
Returns
Since
Set the search criteria to match visible text in a widget that is prefixed by the text parameter.
The matching is case-insensitive.
Parameters
text Value to match
Returns
Protected Methods
Since
Summary
Public Methods
checkForCondition()
abstract
boolean The testing framework calls this handler method automatically when the framework
is unable to find a match using the UiSelector.
Public Methods
The testing framework calls this handler method automatically when the framework is unable
to find a match using the UiSelector. When a match is not found after a predetermined time
has elapsed, the framework calls the checkForCondition() method of all registered watchers
on the device. You can use this method to handle known blocking issues that are preventing
the test from proceeding. For example, you can check if a dialog appeared that is blocking the
the test, then close the dialog or perform some other appropriate action to allow the test to
continue.
Returns
zipalign
zipalign is an archive alignment tool that provides important optimization to Android
application (.apk) files. The purpose is to ensure that all uncompressed data starts with a
particular alignment relative to the start of the file. Specifically, it causes all uncompressed
data within the .apk, such as images or raw files, to be aligned on 4-byte boundaries. This
allows all portions to be accessed directly with mmap() even if they contain binary data with
alignment restrictions. The benefit is a reduction in the amount of RAM consumed when
running the application.
This tool should always be used to align your .apk file before distributing it to end-users. The
Android build tools can handle this for you. When using Eclipse with the ADT plugin, the
Export Wizard will automatically zipalign your .apk after it signs it with your private key.
The build scripts used when compiling your application with Ant will also zipalign your .apk,
as long as you have provided the path to your keystore and the key alias in your project
ant.properties file, so that the build tools can sign the package first.
Caution: zipalign must only be performed after the .apk file has been signed with your
private key. If you perform zipalign before signing, then the signing procedure will undo the
alignment. Also, do not make alterations to the aligned package. Alterations to the archive,
such as renaming or deleting entries, will potentially disrupt the alignment of the modified
entry and all later entries. And any files added to an "aligned" archive will not be aligned.
The adjustment is made by altering the size of the "extra" field in the zip Local File Header
sections. Existing data in the "extra" fields may be altered by this process.
For more information about how to use zipalign when building your application, please read
Signing Your Application.
Usage
The <alignment> is an integer that defines the byte-alignment boundaries. This must always
be 4 (which provides 32-bit alignment) or else it effectively does nothing.
Flags:
See also
Getting Started with Android Studio
Android Studio Basics
Migrating from Eclipse
Video
The Android build system is the toolkit you use to build, test, run and package your apps. The
build system can run as an integrated tool from the Android Studio menu and independently
from the command line. You can use the features of the build system to:
The flexibility of the Android build system enables you to achieve all of this without
modifying your app's core source files. To build an Android Studio project, see Building and
Running from Android Studio. To configure custom build settings in an Android Studio
project, see Configuring Gradle Builds.
The build process involves many tools and processes that generate intermediate files on the
way to producing an .apk. If you are developing in Android Studio, the complete build
process is done every time you run the Gradle build task for your project or modules. The
build process is very flexible so it's useful, however, to understand what is happening under
the hood since much of the build process is configurable and extensible. The following
diagram depicts the different tools and processes that are involved in a build:
The general process for a typical build is outlined below. The build system merges all the
resources from the configured product flavors, build types, and dependencies. If different
folders contain resources with the same name or setting, the following override priority order
is: dependencies override build types, which override product flavors, which override the
main source directory.
The Android Asset Packaging Tool (aapt) takes your application resource files, such
as the AndroidManifest.xml file and the XML files for your Activities, and
compiles them. An R.java is also produced so you can reference your resources from
your Java code.
The aidl tool converts any .aidl interfaces that you have into Java interfaces.
All of your Java code, including the R.java and .aidl files, are compiled by the Java
compiler and .class files are output.
The dex tool converts the .class files to Dalvik byte code. Any 3rd party libraries and
.class files that you have included in your module build are also converted into .dex
files so that they can be packaged into the final .apk file.
All non-compiled resources (such as images), compiled resources, and the .dex files
are sent to the apkbuilder tool to be packaged into an .apk file.
Once the .apk is built, it must be signed with either a debug or release key before it
can be installed to a device.
Finally, if the application is being signed in release mode, you must align the .apk
with the zipalign tool. Aligning the final .apk decreases memory usage when the
application is -running on a device.
Note: Apps are limited to a 64K method reference limit. If your app reaches this limit, the
build process outputs the following error message:
Build output
The build generates an APK for each build variant in the app/build folder: the
app/build/outputs/apk/ directory contains packages named app-<flavor>-
<buildtype>.apk; for example, app-full-release.apk and app-demo-debug.apk.
This section builds on the Build System Overview and Build and Running from Android
Studio to show you how to use build variants based on product flavors and build types.
Android Studio projects contain a top-level build file and a build file for each module. The
build files are called build.gradle, and they are plain text files that use Groovy syntax to
configure the build with the elements provided by the Android plugin for Gradle. In most
cases, you only need to edit the build files at the module level. For example, the build file for
the app module in the BuildSystemExample project looks like this:
android {
compileSdkVersion 19
buildToolsVersion "19.0.0"
defaultConfig {
minSdkVersion 8
targetSdkVersion 19
versionCode 1
versionName "1.0"
}
buildTypes {
release {
minifyEnabled true
proguardFiles getDefaultProguardFile('proguard-android.txt'), \
'proguard-rules.txt'
}
}
}
dependencies {
compile project(":lib")
compile 'com.android.support:appcompat-v7:19.0.1'
compile fileTree(dir: 'libs', include: ['*.jar'])
}
apply plugin: 'com.android.application' applies the Android plugin for Gradle to this
build. This adds Android-specific build tasks to the top-level build tasks and makes the
android {...} element available to specify Android-specific build options.
The defaultConfig element configures core settings and entries in the manifest file
(AndroidManifest.xml) dynamically from the build system. The values in
defaultConfig override those in the manifest file.
The buildTypes element controls how to build and package your app. By default, the build
system defines two build types: debug and release. The debug build type includes debugging
symbols and is signed with the debug key. The release build type is not signed by default. In
this example the build file configures the release version to use ProGuard.
The dependencies element is outside and after the android element. This element declares
the dependencies for this module. Dependencies are covered in the following sections.
Note: When you make changes to the build files in your project, Android Studio requires a
project sync to import the build configuration changes. Click Sync Now on the yellow
notification bar that appears for Android Studio to import the changes.
Declare dependencies
...
dependencies {
// Module dependency
compile project(":lib")
Each of these dependencies is described below. The build system adds all the compile
dependencies to the compilation classpath and includes them in the final package.
Module dependencies
The app module depends on the lib module, because MainActivity launches
LibActivity1 as described in Open an Activity from a Library Module.
The app and lib modules both use the ActionBarActivity class from the Android Support
Library, so these modules depend on it.
Android Studio configures projects to use the Maven Central Repository by default. (This
configuration is included in the top-level build file for the project.)
Some modules do not use any binary dependencies from the local file system. If you have
modules that require local binary dependencies, copy the JAR files for these dependencies
into <moduleName>/libs inside your project.
compile fileTree(dir: 'libs', include: ['*.jar']) tells the build system that any
JAR file inside app/libs is a dependency and should be included in the compilation
classpath and in the final package.
For more information about dependencies in Gradle, see Dependency Management Basics in
the Gradle User Guide.
Run ProGuard
The build system can run ProGuard to obfuscate your classes during the build process. In
BuildSystemExample, modify the build file for the app module to run ProGuard for the
release build:
...
android {
...
buildTypes {
release {
minifyEnabled true
proguardFiles getDefaultProguardFile('proguard-android.txt'), \
'proguard-rules.txt'
}
}
}
...
The debug and the release versions of the app differ on whether the application can be
debugged on secure devices and on how the APK is signed. The build system signs the debug
version with a default key and certificate using known credentials to avoid a password
prompt at build time. The build system does not sign the release version unless you explicitly
define a signing configuration for this build. If you do not have a release key, you can
generate one as described in Signing your Applications.
This section describes how the build system can help you create different versions of the
same application from a single project. This is useful when you have a demo version and a
paid version of your app, or if you want to distribute multiple APKs for different device
configurations on Google Play.
The build system uses product flavors to create different product versions of your app. Each
product version of your app can have different features or device requirements. The build
system also uses build types to apply different build and packaging settings to each product
version. Each product flavor and build type combination forms a build variant. The build
system generates a different APK for each build variant of your app.
Build variants
This example project consists of the two default build types (debug and release) and two
product flavors for app type (demo and full). For more information on advanced uses of build
variants, see Build System Overview .
Product flavors
The rest of this section walks you through these steps in detail using a BuildSystemExample
project. You create two flavors of the BuildSystemExample app, a demo flavor and a full
flavor. Both flavors share MainActivity, to which you add a new button to launch a new
activity, SecondActivity. This new activity is different for each flavor, so you simulate a
situation where the new activity would have more features in the full flavor than in the demo
flavor. At the end of the exercise, you end up with two different APKs, one for each flavor.
To define two product flavors, edit the build file for the app module to add the following
configuration:
...
android {
...
defaultConfig { ... }
signingConfigs { ... }
buildTypes { ... }
productFlavors {
demo {
applicationId "com.buildsystemexample.app.demo"
versionName "1.0-demo"
}
full {
applicationId "com.buildsystemexample.app.full"
versionName "1.0-full"
}
}
}
...
The product flavor definitions support the same properties as the defaultConfig element.
The base configuration for all flavors is specified in defaultConfig, and each flavor
overrides any default values. The build file above uses the applicationId property to assign
a different package name to each flavor: since each flavor definition creates a different app,
they each need a distinct package name.
Note: To distribute your app using Multiple APK Support in Google Play, assign the same
package name to all variants and give each variant a different versionCode. To distribute
different variants of your app as separate apps in Google Play, assign a different package
name to each variant.
Now you create source folders and add a SecondActivity to each flavor. To create the
source directory structure for the demo flavor:
1. On the Project panel, expand BuildSystemExample, and then expand the app directory.
2. Right-click the src directory under app and select New > Directory.
3. Enter "demo" as the name of the new directory and click OK.
4. Similarly, create the following directories:
o app/src/demo/java
o app/src/demo/res
o app/src/demo/res/layout
o app/src/demo/res/values
1. On the Project panel, right click on the app module and select New > Activity.
2. Select Blank Activity and click Next.
3. Enter "SecondActivity" as the activity name.
4. Enter "com.buildsystemexample.app" as the package name and click Finish.
5. Right click on the java directory under app/src/demo and select New > Package.
6. Enter "com.buildsystemexample.app" as the package name and click OK.
7. Drag SecondActivity and drop it under the new package in app/src/demo/java.
8. Accept the default values and click Refactor.
To add the layout for SecondActivity and a strings resource to the demo flavor:
Now you add source folders and SecondActivity to the full flavor by making a copy of the
demo flavor:
1. On the Project panel, right click on the demo directory under app/src and select Copy.
2. Right-click on the src/ directory under app/ and select Paste.
3. On the window that appears, enter "full" as the new name and click OK.
4. Replace the contents of strings.xml under src/full/res/values with the following:
Note: From this point on, you could develop SecondActivity independently inside each
flavor. For example, you could add more features to this activity in the full flavor.
To work on files from a particular flavor, click on Build Variants on the left of the IDE
window and select the flavor you want to modify in the Build Variants panel, as shown in
figure 2. Android Studio may show errors in source files from flavors other than the one
selected in the Build Variants panel, but this does not affect the outcome of the build.
Since the flavor-specific activity (SecondActivity) has the same package name and activity
name in both flavors, you can launch it from the main activity, which is common to all
flavors. To modify the main activity:
<LinearLayout ...>
...
<Button
android:id="@+id/button2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/button2"
android:onClick="onButton2Clicked"/>
</LinearLayout>
2. Click on the areas marked in red in the layout file and press Alt+ Enter. Follow the
suggestions from Android Studio to add a new string resource with value “Open Second
Activity” and an onButton2Clicked method to MainActivity.
3. Add the following code to the onButton2Clicked method of MainActivity:
Build types
Build types represent the build packaging versions generated for each app package. By
default, the debug and release build types are provided.
...
android {
...
defaultConfig { ... }
signingConfigs { ... }
buildTypes { ... }
productFlavors {...}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'),
'proguard-rules.pro'
}
debug {
debuggable true
}
}
}
...
Note: Although only the release build type appears in the default build.gradle file, both the
release and debug build types are applied to each build.
In this example, the product flavors and build types create the following build variants:
demoDebug
demoRelease
fullDebug
fullRelease
To build this example, invoke the assemble task from Android Studio or from the command
line.
See also
Build System Overview
Buidling and Running
Building and Running from Android Studio
Download
Plugin Language Reference
android-gradle-plugin-dsl.zip
The Android build system consists of an Android plugin for Gradle. Gradle is an advanced
build toolkit that manages dependencies and allows you to define custom build logic.
Android Studio uses a Gradle wrapper to fully integrate the Android plugin for Gradle. The
Android plugin for Gradle also runs independent of Android Studio. This means that you can
build your Android apps from which Android Studio and from the command line on your
machine or on machines where Android Studio is not installed (such as continuous
integration servers).
The output of the build is the same whether you are building a project from the command
line, on a remote machine, or using Android Studio.
Build configuration
The build configuration for your project is defined inside build.gradle files, which are
plain text files that use the syntax and options from Gradle and the Android plugin to
configure the following aspects of your build:
Build variants. The build system can generate multiple APKs with different product
and build configurations for the same module. This is useful when you want to build
different versions of your application without having to create a separate projects or
modules for each version.
Dependencies. The build system manages project dependencies and supports
dependencies from your local filesystem and from remote repositories. This prevents
you from having to search, download, and copy binary packages for your
dependencies into your project directory.
Manifest entries. The build system enables you to specify values for some elements of
the manifest file in the build variant configuration. These build values override the
existing values in the manifest file. This is useful if you want to generate multiple
APKs for your modules where each of the apk files has a different application name,
minimum SDK version, or target SDK version. When multiple manifests are present,
manifest settings are merged in priority of buildType and productFlavor, /main
manifest, and the library manifests.
Signing. The build system enables you to specify signing settings in the build
configuration, and it can sign your APKs during the build process.
ProGuard. The build system enables you to specify a different ProGuard rules file for
each build variant. The build system can run ProGuard to obfuscate your classes
during the build process.
Testing. For most templates, the build system creates a test directory, androidTest and
generates a test APK from the test sources in your project, so you do not have to
create a separate test project. The build system can also run your tests during the build
process.
Gradle build files use Domain Specific Language (DSL) to describe and manipulate the build
logic through Groovy syntax. Groovy is a dynamic language that you can use to define
custom build logic and to interact with the Android-specific elements provided by the
Android plugin for Gradle.
Build by convention
The Android Studio build system assumes sensible defaults for the project structure and other
build options. If your project adheres to these conventions, your Gradle build files are very
simple. When some of these conventions do not apply to your project, the flexibility of the
build system allows you to configure almost every aspect of the build process. For example,
if you need to replace the default source folders in your module directories, you can configure
a new directory structure in the module's build file.
A project in Android Studio represents the top-level Android development structure. Android
Studio projects contain project files and one or more application modules. A module is a
component of your app that you can build, test, or debug independently. Modules contain the
source code and resources for your apps. Android Studio projects can contain several kinds of
modules:
Android application modules contain application (mobile, TV, Wear, Glass) code and
may depend on library modules, although many Android apps consists of only one
application module. The build system generates APK packages for application
modules.
Android library modules contain reusable Android-specific code and resources. The
build system generates an AAR (Android ARchive) package for library modules.
App Engine modules contain code and resources for App Engine integration.
Java library modules contain reusable code. The build system generates a JAR
package for Java library modules.
Android Studio projects contain a top-level project Gradle build file that allows you to add
the configuration options common to all application modules in the project. Each application
module also has its own build.gradle file for build settings specific to that module.
buildscript {
repositories {
jcenter()
}
dependencies {
classpath 'com.android.tools.build:gradle:1.0.1'
allprojects {
repositories {
jcenter()
}
}
Note: The SDK location for the Android Studio project is defined in the local.properties file
in the sdk.dir setting or through an ANDROID_HOME environment variable.
The application module Gradle build file allows you to configure module build settings,
including overriding the src/main manifest settings and setting custom packaging options.
android settings
o compileSdkVersion
o buildToolsVersion
defaultConfig and productFlavors
o manifest properties such as applicationId, minSdkVersion, targetSdkVersion,
and test information
buildTypes
o build properties such as debuggable, ProGuard enabling, debug signing,
version name suffix and testinformation
dependencies
This example applies the Android plugin, uses the default configuration to override several
manifest properties, creates two build types: release and debug, and declares several
dependencies.
android {
compileSdkVersion 20
buildToolsVersion "20.0.0"
defaultConfig {
applicationId "com.mycompany.myapplication"
minSdkVersion 13
targetSdkVersion 20
versionCode 1
versionName "1.0"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'),
'proguard-rules.pro'
}
debug {
debuggable true
}
}
}
dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
compile 'com.android.support:appcompat-v7:20.0.0'
compile project(path: ':app2, configuration: 'android-endpoints')
}
Note: You can inject custom build logic for property values defined by a function that gets
called by the property, for example:
def computeVersionName() {
...
}
android {
defaultConfig {
versionName computeVersionName()
...
}
}
Dependencies
The Android Studio build system manages project dependencies and supports module
dependencies, local binary dependencies, and remote binary dependencies.
Module Dependencies
An application module can include in its build file a list of other modules it depends
on. When you build this module, the build system assembles and includes the required
modules.
Local Dependencies
If you have binary archives in your local filesystem that a module depends on, such as
JAR files, you can declare these dependencies in the build file for that module.
Remote Dependencies
When some of your dependencies are available in a remote repository, you do not
have to download them and copy them into your project. The Android Studio build
system supports remote dependencies from repositories, such as Maven, and
dependency managers, such as Ivy.
Many popular software libraries and tools are available in public Maven repositories.
For these dependencies you only have to specify their Maven coordinates, which
uniquely identify each element in a remote repository. The format for Maven
coordinates used in the build system is group:name:version. For example, the
Maven coordinates for version 16.0.1 of the Google Guava libraries are
com.google.guava:guava:16.0.1.
The Maven Central Repository is widely used to distribute many libraries and tools.
Build tasks
The Android Studio build system defines a hierarchical set of build tasks: the top-level or
anchor tasks invoke dependent tasks to produce their collective build outcomes. The top-level
build tasks are:
assemble
check
build
clean
The Android plugin provides additional tasks for connectedCheck and deviceCheck for
checks run on connected, emulated, and remote devices. Gradle tasks can be viewed by
clicking the Gradle tab in the right margin.
Running a top-level task, runs all the dependent tasks. For example, the assemble task has
dependent tasks for assembleDebug and assembleRelease to make the debug and release
APKs. The assemble task depends on these tasks so calling it builds both APKs. These tasks
can also be called independently to build the debug or release APK separately.
You can view the list of available tasks and invoke any task from Android Studio and from
the command line, as described in Building and Running from Android Studio and Build the
project from the command line.
Android Studio projects contain the Gradle wrapper, which consists of:
A JAR file
A properties file
A shell script for Windows platforms
A shell script for Mac and Linux platforms
Note: You should submit all of these files to your source control system.
Using the Gradle wrapper (instead of the local Gradle installation) ensures that you always
run the version of Gradle defined in the local.properties file. To configure your project to use
a newer version of Gradle, edit the properties file and specify the new version there.
Android Studio reads the properties file from the Gradle wrapper directory inside your
project and runs the wrapper from this directory, so you can seamlessly work with multiple
projects that require different versions of Gradle.
Note: Android Studio does not use the shell scripts, so any changes you make to them won't
work when building from the IDE. You should define your custom logic inside Gradle build
files instead.
You can run the shell scripts to build your project from the command line on your
development machine and on other machines where Android Studio is not installed.
Caution: When you create a project, only use the Gradle wrapper scripts and JAR from a
trusted source, such as those generated by Android Studio. /p>
Build variants
Each version of your app is represented in the build system by a build variant. Build variants
are combinations of product flavors and build types. Product flavors represent product build
versions of an app, such as free and paid. Build types represent the build packaging versions
generated for each app package, such as debug and release. The build system generates APKs
for each combination of product flavor and build type.
Adding two product flavors, demo and full along with the default build types debug and
release generates four build variants, each with its own customized configuration:
demoDebug
demoRelease
fullDebug
fullRelease
The priority of the merge order from lowest to highest is libraries/dependencies -> main src -
> productFlavor -> buildType.
Some projects have complex combinations of features along more than one dimension, but
they still represent the same app. For example, in addition to having a demo and a full version
of the app, some games may contain binaries specific to a particular CPU/ABI. The flexibility
of the build system makes it possible to generate the following build variants for such a
project:
x86-demoDebug
x86-demoRelease
x86-fullDebug
x86-fullRelease
arm-demoDebug
arm-demoRelease
arm-fullDebug
arm-fullRelease
mips-demoDebug
mips-demoRelease
mips-fullDebug
mips-fullRelease
This project would consist of two build types (debug and release) and two dimensions of
product flavors, one for app type (demo or full) and one for CPU/ABI (x86, ARM, or MIPS).
Source directories
To build each version of your app, the build system combines source code and resources
from:
src/main/ - the main source directory (the default configuration common to all
variants)
src/<buildType>/ - the source directory
src/<productFlavor>/ - the source directory
Note: The build type and product flavor source directories are optional, as Android Studio
does not create these directories for you. You should create these directories as you add build
types and product flavors to the build configuration files. The build system does not use these
directories if they are not present.
For projects that do not define any flavors, the build system uses the defaultConfig settings,
the main app directory and the default build type directories. For example, to generate the
default debug and release build variants in projects with no product flavors, the build system
uses:
For projects that define a set of product flavors, the build system merges the build type,
product flavor and main source directories. For example, to generate the full-debug build
variant, the build system merges the build type, product flavor and main directories:
src/main/ (default configuration)
src/debug/ (build type)
src/full/ (flavor)
For projects that use flavor dimensions, the build system merges one flavor source directory
per dimension. For example, to generate the arm-demo-release build variant, the build system
merges:
The source code from these directories is used together to generate the output for a build
variant. You can have classes with the same name in different directories as long as those
directories are not used together in the same variant.
The build system also merges all the manifests into a single manifest, so each build variant
can define different components or permissions in the final manifest. The manifest merge
priority from lowest to highest is libraries/dependencies -> main src -> productFlavor ->
buildType.
The build system merges all the resources from the all the source directories. If different
folders contain resources with the same name for a build variant, the priority order is the
following: build type resources override those from the product flavor, which override the
resources in the main source directory, which override those in any libraries.
Note: Build variants enable you to reuse common activities, application logic, and resources
across different versions of your app.
See Also
1. ProGuard
As the Android platform has continued to grow, so has the size of Android apps. When your
application and the libraries it references reach a certain size, you encounter build errors that
indicate your app has reached a limit of the Android app build architecture. Earlier versions
of the build system report this error as follows:
More recent versions of the Android build system display a different error, which is an
indication of the same problem:
Both these error conditions display a common number: 65,536. This number is significant in
that it represents the total number of references that can be invoked by the code within a
single Dalvik Executable (dex) bytecode file. If you have built an Android app and received
this error, then congratulations, you have a lot of code! This document explains how to move
past this limitation and continue building your app.
Note: The guidance provided in this document supersedes the guidance given in the Android
Developers blog post Custom Class Loading in Dalvik.
Android application (APK) files contain executable bytecode files in the form of Dalvik
Executable (DEX) files, which contain the compiled code used to run your app. The Dalvik
Executable specification limits the total number of methods that can be referenced within a
single DEX file to 65,536, including Android framework methods, library methods, and
methods in your own code. Getting past this limit requires that you configure your app build
process to generate more than one DEX file, known as a multidex configuration.
Versions of the platform prior to Android 5.0 use the Dalvik runtime for executing app code.
By default, Dalvik limits apps to a single classes.dex bytecode file per APK. In order to get
around this limitation, you can use the multidex support library, which becomes part of the
primary DEX file of your app and then manages access to the additional DEX files and the
code they contain.
Android 5.0 and higher uses a runtime called ART which natively supports loading multiple
dex files from application APK files. ART performs pre-compilation at application install
time which scans for classes(..N).dex files and compiles them into a single .oat file for
execution by the Android device. For more information on the Android 5.0 runtime, see
Introducing ART.
Avoiding the 65K Limit
Before configuring your app to enable use of 65K or more method references, you should
take steps to reduce the total number of references called by your app code, including
methods defined by your app code or included libraries. The following strategies can help
you avoid hitting the dex reference limit:
Review your app's direct and transitive dependencies - Ensure any large library
dependency you include in your app is used in a manner that outweighs the amount of
code being added to the application. A common anti-pattern is to include a very large
library because a few utility methods were useful. Reducing your app code
dependencies can often help you avoid the dex reference limit.
Remove unused code with ProGuard - Configure the ProGuard settings for your
app to run ProGuard and ensure you have shrinking enabled for release builds.
Enabling shrinking ensures you are not shipping unused code with your APKs.
Using these techniques can help you avoid the build configuration changes required to enable
more method references in your app. These steps can also decrease the size of your APKs,
which is particularly important for markets where bandwidth costs are high.
The Android plugin for Gradle available in Android SDK Build Tools 21.1 and higher
supports multidex as part of your build configuration. Make sure you update the Android
SDK Build Tools tools and the Android Support Repository to the latest version using the
SDK Manager before attempting to configure your app for multidex.
Setting up your app development project to use a multidex configuration requires that you
make a few modifications to your app development project. In particular you need to perform
the following steps:
Modify your app Gradle build file configuration to include the support library and enable
multidex output, as shown in the following Gradle build file snippet:
android {
compileSdkVersion 21
buildToolsVersion "21.1.0"
defaultConfig {
...
minSdkVersion 14
targetSdkVersion 21
...
dependencies {
compile 'com.android.support:multidex:1.0.0'
}
Note: You can specify the multiDexEnabled setting in the defaultConfig, buildType, or
productFlavor sections of your Gradle build file.
In your manifest add the MultiDexApplication class from the multidex support library to
the application element.
When these configuration settings are added to an app, the Android build tools construct a
primary dex (classes.dex) and supporting (classes2.dex, classes3.dex) as needed. The build
system will then package them into an APK file for distribution.
Note: If your app uses extends the Application class, you can override the
attachBaseContext() method and call MultiDex.install(this) to enable multidex. For more
information, see the MultiDexApplication reference documentation.
The multidex support library has some known limitations that you should be aware of and
test for when you incorporate it into your app build configuration:
The installation of .dex files during startup onto a device's data partition is complex
and can result in Application Not Responding (ANR) errors if the secondary dex files
are large. In this case, you should apply code shrinking techniques with ProGuard to
minimize the size of dex files and remove unused portions of code.
Applications that use multidex may not start on devices that run versions of the
platform earlier than Android 4.0 (API level 14) due to a Dalvik linearAlloc bug
(Issue 22586). If you are targeting API levels earlier than 14, make sure to perform
testing with these versions of the platform as your application can have issues at
startup or when particular groups of classes are loaded. Code shrinking can reduce or
possibly eliminate these potential issues.
Applications using a multidex configuration that make very large memory allocation
requests may crash during run time due to a Dalvik linearAlloc limit (Issue 78035).
The allocation limit was increased in Android 4.0 (API level 14), but apps may still
run into this limit on Android versions prior to Android 5.0 (API level 21).
There are complex requirements regarding what classes are needed in the primary dex
file when executing in the Dalvik runtime. The Android build tooling updates handle
the Android requirements, but it is possible that other included libraries have
additional dependency requirements including the use of introspection or invocation
of Java methods from native code. Some libraries may not be able to be used until the
multidex build tools are updated to allow you to specify classes that must be included
in the primary dex file.
A multidex configuration requires significantly increased build processing time because the
build system must make complex decisions about what classes must be included in the
primary DEX file and what classes can be included in secondary DEX files. This means that
routine builds performed as part of the development process with multidex typically take
longer and can potentially slow your development process.
In order to mitigate the typically longer build times for multidex output, you should create
two variations on your build output using the Android plugin for Gradle productFlavors: a
development flavor and a production flavor.
For the development flavor, set a minimum SDK version of 21. This setting generates
multidex output much faster using the ART-supported format. For the release flavor, set a
minimum SDK version which matches your actual minimum support level. This setting
generates a multidex APK that is compatible with more devices, but takes longer to build.
The following build configuration sample demonstrates the how to set up these flavors in a
Gradle build file:
android {
productFlavors {
// Define separate dev and prod product flavors.
dev {
// dev utilizes minSDKVersion = 21 to allow the Android gradle
plugin
// to pre-dex each module and produce an APK that can be tested
on
// Android Lollipop without time consuming dex merging
processes.
minSdkVersion 21
}
prod {
// The actual minSdkVersion for the application.
minSdkVersion 14
}
}
...
buildTypes {
release {
runProguard true
proguardFiles getDefaultProguardFile('proguard-android.txt'),
'proguard-rules.pro'
}
}
}
dependencies {
compile 'com.android.support:multidex:1.0.0'
}
After you have completed this configuration change, you can use the devDebug variant of
your app, which combines the attributes of the dev productFlavor and the debug buildType.
Using this target creates a debug app with proguard disabled, multidex enabled, and
minSdkVersion set to Android API level 21. These settings cause the Android gradle plugin
to do the following:
1. Build each module of the application (including dependencies) as separate dex files.
This is commonly referred to as pre-dexing.
2. Include each dex file in the APK without modification.
3. Most importantly, the module dex files will not be combined, and so the long-running
calculation to determine the contents of the primary dex file is avoided.
These settings result in fast, incremental builds, because only the dex files of modified
modules are recomputed and repackaged into the APK file. The APK that results from these
builds can be used to test on Android 5.0 devices only. However, by implementing the
configuration as a flavor, you preserve the ability to perform normal builds with the release-
appropriate minimum SDK level and proguard settings.
You can also build the other variants, including a prodDebug variant build, which takes
longer to build, but can be used for testing outside of development. Within the configuration
shown, the prodRelease variant would be the final testing and release version. If you are
executing gradle tasks from the command line, you can use standard commands with
DevDebug appended to the end (such as ./gradlew installDevDebug). For more
information about using flavors with Gradle tasks, see the Gradle Plugin User Guide.
Tip: You can also provide a custom manifest, or a custom application class for each flavor,
allowing you to use the support library MultiDexApplication class, or calling
MultiDex.install() only for the variants that need it.
Build variants can be very useful for managing the build process when using multidex.
Android Studio allows you to select these build variants in the user interface.
1. Open the Build Variants window from the left-sidebar. The option is located next to
Favorites.
2. Click the name of the build variant to select a different variant, as shown in Figure 1.
Figure 1. Screen shot of the Android Studio left panel showing a build variant.
Note: The option to open this window is only available after you have successfully
synchronized Android Studio with your Gradle build file using the Tools > Android > Sync
Project with Gradle Files command.
Testing apps that use multidex configuration require some additional steps and configuration.
Since the location of code for classes is not within a single DEX file, instrumentation tests do
not run properly unless configured for multidex.
When testing a multidex app with instrumentation tests, use MultiDexTestRunner from the
multidex testing support library. The following sample build.gradle file, demonstrates how
to configure your build to use this test runner:
android {
defaultConfig {
...
testInstrumentationRunner
"android.support.multidex.MultiDexTestRunner"
}
}
dependencies {
androidTestCompile 'com.android.support:multidex-instrumentation:1.0.0'
}
You may use the instrumentation test runner class directly or extend it to fit your testing
needs. Alternatively, you can override onCreate in existing instrumentations like this:
Note: Use of multidex for creating a test APK is not currently supported.
Support Library
In this document
1. Overview
2. Revisions
See also
1. Support Library Features
2. Support Library Setup
The Android Support Library package is a set of code libraries that provide backward-
compatible versions of Android framework APIs as well as features that are only available
through the library APIs. Each Support Library is backward-compatible to a specific Android
API level. This design means that your applications can use the libraries' features and still be
compatible with devices running Android 1.6 (API level 4) and up.
This guide provides information about what features are enabled by the Support Libraries,
how to use them in your development environment and information about library releases.
Overview
Including the Support Libraries in your Android project is considered a best practice for
application developers, depending on the range of platform versions your app is targeting and
the APIs that it uses. Using the features the libraries provide can help you improve the look of
your application, increase performance and broaden the reach of your application to more
users. If you use the Android code template tools, you will notice that all the Android
application templates include one or more of the Support Libraries by default.
The Support Libraries each target a base Android API level and each provides a different set
of features. In order to effectively use the libraries, it is important to consider what features
you want to support and understand what features are supported by each library at what
Android API level. To get started, review the Support Library Features guide. After that, go
to the Support Library Setup topic to learn how to incorporate the Support Libraries into your
application. For more details about Support Library APIs, see the android.support
packages in the API reference.
Revisions
This section provides details about the Support Library package releases.
Added the RecyclerView widget, which provides a flexible list view for
providing a limited window into a large data set.
Added Palette class, which lets you extract prominent colors from an image.
See also
1. Support Library Revisions
2. Support Library Setup
The Android Support Library package contains several libraries that can be included in your
application. Each of these libraries supports a specific range of Android platform versions
and set of features.
This guide explains the important features and version support provided by the Support
Libraries to help you decide which of them you should include in your application. In
general, we recommend including the v4 support and v7 appcompat libraries, because they
support a wide range of Android versions and provide APIs for recommended user interface
patterns.
In order to use any of the following libraries, you must download the library files to your
Android SDK installation. Follow the directions for downloading the Support Libraries in
Support Library Setup to complete this step. You must take additional steps to include a
specific Support Library in your application. See the end of each library section below for
important information on how to include the library in your application.
v4 Support Library
This library is designed to be used with Android 1.6 (API level 4) and higher. It includes the
largest set of APIs compared to the other libraries, including support for application
components, user interface features, accessibility, data handling, network connectivity, and
programming utilities. Here are a few of the key classes included in the v4 library:
App Components
o Fragment - Adds support for encapsulation of user interface and functionality
with Fragments, enabling applications to provide layouts that adjust between
small and large-screen devices.
o NotificationCompat - Adds support for rich notification features.
o LocalBroadcastManager - Allows applications to easily register for and
receive intents within a single application without broadcasting them globally.
User Interface
o ViewPager - Adds a ViewGroup that manages the layout for the child views,
which the user can swipe between.
o PagerTitleStrip - Adds a non-interactive title strip, that can be added as a
child of ViewPager.
o PagerTabStrip - Adds a navigation widget for switching between paged
views, that can also be used with ViewPager.
o DrawerLayout - Adds support for creating a Navigation Drawer that can be
pulled in from the edge of a window.
o SlidingPaneLayout - Adds widget for creating linked summary and detail
views that appropriately adapt to various screen sizes.
Accessibility
o ExploreByTouchHelper - Adds a helper class for implementing accessibility
support for custom views.
o AccessibilityEventCompat - Adds support for AccessibilityEvent. For
more information about implementing accessibility, see Accessibility.
o AccessibilityNodeInfoCompat - Adds support for
AccessibilityNodeInfo.
o AccessibilityNodeProviderCompat - Adds support for
AccessibilityNodeProvider.
o AccessibilityDelegateCompat - Adds support for
View.AccessibilityDelegate.
Content
o Loader - Adds support for asynchronous loading of data. The library also
provides concrete implementations of this class, including CursorLoader and
AsyncTaskLoader.
o FileProvider - Adds support for sharing of private files between
applications.
There are many other APIs included in this library. For complete, detailed information about
the v4 Support Library APIs, see the android.support.v4 package in the API reference.
Caution: Using dynamic dependencies, especially for higher version numbers, can cause
unexpected version updates and regression incompatibilities.
The Gradle build script dependency identifier for this library is as follows:
com.android.support:support-v4:21.0.+
This dependency notation specifies the latest release version with the 21.0 prefix.
This library provides support for building apps with multiple Dalvik Executable (DEX) files.
Apps that reference more than 65536 methods are required to use multidex configurations.
For more information about using multidex, see Building Apps with Over 65K Methods.
The Gradle build script dependency identifier for this library is as follows:
com.android.support:multidex:1.0.+
This dependency notation specifies the latest release version with the 1.0 prefix.
v7 Support Libraries
There are several libraries designed to be used with Android 2.1 (API level 7) and higher.
These libraries provide specific feature sets and can be included in your application
independently from each other.
v7 appcompat library
This library adds support for the Action Bar user interface design pattern. This library
includes support for material design user interface implementations.
Note: This library depends on the v4 Support Library. If you are using Ant or Eclipse, make
sure you include the v4 Support Library as part of this library's classpath.
Here are a few of the key classes included in the v7 appcompat library:
ActionBar - Provides an implementation of the action bar user interface pattern. For
more information on using the Action Bar, see the Action Bar developer guide.
ActionBarActivity - Adds an application activity class that must be used as a base
class for activities that uses the Support Library action bar implementation.
ShareActionProvider - Adds support for a standardized sharing action (such as
email or posting to social applications) that can be included in an action bar.
The Gradle build script dependency identifier for this library is as follows:
com.android.support:appcompat-v7:21.0.+
This dependency notation specifies the latest release version with the 21.0 prefix.
v7 cardview library
This library adds support for the CardView widget, which lets you show information inside
cards that have a consistent look on any app. These cards are useful for material design
implementations, and are used extensively in layouts for TV apps.
The Gradle build script dependency identifier for this library is as follows:
com.android.support:cardview-v7:21.0.+
This dependency notation specifies the latest release version with the 21.0 prefix.
v7 gridlayout library
This library adds support for the GridLayout class, which allows you to arrange user
interface elements using a grid of rectangular cells. For detailed information about the v7
gridlayout library APIs, see the android.support.v7.widget package in the API reference.
The Gradle build script dependency identifier for this library is as follows:
com.android.support:gridlayout-v7:21.0.+
This dependency notation specifies the latest release version with the 21.0 prefix.
v7 mediarouter library
This library provides MediaRouter, MediaRouteProvider, and related media classes that
support Google Cast.
In general, the APIs in the v7 mediarouter library provide a means of controlling the routing
of media channels and streams from the current device to external screens, speakers, and
other destination devices. The library includes APIs for publishing app-specific media route
providers, for discovering and selecting destination devices, for checking media status, and
more. For detailed information about the v7 mediarouter library APIs, see the
android.support.v7.media package in the API reference.
If you are using Android Studio, all you need to do is specify the Gradle build script
dependency identifier com.android.support:support-v7-mediarouter:<revision>,
where "<revision>" is the minimum revision at which the library is available. For example:
com.android.support:mediarouter-v7:21.0.+
The v7 mediarouter library APIs introduced in Support Library r18 are subject to change in
later revisions of the Support Library. At this time, we recommend using the library only in
connection with Google Cast.
v7 palette library
The v7 palette support library includes the Palette class, which lets you extract prominent
colors from an image. For example, a music app could use a Palette object to extract the
major colors from an album cover, and use those colors to build a color-coordinated song title
card.
The Gradle build script dependency identifier for this library is as follows:
com.android.support:palette-v7:21.0.+
This dependency notation specifies the latest release version with the 21.0 prefix.
v7 recyclerview library
The recyclerview library adds the RecyclerView class. This class provides support for the
RecyclerView widget, a view for efficiently displaying large data sets by providing a limited
window of data items.
The Gradle build script dependency identifier for this library is as follows:
com.android.support:recyclerview-v7:21.0.+
This dependency notation specifies the latest release version with the 21.0 prefix.
v8 Support Library
This library is designed to be used with Android (API level 8) and higher. It adds support for
the RenderScript computation framework. These APIs are included in the
android.support.v8.renderscript package. You should be aware that the steps for
including these APIs in your application is very different from other support library APIs. For
more information about using these APIs in your application, see the RenderScript developer
guide.
Note: Use of RenderScript with the support library is supported with the Android Eclipse
plugin and Ant build tools. It is not currently supported with Android Studio or Gradle-based
builds.
The Gradle build script dependency identifier for this library is as follows:
com.android.support:support-v13:18.0.+
This dependency notation specifies the latest release version with the 18.0 prefix.
The Gradle build script dependency identifier for this library is as follows:
com.android.support:leanback-v17:21.0.+
This dependency notation specifies the latest release version with the 21.0 prefix.
See also
1. Support Library Revisions
2. Support Library Features
How you setup the Android Support Libraries in your development project depends on what
features you want to use and what range of Android platform versions you want to support
with your application.
This document guides you through downloading the Support Library package and adding
libraries to your development environment.
Note: If you're developing with Android Studio, select and install the Android
Support Repository item instead.
After downloading, the tool installs the Support Library files to your existing Android SDK
directory. The library files are located in the following subdirectory of your SDK:
<sdk>/extras/android/support/ directory.
Before adding a Support Library to your application, decide what features you want to
include and the lowest Android versions you want to support. For more information on the
features provided by the different libraries, see Support Library Features.
In order to use a Support Library, you must modify your application's project's classpath
dependencies within your development environment. You must perform this procedure for
each Support Library you want to use.
Some Support Libraries contain resources beyond compiled code classes, such as images or
XML files. For example, the v7 appcompat and v7 gridlayout libraries include resources.
If you are not sure if a library contains resources, check the Support Library Features page.
The following sections describe how to add a Support Library with or without resources to
your application project.
Using Eclipse
To add a Support Library with resources (such as v7 appcompat for action bar) to your
application project:
Using Eclipse
Support Library classes that provide support for existing framework APIs typically have the
same name as framework class but are located in the android.support class packages, or
have a *Compat suffix.
Caution: When using classes from the Support Library, be certain you import the class from
the appropriate package. For example, when applying the ActionBar class:
Note: After including the Support Library in your application project, we strongly
recommend using the ProGuard tool to prepare your application APK for release. In addition
to protecting your source code, the ProGuard tool also removes unused classes from any
libraries you include in your application, which keeps the download size of your application
as small as possible. For more information, see ProGuard.
Further guidance for using some Support Library features is provided in the Android
developer training classes, guides and samples. For more information about the individual
Support Library classes and methods, see the android.support packages in the API
reference.
If you are increasing the backward compatibility of your existing application to an earlier
version of the Android API with the Support Library, make sure to update your application's
manifest. Specifically, you should update the android:minSdkVersion element of the
<uses-sdk> tag in the manifest to the new, lower version number, as shown below:
<uses-sdk
android:minSdkVersion="7"
android:targetSdkVersion="17" />
The manifest setting tells Google Play that your application can be installed on devices with
Android 2.1 (API level 7) and higher.
If you are using Gradle build files, the minSdkVersion setting in the build file overrides the
manifest settings.
android {
...
defaultConfig {
minSdkVersion 8
...
}
...
}
In this case, the build file setting tells Google Play that the default build variant of your
application can be installed on devices with Android 2.2 (API level 8) and higher. For more
information about build variants, see Build System Overview.
Note: If you are including the v4 support and v7 appcompat libraries in your application, you
should specify a minimum SDK version of "7" (and not "4"). The highest support library
level you include in your application determines the lowest API version in which it can
operate.
Code Samples
Each Support Library includes code samples to help you get started using the support APIs.
The code is included in the download from the SDK Manager and is placed inside the
Android SDK installation directory, as listed below:
4v Samples: <sdk>/extras/android/support/samples/Support4Demos/
7v Samples: <sdk>/extras/android/support/samples/Support7Demos/
13v Samples: <sdk>/extras/android/support/samples/Support13Demos/
App Navigation:
<sdk>/extras/android/support/samples/SupportAppNavigation/