Vous êtes sur la page 1sur 506

Android Studio Overview

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:

Flexible Gradle-based build system

Build variants and multiple apk file generation

Code templates to help you build common app features

Rich layout editor with support for drag and drop theme editing

Lint tools to catch performance, usability, version compatibility, and other problems

ProGuard and app-signing capabilities

Built-in support for Google Cloud Platform, making it easy to integrate Google Cloud
Messaging and App Engine

And much more

Download Android Studio now.


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.

Project and File Structure


Android Project View
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.

Figure 1. Show the Android project view.

Figure 2. Project Build Files.


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:

java/

manifests/

res/

- Source files for the module.


- Manifest files for the module.

- Resource files for the module.

For example, Android project view groups all the instances of the ic_launcher.png resource
for different screen densities under the same element.
Note: The project structure on disk differs from this flattened representation. To switch to
back the segregated project view, select Project from the Project

New Project and Directory Structure


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.

Figure 3. Android Studio project structure


For more information, see IntelliJ project organization and Managing Projects.

Creating new files


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.

Android Build System


Android Build System
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:

Customize, configure, and extend the build process.

Create multiple APKs for your app with different features using the same project and
modules.

Reuse code and resources across source sets.

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.

Application ID for Package Identification


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.
apply plugin: 'com.android.application'
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.

Debug and Performance


Android Virtual Device (AVD) Manager
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.
For more information, see Managing AVDs.

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

New Lint inspections


Lint has several new checks to ensure:

Cipher.getInstance()

In custom Views, the associated declare-styleable for the custom view uses the
same base name as the class name.

Security check for fragment injection.

Where ever property assignment no longer works as expected.

Gradle plugin version is compatible with the SDK.

Right to left validation

Required API version

many others

is used with safe values

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

For more information, see Improving Your Code with Lint.

Dynamic layout preview


Android Studio allows you to work with layouts in both a Design View

Figure 5. Hello World App with Design View


and a Text View.

Figure 6. Hello World App with Text View


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.
Installation, Setup, and Update Management

Android Studio installation and setup wizards

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.

Figure 8. Setup Wizard


Expanded template and form factor support

Android Studio supports new templates for Google Services and expands the availabe device
types.
Android Wear and TV support

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.
Google App Engine integration (Google Cloud Platform/Messaging)

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.

Figure 11. Translation Editor


Editor support for the latest Android APIs

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.
Easy access to Android code samples on GitHub

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.

About Android | Legal | Support

Android Studio Tips and Tricks


In this document
1. Productivity Features
2. Working with IntelliJ
3. Key Commands

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.

Bitmap rendering in the debugger


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

Output window message filtering


When checking build results, you can filter messages by message type to quickly locate
messages of interest.

Figure 2. Filter Build Messages

Hierarchical parent setting

The activity parent can now be set in the Activity Wizard when creating a new activity.
Setting a hierarchal parent sets the Up button to automatically appear in the app's Action bar
when viewing a child activity, so the Up button no longer needs to be manually specified in
the menu.xml file.

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.

Figure 3. Preview All Screens


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.

Alt + Enter key binding


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.

Ctrl + D key binding


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.

Image and color preview


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.

New Allocation Tracker integration in the Android/DDMS window


You can now inspect theme attributes using View > Quick Documentation F1, see the theme
inheritance hierarchy, and resolved values for the various attributes.

Figure 4. Allocation Tracker

Keyboard Commands
The following tables list keyboard shortcuts for common operations.
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

Action
Command look-up (autocomplete command name)
Project quick fix
Reformat code
Show docs for selected API
Show parameters for selected method
Generate method
Jump to source
Delete line
Search by symbol name

Android Studio Key Command


CTRL + SHIFT + A
ALT + ENTER
CTRL + ALT + L (Win)
OPTION + CMD + L (Mac)
CTRL + Q (Win)
F1 (Mac)
CTRL + P
ALT + Insert (Win)
CMD + N (Mac)
F4 (Win)
CMD + down-arrow (Mac)
CTRL + Y (Win)
CMD + Backspace (Mac)
CTRL + ALT + SHIFT + N (Win)
OPTION + CMD + O (Mac)

Table 2. Project and editor key commands


Action
Build
Build and run
Toggle project visibility
Navigate open tabs

Android Studio Key Command


CTRL + F9 (Win)
CMD + F9 (Mac)
SHIFT + F10 (Win)
CTRL + R (Mac)
ALT + 1 (Win)
CMD + 1 (Mac)
ALT + left-arrow; ALT + right-arrow (Win)
CTRL + left-arrow; CTRL + right-arrow (Mac)

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.
About Android | Legal | Support

Developer Workflow
To develop apps for Android, you use a set of tools that are included in Android Studio. In
addition to using the tools from Android Studio, you can also access most of the SDK tools
from the command line. Developing with Android Studio is the preferred method because it
can directly invoke the tools that you need while developing applications.
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.

Project Setup and Development


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.

Building, Debugging and Testing


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.

Essential command line tools


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.
About Android | Legal | Support

Managing Virtual Devices


An Android Virtual Device (AVD) is an emulator configuration that lets you model an actual
device by defining hardware and software options to be emulated by the Android Emulator.
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.
An AVD consists of:

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.

Managing AVDs with AVD Manager


In this document
1. Creating an AVD
1. Creating a device definition
2. Hardware options
2. Creating Emulator Skins
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.
To launch the AVD Manager:

In Android Studio, select Tools > Android > AVD Manager, or click the AVD
Manager icon

in the toolbar.

Or, use the command line to navigate to your SDK's tools/ directory and execute:
$ 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 <usessdk> tag.
To create an AVD based on an existing device definition:
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.

Figure 2. The Select Hardware window.


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.
Or, to start from scratch, click New Hardware Profile.
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.
When you're done configuring the device, click Finish.

Figure 3. The Configure Hardware window when creating a custom device


configuration.
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:
Characteristic
Device ram size
Touch-screen
support
Trackball support
Keyboard support
DPad support
GSM modem
support
Camera support

Description
Property
The amount of physical RAM on the
device, in megabytes. Default value is hw.ramSize
"96".
Whether there is a touch screen or not
hw.touchScreen
on the device. Default value is "yes".
Whether there is a trackball on the
hw.trackBall
device. Default value is "yes".
Whether the device has a QWERTY
hw.keyboard
keyboard. Default value is "yes".
Whether the device has DPad keys.
hw.dPad
Default value is "yes".
Whether there is a GSM modem in the
hw.gsmModem
device. Default value is "yes".
Whether the device has a camera.
hw.camera

Default value is "no".


Maximum horizontal
Default value is "640".
camera pixels
Maximum vertical
Default value is "480".
camera pixels
Whether there is a GPS in the device.
GPS support
Default value is "yes".
Whether the device can run on a
Battery support
battery. Default value is "yes".
Whether there is an accelerometer in
Accelerometer
the device. Default value is "yes".
Audio recording
Whether the device can record audio.
support
Default value is "yes".
Audio playback
Whether the device can play audio.
support
Default value is "yes".
Whether the device supports
SD Card support
insertion/removal of virtual SD Cards.
Default value is "yes".
Cache partition
Whether we use a /cache partition on
support
the device. Default value is "yes".
Cache partition size Default value is "66MB".
Sets the generalized density
Abstracted LCD
characteristic used by the AVD's
density
screen. Default value is "160".

hw.camera.maxHorizontalPixels
hw.camera.maxVerticalPixels
hw.gps
hw.battery
hw.accelerometer
hw.audioInput
hw.audioOutput
hw.sdCard
disk.cachePartition
disk.cachePartition.size
hw.lcd.density

Creating Emulator Skins


An Android emulator skin is a collection of files that define the visual and control elements of
an emulator display. If the skin definitions available in the AVD settings don't meet your
needs, you can create your own custom skin definition, then apply it to your AVD from the
advanced settings on the Verify Configuration screen.
Each emulator skin contains:

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

To create and use a custom skin:


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
height
x
y
}
}

320
480
0
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
To generate a list of system image targets, use this command:
android list 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:
Available Android targets:
id: 1 or "android-3"
Name: Android 1.5
Type: Platform
API level: 3
Revision: 4
Skins: QVGA-L, HVGA-L, HVGA (default), HVGA-P, QVGA-P
id: 2 or "android-4"
Name: Android 1.6
Type: Platform
API level: 4
Revision: 3
Skins: QVGA, HVGA (default), WVGA800, WVGA854
id: 3 or "android-7"
Name: Android 2.1-update1
Type: Platform
API level: 7
Revision: 2
Skins: QVGA, WQVGA400, HVGA (default), WVGA854, WQVGA432, WVGA800
id: 4 or "android-8"
Name: Android 2.2
Type: Platform
API level: 8
Revision: 2
Skins: WQVGA400, QVGA, WVGA854, HVGA (default), WVGA800, WQVGA432
id: 5 or "android-9"
Name: Android 2.3
Type: Platform
API level: 9
Revision: 1
Skins: HVGA (default), WVGA800, WQVGA432, QVGA, WVGA854, WQVGA400

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.
Open a terminal window and change to the <sdk>/tools/ directory, if needed.
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.
Here's the command-line usage for creating an AVD:
android create avd -n <name> -t <targetID> [-<option> <value>] ...

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):
android create avd -n my_android1.5 -t 2

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.
Android 1.5 is a basic Android platform.
Do you wish to create a custom hardware profile [no]

If you want to set custom hardware emulation options for the AVD, enter "yes" and set values
as needed. If you want to use the default hardware emulation options for the AVD, just press
the return key (the default is "no"). The android tool creates the AVD with name and system
image mapping you requested, with the options you specified. For more information, see
Setting Hardware Emulation Options.
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.

Customize the device resolution or density

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:
android create avd -n <name> -t <targetID> --skin WVGA800

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 highdensity 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:
emulator -avd WVGA800 -scale 96dpi -dpi-device 160

Default location of AVD files


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:

android create avd -n my_android1.5 -t 2 -p path/to/my/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.

Setting hardware emulation options


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
Characteristic
Device ram size
Touch-screen
support
Trackball support
Keyboard support
DPad support
GSM modem
support
Camera support

Description
Property
The amount of physical RAM on the
device, in megabytes. Default value is hw.ramSize
"96".
Whether there is a touch screen or not
hw.touchScreen
on the device. Default value is "yes".
Whether there is a trackball on the
hw.trackBall
device. Default value is "yes".
Whether the device has a QWERTY
hw.keyboard
keyboard. Default value is "yes".
Whether the device has DPad keys.
hw.dPad
Default value is "yes".
Whether there is a GSM modem in the
hw.gsmModem
device. Default value is "yes".
Whether the device has a camera.
hw.camera
Default value is "no".

Maximum horizontal
Default value is "640".
camera pixels
Maximum vertical
Default value is "480".
camera pixels
Whether there is a GPS in the device.
GPS support
Default value is "yes".
Whether the device can run on a
Battery support
battery. Default value is "yes".
Whether there is an accelerometer in
Accelerometer
the device. Default value is "yes".
Audio recording
Whether the device can record audio.
support
Default value is "yes".
Audio playback
Whether the device can play audio.
support
Default value is "yes".
SD Card support
Whether the device supports
insertion/removal of virtual SD Cards.

hw.camera.maxHorizontalPixels
hw.camera.maxVerticalPixels
hw.gps
hw.battery
hw.accelerometer
hw.audioInput
hw.audioOutput
hw.sdCard

Default value is "yes".


Cache partition
Whether we use a /cache partition on
support
the device. Default value is "yes".
Cache partition size Default value is "66MB".
Sets the generalized density
Abstracted LCD
characteristic used by the AVD's
density
screen. Default value is "160".
Trackball support
Whether there is a trackball present.

disk.cachePartition
disk.cachePartition.size
hw.lcd.density
hw.trackBall

Moving an AVD
If you want to move or rename an AVD, you can do so using this command:
android move avd -n <name> [-<option> <value>] ...

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:
The following Android Virtual Devices could not be loaded:
Name: foo
Path: <path>/.android/avd/foo.avd
Error: Invalid value in image.sysdir. Run 'android update avd -n foo'

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:
android delete avd -n <name>

When you issue the command, the android tool looks for an AVD matching the specified
name deletes the AVD's directory and files.
Using the Emulator
In this document
1. Overview
2. Android Virtual Devices and the Emulator

3. Starting and Stopping the Emulator


4. Installing Applications on the Emulator
5. Using Hardware Acceleration
1. Configuring Graphics Acceleration
2. Configuring Virtual Machine Acceleration
6. SD Card Emulation
1. Creating an SD card image
2. Copying files to an SD card image
3. Loading an SD card image
7. Working with Emulator Disk Images
1. Default image files
2. Runtime images: user data and SD card
3. Temporary images
8. Emulator Networking
1. Network Address Space
2. Local Networking Limitations
3. Using Network Redirection
4. Configuring the Emulator's DNS Settings
5. Using the Emulator with a Proxy
6. Interconnecting Emulator Instances
7. Sending a Voice Call or SMS to Another Emulator Instance
9. Using the Emulator Console
1. Port Redirection
2. Geo Location Provider Emulation
3. Hardware Events Emulation
4. Device Power Characteristics

5. Network Status
6. Network Delay Emulation
7. Network Speed Emulation
8. Telephony Emulation
9. SMS Emulation
10.VM State
11.Emulator Window
12.Terminating an Emulator Instance
10.Emulator Limitations
11.Troubleshooting Emulator Problems
See also
1. Android Emulator
2. Managing AVDs with AVD Manager

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:

An ARMv5 CPU and the corresponding memory-management unit (MMU)

A 16-bit LCD display

One or more keyboards (a Qwerty-based keyboard and associated


Dpad/Phone buttons)

A sound chip with output and input capabilities

Flash memory partitions (emulated through disk image files on the


development machine)

A GSM modem, including a simulated SIM Card

A camera, using a webcam connected to your development computer.

Sensors like an accelerometer, using data from a USB-connected Android


device.

The following sections describe the emulator and its use for development of Android
applications in more detail.
Android Virtual Devices and the Emulator

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.
Starting and Stopping the Emulator

During development and testing of your application, you install and run your application in
the Android emulator. You can launch the emulator as a standalone application from a
command line, or you can run it from within your Android Studio development environment.
In either case, you specify the AVD configuration to load and any startup options you want to
use, as described in this document.
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:
emulator -avd <avd_name> [<options>]

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.
To stop an emulator instance, just close the emulator's window.
For a reference of the emulator's startup commands and keyboard mapping, see the Android
Emulator tool reference.
Installing Applications on the Emulator

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.
Using Hardware Acceleration

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.
Configuring Graphics Acceleration

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:

Android SDK Tools, Revision 17 or higher

Android SDK Platform API 15, Revision 3 or higher

Use the Android SDK Manager to install these components:


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.
To configure an AVD to use 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.
To enable graphics acceleration at runtime for an AVD:

If you are running the emulator from the command line, just include the
-gpu on option:
emulator -avd <avd_name> -gpu on

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.


Configuring Virtual Machine Acceleration

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 systems CPU supports one of the following virtualization extensions
technologies:

Intel Virtualization Technology (VT, VT-x, vmx) extensions

AMD Virtualization (AMD-V, SVM) extensions (only supported for Linux)

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:

Android SDK Tools, Revision 17 or higher

Android x86-based system image

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.
Configuring VM Acceleration on Windows

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)

To install the virtualization driver:


1. Start the Android SDK Manager, select Extras and then select Intel
Hardware Accelerated Execution Manager.
2. After the download completes, execute

<sdk>/extras/intel/Hardware_Accelerated_Execution_Manager/IntelHAXM.e
xe.

3. Follow the on-screen instructions to complete installation.


4. After installation completes, confirm that the virtualization driver is
operating correctly by opening a command prompt window and running
the following command:
sc query intelhaxm

You should see a status message including the following information:


SERVICE_NAME: intelhaxm
...
STATE
...

: 4

RUNNING

To run an x86-based emulator with VM acceleration:

If you are running the emulator from the command line, just specify an
x86-based AVD:
emulator -avd <avd_name>

Note: You must provide an x86-based AVD configuration name, otherwise VM


acceleration will not be enabled.

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 rerunning 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.
Configuring VM Acceleration on Mac

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.
To install the Intel HAXM kernel extension:
1. Start the Android SDK Manager, select Extras and then select Intel
Hardware Accelerated Execution Manager.
2. After the download completes, execute
<sdk>/extras/intel/Hardware_Accelerated_Execution_Manager/IntelHAXM.d
mg.

3. Double click the IntelHAXM.mpkg icon to begin installation.


4. Follow the on-screen instructions to complete installation.
5. After installation completes, confirm that the new kernel extension is
operating correctly by opening a terminal window and running the
following command:

kextstat | grep intel

You should see a status message containing the following extension name, indicating
that the kernel extension is loaded:
com.intel.kext.intelhaxm

To run an x86-based emulator with VM acceleration:

If you are running the emulator from the command line, just specify an
x86-based AVD:
emulator -avd <avd_name>

Note: You must provide an x86-based AVD configuration name, otherwise VM


acceleration will not be enabled.

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 rerunning 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

Configuring VM Acceleration on Linux

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.

To run an x86-based emulator with VM acceleration:

If you are running the emulator from the command line, start the emulator
with an x86-based AVD and include the KVM options:
emulator -avd <avd_name> -qemu -m 512 -enable-kvm

Note: You must provide an x86-based AVD configuration name, otherwise VM


acceleration will not be enabled.

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:
-qemu -m 512 -enable-kvm

5. Run your Android project using this run configuration.

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.

Creating an SD card image

There are several ways of creating an SD card image. The easiest way is to use the AVD
Manager to create a new SD card by specifying a size when you create an AVD. You can
also use the android command line tool when creating an AVD. Just add the -c option to
your command:
android create avd -n <avd_name> -t <targetID> -c <size>[K|M]
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:
mksdcard <size> <file>

For example:
mksdcard 1024M sdcard1.iso
For more information, see mksdcard.

Copying files to an SD card image

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.
Loading an SD card image

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):
emulator -sdcard <filepath>

Working with Emulator Disk Images

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.
Default image files

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>).
Name
userdata.img

Description
The initial user-data disk
image

Comments
Override using -initdata <file>. Also
see -data <file>, below.

Runtime images: user data and SD card

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).
Name

Description

An image to which the

userdataemulator writes runtime


qemu.img

user-data for a unique user.

Comments
Override using -data <filepath>,
where <filepath> is the path the
image, relative to the current working
directory. If you supply a filename only,
the emulator looks for the file in the
current working directory. If the file at
<filepath> does not exist, the emulator
creates an image from the default
userdata.img, stores it under the name
you specified, and persists user data to
it at shutdown.

Override using -sdcard <filepath>,


where <filepath> is the path the
An image representing an SD
image, relative to the current working
sdcard.img card inserted into the
directory. If you supply a filename only,
emulated device.
the emulator looks for the file in the
current working directory.
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:

A writable copy of the Android system image

The /cache partition image

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.
Network Address Space

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:
Network Address

Description

10.0.2.1

Router/gateway address

10.0.2.2

Special alias to your host loopback interface (i.e., 127.0.0.1


on your development machine)

10.0.2.3

First DNS server

10.0.2.4 / 10.0.2.5 /
Optional second, third and fourth DNS server (if any)
10.0.2.6
10.0.2.15

The emulated device's own network/ethernet interface

127.0.0.1

The emulated device's own loopback interface

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)
Local Networking Limitations

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.
Using Network Redirection

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.
Setting up Redirection through the Emulator Console

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:
telnet localhost 5554
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.:
redir add tcp:5000: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.
Configuring the Emulator's DNS Settings

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).
Using the Emulator with a Proxy

If your emulator must access the Internet through a proxy server, you can use the -httpproxy <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 -httpproxy 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.
Assume that your environment is

A is you development machine

B is your first emulator instance, running on A

C is your second emulator instance, also running on A

and you want to run a server on B, to which C will connect, here is how you could set it up:
1. Set up the server on B, listening to 10.0.2.15:<serverPort>
2. On B's console, set up a redirection from A:localhost:<localPort> to
B:10.0.2.15:<serverPort>

3. On C, have the client connect to 10.0.2.2:<localPort>

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

Sending a Voice Call or SMS to Another Emulator Instance

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 initiate a simulated voice call to another emulator instance:
1. Launch the dialer application on the originating emulator instance.
2. As the number to dial, enter the console port number of the instance you'd
like to call. You can determine the console port number of the target
instance by checking its window title, where the console port number is
reported as "Android Emulator (<port>).
3. Press "Dial". A new inbound call appears in the target emulator instance.

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.
Using the Emulator Console

Each running emulator instance provides a console that lets you query and control the
emulated device environment. For example, you can use the console to manage port
redirection, network characteristics, and telephony events while your application is running
on the emulator. To access the console and enter commands, use telnet to connect to the
console's port number.
To connect to the console of any running emulator instance at any time, use this command:
telnet localhost <console-port>

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:
Android Emulator (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.
To exit the console session, use quit or exit.

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

Subcommand

the subcommands listed in the table below.


Description

Comments

List the current port


redirection.

list

add <protocol>:<host- Add a new port


port>:<guest-port>
redirection.

del <protocol>:<hostDelete a port redirection.


port>

<protocol> must be
either "tcp" or "udp"

<host-port> is the port


number to open on the
host

<guest-port> is the port


number to route data to
on the emulator/device

The meanings of <protocol>


and <host-port> are listed in
the previous row.

Geo Location Provider Emulation

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.

Subcommand
fix <longitude>
<latitude>
[<altitude>]
nmea <sentence>

Description
Send a simple GPS fix to
the emulator instance.

Comments
Specify longitude and latitude
in decimal degrees. Specify
altitude in meters.

Send an NMEA 0183


<sentence> must begin with
sentence to the emulated '$GP'. Only '$GPGGA' and
device, as if it were sent '$GPRCM' sentences are

from an emulated GPS


modem.

currently supported.

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")

For more information about the Location Manager, see LocationManager.


Hardware Events Emulation

The event console commands sends hardware events to the emulator. The syntax for this
command is as follows:
event <send|types|codes|text>
The event command supports the subcommands

Subcommand

listed in the table below.

Description

Comments

You can use text names or


send
Send one or more events
<type>:<code>:<value>
integers for <type> and
to the Android kernel.
[...]
<value>.
types

List all <type> string


aliases supported by the
event subcommands.

codes <type>

List all <codes> string


aliases supported by the
event subcommands for
the specified <type>.

Simulate keypresses to
send the specified string
event text <message>
of characters as a
message,

The message must be a UTF-8


string. Unicode posts will be
reverse-mapped according to
the current device keyboard.
Unsupported characters will be
discarded silently.

Device Power Characteristics

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.

Subcommand

Descriptio
n

display

Display
battery and
charger
state.

ac <on|off>

Set AC
charging
state to on
or off.

status <unknown|charging|discharging|notcharging|full>

Change
battery
status as
specified.

present <true|false>

Set battery
presence
state.

Comments

Set battery

health <unknown|good|overheat|dead|overvoltage|
health
failure>

state.

capacity <percent>

Set
remaining
battery
capacity
state (0100).

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

Network Delay Emulation

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:

emulator -netdelay gprs


emulator -netdelay 40 100

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.
network delay gprs

The format of network <delay> is one of the following (numbers are milliseconds):
Value

Description

Comments

gprs

GPRS

(min 150, max 550)

edge

EDGE/EGPRS

(min 80, max 400)

umts

UMTS/3G

(min 35, max 200)

none

No latency

(min 0, max 0)

<num>

Emulate an exact latency


(milliseconds).

<min>:<max>

Emulate an specified
latency range (min, max
milliseconds).

Network Speed Emulation

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:
emulator -netspeed gsm
emulator -netspeed 14.4 80

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.
network speed 14.4 80
The format of network <speed>

is one of the following (numbers are kilobits/sec):

Value

Description

Comments

gsm

GSM/CSD

(Up: 14.4, down: 14.4)

hscsd

HSCSD

(Up: 14.4, down: 43.2)

gprs

GPRS

(Up: 40.0, down: 80.0)

edge

EDGE/EGPRS

(Up: 118.4, down: 236.8)

umts

UMTS/3G

(Up: 128.0, down: 1920.0)

hsdpa

HSDPA

(Up: 348.0, down: 14400.0)

full

no limit

(Up: 0.0, down: 0.0)

<num>

Set an exact rate used for


both upload and download.

<up>:<down>

Set exact rates for upload


and download separately.

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.

Subcommand

Description

Comments

call
<phonenumber>

Simulate an
inbound phone call
from
<phonenumber>.

accept
<phonenumber>

Accept an inbound
call from
You can change a call's state to "active"
<phonenumber>
only if its current state is "waiting" or
and change the
"held".
call's state "active".

busy
<phonenumber>

Close an outbound
call to
<phonenumber>
You can change a call's state to "busy"
and change the
only if its current state is "waiting".
call's state to
"busy".

cancel
<phonenumber>

Terminate an
inbound or
outbound phone
call to/from
<phonenumber>.

Supported <state> values are:

unregistered -- No network

available

data <state>

Change the state of


the GPRS data
connection to
<state>.

home -- On local network, non-

roaming

roaming -- On roaming network

searching -- Searching networks

denied -- Emergency calls only

off -- Same as 'unregistered'

on -- same as 'home'

hold

You can change a call's state to "held"


Change the state of
only if its current state is "active" or
a call to "held".
"waiting".

list

List all inbound and


outbound calls and
their states.
Supported <state> values are:

unregistered -- No network

available

voice <state>

status

SMS Emulation

Change the state of


the GPRS voice
connection to
<state>.

Report the current


GSM voice/data
state.

home -- On local network, non-

roaming

roaming -- On roaming network

searching -- Searching networks

denied -- Emergency calls only

off -- Same as 'unregistered'

on -- Same as 'home'

Values are those described for the voice


and data commands.

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:
sms send <senderPhoneNumber> <textmessage>
where <senderPhoneNumber> contains an arbitrary numeric

string.

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>
The vm command supports the subcommands

Subcommand

listed in the table below.

Description

start

Start the VM on the


instance.

stop

Stop the VM on the


instance.

start

Display the current status


of the VM (running or
stopped).

Comments

Emulator Window

You can use the window command to manage the emulator window. The syntax for this
command is as follows:
window <scale>
The vm command supports

Subcommand

scale <scale>

the subcommands listed in the table below.


Description

Scale the emulator


window.

Terminating an Emulator Instance

Comments
A number between 0.1 and 3
that sets the scaling factor. You
can also specify scale as a DPI
value if you add the suffix "dpi"
to the scale value. A value of
"auto" tells the emulator to
select the best window size.

You can terminate an emulator instance through the console, using the kill command.
Emulator Limitations

The functional limitations of the emulator include:

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

Troubleshooting Emulator Problems

The adb utility sees the emulator as an actual physical device. For this reason, you might
have to use the -d flag with some common adb commands, such as install. The -d flag lets
you specify which of several connected devices to use as the target of a command. If you
don't specify -d, the emulator targets the first device in its list. For more information about
adb, see Android Debug Bridge.
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 Frequently Asked Questions for more troubleshooting information.

Using Hardware Devices


In this document
1. Enabling On-device Developer Options
2. Setting up a Device for Development
1. USB Vendor IDs

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 Androidpowered 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.

Enabling On-device Developer Options

Android-powered devices have a host of developer options that you can access on the phone,
which let you:

Enable debugging over USB.

Quickly capture bug reports onto the device.

Show CPU usage on screen.

Draw debugging information on screen such as layout bounds, updates on GPU views
and hardware layers, and other information.

Plus many more options to simulate app stresses or enable debugging options.

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.

Setting up a Device for Development


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:
1. Verify that your application is "debuggable" in your manifest or build.gradle file.
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).
2. 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.
Note: On Android 4.2 and newer, Developer options is hidden by default. To
make it available, go to Settings > About phone and tap Build number seven
times. Return to the previous screen to find Developer options.
3. Set up your system to detect your device.
o If you're developing on Windows, you need to install a USB driver for adb.
For an installation guide and links to OEM drivers, see the OEM USB Drivers
document.
o If you're developing on Mac OS X, it just works. Skip this step.
o If you're developing on Ubuntu Linux, you need to add a udev rules file that
contains a USB configuration for each type of device you want to use for
development. In the rules file, each device manufacturer is identified by a
unique vendor ID, as specified by the ATTR{idVendor} property. For a list of
vendor IDs, see USB Vendor IDs, below. To set up device detection on Ubuntu
Linux:
a. Log in as root and create this file: /etc/udev/rules.d/51android.rules.
Use this format to add each vendor to the file:

SUBSYSTEM=="usb", ATTR{idVendor}=="0bb4", MODE="0666",


GROUP="plugdev"

In this example, the vendor ID is for HTC. The MODE assignment


specifies read/write permissions, and GROUP defines which Unix group
owns the device node.
Note: The rule syntax may vary slightly depending on your
environment. Consult the udev documentation for your system as

needed. For an overview of rule syntax, see this guide to writing udev
rules.
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.

USB Vendor IDs


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.
Company
Acer
ASUS
Dell
Foxconn
Fujitsu
Fujitsu Toshiba
Garmin-Asus
Google
Haier
Hisense
HTC
Huawei
Intel
K-Touch
KT Tech

USB Vendor ID
0502
0b05
413c
0489
04c5
04c5
091e
18d1
201E
109b
0bb4
12d1
8087
24e3
2116

Kyocera
Lenovo
LG
Motorola
MTK
NEC
Nook
Nvidia
OTGV
Pantech
Pegatron
Philips
PMC-Sierra
Qualcomm
SK Telesys
Samsung
Sharp
Sony
Sony Ericsson
Sony Mobile Communications
Teleepoch
Toshiba
ZTE

0482
17ef
1004
22b8
0e8d
0409
2080
0955
2257
10a9
1d4d
0471
04da
05c6
1f53
04e8
04dd
054c
0fce
0fce
2340
0930
19d2

OEM USB Drivers


In this document
1. Installing a USB Driver
1. Windows 7
2. Windows Vista
2. OEM Drivers

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).

Installing a USB Driver


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:
1. Connect your Android-powered device to your computer's USB port.
2. Right-click on Computer from your desktop or Windows Explorer, and select
Manage.
3. Select Devices in the left pane.
4. Locate and expand Other device in the right pane.
5. Right-click the device name (such as Nexus S) and select Update Driver Software.
This will launch the Hardware Update Wizard.

6. Select Browse my computer for driver software and click Next.


7. Click Browse and locate the USB driver folder. (The Google USB Driver is located in
<sdk>\extras\google\usb_driver\.)
8. Click Next to install the driver.
Or, to upgrade an existing Android USB driver on Windows 7 with the new driver:
1. Connect your Android-powered device to your computer's USB port.
2. Right-click on Computer from your desktop or Windows Explorer, and select
Manage.
3. Select Device Manager in the left pane of the Computer Management window.
4. Locate and expand Android Phone in the right pane.
5. Right-click Android Composite ADB Interface and select Update Driver. This will
launch the Hardware Update Wizard.
6. Select Install from a list or specific location and click Next.
7. Select Search for the best driver in these locations; un-check Search removable
media; and check Include this location in the search.
8. Click Browse and locate the USB driver folder. (The Google USB Driver is located in
<sdk>\extras\google\usb_driver\.)
9. Click Next to upgrade the 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:
1. Connect your Android-powered device to your computer's USB port.
2. Right-click on Computer from your desktop or Windows Explorer, and select
Manage.
3. Select Device Manager in the left pane.
4. Locate and expand ADB Interface in the right pane.
5. Right-click on HTC Dream Composite ADB Interface, and select Update Driver
Software.
6. When Vista starts updating the driver, a prompt will ask how you want to search for
the driver software. Select Browse my computer for driver software.
7. 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.
8. Click Next. Vista might prompt you to confirm the privilege elevation required for
driver installation. Confirm it.
9. When Vista asks if you'd like to install the Google ADB Interface device, click Install
to upgrade the 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).
OEM
Acer
ALCATEL ONE TOUCH

Asus
Dell
Foxconn

Driver URL
http://www.acer.com/worldwide/support/mobile.html
http://www.alcatelonetouch.com/global-en/support/faq/usbdriver.html
http://support.asus.com/download/
http://support.dell.com/support/downloads/index.aspx?
c=us&cs=19&l=en&s=dhs&~ck=anavml
http://drivers.cmcs.com.tw/

Fujitsu
Garmin-Asus
Hisense
HTC
Huawei
Intel
KT Tech
Kyocera
Lenovo
LGE
Motorola
MTK
Oppo
Pantech
Pegatron
Samsung
Sharp
SK Telesys
Sony Mobile
Communications
Teleepoch
Toshiba

http://www.fmworld.net/product/phone/sp/android/develop/
https://www.garminasus.com/en_US/support/pcsync/
http://app.hismarttv.com/dss/resourcecontent.do?
method=viewResourceDetail&resourceId=16&type=5
http://www.htc.com
Click on the support tab to select your products/device. Different
regions will have different links.
http://www.huaweidevice.com/worldwide/downloadCenter.do?
method=index
http://www.intel.com/software/android
http://www.kttech.co.kr/cscenter/download05.asp for EV-S100 (Take)
http://www.kyocera-wireless.com/support/phone_drivers.htm
http://developer.lenovomm.com/developer/download.jsp
http://www.lg.com/us/mobile-phones/mobile-support/mobile-lgmobile-phone-support.jsp
http://developer.motorola.com/docstools/USB_Drivers/
http://online.mediatek.com/Public
%20Documents/MTK_Android_USB_Driver.zip
http://www.oppo.com/index.php?q=software/view&sw_id=631
http://www.isky.co.kr/cs/software/software.sky?fromUrl=index
http://www.pegatroncorp.com/download/New_Duke_PC_Driver_0705
.zip (ZIP download)
http://www.samsung.com/us/support/downloads
http://k-tai.sharp.co.jp/support/
http://www.sk-w.com/service/wDownload/wDownload.jsp
http://developer.sonymobile.com/downloads/drivers/

http://www.teleepoch.com/android.html
http://support.toshiba.com/sscontent?docId=4001814
http://www.yulong.com/product/product/product/downloadList.html#d
Yulong Coolpad
ownListUL
Xiaomi
http://www.xiaomi.com/c/driver/index.html
http://support.zte.com.cn/support/news/NewsDetail.aspx?
ZTE
newsId=1000442
Except as noted, this content is licensed under Creative Commons Attribution 2.5. For details
and restrictions, see the Content License.
About Android | Legal | Support

Managing Projects Overview


In this document
1. Android Project Files
2. Android Application Modules
3. Library Modules
1. Development considerations
4. Test Modules
5. Testing a Library Module
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:
Android Application Modules
An Android Application Module is the container for your application's source code,
resource files, and application level settings, such as the module-level build file,
resource files, and Android Manifest file. The application module contents are
eventually built into the .apk file that gets installed on a device.
Test Modules
These modules contain code to test your application projects and are built into test
applications that run on a device. By default, Android Studio creates the androidTest
module for inserting JUnit tests.
Library Modules
These modules contain shareable Android source code and resources that you can
reference in Android projects. This is useful when you have common code that you
want to reuse. Library modules cannot be installed onto a device, however, they are
pulled into the .apk file at build time.
App Engine Modules
Android Studio lets you easily add a cloud backend to your application. A backend
allows you to implement functionality such as backing up user data to the cloud,
serving content to client apps, real-time interactions, sending push notifications
through Google Cloud Messaging for Android (GCM), and more. App Engine
modules are App Engine java Servlet Module for backend development, App Engine
java Endpoints Module to convert server-side Java code annotations into RESTful
backend APIs, and App Engine Backend with Google Cloud Messaging to send push
notifications from your server to your Android devices.

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 Project Files


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

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/

libs/

Contains build folders for the specified build variants. Stored in the main application
module.
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
Library module example code
The SDK includes an example application called TicTacToeMain that shows how a
dependent application can use code and resources from an Android Library module. The
TicTacToeMain application uses code and resources from an example library module called
TicTacToeLib.
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.

Structurally, a library module is similar to a standard Android application module. For


example, it includes a manifest file at the module root, as well as src/, res/ and similar
directories. The module can contain the same types of source code and resources as a
standard Android module, stored in the same way. For example, source code in the library
module can access its own resources through its R class.
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.

Use prefixes to avoid resource conflicts


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).

You cannot export a library module to a JAR file


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.

A library module can include a JAR library


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.

A library module can depend on an external JAR library


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.

Library modules cannot include raw assets

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.

Platform version must be lower than or equal to the Android module


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.

No restriction on library module names


There is no requirement for the package name of a library to be the same as that of
applications that use it.

Each library module creates its own R class


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.

Library module storage location


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.
For more information, see the Testing section.

Testing a Library Module


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.

Managing Projects from Android Studio


In this document
1. Creating an Android Project
1. Create a New Project
2. Select Form Factors and API Level
3. Add an Activity
4. Configure Your App
5. Develop Your App
2. Creating an Android Module
3. Setting up a Library Module
4. Referencing a Library Module
5. Setting up an App Eng Module
6. Using the Android Project View
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.

Creating an Android Project


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.
Follow the steps in this section to create a project in Android Studio.

Step 1: Create a New Project


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.


Enter the values for your project then click Next.

Step 2: Select Form Factors and API Level


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.


Then, on the Form Factors Window, click Next.

Step 3: Add an Activity


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.


Choose an activity type then click Next.
Note: If you choose "Add No Activity", click Finish to create the project.

Step 4: Configure Your Activity


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.

Step 5: Develop Your App


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

Creating an Android Module


Android application modules contain the src/main/, AndroidManifest.xml,
build.gradle, build output and other files you need to generate your app's APK files.
Android Studio provides a New Module Wizard that you can use to quickly create a new
Android module (or a module from existing code) based on selected application settings, such
as minimum SDK level and activity template.
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 Javabased 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.

Setting up a Library Module

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.
apply plugin: 'com.android.application'
android {...}
apply plugin: 'com.android.library'
android {...}

Adding a dependency on a library module


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.

Referencing a library module

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.
To add a reference to a library module, follow these steps:
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.

Declaring library components in the manifest file


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.

Using the Android Project View


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.

Figure 9: Show the Android project view.

Enable and use the Android Project View


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:

java/

manifests/

res/

- Source files for the module.


- Manifest files for the module.

- Resource files for the module.

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).

Managing Projects from the Command


Line
In this document
1. Creating an Android Project
2. Updating a Project
3. Setting up a Library Project
1. Creating the manifest file
2. Updating a library project
4. Referencing a Library Project
1. Declaring library components in the manifest file
2. Building a dependent application

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.

Creating an Android Project


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:
android create project \
--target <target_ID> \
--name <your_project_name> \
--path path/to/your/project \
--activity <your_activity_name> \
--package <your_package_namespace>

target

name

path

activity

package

is the "build target" for your application. It corresponds to an Android


platform library (including any add-ons, such as Google APIs) that you would like to
build your project against. To see a list of available targets and their corresponding
IDs, execute: android list targets.
is the name for your project. This is optional. If provided, this name will be used
for your .apk filename when you build your application.
is the location of your project directory. If the directory does not exist, it will be
created for you.
is the name for your default Activity class. This class file will be created
for you inside
<path_to_your_project>/src/<your_package_namespace_path>/ . This will
also be used for your .apk filename unless you provide a name.
is the package namespace for your project, following the same rules as for
packages in the Java programming language.

Here's an example:
android create project \
--target 1 \
--name MyAndroidApp \
--path ./MyAndroidAppProject \
--activity MyAndroidAppActivity \
--package com.example.myandroid

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:
android update project --name <project_name> --target <target_ID>
--path <path_to_your_project>

target

path

name

is the "build target" for your application. It corresponds to an Android


platform library (including any add-ons, such as Google APIs) that you would like to
build your project against. To see a list of available targets and their corresponding
IDs, execute: android list targets.
is the location of your project directory.

is the name for the project. This is optionalif you're not changing the project
name, you don't need this.

Here's an example:
android update project --name MyApp --target 2 --path ./MyAppProject

Setting up a Library Project


A library project is a standard Android project, so you can create a new one in the same way
as you would a new application project. Specifically, you can use the android tool to
generate a new library project with all of the necessary files and folders.
To create a new library project, navigate to the <sdk>/tools/ directory and use this
command:
android create lib-project --name <your_project_name> \
--target <target_ID> \
--path path/to/your/project \
--package <your_library_package_namespace>

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.

Creating the manifest 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>

Updating a library project


If you want to update the build properties (build target, location) of the library project, use
this command:
android update lib-project \
--target <target_ID> \
--path path/to/your/project

Referencing a Library Project


If you are developing an application and want to include the shared code or resources from a
library project, you can do so easily by adding a reference to the library project in the
application project's build properties.
To add a reference to a library project, navigate to the <sdk>/tools/ directory and use this
command:
android update project \
--target <target_ID> \
--path path/to/your/project
--library path/to/library_projectA

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.

Declaring library components in the manifest file


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.

Building a dependent application

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.

Using Code Templates


In this document
1. Application Templates
1. BlankActivity Template
2. Full Screen Activity Template
3. Master Detail Flow Template
2. Activity Templates
1. Login Activity Template
2. Settings Activity Template
3. Other Templates
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.

To use Android application templates:


1. In Android Studio, select File > New > Module.
2. Enter the settings for your application, including Application Name, Company
Domain, Package name, and minimum SDK, then click Next.
3. Select an application template to use, then click Next. For example,
o BlankActivity
o FullScreenActivity
o MasterDetailFlow
4. Enter the settings for your activity, including Activity Name, layout Name, Title,
and Menu Resource Name, then click Finish.
Note: The other activity template options also create applications, however these applications
require further modification before they can be launched on an Android device.

Blank Activity Template


Example

Description

The BlankActivity template with the Navigation Type:


None option creates a simple application that follows the
Android Design guidelines. Use this template to create a
basic, minimal app as a starting point for your project.
This template includes:

Title bar (ActionBar on Android 3.0 and later)

Options menu (action overflow on Android 3.0 and


later)

Basic layout

The BlankActivity template with the Navigation Type:


Tabs or Tabs + Swipe option creates an application with
three sections based on the Fragment class and a tabbed user
interface.
This template includes:

ActionBar

Fragment

Optional swipe gesture support based on the swipe


view design pattern, which extends
FragmentPagerAdapter to manage section
fragments

for tab controls

objects for section content

The BlankActivity template with the Navigation Type:


Swipe Views + Title Strip option creates an application
with three Fragment sections, a compact title strip header
(known as Scrollable Tabs in the Android Design guide) and
swipe navigation between the sections, based on the swipe
view design pattern.
This template includes:

PagerTitleStrip

Fragment

FragmentPagerAdapter

fragments

for section titles

objects for section content


to manage section

The BlankActivity template with the Navigation Type:


Dropdown option creates an application that extends
FragmentActivity, containing three Fragment sections,
with an ActionBar using list mode navigation.
This template includes:

ActionBar

Fragment

for list mode navigation

objects for section content

Full Screen Activity Template


Example

Description

This template provides an implementation of an


activity which alternates between a primary, full screen
view and a view with standard user interface controls,
including the notification bar and application title bar.
The full screen view is the default and a user can
activate the standard view by touching the device
screen.
This template includes:

Master Detail Flow Template

SystemUiHider

Basic layout

implementation that manages


hiding of the system user interface using a
version-compatible approach

Example

Description
This template creates an adaptive
layout for a set of items and
associated details. On a tablet device,
the item list and item details are
displayed on the same screen. On a
smaller device, the list and details are
displayed on separate screens.
Note: This template follows the
recommendations of the Designing for
Multiple Screens Android training.
This template includes:

Adaptive layout using


alternative resource XML files

FragmentActivity,
Fragment and ListFragment

implementations

Activity Templates
Android activity templates provide options to add new activities to your existing application.
To use Android activity templates:
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.

Login Activity Template


Example

Description

This activity template provides input fields and a sample


implementation of an AsyncTask that asks users to login or
register with their credentials.
This template includes:

Recommended user interface for requesting login


information

AsyncTask

Progress indicator during network operations

implementation for handing network


operations separately from the main user interface
thread

Settings Activity Template


Example

Description

This template extends the PreferenceActivity class and


uses an XML file to create preference settings. This template
also demonstrates how to implement several data types for
settings.
This template includes:

Activity extending PreferenceActivity

Preference values defined using XML files added to


the res/xml/ directory of your project.

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:
To use Android object templates:
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:

Building and Running from Android Studio


In this document
1. Building your Project in Android Studio
1. Build a release version
2. Running your App
1. Creating a Run Configuration
2. Automatic and manual target modes
3. Running on an Emulator
4. Running on a Device

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.

Build your Project in Android Studio


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:
Gradle: Executing tasks: [:app:assembleDebug, :lib:bundleDebug]

Click
as shown in figure 2.

on the bottom right part of the window to show the Gradle Console,

Figure 2. The Gradle Console in Android Studio.


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.

Figure 3. The list of build tasks in Android Studio.

Build a release version


You can now build the release version of your application for distribution. To build it from
Android Studio:

1. Click Gradle on the right side of the IDE window.


2. On the All tasks section of the sidebar that appears, expand BuildSystemExample.
3. Expand :app and double-click assembleRelease.
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.
For more build system information, see Build System.

Running your app


This section shows you how to run your application on an emulator or a real device from
Android Studioall 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

Creating a Run Configuration


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.
To create or modify a run configuration, see the IntelliJ documentation on Run/Debug
configurations.
The following steps highlight the important things you need to do for an Android project:
1. Open Edit Configurations from the Run Menu.
2. Expand the Android Application item and create a new configuration or open an
existing one.
3. With the Run Configuration selected, adjust your desired run configuration settings:
o In the General tab, specify the Module settings to launch. In Target tab,
consider whether you'd like to use Manual or Automatic mode when selecting
an AVD to run your application. See the following section on Automatic and
manual target modes).

o In the Emulator tab, specify any emulator options to the Additional Emulator
Command Line Options field. For example, you could add -scale 96dpi to
scale the AVD's screen to an accurate size, based on the dpi of your computer
monitor. For a full list of emulator options, see the Android Emulator
document.
o In the Logcat tab, set the LogCat options for the application.

Automatic and manual target modes


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.

Running on the emulator


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.
Note: On Android 4.2 and newer, Developer options is hidden by default. To
make it available, go to Settings > About phone and tap Build number seven
times. Return to the previous screen to find Developer options.

Ensure that your development computer can detect your device when connected via
USB

Read Using Hardware Devices for more information.

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.

Building and Running from the Command


Line
In this document
1. Building in Debug Mode
2. Building in Release Mode
1. Build unsigned
2. Build signed and aligned
3. Once built and signed in release mode
3. Running on the Emulator
4. Running on a Device
5. Application Signing
6. Gradle Command Reference

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 devicewith 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

Building in Debug Mode


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.
On Windows platforms, type this command:
> gradlew.bat assembleDebug

On Mac OS and Linux platforms, type these commands:


$ chmod +x gradlew
$ ./gradlew assembleDebug

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.

Building in Release Mode


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.
On Windows platforms, type this command:
> gradlew.bat assembleRelease

On Mac OS and Linux platforms, type this command:


$ ./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.

Build signed and aligned


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:
1. Open a command-line and navigate to the root of your module directory.
2. Edit the gradle.build file to build your project 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.


Caution: As described above, your password will be visible on the screen.

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 built and signed in release mode


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.)

Running on the Emulator


Before you can run your application on the Android Emulator, you must create an AVD.
To run your application:
1. Open the AVD Manager and launch a virtual device
From your SDK's platform-tools/ directory, execute the android tool with the avd
options:
android avd

In the Virtual Devices view, select an AVD and click Start.


2. Install your application
From your SDK's tools/ directory, install the .apk on the emulator:
adb install <path_to_your_bin>.apk

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:
adb -s emulator-5554 install path/to/your/app.apk

To see a list of available device serial numbers, execute adb devices.


If you don't see your application on the emulator, try closing the emulator and launching the
virtual device again from the AVD Manager. Sometimes when you install an application for
the first time, it won't show up in the application launcher or be accessible by other
applications. This is because the package manager usually examines manifests completely
only on emulator startup.

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:

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.
Note: On Android 4.2 and newer, Developer options is hidden by default. To
make it available, go to Settings > About phone and tap Build number seven
times. Return to the previous screen to find Developer options.

Ensure that your development computer can detect your device when connected via
USB

Read Setting up a Device for Development for more information.


Once your device is set up and connected via USB, navigate to your SDK's platformtools/ directory and install the .apk on the device:
adb -d install path/to/your/app.apk

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.

Gradle Build Language Reference


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

New Gingerbread API: StrictMode

StrictMode is a new API in Gingerbread which primarily lets you set a policy on a thread
declaring what youre 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.

Traceview War Story

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 havent 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.
The testing framework has these key features:

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

Tests, like Android applications, are organized into 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:

Automatically set up your test package to use InstrumentationTestRunner


as the test case runner. You must use InstrumentationTestRunner (or a
subclass) to run JUnit tests.

Create an appropriate name for the test package. If the application under
test has a package name of com.mydomain.myapp, then the Android tools set
the test package name to com.mydomain.myapp.test. This helps you identify
their relationship, while preventing conflicts within the system.

Automatically create the proper build files, manifest file, and directory
structure for the test project. This helps you to build the test package
without having to modify build files and sets up the linkage between your
test package and the application under test. The

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 Testing API

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:
// Start the main activity of the application under test
mActivity = getActivity();
// Get a handle to the Activity object's main UI widget, a Spinner
mSpinner =
(Spinner)mActivity.findViewById(com.android.example.spinner.R.id.Spinner01)
;

// Set the Spinner to a known position


mActivity.setSpinnerPosition(TEST_STATE_DESTROY_POSITION);
// 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();
// Get the Spinner's current position
int currentPosition = mActivity.getSpinnerPosition();
// Assert that the current position is the same as the starting
position
assertEquals(TEST_STATE_DESTROY_POSITION, currentPosition);
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.
Test case classes

Android provides several test case classes that extend TestCase and Assert with Androidspecific 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.
Component-specific test cases

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:

MoreAsserts contains more powerful assertions such as


assertContainsRegex(String, String), which does regular expression

matching.

ViewAsserts contains useful assertions about Views. For example it


contains assertHasScreenCoordinates(View, View, int, int) that tests if a

View has a particular X and Y position on the visible screen. These asserts
simplify testing of geometry and alignment in the UI.
Mock object 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.
These are the mock object classes available in Android:
Simple mock object classes
MockApplication, MockContext, MockContentProvider, MockCursor,
MockDialogInterface, MockPackageManager,

and MockResources provide a simple and


useful mock strategy. They are stubbed-out versions of the corresponding system object class,
and all of their methods throw an UnsupportedOperationException exception if called. To
use them, you override the methods you need in order to provide mock dependencies.
Note: MockContentProvider and MockCursor are new as of API level 8.
Resolver mock objects

provides isolated testing of content providers by masking out the


normal system resolver framework. Instead of looking in the system to find a content
provider given an authority string, MockContentResolver uses its own internal table. You
must explicitly add providers to this table using addProvider(String, ContentProvider).
MockContentResolver

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.
Contexts for testing

Android provides two Context classes that are useful for testing:

IsolatedContext provides an isolated Context, File, directory, and database

operations that use this Context take place in a test area. Though its
functionality is limited, this Context has enough stub code to respond to
system calls.

This class allows you to test an application's data operations without affecting real
data that may be present on the device.

RenamingDelegatingContext provides a Context in which most functions are


handled by an existing Context, but file and database operations are
handled by a IsolatedContext. The isolated part uses a test directory and

creates special file and directory names. You can control the naming
yourself, or let the constructor determine it automatically.

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.
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.
InstrumentationTestRunner

You specify InstrumentationTestRunner or a subclass in your test package's manifest file,


in the <instrumentation> element. Also, InstrumentationTestRunner code resides in the
shared library android.test.runner, which is not normally linked to Android code. To
include it, you must specify it in a <uses-library> element. You do not have to set up these
elements yourself. Both Eclipse with ADT and the android command-line tool construct
them automatically and add them to your test package's manifest file.
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.
To run InstrumentationTestRunner, you use internal system classes called by Android
tools. When you run a test in Eclipse with ADT, the classes are called automatically. When
you run a test from the command line, you run these classes with Android Debug Bridge
(adb).
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.
Seeing Test Results

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.
monkey and monkeyrunner

The SDK provides two tools for functional-level application testing:

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 commandline tool.

Working With Package names

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.

Testing from Eclipse with ADT


In this document
1. Creating a Test Project
2. Creating a Test Package
3. Running Tests
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.

Creating a Test Project

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.
To create a test project in Eclipse with ADT:
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.

Creating a Test Package


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.
To add a test case class to your project:
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

tearDown(): 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.
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
Running tests from the command line
If you've created your tests in Eclipse, you can still run your tests and test suites by using
command-line tools included with the Android SDK. You may want to do this, for example, if
you have a large number of tests to run, if you have a large test case, or if you want a fine
level of control over which tests are run at a particular time.
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.

To run a test in Eclipse, you have two choices:

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.
Creating and running test configurations is described in the next section.

To create and run a test suite using a run 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.
4. Now click the Target tab.
o Optional: If you are using the emulator, click Automatic, then in the Android
Virtual Device (AVD) selection table, select an existing AVD.
o In the Emulator Launch Parameters pane, set the Android emulator flags you
want to use. These are documented in the topic Android Emulator.
5. Click the Common tab. In the Save As pane, click Local to save this run configuration
locally, or click Shared to save it to another project.
6. Optional: Add the configuration to the Run toolbar and the Favorites menu: in the
Display in Favorites pane click the checkbox next to Run.
7. Optional: To add this configuration to the Debug menu and toolbar, click the
checkbox next to Debug.
8. To save your settings, click Close.
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.
[yyyy-mm-dd hh:mm:ss - testfile] Waiting for HOME
('android.process.acore') to be launched...

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:
HOME is up on device 'devicename-port'

If you have not already installed your test package, then you see the message:
Uploading testfile onto device 'devicename-port'

then the message Installing testfile.


and finally the message Success!
The following lines are an example of this message sequence:
[2010-07-01
[2010-07-01
5554'
[2010-07-01
[2010-07-01

12:44:40 - MyTest] HOME is up on device 'emulator-5554'


12:44:40 - MyTest] Uploading MyTest.apk onto device 'emulator12:44:40 - MyTest] Installing MyTest.apk...
12:44:49 - MyTest] Success!

Next, if you have not yet installed the application under test to the device or emulator,
you see the message
Project dependency found, installing: appfile

then the message Uploading appfile onto device 'devicename-port'


then the message Installing appfile
and finally the message Success!
The following lines are an example of this message sequence:
[2010-07-01
[2010-07-01
5554'
[2010-07-01
[2010-07-01

12:44:49 - MyTest] Project dependency found, installing: MyApp


12:44:49 - MyApp] Uploading MyApp.apk onto device 'emulator12:44:49 - MyApp] Installing MyApp.apk...
12:44:54 - MyApp] Success!

Next, you see the message Launching instrumentation instrumentation_class


on device devicename-port

is the fully-qualified class name of the instrumentation test


runner you have specified (usually InstrumentationTestRunner.
instrumentation_class

Next, as InstrumentationTestRunner builds a list of tests to run, you see the


message
Collecting test information

followed by
Sending test information to Eclipse

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 following lines are an example of this message sequence:


[2010-01-01 12:45:02 - MyTest] Launching instrumentation
android.test.InstrumentationTestRunner on device emulator-5554
[2010-01-01 12:45:02 - MyTest] Collecting test information
[2010-01-01 12:45:02 - MyTest] Sending test information to Eclipse
[2010-01-01 12:45:02 - MyTest] Running tests...
[2010-01-01 12:45:22 - MyTest] Test run complete

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 results of a successful test are shown in figure 1.

Figure 1. Messages for a successful test.


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.

The results of a failed test are shown in figure 2.

Figure 2. Messages for a test failure.


Testing from Other IDEs
In this document
1. Working with Test Projects
1. Creating a test project
2. Updating a test project
2. Creating a Test Package
3. Running Tests
1. Quick build and run with Ant
2. Running tests on a device or emulator
4. Using the Instrument Command

1. Instrument options
2. Instrument examples
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.
Working with Test Projects

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.
Creating a test project

To create a test project with the android tool, enter:


android create test-project -m <main_path> -n <project_name> -p <test_path>

You must supply all the flags. The following table explains them in detail:
Flag

Value

Description

For example, if the application under test is in


Path to the project of source/HelloAndroid, and you want to create the test
project in source/HelloAndroidTest, then the value of
the application
-m,
--mai under test, relative --main should be ../HelloAndroid.
n
to the test package
To learn more about choosing the location of test projects,
directory.

please read Testing Fundamentals.

-n,
Name that you want
--nam to give the test
e

project.
The android tool creates the test project files and
Directory in which
-p,
--pat you want to create
directory structure in this directory. If the directory
h
the new test project. does not exist, 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.
The operation also creates an AndroidManifest.xml file with instrumentation information.
When you run the test, Android uses this information to load the application you are testing
and control it with instrumentation.
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:

<application>: to contain the <uses-library> element.

<uses-library android:name="android.test.runner": specifies this testing


application uses the android.test.runner library.

<instrumentation>: contains attributes that control Android

instrumentation. The attributes are:


o

android:name="android.test.InstrumentationTestRunner":
InstrumentationTestRunner runs test cases. It extends both JUnit

test case runner classes and Android instrumentation classes.


o

android:targetPackage="com.example.helloandroid": specifies that

android:label="Tests for .HelloAndroid": specifies a user-readable


label for the instrumentation class. By default, the android tool

the tests in HelloAndroidTest should be run against the application


with the Android package name com.example.helloandroid.

gives it the value "Tests for " plus the name of the main Activity of
the application under test.

Updating a test project

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.
To update a test project with the android tool, enter:
android update test-project -m <main_path> -p <test_path>

Flag

Value

Description

The path to the


project of the
-m,
--mai application under
n
test, relative to the
test project

For example, if the application under test is in


source/HelloAndroid, and the test project is in
source/HelloAndroidTest, then the value for --main
is ../HelloAndroid.

-p,
The of the test
--pat
project.
h

For example, if the test project is in


source/HelloAndroidTest, then the value for --path
is HelloAndroidTest.

If the operation is successful, android lists to STDOUT the names of the files and directories
it has created.
Creating a Test Package

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.
Quick build and run with Ant

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.

Running tests on a device or emulator

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.
To run a test with am instrument:
1. If necessary, rebuild your main application and test package.
2. Install your test package and main application Android package files ( .apk
files) to your current Android device or emulator
3. At the command line, enter:
$ adb shell am instrument -w <test_package_name>/<runner_class>
where <test_package_name> is the Android package name of your test application,

and <runner_class> is the name of the Android test runner class you are using. The
Android package name is the value of the package attribute of the manifest element
in the manifest file (AndroidManifest.xml) of your test package. The Android test
runner class is usually InstrumentationTestRunner.
Your test results appear in STDOUT.
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.
Using the am instrument Command

The general syntax of the am instrument command is:


The

am instrument [flags] <test_package>/<runner_class>


main input parameters to am instrument are described in the following

table:

Parameter

Value

Description

The Android package The value of the package attribute of the


<test_package> name of the test
manifest element in the test package's
package.
manifest file.
The class name of the
<runner_class> instrumented test

This is usually InstrumentationTestRunner.

runner you are using.

The flags for am instrument are described in the following table:


Fla
g

Value

Description

-w (none)

Forces am instrument to wait until the instrumentation


terminates before terminating itself. The net effect is to keep the
shell open until the tests have finished. This flag is not required,
but if you do not use it, you will not see the results of your tests.

-r (none)

Outputs results in raw format. Use this flag when you want to
collect performance measurements, so that they are not
formatted as test results. This flag is designed for use with the
flag -e perf true (documented in the section Instrument
options).

Provides testing options as key-value pairs. The am instrument


tool passes these to the specified instrumentation class via its
onCreate() method. You can specify multiple occurrences of -e
<test_options>. The keys and values are described in the
<test_optio
-e
section am instrument options.
ns>

The only instrumentation class that uses these key-value pairs is


InstrumentationTestRunner (or a subclass). Using them with any other
class has no effect.
am instrument options

The am instrument tool passes testing options to InstrumentationTestRunner or a


subclass in the form of key-value pairs, using the -e flag, with this syntax:
-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:
$ adb shell am instrument -w -e package
com.android.test.package1,com.android.test.package2 \
> com.android.test/android.test.InstrumentationTestRunner

The following table describes the key-value pairs and their result. Please review the Usage
Notes following the table.
Key

package

Value

Description

The fully-qualified Java package name for one


of the packages in the test application. Any test
case class that uses this package name is
<Java_package_na
executed. Notice that this is not an Android
me>
package name; a test package has a single
Android package name but may have several
Java packages within it.
<class_name>

The fully-qualified Java class name for one of


the test case classes. Only this test case class
is executed.

class

A fully-qualified test case class name, and one


<class_name>#m of its methods. Only this method is executed.
ethod name
Note the hash mark (#) between the class
name and the method name.

func

true

Runs all test classes that extend


InstrumentationTestCase.

unit

true

Runs all test classes that do not extend either


InstrumentationTestCase or
PerformanceTestCase.

size

[small | medium |
large]

Runs a test method annotated by size. The


annotations are @SmallTest, @MediumTest, and
@LargeTest.

perf

true

Runs all test classes that implement


PerformanceTestCase. When you use this option,
also specify the -r flag for am instrument, so
that the output is kept in raw format and not reformatted as test results.

debug

true

Runs tests in debug mode.

log

true

Loads and logs all specified tests, but does not


run them. The test information appears in
STDOUT. Use this to verify combinations of other
filters and test specifications.

emma

true

Runs an EMMA code coverage analysis and


writes the output to /data//coverage.ec on the
device. To override the file location, use the
coverageFile key that is described in the

following entry.

Note: This option requires an EMMA-instrumented


build of the test application, which you can generate
with the coverage target.

coverageFile <filename>

Overrides the default location of the EMMA


coverage file on the device. Specify this value
as a path and filename in UNIX format. The
default filename is described in the entry for
the emma key.

-e Flag Usage Notes

am instrument invokes onCreate(Bundle) with a Bundle containing the key-

value pairs.

The package key takes precedence over the class key. If you specifiy a
package, and then separately specify a class within that package, Android
will run all the tests in the package and ignore the class key.

The func key and unit key are mutually exclusive.

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.

FunctionTests, which contains the methods testCamera, testXVGA,


and testHardKeyboard.

IntegrationTests, which contains the method


testActivityProvider.

The test runner is InstrumentationTestRunner.

Running the entire test package

To run all of the test classes in the test package, enter:


$ adb shell am instrument -w
com.android.demo.app.tests/android.test.InstrumentationTestRunner

Running all tests in a test case class

To run all of the tests in the class UnitTests, enter:


$ adb shell am instrument -w \
> -e class com.android.demo.app.tests.UnitTests \
> com.android.demo.app.tests/android.test.InstrumentationTestRunner
am instrument gets the value of the -e flag, detects the class keyword, and runs all the

methods in the UnitTests class.


Selecting a subset of tests

To run all of the tests in UnitTests, and the testCamera method in FunctionTests, enter:
$ adb shell am instrument -w \
> -e class
com.android.demo.app.tests.UnitTests,com.android.demo.app.tests.FunctionTes
ts#testCamera \
> com.android.demo.app.tests/android.test.InstrumentationTestRunner

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
Activity testing is particularly dependent on the Android instrumentation framework. Unlike
other components, activities have a complex lifecycle based on callback methods; these can't
be invoked directly except by instrumentation. Also, the only way to send events to the user
interface from a program is through instrumentation.
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.

The Activity Testing API


The activity testing API base class is InstrumentationTestCase, which provides
instrumentation to the test case subclasses you use for Activities.
For activity testing, this base class provides these functions:

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.
The two main testing subclasses are ActivityInstrumentationTestCase2 and
ActivityUnitTestCase. To test an Activity that is launched in a mode other than standard,
you use SingleLaunchActivityTestCase.

ActivityInstrumentationTestCase2
The ActivityInstrumentationTestCase2 test case class is designed to do functional
testing of one or more Activities in an application, using a normal system infrastructure. It
runs the Activities in a normal instance of the application under test, using a standard system
Context. It allows you to send mock Intents to the activity under test, so you can use it to test
an activity that responds to multiple types of intents, or an activity that expects a certain type
of data in the intent, or both. Notice, though, that it does not allow mock Contexts or
Applications, so you can not isolate the test from the rest of a production system.

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
The SingleLaunchActivityTestCase class is a convenience class for testing a single
activity in an environment that doesn't change from test to test. It invokes setUp() and
tearDown() only once, instead of once per method call. It does not allow you to inject any
mock objects.
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.

Mock objects and activity testing


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().

Assertions for activity testing

defines assertions for Views. You use it to verify the alignment and position of
View objects, and to look at the state of ViewGroup objects.
ViewAsserts

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.

Appendix: UI Testing Notes

The following sections have tips for testing the UI of your Android application, specifically
to help you handle actions that run in the UI thread, touch screen and keyboard events, and
home screen unlock during testing.

Testing on the UI thread


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:
private MyActivity mActivity; // MyActivity is the class name of the app
under test
private Spinner mSpinner;
...
protected void setUp() throws Exception {
super.setUp();
mInstrumentation = getInstrumentation();
mActivity = getActivity(); // get a references to the app under test
/*
* 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);
...
public void aTest() {
/*
* request focus for the Spinner, so that the test can send key
events to it

* This request must be run on the UI thread. To do this, use the


runOnUiThread method
* and pass it a Runnable that contains a call to requestFocus on the
Spinner.
*/
mActivity.runOnUiThread(new Runnable() {
public void run() {
mSpinner.requestFocus();
}
});
mInstrumentation.waitForIdleSync();
this.sendKeys(KeyEvent.KEYCODE_DPAD_CENTER);

Turning off touch mode


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.
To turn off touch mode, you invoke
ActivityInstrumentationTestCase2.setActivityTouchMode(false) before you call
getActivity() to start the activity. You must invoke the method in a test method that is not

running on the UI thread. For this reason, you can't invoke the touch mode method from a test
method that is annotated with @UIThread. Instead, invoke the touch mode method from
setUp().

Unlocking the emulator or device


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.
To add the permission, add the element <uses-permission
android:name="android.permission.DISABLE_KEYGUARD"/> as a child of the
<manifest> element. To disable the KeyGuard, add the following code to the onCreate()

method of activities you intend to test:


mKeyGuardManager = (KeyguardManager) getSystemService(KEYGUARD_SERVICE);
mLock = mKeyGuardManager.newKeyguardLock("activity_classname");
mLock.disableKeyguard();

where activity_classname is the class name of the activity.

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:
Remove the @UiThreadTest annotation, remove the runOnUiThread() call, or refactor your tests.

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.

Service Design and Testing


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

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.
ServiceTestCase

ServiceTestCase defers initialization of the test environment until you call


ServiceTestCase.startService() or ServiceTestCase.bindService(). This

allows
you to set up your test environment, particularly your mock objects, before the Service is
started.
Notice that the parameters to ServiceTestCase.bindService()are different from those for
Service.bindService(). For the ServiceTestCase version, you only provide an Intent.
Instead of returning a boolean, ServiceTestCase.bindService() returns an object that
subclasses IBinder.
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.
The methods setApplication() and setContext(Context) setContext()} allow you to set
a mock Context or mock Application (or both) for the Service, before you start it. These
mock objects are described in Mock object classes.
By default, ServiceTestCase runs the test method
testAndroidTestCaseSetupProperly(), which asserts that the base test case class
successfully set up a Context before running.

Mock object classes


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
ServiceTestCase

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:

Ensure that the onCreate() is called in response to Context.startService() or


Context.bindService(). Similarly, you should ensure that onDestroy() is called in
response to Context.stopService(), Context.unbindService(), stopSelf(), or
stopSelfResult().

Test that your Service correctly handles multiple calls from


Context.startService(). Only the first call triggers Service.onCreate(), but all
calls trigger a call to Service.onStartCommand().
In addition, remember that startService() calls don't nest, so a single call to
Context.stopService() or Service.stopSelf() (but not stopSelf(int)) will
stop the Service. You should test that your Service stops at the correct point.

Test any business logic that your Service implements. Business logic includes
checking for invalid values, financial and arithmetic calculations, and so forth.

Content Provider Testing


In this document
1. Content Provider Design and Testing
2. The Content Provider Testing API
1. ProviderTestCase2
2. Mock object classes
3. What To Test
4. Next Steps

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.

Content Provider Design and Testing


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.

Content Provider Testing API

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.

Mock object classes


uses IsolatedContext and MockContentResolver, which are
standard mock object classes. To learn more about them, please read Testing Fundamentals.
ProviderTestCase2

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.
Accessibility Testing Checklist
In this document
1. Testing Goals
2. Testing Requirements
3. Testing Recommendations

4. Special Cases and Considerations


5. Testing Accessibility Features
1. Testing audible feedback
2. Testing focus navigation
3. Testing gesture navigation
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:

Set up and use the application without sighted assistance

All task workflows in the application can be easily navigated using


directional controls and provide clear and appropriate feedback

Testing Requirements

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.
Testing Accessibility Features

Testing of accessibility features such as TalkBack, Explore by Touch and accessibility


Gestures requires setup of your testing device. This section describes how to enable these
features for accessibility testing.
Testing audible feedback

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.
Audible feedback for users on Android is typically provided by TalkBack accessibility
service and the Explore by Touch system feature. The TalkBack accessibility service comes
preinstalled on most Android devices and can also be downloaded for free from Google Play.
The Explore by Touch system feature is available on devices running Android 4.0 and later.
Testing with TalkBack

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.

To enable the TalkBack accessibility service:


1. Launch the Settings application.
2. Navigate to the Accessibility category and select it.
3. Select Accessibility to enable it.
4. Select TalkBack to enable it.

Note: While TalkBack is the most available Android accessibility service for users with
disabilities, other accessibility services are available and may be installed by users.
For more information about using TalkBack, see TalkBack.
Testing with Explore by Touch

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.
To enable Explore by Touch on Android 4.0 and later:
1. Launch the Settings application.
2. Navigate to the Accessibility category and select it.
3. Select the TalkBack to enable it.

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.
Testing focus navigation

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.
Testing gesture navigation

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.
To enable gesture navigation on Android 4.1 and later:

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 applications 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 errorprone. 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:

uiautomatorviewer

- A GUI tool to scan and analyze the UI components of an

Android application.

- A Java library containing APIs to create customized functional UI


tests, and an execution engine to automate and run the tests.
uiautomator

To use these tools, you must have the following versions of the Android development tools
installed:

Android SDK Tools, Revision 21 or higher

Android SDK Platform, API 16 or higher

Workflow for the the uiautomator testing framework


Here's a short overview of the steps required to automate UI testing:
1. Prepare to test by installing the app on a test device, analyzing the apps 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.

Analyzing Your Application's UI

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.


To analyze the UI components of the application that you want to test:

1. Connect your Android device to your development machine.


2. Open a terminal window and navigate to <android-sdk>/tools/.
3. Run the tool with this command:
$ 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

b. Set the ANDROID_SERIAL environment variable to select the device to test:

In Windows:
set ANDROID_SERIAL=<device serial number>

In UNIX:
export ANDROID_SERIAL=<device serial number>

If you are connected to only a single device, you do not need to set the
ANDROID_SERIAL environment variable.
5. View the UI properties for your application:
a. Hover over the snapshot in the left-hand panel to see the UI components
identified by the uiautomatorviewer tool. You can view the components
properties listed in the lower right-hand panel, and the layout hierarchy in the
upper right-hand panel.
b. Optionally, click on the Toggle NAF Nodes button to see UI components that
are not accessible to the uiautomator testing framework. Only limited
information may be available for these components.

Preparing to Test
Before using the uiautomator testing framework, complete these pre-flight tasks:

Load the application to a device

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.

Identify the applications UI components


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 Applications UI. For more information about
the common types of UI components provided by Android, see User Interface.

Ensure that the application is accessible


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:

Use the android:contentDescription attribute to label the ImageButton,


ImageView, CheckBox and other user interface controls.

Provide an android:hint attribute instead of a content description for EditText


fields

Associate an android:hint attribute with any graphical icons used by controls that
provide feedback to the user (for example, status or state information).

Make sure that all the user interface elements are accessible with a directional
controller, such as a trackball or D-pad.

Use the uiautomatorviewer tool to ensure that the UI component is accessible to the
testing framework. You can also test the application by turning on accessibility
services like TalkBack and Explore by Touch, and try using your application using
only directional controls.

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.

Configure your development environment


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 youre 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.

Creating 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.
Because the UiAutomatorTestCase class extends junit.framework.TestCase, you can use
the JUnit Assert class to test that UI components in the app return the expected results. To
learn more about JUnit, you can read the documentation on the junit.org home page.
The first thing your test case should do is access the device that contains the target app. Its
also good practice to start the test from the Home screen of the device. From the Home screen
(or some other starting location youve 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 <androidsdk>/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.
To get an instance of UiDevice and simulate a Home button press:
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.
UiObject cancelButton = new UiObject(new
UiSelector().text("Cancel"));
UiObject okButton = new UiObject(new UiSelector().text("OK"));

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.
if(okButton.exists() && okButton.isEnabled())
{
okButton.click();
}

You can also restrict the search to find only elements of a specific class. For example,
to find matches of the Button class:
UiObject cancelButton = new UiObject(new UiSelector().text("Cancel")
.className("android.widget.Button"));
UiObject okButton = new UiObject(new UiSelector().text("OK")
.className("android.widget.Button"));
UiCollection

Represents a collection of items, for example songs in a music album or a list of


emails in an inbox. Similar to a UiObject, you construct a UiCollection instance by
specifying a UiSelector. The UiSelector for a UiCollection should search for a
UI element that is a container or wrapper of other child UI elements (such as a layout
view that contains child UI elements). For example, the following code snippet shows
how to construct a UiCollection to represent a video album that is displayed within
a FrameLayout:
UiCollection videos = new UiCollection(new UiSelector()
.className("android.widget.FrameLayout"));

If the videos are listed within a LinearLayout view, and you want to to retrieve the
number of videos in this collection:
int count = videos.getChildCount(new UiSelector()
.className("android.widget.LinearLayout"));

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:
UiObject video = videos.getChildByText(new UiSelector()
.className("android.widget.LinearLayout"), "Cute Baby Laughing");
video.click();

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:
UiObject checkBox = video.getChild(new UiSelector()
.className("android.widget.Checkbox"));
if(!checkBox.isSelected()) checkbox.click();
UiScrollable

Represents a scrollable collection of UI elements. You can use the UiScrollable


class to simulate vertical or horizontal scrolling across a display. This technique is
helpful when a UI element is positioned off-screen and you need to scroll to bring it
into view.

For example, the following code shows how to simulate scrolling down the Settings
menu and clicking on an About tablet option:
UiScrollable settingsItem = new UiScrollable(new UiSelector()
.className("android.widget.ListView"));
UiObject about = settingsItem.getChildByText(new UiSelector()
.className("android.widget.LinearLayout"), "About tablet");
about.click()

For more information about these APIs, see the uiautomator reference.

A sample uiautomator test case


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;
// Import the uiautomator libraries
import com.android.uiautomator.core.UiObject;
import com.android.uiautomator.core.UiObjectNotFoundException;
import com.android.uiautomator.core.UiScrollable;
import com.android.uiautomator.core.UiSelector;
import com.android.uiautomator.testrunner.UiAutomatorTestCase;
public class LaunchSettings extends UiAutomatorTestCase {
public void testDemo() throws UiObjectNotFoundException {
// Simulate a short press on the HOME button.
getUiDevice().pressHome();
// Were now in the home screen. Next, we want to simulate
// a user bringing up the All Apps screen.
// If you use the uiautomatorviewer tool to capture a snapshot
// of the Home screen, notice that the All Apps buttons
// content-description property has the value Apps. We can
// use this property to create a UiSelector to find the button.
UiObject allAppsButton = new UiObject(new UiSelector()
.description("Apps"));
// Simulate a click to bring up the All Apps screen.
allAppsButton.clickAndWaitForNewWindow();
// In the All Apps screen, the Settings app is located in
// the Apps tab. To simulate the user bringing up the Apps tab,
// we create a UiSelector to find a tab with the text
// label Apps.
UiObject appsTab = new UiObject(new UiSelector()
.text("Apps"));
// Simulate a click to enter the Apps tab.
appsTab.click();
// Next, in the apps tabs, we can simulate a user swiping until

// they come to the Settings app icon. Since the container view
// is scrollable, we can use a UiScrollable object.
UiScrollable appViews = new UiScrollable(new UiSelector()
.scrollable(true));
// Set the swiping mode to horizontal (the default is vertical)
appViews.setAsHorizontalList();
// Create a UiSelector to find the Settings app and simulate
// a user click to launch the app.
UiObject settingsApp = appViews.getChildByText(new UiSelector()
.className(android.widget.TextView.class.getName()),
"Settings");
settingsApp.clickAndWaitForNewWindow();
// Validate that the package name is the expected one
UiObject settingsValidation = new UiObject(new UiSelector()
.packageName("com.android.settings"));
assertTrue("Unable to detect Settings",
settingsValidation.exists());
}

Building and Deploying Your uiautomator Tests


Once you have coded your test, follow these steps to build and deploy your test JAR to your
target Android test device:
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:
<android-sdk>/tools/android create uitest-project -n <name> -t 1 -p
<path>

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.
2. From the command line, set the ANDROID_HOME variable:
o In Windows:
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:
adb push <path_to_output_jar> /data/local/tmp/

Heres an example:
adb push ~/dev/workspace/LaunchSettings/bin/LaunchSettings.jar
/data/local/tmp/

Running uiautomator Tests


Heres 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:
adb shell uiautomator runtest LaunchSettings.jar -c
com.uia.example.my.LaunchSettings

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 androiddevelopers Google Groups site is another resource for information about testing.
Ideas for 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 restart 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.
Dependence on external resources

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 IPbased 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.

Activity Testing Tutorial


In this document
1. Prerequisites
2. Installing the Tutorial Sample Code
3. Setting Up the Emulator
4. Setting Up the Projects
5. Creating the Test Case Class
1. Adding the test case class file
2. Adding the test case constructor
3. Adding the setup method
4. Adding an initial conditions test
5. Adding a UI test
6. Adding state management tests
6. Running the Tests and Seeing the Results
7. Forcing Some Tests to Fail
8. Next Steps

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
The instructions and code in this tutorial depend on the following:

Basic knowledge of Android programming. If you haven't yet written an Android


application, do the class Building Your First App. If you want to learn more about
Spinner, the application under test, then you might want to review the "Spinner"
sample app.

Some familiarity with the Android testing framework and concepts. If you haven't
explored Android testing yet, start by reading the Testing Fundamentals guide.

Eclipse with ADT. This tutorial describes how to set up and run a test application
using Eclipse with ADT. If you haven't yet installed Eclipse and the ADT plugin,
follow the steps in Installing the SDK to install them before continuing. If you are not
developing in Eclipse, you will find instructions for setting up and running the test
application in the appendix of this document.

Installing the Tutorial Sample Code


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-bystep. 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.

Setting Up the Emulator

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.

Setting Up the Projects


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"
The following screenshot summarizes these values:

To create a new test project for the SpinnerTest application, follow these steps:
1. Click Next. The New Android Test Project dialog appears.
2. Set "Create a Test Project".
3. Leave the other values unchanged. The result should be:

o Create a Test Project: checked


o Test Project Name: "SpinnerActivityTest"
o Use default location: checked (this should contain the directory name
"workspace/SpinnerActivityTest").
o Build Target: Use the same API level you used in the previous step.
o Application name: "SpinnerActivityTest"
o Package name: "com.android.example.spinner.test"
o Min SDK Version: "3"
The following screenshot summarizes these values:

4. Click Finish. Entries for SpinnerActivity and SpinnerActivityTest should appear in


the Package Explorer.
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:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.android.example.spinner.test"
android:versionCode="1"
android:versionName="1.0">
<uses-sdk android:minSdkVersion="3" />
<instrumentation
android:targetPackage="com.android.example.spinner"
android:name="android.test.InstrumentationTestRunner" />
<application android:icon="@drawable/icon"
android:label="@string/app_name">
<uses-library android:name="android.test.runner" />
...
</application>
</manifest>

Notice the <instrumentation> element. The attribute


android:targetPackage="com.android.example.spinner" tells Android that the
application under test is defined in the Android package com.android.example.spinner.
Android now knows to use that package's AndroidManifest.xml file to launch the
application under test. The <instrumentation> element also contains the attribute
android:name="android.test.InstrumentationTestRunner", which tells Android

instrumentation to run the test application with Android's instrumentation-enabled test runner.

Creating the Test Case Class


You now have a test project SpinnerActivityTest, and the basic structure of a test application
also called SpinnerActivityTest. The basic structure includes all the files and directories you
need to build and run a test application, except for the class that contains your tests (the test
case class).
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.

Adding the test case class file


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:

The New Java Class wizard appears:

3. In the wizard, enter the following:


o Name: "SpinnerActivityTest". This becomes the name of your test class.
o Superclass:
"android.test.ActivityInstrumentationTestCase2<SpinnerActivity>
". The superclass is parameterized, so you have to provide it your main
application's class name.
Do not change any of the other settings. Click Finish.

4. You now have a new file SpinnerActivityTest.java in the project.


5. To resolve the reference to SpinnerActivity, add the following import:
import com.android.example.spinner.SpinnerActivity;

Adding the test case constructor


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.

Adding the setup method


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.
The method you are going to add does the following:

super.setUp().

Invokes the superclass constructor for setUp(), which is required by

JUnit.

Calls setActivityInitialTouchMode(false). This turns off touch mode in the


device or emulator. If any of your test methods send key events to the application, you
must turn off touch mode before you start any activities; otherwise, the call is ignored.

Stores references to system objects. Retrieves and stores a reference to the activity
under test, the Spinner widget used by the activity, the SpinnerAdapter that backs
the widget, and the string value of the selection that is set when the application is first
installed. These objects are used in the state management test. The methods invoked
are:
o getActivity(). Gets a reference to the activity under test
(SpinnerActivity). This call also starts the activity if it is not already
running.
o findViewById(int). Gets a reference to the Spinner widget of the
application under test.

o getAdapter(). Gets a reference to the adapter (an array of strings) backing


the spinner.
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();
} // end of setUp() method definition

Add these members to the test case class:


private SpinnerActivity mActivity;
private Spinner mSpinner;
private SpinnerAdapter mPlanetData;

Add these imports:


import android.widget.Spinner;
import android.widget.SpinnerAdapter;

You now have the complete setUp() method.

Adding an initial conditions test


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():

public void testPreConditions() {


assertTrue(mSpinner.getOnItemSelectedListener() != null);
assertTrue(mPlanetData != null);
assertEquals(mPlanetData.getCount(),ADAPTER_COUNT);
} // end of testPreConditions() method definition

Add this member:


public static final int ADAPTER_COUNT = 9;

Adding a UI test
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 predetermined 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:
public void testSpinnerUI() {
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

Add the following member to the test case class.


public static final int INITIAL_POSITION = 0;

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);

Add the following member to the test case class:


public static final int TEST_POSITION = 5;

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
);
String resultText = (String) resultView.getText();
assertEquals(resultText,mSelection);
} // end of testSpinnerUI() method definition

Add the following members to the test case class:


private String mSelection;
private int mPos;

Add the following imports to the test case class:

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).
SpinnerActivity manages its state in these ways:

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.
When an activity is hidden, it is paused. When it re-appears, it resumes. Recognizing that
these are key points in an activity's life cycle, the Activity class provides two callback
methods onPause() and onResume() for handling pauses and resumes. SpinnerActivity uses
them for code that saves and restores state.

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:
public void testStateDestroy() {
mActivity.setSpinnerPosition(TEST_STATE_DESTROY_POSITION);
mActivity.setSpinnerSelection(TEST_STATE_DESTROY_SELECTION);

2. Terminate the activity and restart it:


mActivity.finish();
mActivity = this.getActivity();

3. Get the current spinner settings from the activity:


int currentPosition = mActivity.getSpinnerPosition();
String currentSelection = mActivity.getSpinnerSelection();

4. Test the current settings against the test values:


assertEquals(TEST_STATE_DESTROY_POSITION, currentPosition);
assertEquals(TEST_STATE_DESTROY_SELECTION, currentSelection);
} // end of testStateDestroy() method definition

Add the following members to the test case class:


public static final int TEST_STATE_DESTROY_POSITION = 2;
public static final String TEST_STATE_DESTROY_SELECTION = "Earth";

To add the code for testing state management across a pause and resume, follow these steps:
1. Add the test method testStatePause():

@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.
2. Set up instrumentation. Get the instrumentation object that is controlling the
application under test. This is used later to invoke the onPause() and onResume()
methods:
Instrumentation mInstr = this.getInstrumentation();

3. Set the spinner selection to a test value:


mActivity.setSpinnerPosition(TEST_STATE_PAUSE_POSITION);
mActivity.setSpinnerSelection(TEST_STATE_PAUSE_SELECTION);

4. Use instrumentation to call the Activity's onPause():


mInstr.callActivityOnPause(mActivity);

Under test, the activity is waiting for input. The invocation of


callActivityOnPause(android.app.Activity) performs a call directly to the
activity's onPause() instead of manipulating the activity's UI to force it into a paused
state.
5. Force the spinner to a different selection:
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.
6. Use instrumentation to call the Activity's onResume():
mInstr.callActivityOnResume(mActivity);

Invoking callActivityOnResume(android.app.Activity) affects the activity in a


way similar to callActivityOnPause. The activity's onResume() method is invoked
instead of manipulating the activity's UI to force it to resume.
7. Get the current state of the spinner:
int currentPosition = mActivity.getSpinnerPosition();
String currentSelection = mActivity.getSpinnerSelection();

8. Test the current spinner state against the test values:

assertEquals(TEST_STATE_PAUSE_POSITION,currentPosition);
assertEquals(TEST_STATE_PAUSE_SELECTION,currentSelection);
} // end of testStatePause() method definition

Add the following members to the test case class:


public static final int TEST_STATE_PAUSE_POSITION = 4;
public static final String TEST_STATE_PAUSE_SELECTION = "Jupiter";

9. Add the following imports:


import android.app.Instrumentation;
import android.test.UiThreadTest;

Running the Tests and Seeing the Results


The most simple way to run the SpinnerActivityTest test case is to run it directly from the
Package Explorer.
To run the SpinnerActivityTest test, follow these steps:

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:

The upper pane summarizes the test:

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 doubleclicking 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.

Forcing Some Tests to Fail


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.
To force the tests to fail, follow these steps:
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);

3. The testPreConditions() method in SpinnerActivityTest contains the following


test: assertTrue(mSpinner.getOnItemSelectedListener() != null);. This test
asserts that the listener callback is not null. Since you have modified the application
under test, this assertion now fails.
4. Run the test, as described in the previous section Running the Tests and Seeing the
Results.
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.
To examine the failures, follow these steps:
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.
Remember to go back to SpinnerActivity.java and re-comment the line you
uncommented in an earlier step.
You have now completed the tutorial.

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:
Learn more about testing on Android

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.

Review the main Android test case classes

ActivityInstrumentationTestCase2

ActivityUnitTestCase

ProviderTestCase2

ServiceTestCase

Learn more about the assert and utility classes

Assert,

the JUnit Assert class.

MoreAsserts,

additional Android assert methods.

ViewAsserts,

useful assertion methods for testing Views.

TouchUtils,

utility methods for simulating touch events in an Activity.

Learn about instrumentation and the instrumented test runner

Instrumentation,

InstrumentationTestCase,

InstrumentationTestRunner,

the base instrumentation class.


the base instrumentation test case.
the standard Android test runner.

Appendix
Installing the Completed Test Application File
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.
To install the test application file, follow these steps:
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/android8/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.

For Users Not Developing In Eclipse


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:
$ android create project -t <APItarget> -k
com.android.example.spinner -a SpinnerActivity -n SpinnerActivity -p
Spinner

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.
4. Create a new Android test project using android create test-project:
$ android create test-project -m ../Spinner -n SpinnerActivityTest -p
SpinnerActivityTest

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:
$ adb install Spinner/bin/SpinnerActivity-debug.apk

6. To create the test application, create a file SpinnerActivityTest.java in the


directory SpinnerActivityTest/src/com/android/example/spinner/test/.
7. Follow the tutorial, starting with the section Creating the Test Case Class. When you
are prompted to run the sample application, go to the Launcher screen in your device
or emulator and select SpinnerActivity. When you are prompted to run the test
application, return here to continue with the following instructions.
8. Build the test 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 Android file
SpinnerActivityTest/bin/SpinnerActivityTest-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:
$ adb install SpinnerActivityTest/bin/SpinnerActivityTest-debug.apk

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:
$ adb shell am instrument -w
com.android.example.spinner.test/android.test.InstrumentationTestRunn

er

The result of a successful test looks like this:


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.
About Android | Legal | Support

Debugging
In this document
1. Debugging Environment
2. Additional Debugging Tools
3. Debugging Tips
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
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.
adb

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:
Heirarchy Viewer and layoutopt
Graphical programs that let you debug and profile user interfaces.
Traceview
A graphical viewer that displays trace file data for method calls and times saved by
your application, which can help you profile the performance of your application.
Dev Tools Android application
The Dev Tools application included in the emulator system image exposes several
settings that provide useful information such as CPU usage and frame rate. You can
also transfer the application to a hardware device.

Debugging Tips
While debugging, keep these helpful tips in mind to help you figure out common problems
with your applications:
Dump the stack trace
To obtain a stack dump from emulator, you can log in with adb shell, use ps to find
the process you want, and then kill -3. The stack trace appears in the log file.
Display useful info on the emulator screen

The device can display useful information such as CPU usage or highlights around
redrawn areas. Turn these features on and off in the developer settings window as
described in Debugging with the Dev Tools App.
Get application and system state information from the emulator
You can access dumpstate information from the adb shell commands. See dumpsys
and dumpstate on the adb topic page.
Get wireless connectivity information
You can get information about wireless connectivity using DDMS. From the Device
menu, select Dump radio state.
Log trace data
You can log method calls and other tracing data in an activity by calling
startMethodTracing(). See Profiling with Traceview and dmtracedump for details.
Log radio data
By default, radio information is not logged to the system (it is a lot of data). However,
you can enable radio logging using the following commands:
adb shell
logcat -b radio

Capture screenshots
The Dalvik Debug Monitor Server (DDMS) can capture screenshots from the
emulator. Select Device > Screen capture.
Use debugging helper classes
Android provides debug helper classes such as util.Log and Debug for your
convenience.
Garbage collection
The debugger and garbage collector are currently loosely integrated. The VM
guarantees that any object the debugger is aware of is not garbage collected until after
the debugger disconnects. This can result in a buildup of objects over time while the
debugger is connected. For example, if the debugger sees a running thread, the
associated Thread object is not garbage collected even after the thread terminates.

Debugging with Android Studio


In this document
1. Run your App in Debug Mode
1. Attach the debugger to a running process
2. Use the System Log
1. Write log messages in your code
2. View the system log
3. Work with Breakpoints
1. View and configure breakpoints

2. Debug your app with breakpoints


4. Track Object Allocation
5. Analyze Runtime Metrics to Optimize your App
6. Capture Screenshots and Videos

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:

Select a device to debug your app on.

View the system log.

Set breakpoints in your code.

Examine variables and evaluate expressions at run time.

Run the debugging tools from the Android SDK.

Capture screenshots and videos of your app.

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.

Run your App in Debug Mode

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.
To debug your app in Android Studio:
1. Open your project in Android Studio.
2. Click Debug

in the toolbar.

3. On the Choose Device window, select a hardware device from the list or choose a
virtual device.
4. Click OK. Your app starts on the selected device.
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.

Attach the debugger to a running process


You don't always have to restart your app to debug it. To debug an app that you're already
running:
1. Click Attach debugger to Android proccess

2. In the Choose Process window, select the device and app you want to attach the
debugger to.
3. To open the Debug tool window, click Debug

Use the System Log


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.

Write log messages in your code


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.

View the system log


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:
1. Start your app as described in Run your App in Debug Mode.
2. Click Android

to open the Android DDMS tool window.

3. If the system log is empty in the Logcat view, click Restart

Figure 4. The system log in 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.

Work with Breakpoints


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:
1. Open the source file in which you want to set a breakpoint.
2. Locate the line where you want to set a breakpoint and click on it.
3. Click on the yellow portion of the side bar to the left of this line, as shown in figure 5.

4. Start your app as described in Run your App in Debug Mode.


Android Studio pauses the execution of your app when it reaches the breakpoint. You can
then use the tools in the Debug tool window to identify the cause of the error.

Figure 5. A red dot appears next to the line when you set a breakpoint.

View and configure breakpoints


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.

Debug your app with 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

To continue running the app normally, click Resume Program

.
.

Figure 7. The Variables view in the Debug tool window.

Track Object Allocation


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.
To track memory allocation of objects:
1. Start your app as described in Run Your App in Debug Mode.

2. Click Android

to open the Android DDMS tool window.

3. On the Android DDMS tool window, select the Devices | logcat tab.
4. Select your device from the dropdown list.
5. Select your app by its package name from the list of running apps.
6. Click Start Allocation Tracking
7. Interact with your app on the device.
8. Click Stop Allocation Tracking
Android Studio shows the objects that the system allocated with the following information:

Allocation order

Allocated class

Allocation size

Thread ID

Allocation method, class, and line number

Stack trace at the point of allocation

Figure 8. Object allocation tracking in Android Studio.

Analyze Runtime Metrics to Optimize your App

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:

Does your app use memory efficiently?

Does your app generate unnecessary network traffic?

What methods should you focus your attention on to improve the performance of your
app?

Does your app behave properly when the user receives a phone call or a message?

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
The Android Device Monitor opens in a new window.

on the toolbar.

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.
To take a screenshot of your app:
1. Start your app as described in Run your App in Debug Mode.
2. Click Android
3. Click Screen Capture

to open the Android DDMS tool window.


on the left side of the Android DDMS tool window.

4. Optional: To add a device frame around your screenshot, enable the Frame screenshot
option.
5. Click Save.
To take a video recording of your app:
1. Start your app as described in Run your App in Debug Mode.

2. Click Android
3. Click Screen Record

to open the Android DDMS tool window.


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.

Debugging from Other IDEs


In this document
1. Starting a Debugging Environment
o Configuring Your IDE to Attach to the Debugging Port
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.

Configuring Your IDE to Attach to the Debugging Port


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.

How DDMS Interacts with a Debugger

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.
When DDMS starts, it connects to adb. When a device is connected, a VM monitoring
service is created between adb and DDMS, which notifies DDMS when a VM on the device
is started or terminated. Once a VM is running, DDMS retrieves the VM's process ID (pid),
via adb, and opens a connection to the VM's debugger, through the adb daemon (adbd) on the
device. DDMS can now talk to the VM using a custom wire protocol.
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.
Known debugging issues with Dalvik
Debugging an application in the Dalvik VM should work the same as it does in other VMs.
However, when single-stepping out of synchronized code, the "current line" cursor may jump
to the last line in the method for one step.
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.
Viewing heap usage for a process

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.
To view heap usage for a process:
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.
Tracking memory allocation of objects

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.
To track memory allocation of objects:

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.
Working with an emulator or device's file system

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.
To work with an emulator or device's file system:
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.
Examining thread information

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.
Starting method profiling

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.

To start method profiling:


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.
Using the Network Traffic tool

In Android 4.0, the DDMS (Dalvik Debug Monitor Server) includes a Detailed Network
Usage tab that makes it possible to track when your application is making network requests.
Using this tool, you can monitor how and when your app transfers data and optimize the
underlying code appropriately. You can also distinguish between different traffic types by
applying a tag to network sockets before use.
These tags are shown in a stack area chart in DDMS, as shown in figure 2:

Figure 2. Network Usage tab.


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 batteryefficient. 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.
Emulating phone operations and location

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.
Changing network state, speed, and latency

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:

Voice - unregistered, home, roaming, searching, denied

Data - unregistered, home, roaming, searching, denied

Speed - Full, GSM, HSCSD, GPRS, EDGE, UMTS, HSDPA

Latency - GPRS, EDGE, UMTS

Spoofing calls or SMS text messages

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.

Setting the location of the phone

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.

Reading and Writing Logs


In this document
1. The Log class
2. Starting LogCat
3. Filtering Log Output
4. Controlling Log Output Format
5. Viewing Alternative Log Output Buffers
6. Viewing stdout and stderr
7. Debugging Web Pages

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.

The Log class


is a logging class that you can utilize in your code to print out messages to the LogCat.
Common logging methods include:
Log

v(String, String)

(verbose)

d(String, String)

(debug)

i(String, String)

(information)

w(String, String)

(warning)

e(String, String)

(error)

For example:

Log.i("MyActivity", "MyClass.getView() get item number " + position);

The LogCat will then output something like:


I/MyActivity( 1557): MyClass.getView() get item number 1

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:
[adb] logcat [<option>] ... [<filter-spec>] ...

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

and from a remote adb shell you use


# logcat

The following table describes the logcat command line options:

-c
-d
-f <filename
>
-g
-n <count>
-r <kbytes>
-s
-v <format>

Clears (flushes) the entire log and exits.


Dumps the log to the screen and exits.
Writes log message output to <filename>. The default is stdout.
Prints the size of the specified log buffer and exits.
Sets the maximum number of rotated logs to <count>. The default value is 4.
Requires the -r option.
Rotates the log file every <kbytes> of output. The default value is 16.
Requires the -f option.
Sets the default filter spec to silent.
Sets the output format for log messages. The default is brief format. For a
list of supported formats, see Controlling Log Output Format.

Filtering Log Output


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":
I/ActivityManager( 585): Starting activity: Intent
{ action=android.intent.action...}

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:
adb logcat ActivityManager:I MyApp:D *:S

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:
adb logcat *:W

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:
export ANDROID_LOG_TAGS="ActivityManager:I MyApp:D *:S"

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.

Controlling Log Output Format


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

process

tag

Display the priority/tag only.

raw

Display the raw log message, with no other metadata fields.

Display priority/tag and PID of the process issuing the message (the default
format).
Display PID only.

time

threadtime

long

Display the date, invocation time, priority/tag, and PID of the process issuing
the message.
Display the date, invocation time, priority, tag, and the PID and TID
of the thread issuing the message.
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:
[adb] logcat [-v <format>]

Here's an example that shows how to generate messages in thread output format:
adb logcat -v thread

Note that you can only specify one output format with the -v option.

Viewing Alternative Log Buffers


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:

radio

events

main

View the buffer that contains radio/telephony related messages.


View the buffer containing events-related messages.

View the main log buffer (default)

The usage of the -b option is:


[adb] logcat [-b <buffer>]

Here's an example of how to view a log buffer containing radio and telephony messages:
adb logcat -b radio

Viewing stdout and stderr


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:

$ adb shell stop


$ adb shell setprop log.redirect-stdio true
$ adb shell start

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.

Debugging Web Apps


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.
Improving Your Code with lint
In This Document
1. Overview
2. Running lint from Eclipse
3. Running lint from the command-line
4. Configuring lint
1. Configuring lint in Eclipse
2. Configuring the lint file
3. Configuring lint checking in Java and XML source files
See Also
1. lint (reference)

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.

Figure 1. Code scanning workflow with the lint tool


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.
The lint.xml file
A configuration file that you can use to specify any lint checks that you
want to exclude and to customize problem severity levels.
The lint tool
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.
Results of lint checking
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.
Running lint from Eclipse

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.
Figure 2 shows an example of the output in the Lint Warnings view.

Figure 2. Sample output in the Lint Warnings view


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.
Running lint from the Command-Line

To run lint against a list of files in a project directory:


lint [flags] <project directory>

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.
lint --check MissingPrefix myproject

To see the full list of flags and command-line arguments supported by the tool:
lint --help

Example lint output

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 lint checking at different levels:

Globally, for all projects

Per project

Per file

Per Java class or method (by using the @SuppressLint annotation), or per
XML element (by using the tools:ignore attribute.

Configuring lint in Eclipse

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.

Project and file-specific preferences


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.

Ignore in this file - Disables checking for this lint issue in this file.

Ignore in this project - Disables checking for this lint issue in


this project.

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.
Configuring the lint file

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.
<?xml version="1.0" encoding="UTF-8"?>
<lint>
<!-- list of issues to configure -->
</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.

Sample lint.xml file

The following example shows the contents of a lint.xml file.


<?xml version="1.0" encoding="UTF-8"?>
<lint>
<!-- Disable the given check in this project -->
<issue id="IconMissingDensityFolder" severity="ignore" />
<!-- Ignore the ObsoleteLayoutParam issue in the specified files -->
<issue id="ObsoleteLayoutParam">
<ignore path="res/layout/activation.xml" />
<ignore path="res/layout-xlarge/activation.xml" />
</issue>
<!-- Ignore the UselessLeaf issue in the specified file -->
<issue id="UselessLeaf">
<ignore path="res/layout/main.xml" />
</issue>
<!-- Change the severity of hardcoded strings to "error" -->
<issue id="HardcodedText" severity="error" />
</lint>

Configuring lint checking in Java and XML source files

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.
Configuring lint checking in Java

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 FeedProvider class:

the ParserError issue in

@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")

Configuring lint checking in XML

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.

Using Hierarchy Viewer


Running Hierarchy Viewer and choosing a window
To run Hierarchy Viewer, follow these steps:
1. Connect your device or launch an emulator.
To preserve security, Hierarchy Viewer can only connect to devices running a
developer version of the Android system.
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

About the View Hierarchy 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.
You should see four panes:

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.
To save a layered screenshot of your device or emulator to an Adobe Photoshop
(PSD) file, click Capture Layers at the top of the View Hierarchy window. This
displays a dialog in which you can choose a directory or file name. Each View in the
UI is saved as a separate Photoshop layer.
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 properties are organized by category. To find an individual property, expand a
category name by clicking the arrow on its left. This reveals all the properties in that
category.

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.
The outline colors of blocks in Layout View provide additional information:

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.
A screenshot of the View Hierarchy window appears in figure 2.

Figure 2. The View Hierarchy window

Working with an individual View in Tree View

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:
1. View class: The View object's class.
2. View object address: A pointer to View object.
3. View object ID: The value of the android:id attribute.
4. Performance indicators: A set of three colored dots that indicate the rendering speed
of this View relative to other View objects in the tree. The three dots represent (from
left to right) the measure, layout, and draw times of the rendering.
The colors indicate the following relative performance:
o Green: For this part of the render time, this View is in the faster 50% of all the
View objects in the tree. For example, a green dot for the measure time means
that this View has a faster measure time than 50% of the View objects in the
tree.
o Yellow: For this part of the render time, this View is in the slower 50% of all
the View objects in the tree. For example, a yellow dot for the layout time
means that this View has a slower layout time than 50% of the View objects in
the tree.
o Red: For this part of the render time, this View is the slowest one in the tree.
For example, a red dot for the draw time means that this View takes the most
time to draw of all the View objects in the tree.
5. View index: The zero-based index of the View in its parent View. If it is the only
child, this is 0.
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

Debugging with View Hierarchy


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.
To redraw a View in the display:

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.

Optimizing with View Hierarchy


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.

Using Pixel Perfect


Pixel Perfect is a tool for examining pixel properties and laying out UIs from a design
drawing.

About the Pixel Perfect window


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.
In it, you see three panes:

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.

Working with Pixel Perfect overlays


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.
To use a bitmap image as an overlay:

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.
A screenshot of the Pixel Perfect window appears in figure 4.

Figure 4. The Pixel Perfect window

Using lint to Optimize Your UI


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.

Profiling with Traceview and dmtracedump


In this document
1. Traceview Layout
1. Timeline Panel
2. Profile Panel

2. Creating Trace Files


3. Copying Trace Files to a Host Machine
4. Viewing Trace Files in Traceview
5. Using dmtracedump
6. Traceview Known Issues
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 threads 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.

Figure 1. The Traceview Timeline Panel

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.

Figure 2. The Traceview Profile Panel

Creating Trace Files


To use Traceview, you need to generate log files containing the trace information you want to
analyze.
There are two ways to generate trace logs:

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.
// start tracing to "/sdcard/calc.trace"
Debug.startMethodTracing("calc");
// ...
// stop tracing
Debug.stopMethodTracing();

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.

Copying Trace Files to a Host Machine


After your application has run and the system has created your trace files <trace-basename>.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:
adb pull /sdcard/calc.trace /tmp

Viewing Trace Files in Traceview


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
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.
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


For each node, dmtracedump shows <ref> callname (<inc-ms>, <excms>,<numcalls>), where

<ref>

<inc-ms>

-- Call reference number, as used in trace logs


-- Inclusive elapsed time (milliseconds spent in method, including all child

methods)

<exc-ms>

<numcalls>

-- Exclusive elapsed time (milliseconds spent in method, not including any


child methods)
-- Number of calls

The usage for dmtracedump is:


dmtracedump [-ho] [-s sortable] [-d trace-base-name] [-g outfile] <tracebase-name>

The tool then loads trace log data from <trace-base-name>.data and <trace-basename>.key. The table below lists the options for dmtracedump.
Option
-d <tracebase-name>
-g <outfile>

Description
Diff with this trace name
Generate output to <outfile>

-h
-o
-d <tracebase-name>
-t <percent>

Turn on HTML output


Dump the trace file instead of profiling
URL base to the location of the sortable javascript file
Minimum threshold for including child nodes in the graph (child's
inclusive time as a percentage of parent inclusive time). If this option is
not used, the default threshold is 20%.

Traceview Known Issues


Threads
Traceview logging does not handle threads well, resulting in these two problems:
1. If a thread exits during profiling, the thread name is not emitted;
2. The VM reuses thread IDs. If a thread stops and another starts, they may get
the same ID.

Analyzing Display and Performance


In this document
1. Overview
2. Generating Traces
1. Limiting trace data
2. Tracing on Android 4.3 and higher
3. Tracing on Android 4.2 and lower
3. Tracing Application Code
4. Analyzing Traces
1. Long running processes
2. Interruptions in display execution

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.

Figure 1. An example Systrace report on 5 seconds of process execution for a running


application and related Android system processes.

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.

Limiting trace data


The Systrace tool can generate a potentially huge amount of data from applications and
system sources. To limit the amount of data the tool collects and make the data more relevant
to your analysis, use the following 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.

Tracing on Android 4.3 and higher


To run a trace on Android 4.3 and higher devices:
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.

Tracing on Android 4.2 and lower

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).

To set trace tags for Systrace using the command-line:


1. Use the --set-tags option:
$ 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.
To run a trace using the current trace tag settings:
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:
$ python systrace.py --cpu-freq --cpu-load --time=10 -o
mytracefile.html

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.

Tracing Application Code


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.
public void ProcessPeople() {
Trace.beginSection("ProcessPeople");
try {
Trace.beginSection("Processing Jane");
try {
// code for Jane task...
} finally {
Trace.endSection(); // ends "Processing Jane"
}

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.

Long running processes


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.

Interruptions in display execution


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.

Regular, rhythmic execution of the SurfaceFlinger process is essential to smooth display of


screen content, particularly for animations and motion. Interruptions in the regular execution
pattern of this thread is not always an indication of a display problem with your application.
Further testing is required to determine if this is actually a performance problem from a user
perspective. Being able to identify display execution patterns like the example above can help
you detect display problems and build a smooth-running, high-performance application.
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.
Investigating Your RAM Usage
In this document
1. Interpreting Log Messages
2. Viewing Heap Updates
3. Tracking Allocations
4. Viewing Overall Memory Allocations
5. Capturing a Heap Dump
6. Triggering Memory Leaks
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 Androids Dalvik virtual
machine performs routine garbage collection, this doesnt 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, its 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 apps memory usage with tools. This guide shows you how to do that.
Interpreting Log Messages

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:
D/dalvikvm: <GC_Reason> <Amount_freed>, <Heap_stats>,
<External_memory_stats>, <Pause_time>

GC Reason

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
The amount of memory reclaimed from this garbage collection.
Heap stats
Percentage free and (number of live objects)/(total heap size).
External memory 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:
D/dalvikvm( 9050): GC_CONCURRENT freed 2049K, 65% free 3571K/9991K,
external 4703K/5261K, paused 2ms+2ms
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.
Viewing Heap Updates

To get a little information about what kind of memory your app is using and when, you can
view real-time updates to your app's heap in the Device Monitor:
1. Open the Device Monitor.

From your <sdk>/tools/ directory, launch the monitor tool.


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.
To use Allocation Tracker:
1. Open the Device Monitor.

From your <sdk>/tools/ directory, launch the monitor tool.


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.
Viewing Overall Memory Allocations

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:
adb shell dumpsys meminfo <package_name>

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:
Private (Clean and Dirty) RAM
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 apps 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 cant 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.
Proportional Set Size (PSS)
This is a measurement of your apps 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 Gmails 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.
** MEMINFO in pid 9953 [com.google.android.gm] **
Pss
Pss Shared Private Shared Private
Heap
Heap
Heap
Total
Clean
Dirty
Dirty
Clean
Clean
Size
Alloc
Free
------ ------ ------ ------ ------ ------ ----------- -----Native Heap
0
0
0
0
0
0
7800
7637(6) 126
Dalvik Heap
5110(3)
0
4136
4988(3)
0
0
9168
8958(6) 210
Dalvik Other
2850
0
2684
2772
0
0
Stack
36
0
8
36
0
0
Cursor
136
0
0
136
0
0
Ashmem
12
0
28
0
0
0
Other dev
380
0
24
376
0
4
.so mmap
5443(5) 1996
2584
2664(5) 5788
1996(5)
.apk mmap
235
32
0
0
1252
32
.ttf mmap
36
12
0
0
88
12
.dex mmap
3019(5) 2148
0
0
8936
2148(5)
Other mmap
107
0
8
8
324
68
Unknown
6994(4)
0
252
6992(4)
0
0
TOTAL 24358(1) 4188
9724
17972(2)16388
4260(2)16968
16595
336
Objects
Views:
AppContexts:
Assets:
Local Binders:
Death Recipients:

426
6(7)
2
64
0

ViewRootImpl:
Activities:
AssetManagers:
Proxy Binders:

3(8)
2(7)
2
34

OpenSSL Sockets:

MEMORY_USED:
PAGECACHE_OVERFLOW:

1739
1164

SQL

MALLOC_SIZE:
62
only the Pss Total and Private Dirty

Generally, you should be concerned with


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 apps heap, composed of your own
allocations and any Zygote allocation pages that have been modified since
forking your apps 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.
.so mmap and .dex mmap

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 apps own code. Generally, the actual mapped size will be
much largerthe 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.
AppContexts and Activities

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
cant 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.
Capturing a Heap Dump

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.
To retrieve your heap dump:
1. Open the Device Monitor.

From your <sdk>/tools/ directory, launch the monitor tool.


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 dont 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:
hprof-conv heap-original.hprof heap-converted.hprof

Note: If you're using the version of DDMS that's integrated into Eclipse, you do not need to
perform the HPROF converstionit 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.

Using the Eclipse Memory Analyzer Tool

The Eclipse Memory Analyzer Tool (MAT) is just one tool that you can use to analyze your
heap dump. It's also quite powerful so most of its capabilities are beyond the scope of this
document, but here are a few tips to get you started.
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.
Comparing heap dumps

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:
1. Create two HPROF files as described above, in Capturing a Heap Dump.
2. Open the first HPROF file in MAT (File > Open Heap Dump).
3. In the Navigation History view (if not visible, select Window >
Navigation History), right-click on Histogram and select Add to
Compare Basket.
4. Open the second HPROF file and repeat steps 2 and 3.
5. Switch to the Compare Basket view and click Compare the Results (the
red "!" icon in the top-right corner of the view).
Triggering Memory Leaks

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.

Using the Dev Tools App


The Dev Tools application is installed by default on all system images included with the
SDK, so you can use it with the Android Emulator. With the Dev Tools application, you can
enable a number of settings on your device that will make it easier to test and debug your
applications.
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:

It will prevent Android from throwing an error if you pause on a breakpoint


for a long time while debugging.

It will enable you to select the Wait for Debugger option to pause application
startup until your debugger attaches (described next).

Wait for debugger


Blocks the selected application from loading until a debugger attaches. This way you
can set a breakpoint in onCreate(), which is important to debug the startup process
of an Activity. When you change this option, any currently running instances of the
selected application will be killed. In order to check this box, you must have selected
a debug application as described in the previous option. You can do the same thing by
adding waitForDebugger() to your code.
Show screen updates
Flashes a momentary pink rectangle on any screen sections that are being redrawn.
This is very useful for discovering unnecessary screen drawing.
Immediately destroy activities

Tells the system to destroy an activity as soon as it is stopped (as if Android had to
reclaim memory). This is very useful for testing the
onSaveInstanceState(Bundle) / onCreate(android.os.Bundle) code path,
which would otherwise be difficult to force. Choosing this option will probably reveal
a number of problems in your application due to not saving state. For more
information about saving an activity's state, see the Activities document.
Show CPU usage
Displays CPU meters at the top of the screen, showing how much the CPU is being
used. The top red bar shows overall CPU usage, and the green bar underneath it
shows the CPU time spent in compositing the screen.
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.
These settings will be remembered across emulator restarts.

Publishing Overview
Quickview

Learn how to publish Android apps.

Find out how to prepare apps for release.

Learn how to release apps to users.

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:

You prepare the application for release.

During the preparation step you build a release version of your application, which
users can download and install on their Android-powered devices.

You release the application to users.

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:

Configuring your application for release.

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.

Building and signing a release version of your application.

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.

Testing the release version of your application.

Before you distribute your application, you should thoroughly test the release version
on at least one target handset device and one target tablet device.

Updating application resources for release.

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.
Releasing Your Application to Users

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.
Releasing through an App Marketplace

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.
Releasing Your Applications on Google Play

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:

Preparing promotional materials.

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.

Configuring options and uploading assets.

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.

Publishing the release version of your application.

If you are satisfied that your publishing settings are correctly configured and your
uploaded application is ready to be released to the public, you can simply click
Publish in the developer console and within minutes your application will be live and
available for download around the world.
For information complete information, see Google Play.
Releasing your application through email

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.
Releasing through a web site

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 Inapp 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.
User Opt-In for Apps from Unknown Sources

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.
Preparing for Release
Quickview

Learn which resources you'll need to release your app.

Find out how to configure and build your app for release.

Learn best practices for releasing your app.

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.
Gathering Materials and Resources

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 selfsigned 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.
End-user License Agreement

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

Configuring Your Application for Release

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.
Choose a good package name

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.
Turn off logging and debugging

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 directories

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.

Review and update your manifest and Gradle build settings

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.

android:icon and android:label attributes

You must specify values for these attributes, which are located in the <application>
element.

android:versionCode and android:versionName attributes.

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.
Address compatibility issues

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:

Add support for multiple screen configurations

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.

Optimize your application for Android tablet devices.

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 .

Consider using the Support Library

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.
Update URLs for servers and services

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.
Implement Licensing (if you are releasing on Google Play)

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.
Building Your Application for Release

After you finish configuring your application you can build it into a release-ready .apk file
that is signed and optimized. The JDK includes the tools for signing the .apk file (Keytool
and Jarsigner); the Android SDK includes the tools for compiling and optimizing the .apk
file. If you are using Android Studio or you are using the Gradle build system from the
command line, you can automate the entire build process. For more information about
configuring Gradle builds, see Configuring Gradle Builds.
Building with Android Studio

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.
Preparing External Servers and Resources

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 Your Application for Release

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.

Versioning Your Applications


Quickview

Your application must be versioned

You set the version in the application's manifest file

How you version your applications affects how users upgrade

Determine your versioning strategy early in the development process, including


considerations for future releases.

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
Versioning is a critical component of your application upgrade and maintenance strategy.
Versioning is important because:

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.

Setting Application 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:

An integer value that represents the version of the


application code, relative to other versions.
android:versionCode

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.

A string value that represents the release version of the


application code, as it should be shown to users.
android:versionName

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.
Here's an example manifest that shows the android:versionCode and
android:versionName attributes in the <manifest> element.
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.package.name"
android:versionCode="2"
android:versionName="1.1">
<application android:icon="@drawable/icon"
android:label="@string/app_name">
...
</application>
</manifest>

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.

Specifying Your Application's System API Requirements


If your application requires a specific minimum version of the Android platform, or is
designed only to support a certain range of Android platform versions, you can specify those
version requirements as API Level identifiers in the application's manifest file. Doing so
ensures that your application can only be installed on devices that are running a compatible
version of the Android system.
To specify API Level requirements, add a <uses-sdk> element in the application's manifest,
with one or more of these attributes:

android:minSdkVersion

android:targetSdkVersion

android:maxSdkVersion

The minimum version of the Android platform on which


the application will run, specified by the platform's API Level identifier.
Specifies the API Level on which the application is
designed to run. In some cases, this allows the application to use manifest elements or
behaviors defined in the target API Level, rather than being restricted to using only
those defined for the minimum API Level.
The maximum version of the Android platform on
which the application is designed to run, specified by the platform's API Level
identifier. Important: Please read the <uses-sdk> documentation before using this
attribute.

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.

Signing Your Applications


In this document

1. Signing Overview
1. Signing in Debug Mode
2. Signing in Release Mode
3. Signing Android Wear Apps
2. Signing Your App in Android Studio
1. Automatically Signing Your App
3. Signing Your App with Android Studio
4. Signing Considerations
5. Securing Your Private Key
6. Expiry of the Debug Certificate
7. Signing Your App Manually

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.

Signing in Debug Mode


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
}
}
}
...

4. Invoke the assembleRelease build task from Android Studio.


The package in app/build/apk/app-release.apk is now signed with your release key.
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.

To obtain these passwords from environment variables:


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:
storePassword System.console().readLine("\nKeystore password: ")
keyPassword System.console().readLine("\nKey password: ")

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.

Signing Android Wear Apps


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.

Signing Your App in Android Studio


To sign your app in release mode in Android Studio, follow these steps:
1. On the menu bar, click Build > Generate Signed APK.
2. On the Generate Signed APK Wizard window, click Create new to create a new
keystore.
If you already have a keystore, go to step 4.
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.

Figure 2. Select a private key in Android Studio.


5. On the next window, select a destination for the signed APK and click Finish.

Figure 3. Generate a signed APK in Android Studio.

Automatically Signing Your App


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.

Figure 4. Create a signing configuration in Android Studio.

5. Click on the Build Types tab.


6. Select the release build.
7. Under Signing Config, select the signing configuration you just created.

Figure 5. Select a signing configuration in Android Studio.


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 applicationin 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.

Securing Your Private Key


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:

Select strong passwords for the keystore and key.

Do not give or lend anyone your private key, and do not let unauthorized persons
know your keystore and key passwords.

Keep the keystore file containing your private key in a safe, secure place.

In general, if you follow common-sense precautions when generating, using, and storing your
key, it will remain secure.

Expiry of the Debug Certificate


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.

Signing Your App Manually


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:
1. Generate a private key using keytool. For example:
$ keytool -genkey -v -keystore my-release-key.keystore
-alias alias_name -keyalg RSA -keysize 2048 -validity 10000

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.
2. Compile your app in release mode to obtain an unsigned APK.
3. Sign your app with your private key using jarsigner:
$ jarsigner -verbose -sigalg SHA1withRSA -digestalg SHA1
-keystore my-release-key.keystore my_application.apk alias_name

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.
4. Verify that your APK is signed. For example:
$ jarsigner -verify -verbose -certs my_application.apk

5. Align the final APK package using zipalign.

$ zipalign -v 4 your_project_name-unaligned.apk your_project_name.apk

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.
zipalign

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 toolsthe Android Debug Bridge (adb). Android Debug
Bridge is a versatile tool that lets you manage the state of an emulator instance or Androidpowered 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

In this document
1. Enabling adb Debugging
2. Syntax
3. Commands
4. Querying for Emulator/Device Instances
5. Directing Commands to a Specific Emulator/Device Instance
6. Installing an Application
7. Forwarding Ports
8. Copying Files to or from an Emulator/Device Instance
9. Issuing Shell Commands
1. Using activity manager (am)
2. Using package manager (pm)
3. Examining sqlite3 databases from a remote shell
4. Recording a device screen
5. UI/Application Exerciser Monkey
6. Other shell commands
10.Enabling logcat logging
11.Stopping the adb server
12.Wireless usage

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.

You can find the adb tool in <sdk>/platform-tools/.


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 clientsall 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:
Emulator 1, console: 5554
Emulator 1, adb: 5555
Emulator 2, console: 5556
Emulator 2, adb: 5557
and so on...
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).
Enabling adb Debugging

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:
adb [-d|-e|-s <serialNumber>] <command>

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.
Table 1. Available adb commands
Category

Command

Target Device

Description

Comments

-d

Direct an adb
Returns an error if
command to the only more than one USB
attached USB device. device is attached.

-e

Direct an adb
command to the only
running emulator
instance.

Returns an error if
more than one
emulator instance
is running.

Direct an adb
command a specific
emulator/device
instance, referred to
by its adb-assigned
serial number (such

See Directing
Commands to a
Specific
Emulator/Device
Instance.

-s <serialNumber>

as "emulator-5556").

devices

Prints a list of all


attached
emulator/device
instances.

help

Prints a list of
supported adb
commands.

version

Prints the adb version


number.

logcat [option]
[filter-specs]

Prints log data to the


screen.

bugreport

Prints dumpsys,
dumpstate, and logcat
data to the screen, for
the purposes of bug
reporting.

General

See Querying for


Emulator/Device
Instances for more
information.

You can use the


forward jdwp:<pid>

Debug

jdwp

port-forwarding
specification to
Prints a list of
connect to a
available JDWP
specific JDWP
processes on a given process. For
device.
example:
adb forward
tcp:8000 jdwp:472
jdb -attach
localhost:8000

Data

install <path-toapk>

Copies a specified
file from an
pull <remote> <l emulator/device
ocal>
instance to your
development
computer.
push <local> <re Copies a specified
mote>
file from your

Pushes an Android
application (specified
as a full path to an
.apk file) to an
emulator/device.

development
computer to an
emulator/device
instance.
Port specifications
can use these
schemes:
Forwards socket
connections from a
specified local port to
forward <local> <r
a specified remote
emote>
port on the
emulator/device
instance.

tcp:<portnum
>

local:<UNIX
domain
socket name>

dev:<charact
er device
name>

jdwp:<pid>

Run PPP over USB.

Ports and
Networking

<tty> the tty

for PPP stream.


For example
dev:/dev/omap_
csmi_ttyl.

ppp <tty> [parm]..


.

[parm]...

zero or more
PPP/PPPD
options, such
as
defaultroute,
local, notty,
etc.

Note that you should not


automatically start a PPP
connection.
Scripting
get-serialno

get-state

Prints the adb


instance serial
number string.
Prints the adb state of
an emulator/device
instance.

See Querying for


Emulator/Device
Instances for more
information.

wait-for-device

Blocks execution until


the device is online
that is, until the
instance state is
device.

You can prepend


this command to
other adb
commands, in
which case adb will
wait until the
emulator/device
instance is
connected before
issuing the other
commands. Here's
an example:
adb wait-fordevice shell
getprop

Note that this


command does not
cause adb to wait
until the entire
system is fully
booted. For that
reason, you should
not prepend it to
other 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-fordevice 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.

start-server

Checks whether the


adb server process is
running and starts it,
if not.

kill-server

Terminates the adb


server process.

shell

Starts a remote shell


in the target
emulator/device
instance.

Server

See Issuing Shell


Issues a shell
Commands for
command in the
more information.
shell [shellComman target
d]
emulator/device
instance and then
exits the remote shell.

Shell

Querying for Emulator/Device Instances

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

In response, adb prints this status information for each instance:

Serial number A string created by adb to uniquely identify an


emulator/device instance by its console port number. The format of the
serial number is <type>-<consolePort>. Here's an example serial number:
emulator-5554

State The connection state of the instance may be one of the following:
o

offline the instance is not connected to adb or is not responding.

device the instance is now connected to the adb server. Note that

no device there is no emulator/device connected.

this state does not imply that the Android system is fully booted and
operational, since the instance connects to adb while the system is
still booting. However, after boot-up, this is the normal operational
state of an emulator/device instance.

The output for each instance is formatted like this:


[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

Directing Commands to a Specific Emulator/Device Instance

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:
adb -s <serialNumber> <command>

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:
adb -s emulator-5556 install helloWorld.apk

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:
adb install <path_to_apk>

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:
adb forward tcp:6100 tcp:7100

You can also use adb to set up forwarding to named abstract UNIX domain sockets, as
illustrated here:
adb forward tcp:6100 local:logd

Copying Files to or from an Emulator/Device Instance

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
adb pull <remote> <local>

To copy a file or directory (and its sub-directories) to the emulator or device, use
adb push <local> <remote>
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 push foo.txt /sdcard/foo.txt

Issuing Shell Commands

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>

Or enter a remote shell on an emulator/device like this:


adb [-d|-e|-s <serialNumber>] shell

When you are ready to exit the remote shell, press CTRL+D or type exit.
Using activity manager (am)

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:
adb shell am start -a android.intent.action.VIEW

Table 2. Available activity manager commands


Command
start [options] <INTENT>

Description
Start an Activity specified by <INTENT>.

See the Specification for <INTENT> arguments.


Options are:

-D: Enable debugging.

-W: Wait for launch to complete.

--start-profiler <FILE>: Start


profiler and send results to <FILE>.

-P <FILE>: Like --start-profiler,

but profiling stops when the app


goes idle.

-R: Repeat the activity launch


<COUNT> times. Prior to each repeat,

the top activity will be finished.

-S: Force stop the target app before

starting the activity.

--opengl-trace: Enable tracing of

OpenGL functions.

--user <USER_ID> | current:

Specify which user to run as; if not

specified, then run as the current


user.
Start the Service specified by <INTENT>.

See the Specification for <INTENT> arguments.


startservice [options] <INTENT>

Options are:

force-stop <PACKAGE>

--user <USER_ID> | current:

Specify which user to run as; if not


specified, then run as the current
user.

Force stop everything associated with


<PACKAGE> (the app's package name).
Kill all processes associated with <PACKAGE>
(the app's package name). This command
kills only processes that are safe to kill and
that will not impact the user experience.

kill [options] <PACKAGE>

Options are:

kill-all

--user <USER_ID> | all | current:

Specify user whose processes to kill;


all users if not specified.

Kill all background processes.


Issue a broadcast intent.

See the Specification for <INTENT> arguments.


broadcast [options] <INTENT>

Options are:

[--user <USER_ID> | all |


current]: Specify which user to

send to; if not specified then send


to all users.
instrument [options] <COMPONENT>

Start monitoring with an Instrumentation


instance. Typically the target <COMPONENT>
is the form
<TEST_PACKAGE>/<RUNNER_CLASS>.

Options are:

-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.

profile start <PROCESS> <FILE>

Start profiler on <PROCESS>, write results to


<FILE>.

profile stop <PROCESS>

Stop profiler on <PROCESS>.


Dump the heap of <PROCESS>, write to
<FILE>.

Options are:
dumpheap [options] <PROCESS> <FILE>

supplying a process name, specify


user of process to dump; uses
current user if not specified.

set-debug-app [options] <PACKAGE>

--user [<USER_ID>|current]: When

-n: Dump native heap instead of

managed heap.

Set application <PACKAGE> to debug.

Options are:

-w: Wait for debugger when

application starts.

clear-debug-app

--persistent: Retain this value.

Clear the package previous set for


debugging with set-debug-app.
Start monitoring for crashes or ANRs.

monitor [options]

Options are:

screen-compat [on|off] <PACKAGE>

display-size [reset|<WxH>]

--gdb: Start gdbserv on the given

port at crash/ANR.

Control screen compatibility mode of


<PACKAGE>.
Override emulator/device display size. This
command is helpful for testing your app
across different screen sizes by mimicking
a small screen resolution using a device
with a large screen, and vice versa.

Example:
am display-size 1280x800

display-density <dpi>

Override emulator/device display density.


This command is helpful for testing your
app across different screen densities on
high-density screen environment using a
low density screen, and vice versa.

Example:
am display-density 480

to-uri <INTENT>

Print the given intent specification as a


URI.

See the Specification for <INTENT> arguments.

to-intent-uri <INTENT>

Print the given intent specification as an


intent: URI.

See the Specification for <INTENT> arguments.


Specification for <INTENT> arguments
Using package manager (pm)

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:
adb shell pm uninstall com.example.MyApp

Table 3. Available package manager commands.


Command

Description
Prints all packages, optionally
only those whose package
name contains the text in
<FILTER>.

Options:

-f: See their associated

file.

-d: Filter to only show

disabled packages.

-e: Filter to only show

enabled packages.

list packages [options] <FILTER>

-s: Filter to only show

system packages.

-3: Filter to only show

third party packages.

-i: See the installer for

the packages.

-u: Also include

uninstalled packages.

list permission-groups
list permissions [options] <GROUP>

--user <USER_ID>: The

user space to query.

Prints all known permission


groups.
Prints all known permissions,
optionally only those in <GROUP>.

Options:

-g: Organize by group.

-f: Print all information.

-s: Short summary.

-d: Only list dangerous

permissions.

-u: List only the

permissions users will


see.

List all test packages.

Options:
list instrumentation

-f: List the APK file for

the test package.

<TARGET_PACKAGE>: List

test packages for only


this app.

list features

Prints all features of the


system.

list libraries

Prints all the libraries supported


by the current device.

list users

Prints all users on the system.

path <PACKAGE>

Print the path to the APK of the


given <PACKAGE>.

install [options] <PATH>

Installs a package (specified by


<PATH>) to the system.

Options:

-l: Install the package

with forward lock.

-r: Reinstall an exisiting

app, keeping its data.

-t: Allow test APKs to be

installed.

-i
<INSTALLER_PACKAGE_NAME
>: Specify the installer

package name.

-s: Install package on the

shared mass storage


(such as sdcard).

-f: Install package on the

internal system memory.

-d: Allow version code

downgrade.

Removes a package from the


system.
uninstall [options] <PACKAGE>

Options:

-k: Keep the data and

cache directories around


after package removal.

clear <PACKAGE>

Deletes all data associated with


a package.

enable <PACKAGE_OR_COMPONENT>

Enable the given package or


component (written as
"package/class").

disable <PACKAGE_OR_COMPONENT>

Disable the given package or


component (written as
"package/class").

Options:
disable-user [options] <PACKAGE_OR_COMPONENT>

grant <PACKAGE_PERMISSION>

revoke <PACKAGE_PERMISSION>

--user <USER_ID>: The

user to disable.

Grant permissions to
applications. Only optional
permissions the application has
declared can be granted.
Revoke permissions to
applications. Only optional
permissions the application has

declared can be revoked.


Changes the default install
location. Location values:

0: AutoLet system

decide the best location.

1: Internalinstall on

internal device storage.

set-install-location <LOCATION>

2: Externalinstall on

external media.

Note: This is only intended for


debugging; using this can cause
applications to break and other
undesireable behavior.
Returns the current install
location. Return values:

0 [auto]: Lets system

decide the best location


get-install-location

1 [internal]: Installs on

internal device storage

2 [external]: Installs on

external media

set-permission-enforced <PERMISSION> [true|


false]

Specifies whether the given


permission should be enforced.

trim-caches <DESIRED_FREE_SPACE>

Trim cache files to reach the


given free space.

create-user <USER_NAME>

Create a new user with the


given <USER_NAME>, printing the
new user identifier of the user.

remove-user <USER_ID>

Remove the user with the given


<USER_IDENTIFIER>, deleting all
data associated with that user

get-max-users

Prints the maximum number of


users supported by the device.

Examining sqlite3 databases from a remote shell

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:
adb -s emulator-5554 shell
# sqlite3
/data/data/com.example.google.rss.rssexample/databases/rssitems.db
SQLite version 3.3.12
Enter ".help" for instructions
.... enter commands, then quit...
sqlite> .exit
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.


Recording a device screen

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:
$ adb shell screenrecord /sdcard/demo.mp4

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.

Table 4. screenrecord options


Options
--help

Description
Displays a usage summary.

Sets the video size, for example: 1280x720. The default


value is the device's main display resolution (if
--size <WIDTHxHEIGHT> supported), 1280x720 if not. For best results, use a size
supported by your device's Advanced Video Coding (AVC)
encoder.

--bit-rate <RATE>

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 quality or lower it for smaller
movie files. The following example sets the recording bit
rate to 6Mbps:
screenrecord --bit-rate 6000000 /sdcard/demo.mp4

--time-limit <TIME>

Sets the maximum recording time, in seconds. The


default and maximum value is 180 (3 minutes).

--rotate

Rotates the output 90 degrees. This feature is


experimental.

--verbose

Displays log information on command line screen. If you


do not set this option, the utility does not display any
information while running.

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 systemlevel 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.
Other shell commands

For a list of all the available shell programs, use the following command:
adb shell ls /system/bin

Help is available for most of the commands.


Table 5 lists some of the more common adb shell commands.
Table 5. Some other adb shell commands
Shell Command

Description

Comments

dumpsys

The Dalvik Debug Monitor


Server (DDMS) tool offers
Dumps system data
integrated debug
to the screen.
environment that you may
find easier to use.

dumpstate

Dumps state to a file.

logcat [option]... [filterspec]...

Enables system and


app logging and
prints output to the
screen.

dmesg

Prints kernel
debugging messages
to the screen.

start

Starts (restarts) an
emulator/device
instance.

stop

Stops execution of
an emulator/device
instance.

Enabling logcat logging

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:
[adb] logcat [option] ... [filter-spec] ...
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

and from a remote adb shell you use


logcat

See Reading and Writing Logs for complete information about logcat commend options and
filter specifications.
Stopping the adb server

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

4. Connect to the device over USB.


$ adb devices
List of devices attached
######## device

5. Restart host adb in tcpip mode.


$ adb tcpip 5555
restarting in TCP mode port: 5555

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:
$ adb connect #.#.#.#
connected to #.#.#.#:5555

8. Remove USB cable from device, and confirm you can still access device:
$ adb devices
List of devices attached
#.#.#.#:5555 device

You're now good to go!


If the adb connection is ever lost:
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

and then start over from the beginning.

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.

AVD actions and options


Action

Option

avd

None

sdk

None

create avd -n <name>

-t <targetID>

Description
Comments
Launch the AVD Manager
Launch the Android SDK
Manager
The name for the AVD. Required
Target ID of the system
image to use with the new
AVD. To obtain a list of Required
available targets, use
android list targets

The path to the SD card


image to use with this
AVD or the size of a new
SD card image to create
-c <path>|
<size>[K|M]
for this AVD. For
example, -c
path/to/sdcard or -c
1000M.
-f
Force creation of the AVD
Path to the location at
which to create the
-p <path>
directory for this AVD's
files.
-s <name>|<width>- The skin to use for this
<height>
AVD, identified by name
or dimensions. The
android tool scans for a
matching skin by name or
dimension in the skins/
directory of the target
referenced in the -t

argument.
For example, -s HVGA-L
The name of the AVD to
Required
delete
The name of the AVD to
Required
move
Path to the location at
which to create the
directory for this AVD's
files.
New name of the AVD if
you want to rename it
The name of the AVD to
Required
move
<targetID>

delete avd -n <name>


-n <name>

move avd

-p <path>

-r <new-name>
update avd -n <name>

Project actions and options


Action

Option
-n <name>

-t <targetID>
create
project

android list targets


-k <path>|
<size>[K|M]
-a
-p
-n
-p

update
project

-l

-s
-t
create
testproject
update

Description
Comments
The name for the project Required
Target ID of the system
image to use with the new
AVD. To obtain a list of Required
available targets, use

-n
-p
-m
-p

Package namespace

Name for the default


Activity class
Location of your project
<path>
directory
The name of the project
<name>
to update
Location path of the
<path>
project
Location path of an
Android Library to add,
<library path>
relative to the main
project
Update any projects in
<subprojects> subfolders such as test
projects
Target id to set for the
<targetID>
project
<name>
The name of the project
Location path of the
<path>
project
<main>
The name of the project
<path>
Location path of the

Required
Required
Required

Required

Required
Required
Required

testproject

-m <main>
-k <packageName>

create
libproject

-p <path>
-t <targetID>
-n <name>
-p <path>

update
libproject

-l <libraryPath>

-t <name>
-n <name>
create
uitestproject

-t <name>
-p <path>

project to test, relative to


the new project
The main class of the
project to test
(Required) Package name
of the library project
Location path of the
project
Target ID of the library
project
The name of the project
Location path of the
project
Location path of an
Android Library to add,
relative to the main
project
Target ID of the library
project
The name of the UI test
project
Target ID of the UI test
project
Location path of the UI
test project

Required
Required
Required
Required
Required
Required

Required
Required

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.

For more information, see Managing AVDs with AVD Manager.

bmgr
In this document
1. Forcing a Backup Operation
2. Forcing a Restore Operation
3. Other Commands

See also
1. Data Backup
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.
bmgr

For information about adding support for backup in your application, read Data Backup,
which includes a guide to testing your application using bmgr.

Forcing a Backup Operation


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:
adb shell bmgr backup <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:
<package>

adb shell bmgr run

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.

Forcing a Restore Operation


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:
adb shell bmgr restore <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.
<package>

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:
adb shell bmgr wipe <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.
<package>

Enabling and disabling backup


You can see whether the Backup Manager is operational at all with the bmgr enabled
command:
adb shell bmgr enabled

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:
adb shell bmgr enable <boolean>

is either true or false. This is equivalent to disabling or enabling backup in the


device's main Settings UI.
<boolean>

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

is a tool that gives you an alternate way of generating graphical call-stack


diagrams from trace log files (instead of using Traceview).
dmtracedump

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 usage for dmtracedump is:
dmtracedump [-ho] [-s sortable] [-d trace-base-name] [-g outfile] <tracebase-name>
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 <tracebase-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 <tracebase-name>

URL base to the location of the sortable javascript file

-t <percent>

Minimum threshold for including child nodes in the graph


(child's inclusive time 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...
Your image will be saved with the .9.png file name.
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.
Table 1. Emulator keyboard mapping
Emulated Device Key

Keyboard Key

Home
HOME
Menu (left softkey)
F2 or Page-up button
Star (right softkey)
Shift-F2 or Page Down
Back
ESC
Call/dial button
F3
Hangup/end call button
F4
Search
F5
Power button
F7
Audio volume up button
KEYPAD_PLUS, Ctrl-F5
Audio volume down button
KEYPAD_MINUS, Ctrl-F6
Camera button
Ctrl-KEYPAD_5, Ctrl-F3
Switch to previous layout orientation (for example,
KEYPAD_7, Ctrl-F11
portrait, landscape)
Switch to next layout orientation (for example,
KEYPAD_9, Ctrl-F12
portrait, landscape)
Toggle cell networking on/off
F8
F9 (only with -trace startup option)
Toggle code profiling
Toggle fullscreen mode
Alt-Enter
Toggle trackball mode
F6
Enter trackball mode temporarily (while key is
Delete
pressed)
DPad left/up/right/down
KEYPAD_4/8/6/2
DPad center click
KEYPAD_5
KEYPAD_MULTIPLY(*) /
Onion alpha increase/decrease
KEYPAD_DIVIDE(/)

Command Line Parameters

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>]

Table 2. Emulator command line parameters


S
Category

AVD

Option
-avd <avd_name>
@<avd_name>

Description

or

Disk
Images
-cache <filepath>

Comments
You must create an AVD
Required. Specifies
configuration before launching the
the AVD to load for
emulator. For information, see
this emulator
Managing AVDs with AVD
instance.
Manager.
An absolute or relative path to the
current working directory. If no
cache file is specified, the
Use <filepath> as the emulator's default behavior is to
use a temporary file instead.
working cache
partition image.
For more information on disk
images, use -help-disk-images.

Optionally, you can specify a path


relative to the current working
Use <filepath> as directory. If -data is not used, the
-data <filepath>
emulator looks for a file named
the working useruserdata-qemu.img in the
data disk image.
storage area of the AVD being
used (see -avd).
When resetting the
user-data image
Optionally, you can specify a path
(through -wiperelative to the current working
data), copy the
contents of this file directory. See also -wipe-data.
-initdata <filepath
to the new user-data
>
For more information on disk
disk image. By
default, the emulator images, use -help-disk-images.
copies the
<system>/userdata
.img.

Start the emulator


See also -cache <file>.
without a cache
partition.
-ramdisk <filepath> Use <filepath> as the Default value is
ramdisk image.
<system>/ramdisk.img.
-nocache

Category

Option

Description

Comments
Optionally, you can specify a path
relative to the current working
directory. For more information
on disk images, use -help-diskimages.
Default value is
<system>/sdcard.img.

-sdcard <filepath>

-wipe-data

Debug
-debug <tags>

-debug-<tag>

-debug-no-<tag>
-logcat <logtags>

Optionally, you can specify a path


Use <file> as the SD
relative to the current working
card image.
directory. For more information
on disk images, use -help-diskimages.
Reset the current
user-data disk image
(that is, the file
specified by
-datadir and
See also -initdata.
-data, or the default
file). The emulator
For more information on disk
deletes all data from
images, use -help-disk-images.
the user data image
file, then copies the
contents of the file at
-inidata data to the
image file before
starting.
<tags> is a
space/comma/column-separated
Enable/disable debug
list of debug component names.
messages for the
Use -help-debug-tags to print a
specified debug tags.
list of debug component names
that you can use.
Enable/disable debug
messages for the
Use -help-debug-tags to print a
specified debug tag.
list of debug component names
Disable debug
that you can use in <tag>.
messages for the
specified debug tag.
Enable logcat output If the environment variable
with given tags.
ANDROID_LOG_TAGS is
defined and not empty, its value
will be used to enable logcat
output by default.

Category

Option

-shell

Description
Create a root shell
console on the
current terminal.

Comments
You can use this command even if
the adb daemon in the emulated
system is broken. Pressing Ctrl-c
from the shell stops the emulator
instead of the shell.
<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.
Here are some examples:

Enable the root shell


(as in -shell and
specify the QEMU
-shell-serial <devi
character device to
ce>
use for
communication with
the shell.

-shell-serial stdio
identical to -shell

-shell-serial
tcp::4444,server,nowa
it lets you communicate

is

with the shell over TCP


port 4444

-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>

-trace <name>
-verbose

Display kernel
messages.
Enable code
profiling (press F9 to
start), written to a
specified file.
Enable verbose
Equivalent to -debug-init.
output.
You can define the default verbose
output options used by emulator
instances in the Android
environment variable
ANDROID_VERBOSE. Define

Category

Option

Description

Comments
the options you want to use in a
comma-delimited list, specifying
only the stem of each option:
-debug-<tags>.

Here's an example showing


ANDROID_VERBOSE defined
with the -debug-init and
-debug-modem options:
ANDROID_VERBOSE=init,modem

For more information about debug


tags, use <-help-debug-tags>.
Use the specified
audio backend.
Use the specified
-audio-in <backend>
audio-input backend.
Use the specified
-audio-out
audio-output
<backend>
backend.
Disable audio
-noaudio
support in the current
emulator instance.
Redirect radio
modem interface to a
-radio <device>
host character
device.
Enable audio support
-useaudio
in the current
Enabled by default.
emulator instance.
The value of <servers> must be a
-dns-server
Use the specified
comma-separated list of up to 4
<servers>
DNS server(s).
DNS server names or IP
addresses.
-http-proxy <proxy> Make all TCP
The value of <proxy> can be one
connections through of the following:
http://<server>:<port>
a specified
HTTP/HTTPS proxy http://<username>:<password
-audio <backend>

Media

Network

>@<server>:<port>

The http:// prefix can be


omitted. If the -http-proxy
<proxy> command is not
supplied, the emulator looks up
the http_proxy environment

Category

Option

Description

Comments
variable and automatically uses
any value matching the <proxy>
format described above.

-netdelay <delay>

-netfast

-netspeed <speed>

-port <port>

-report-console
<socket>

Set network latency Default value is none. See the


emulation to
table in Network Delay Emulation
<delay>.
for supported <delay> values.
Shortcut for
-netspeed full
-netdelay none

Default value is full. See the


table in Network Speed Emulation
for supported <speed> values.
The console port number must be
Set the console port
an even integer between 5554 and
number for this
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:
Set network speed
emulation to
<speed>.

Report the assigned


console port for this
emulator instance to
a remote third party
before starting the
emulation.

tcp:<port>[,server]
[,max=<seconds>]
unix:<port>[,server]
[,max=<seconds>]

Use -help-report-console
to view more information about
this topic.
Supported values for <delay> are
integers between 0 and 1000.

System

Note that the <delay> does not


correlate to clock speed or other
Slow down emulated absolute metrics it simply
-cpu-delay <delay> CPU speed by
represents an abstract, relative
<delay>
delay factor applied nondeterministically in the emulator.
Effective performance does not
always scale in direct relationship
with <delay> values.
-gps <device>

Redirect NMEA
GPS to character
device.

Use this command to emulate an


NMEA-compatible GPS unit
connected to an external character
device or socket. The format of

Category

Option

-nojni

-qemu

-qemu -enable-kvm

Description

Comments
<device> must be QEMUspecific serial device
specification. See the
documentation for 'serial -dev' at
http://wiki.qemu.org/download/qe
mu-doc.html.

Disable JNI checks


in the Dalvik
runtime.

Pass arguments to
the qemu emulator
software.

Enable KVM
acceleration of the
emulator virtual
machine.

Important: When using this


option, make sure it is the last
option specified, since all options
after it are interpretted as qemuspecific options.
This option is only effective when
your system is set up to use
KVM-based VM acceleration.
You can optionally specify a
memory size (-m <size>) for the
VM, which should match your
emulator's memory size:
-qemu -m 512 -enable-kvm
-qemu -m 1024 -enable-kvm

-qemu -h

-gpu on

-radio <device>

-timezone
<timezone>

-version

UI

-dpi-device <dpi>

Display qemu help.


Turn on graphics
This option is only available for
acceleration for the emulators using a system image
emulator.
with API Level 15, revision 3 and
higher. For more information, see
Using the Android Emulator.
The format of <device> must be
QEMU-specific serial device
Redirect radio mode
specification. See the
to the specified
documentation for 'serial -dev' at
character device.
http://wiki.qemu.org/download/qe
mu-doc.html.
<timezone> must be specified in
Set the timezone for
zoneinfo format. For example:
the emulated device
to <timezone>,
"America/Los_Angeles"
instead of the host's
"Europe/Paris"
timezone.
Display the
emulator's version
number.
Scale the resolution The default value is 165. See also
of the emulator to
-scale.

Category

Option

-no-boot-anim

-no-window

-scale <scale>

-raw-keys

-noskin

-keyset <file>

-onion <image>
-onion-alpha
<percent>
-onion-rotation
<position>

-skin <skinID>

-skindir <dir>

Description
Comments
match the screen size
of a physical device.
Disable the boot
Disabling the boot animation can
animation during
speed the startup time for the
emulator startup.
emulator.
Disable the
emulator's graphical
window display.
<scale> is a number between 0.1
and 3 that represents the desired
scaling factor. You can also
Scale the emulator specify scale as a DPI value if you
window.
add the suffix "dpi" to the scale
value. A value of "auto" tells the
emulator to select the best
window size.
Disable Unicode
keyboard reversemapping.
Don't use any
emulator skin.
The keyset file defines the list of
key bindings between the
Use the specified
emulator and the host keyboard.
keyset file instead of
For more information, use -helpthe default.
keyset to print information about
this topic.
Use overlay image No support for JPEG. Only PNG
over screen.
is supported.
Specify onion skin Default is 50.
translucency value
(as percent).
Specify onion skin <position> must be one of the
rotation.
values 0, 1, 2, 3.
Please set skin options using
AVDs, rather than by using this
emulator option. Using this option
may yield unexpected and in some
cases misleading results, since the
This emulator option density with which to render the
is deprecated.
skin may not be defined. AVDs let
you associate each skin with a
default density and override the
default as needed. For more
information, see Managing Virtual
Devices with AVD Manager.
This emulator option See comments for -skin, above.

Category

Option
-help
-help-all

-help-<option>

-help-debug-tags

-help-disk-images

Help
-help-environment

-help-keys

-help-keyset-file

-help-virtualdevice

Description
is deprecated.
Print a list of all
emulator options.
Print help for all
startup options.
Print help for a
specific startup
option.
Print a list of all tags
for -debug <tags>.
Print help for using
emulator disk
images.
Print help for
emulator
environment
variables.
Print the current
mapping of keys.
Print help for
defining a custom
key mappings file.
Print help for
Android Virtual
Device usage.

Comments

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.
etc1tool

The usage for etc1tool is:


etc1tool infile [--help | --encode | --encodeNoHeader | --decode] [-showDifference
diff-file] [-o outfile]

Option

Description

infile

The input file to compress

--help

Print usage information

--encode

Create an ETC1 file from a PNG file. This is the default mode
for the tool if nothing is specified.

--encodeNoHeader

Create a raw ETC1 data file (without a header) from a PNG


file.

Option

Description

--decode

Create a PNG file from an ETC1 file

--showDifference
diff-file

Write the difference between the original and encoded


image to diff-file (only valid when encoding).

-o outfile

Specify the name of the output file. If outfile is not


specified, the 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.
hprof-conv <infile> <outfile>
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

The syntax for running jobb is as follows:


jobb [-d <directory>][-o <filename>][-pn <package>][-pv <version>] \
[-k <key>][-ov][-dump <filename>][-v][-about]

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.
$ jobb -d /temp/assets/ -o my-app-assets.obb -k secret-key -pn
com.my.app.package -pv 11

This example shows how to dump (extract) the contents of an existing OBB file:
$ jobb -d /temp/obb-output/ -o my-app-assets.obb -k secret-key

Options

The table below lists the command line options for the jobb tool.
Option

Description

-d <directory>

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 the specified directory
and all its sub-directories are included in the OBB file system.

-o <filename>

Specify the filename for the OBB file. This parameter is


required when creating an OBB and extracting (dumping) its
contents.

-pn <package>

Specify the package name for the application that mounts the
OBB file, which corresponds to the package value specified in
your application's manifest. This parameter is required when
creating an OBB file.

-pv <version>

Set the minimum version for the application that can mount
the OBB file, which corresponds to the android:versionCode
value in your application's manifest. This parameter is required
when creating an OBB file.

-k <key>

Specify a password for encrypting a new OBB file or decrypting


an existing, encypted OBB file.

-ov

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 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
Table 1 describes the command-line options for lint.
Table 1. Command-line options for lint

Category

Option

Description
Disable checking for
--disable <list> a specific list of
issues.
Check for all the
default issues
supported by lint as
--enable <list>
well as the
specifically enabled
list of issues.
--check <list>

Checking

Check for a specific


list of issues.

Comments
The <list> must be a commaseparated list of lint issue IDs or
categories.
The <list> must be a commaseparated list of lint issue IDs or
categories.
The <list> must be a commaseparated list of lint issue IDs or
categories.

Only check for errors


and ignore warnings
Check for all
warnings, including
-Wall
those that are disabled
by default
Report all warnings as
-Werror
errors
Use the specified
configuration file to If the project contains a lint.xml file,
--config
determine if issues are the lint.xml file will be used as the
<filename>
enabled or disabled configuration file by default.
for lint checking
Reporting
The report is saved in the output file
specified in the argument. The HTML
output includes code snippets of the
--html
Generate an HTML
source code where lint detected an
<filename>
report.
issue, a verbose description of the
issue found, and links to the source
file.
The --url option only applies when
you are generating an HTML report
with the --html option. You can
In the HTML output, specify multiple <filepath>=<url>
replace a local path mappings in the argument by
--url
separating each mapping with a
<filepath>=<url> prefix <filepath>
with a url prefix
comma.
<url>.
To turn off linking to files, use --url
-w

or --nowarn

none

Generate a simple
HTML report
Generate an XML
--xml <filename>
report
--fullpath
Show the full file
--simplehtml
<filename>

The report is saved in the output file


specified in the argument.
The report is saved in the output file
specified in the argument.

--showall

--nolines

--exitcode
--quiet

--help

--list

Help
--show

--version

paths in the lint


checking results.
Don't truncate long
messages or lists of
alternate locations.
Don't include code
snippets from the
source files in the
output.
Set the exit code to 1
if errors are found.
Don't show the
progress indicator.
List the commandUse --help <topic> to see help
line arguments
information for a specific topic, such
supported by the lint
as "suppress".
tool.
List the ID and short
description for issues
that can be checked
by lint
List the ID and
verbose description Use --show <ids> to see descriptions
for issues that can be for a specific list of lint issue IDs.
checked by lint
Show the lint
version

Configuring Java and XML Source Files


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

You can create a shell connection to a device and execute:


$ adb shell
# logcat

Options

The following table describes the command line options of logcat.


Option

Description

-b <buffer>

Loads an alternate log buffer for viewing, such as events or radio.


The main buffer is used by default. See Viewing Alternative Log
Buffers.

-c

Clears (flushes) the entire log and exits.

-d

Dumps the log to the screen and exits.

-f <filename
Writes log message output to <filename>. The default is stdout.
>
-g

Prints the size of the specified log buffer and exits.

-n <count>

Sets the maximum number of rotated logs to <count>. The default


value is 4. Requires the -r option.

-r <kbytes>

Rotates the log file every <kbytes> of output. The default value is
16. Requires the -f option.

-s

Sets the default filter spec to silent.

-v <format>

Sets the output format for log messages. The default is brief
format. For a list of 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

The following table describes the command-line options of mksdcard


Opti
on

Description

-l

A volume label for the disk image to create.

size

An integer that specifies the size (in bytes) of disk image to create. You
can also specify size in kilobytes or megabytes, by appending a "K" or "M"
to <size>. For example, 1048576K, 1024M.

file

The path/filename of the disk image to create.

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.
The usage for the -sdcard option is as follows:
emulator -sdcard <file>

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 systemlevel 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:

Basic configuration options, such as setting the number of events to attempt.

Operational constraints, such as restricting the test to a single package.

Event types and frequencies.

Debugging options.

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.

Basic Use of the Monkey


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 basic syntax is:
$ adb shell monkey [options] <event-count>

With no options specified, the Monkey will launch in a quiet (non-verbose) mode, and will
send events to any (and all) packages installed on your target. Here is a more typical
command line, which will launch your application and send 500 pseudo-random events to it:
$ adb shell monkey -p your.package.name -v 500

Command Options Reference


The table below lists all options you can include on the Monkey command line.
Category

Option
--help

General

-v

-s <seed>

--throttle
<milliseconds>
--pct-touch
<percent>
--pct-motion
<percent>
--pct-trackball
<percent>

Events

--pct-nav
<percent>

--pct-majornav
<percent>

--pct-syskeys
<percent>
--pct-appswitch
<percent>
--pct-anyevent
<percent>

Constraints -p <allowed-

package-name>

Description
Prints a simple usage guide.
Each -v on the command line will increment the verbosity
level. Level 0 (the default) provides little information beyond
startup notification, test completion, and final results. Level 1
provides more details about the test as it runs, such as
individual events being sent to your activities. Level 2
provides more detailed setup information such as activities
selected or not selected for testing.
Seed value for pseudo-random number generator. If you rerun the Monkey with the same seed value, it will generate the
same sequence of events.
Inserts a fixed delay between events. You can use this option
to slow down the Monkey. If not specified, there is no delay
and the events are generated as rapidly as possible.
Adjust percentage of touch events. (Touch events are a downup event in a single place on the screen.)
Adjust percentage of motion events. (Motion events consist
of a down event somewhere on the screen, a series of pseudorandom movements, and an up event.)
Adjust percentage of trackball events. (Trackball events
consist of one or more random movements, sometimes
followed by a click.)
Adjust percentage of "basic" navigation events. (Navigation
events consist of up/down/left/right, as input from a
directional input device.)
Adjust percentage of "major" navigation events. (These are
navigation events that will typically cause actions within your
UI, such as the center button in a 5-way pad, the back key, or
the menu key.)
Adjust percentage of "system" key events. (These are keys
that are generally reserved for use by the system, such as
Home, Back, Start Call, End Call, or Volume controls.)
Adjust percentage of activity launches. At random intervals,
the Monkey will issue a startActivity() call, as a way of
maximizing coverage of all activities within your package.
Adjust percentage of other types of events. This is a catch-all
for all other types of events such as keypresses, other lessused buttons on the device, and so forth.
If you specify one or more packages this way, the Monkey
will only allow the system to visit activities within those
packages. If your application requires access to activities in
other packages (e.g. to select a contact) you'll need to specify

those packages as well. If you don't specify any packages, the


Monkey will allow the system to launch activities in all
packages. To specify multiple packages, use the -p option
multiple times one -p option per package.
If you specify one or more categories this way, the Monkey
will only allow the system to visit activities that are listed
with one of the specified categories. If you don't specify any
-c <maincategories, the Monkey will select activities listed with the
category>
category Intent.CATEGORY_LAUNCHER or
Intent.CATEGORY_MONKEY. To specify multiple
categories, use the -c option multiple times one -c option
per category.
When specified, the Monkey will perform the initial launch
into a test activity, but will not generate any further events.
For best results, combine with -v, one or more package
--dbg-no-events constraints, and a non-zero throttle to keep the Monkey
running for 30 seconds or more. This provides an
environment in which you can monitor package transitions
invoked by your application.
If set, this option will generate profiling reports immediately
before and after the Monkey event sequence. This will
--hprof
generate large (~5Mb) files in data/misc, so use with care.
See Traceview for more information on trace files.
Normally, the Monkey will stop when the application crashes
--ignoreor experiences any type of unhandled exception. If you
crashes
specify this option, the Monkey will continue to send events
to the system, until the count is completed.
Normally, the Monkey will stop when the application
experiences any type of timeout error such as a "Application
--ignoreNot Responding" dialog. If you specify this option, the
timeouts
Monkey will continue to send events to the system, until the
Debugging
count is completed.
Normally, the Monkey will stop when the application
experiences any type of permissions error, for example if it
--ignoreattempts to launch an activity that requires certain
securitypermissions. If you specify this option, the Monkey will
exceptions
continue to send events to the system, until the count is
completed.
Normally, when the Monkey stops due to an error, the
application that failed will be left running. When this option
--kill-process- is set, it will signal the system to stop the process in which
after-error
the error occurred. Note, under a normal (successful)
completion, the launched process(es) are not stopped, and the
device is simply left in the last state after the final event.
Watches for and reports crashes occurring in the Android
--monitornative-crashes system native code. If --kill-process-after-error is set, the
system will stop.
Stops the Monkey from executing until a debugger is
--wait-dbg
attached to it.

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.

A Simple monkeyrunner Program


Here is a simple monkeyrunner program that connects to a device, creating a MonkeyDevice
object. Using the MonkeyDevice object, the program installs an Android application package,
runs one of its activities, and sends key events to the activity. The program then takes a
screenshot of the result, creating a MonkeyImage object. From this object, the program writes
out a .png file containing the screenshot.
# Imports the monkeyrunner modules used by this program
from com.android.monkeyrunner import MonkeyRunner, MonkeyDevice
# Connects to the current device, returning a MonkeyDevice object
device = MonkeyRunner.waitForConnection()
# 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')
# sets a variable with the package's internal name
package = 'com.example.android.myapplication'
# sets a variable with the name of an Activity in the package
activity = 'com.example.android.myapplication.MainActivity'
# sets the name of the component to start
runComponent = package + '/' + activity
# Runs the component
device.startActivity(component=runComponent)
# Presses the Menu button
device.press('KEYCODE_MENU', MonkeyDevice.DOWN_AND_UP)
# Takes a screenshot
result = device.takeSnapshot()

# Writes the screenshot to a file


result.writeToFile('myproject/shot1.png','png')

The monkeyrunner API


The monkeyrunner API is contained in three modules in the package
com.android.monkeyrunner:

MonkeyRunner: A class

MonkeyDevice:

MonkeyImage:

of utility methods for monkeyrunner programs. This class


provides a method for connecting monkeyrunner to a device or emulator. It also
provides methods for creating UIs for a monkeyrunner program and for displaying the
built-in help.
Represents a device or emulator. This class provides methods for
installing and uninstalling packages, starting an Activity, and sending keyboard or
touch events to an application. You also use this class to run test packages.
Represents a screen capture image. This class provides methods for
capturing screens, converting bitmap images to various formats, comparing two
MonkeyImage objects, and writing an image to a file.

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:
from com.android.monkeyrunner import <module>

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.
The syntax of the monkeyrunner command is
monkeyrunner -plugin <plugin_jar> <program_filename> <program_options>

Table 1 explains the flags and arguments.


Table 1. monkeyrunner flags and arguments.
Argument

Description

(Optional) Specifies a .jar file containing a plugin for


monkeyrunner. To learn more about monkeyrunner plugins, see
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>.
-plugin
<plugin_jar>

monkeyrunner Built-in Help


You can generate an API reference for monkeyrunner by running:
monkeyrunner help.py <format> <outfile>

The arguments are:

<format>

<outfile>

is either text for plain text output or html for HTML output.
is a path-qualified name for the output file.

Extending monkeyrunner with Plugins


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 plugin startup class


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;
public class Main implements Predicate<PythonInterpreter> {
@Override
public boolean apply(PythonInterpreter anInterpreter) {
/*
* 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.
About Android | Legal | Support
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()

you would use:


newdevice = MonkeyRunner.waitForConnection()

Summary

Constants
strin
DOWN
g

Use this with the type argument of press() or touch()


to send a DOWN event.

strin
UP
g

Use this with the type argument of press() or touch()


to send an UP event.

Use this with the type argument of press() or touch()


strin DOWN_AND_
to send a DOWN event immediately followed by an UP
g
UP
event.
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.
drag (tuple start, tuple end, float duration, integer steps)

void

Simulates a drag gesture (touch, hold, and move) on this


device's screen.
getProperty (string key)

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.
getSystemProperty (string key)

object

. The API equivalent of adb shell getprop <key>. This is


provided for use by platform developers.

installPackage (string path)


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.

dictionary

instrument (string className, dictionary args)


Runs the specified component under 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.


press (string name, dictionary type)
void

Sends the key event specified by type to the key specified by


keycode.
reboot (string into)

void

Reboots this device into the bootloader specified by


bootloadType.
removePackage (string package)

void

object

void

Deletes the specified package from this device, including its


data and cache.
shell (string cmd)
Executes an adb shell command and returns the result, if any.
startActivity (string uri, string action, string data, string
mimetype, iterable categories dictionary extras, component
component, flags)
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.
touch (integer x, integer y, integer type)
void

Sends a touch event specified by type to the screen location


specified by x and y.
type (string message)

void

void
Constants

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 ()
Wakes the screen of this device.

string DOWN

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.
press()

string UP

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.
press()

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
The URI for the Intent. (see Intent.setData()).
uri
action The action for this Intent (see Intent.setAction()).
data

The data URI for this Intent (see Intent.setData()).

mimety
The MIME type for the Intent (see Intent.setType()).
pe
categori An iterable data structure containing strings that define categories for
this Intent (see Intent.addCategory()).
es
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


compon
argument will direct the Intent to a specific class within a specific
ent
Android package.
flags

An iterable data structure containing flags that control how the Intent
is handled (see 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
start
x and y are integers.
The end point of the drag gesture, in the form of a tuple (x,y) where x
and y are integers.

end

durati
The duration of the drag gesture in seconds. The default is 1.0 seconds.
on
steps The number of steps to take when interpolating points. The default is 10.
object getProperty (string key)

Given the name of a system environment variable, returns its value for this device.
Arguments
ke The name of the system environment variable. The available variable names
y are listed in Table 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.

object getSystemProperty (string key)

Synonym for getProperty().


Arguments
ke The name of the system environment variable. The available variable names
y are listed in Table 1. Property Variable Names.
Returns

The value of the variable. The data format varies according to the variable
requested.

void installPackage (string path)

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
classNa
device, and classname is the class name of an Android component
me
(Activity, ContentProvider, Service, or BroadcastReceiver) in that file.
Both packagename and classname must be fully qualified. See
ComponentName for more details.
args

A dictionary containing flags and their values. These are passed to the
component as it is 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.
If you use InstrumentationTestRunner as the class name in the componentName
argument, then the result dictionary contains the single key "stream". The value of
"stream" is a string containing the test output, as if InstrumentationTestRunner
was run from the command line. The format of this output is described in Testing in
Other IDEs.

void press (string name, integer type)

Sends the key event specified by type to the key specified by keycode.
Arguments
nam The name of the keycode to send. See KeyEvent for a list of keycode names.
e Use the keycode name, not its integer value.
type

The type of key event to send. The allowed values are DOWN, UP, and
DOWN_AND_UP.

void reboot (string bootloadType)

Reboots this device into the bootloader specified by bootloadType.


Arguments
int The type of bootloader to reboot into. The allowed values are "bootloader",

o "recovery", or "None".
void removePackage (string package)

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.
object shell (string cmd)

Executes an adb shell command and returns the result, if any.


Arguments
cm The command to execute in the adb shell. The form of these commands is
d described in the 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
The URI for the Intent. (see Intent.setData()).
uri
action The action for the Intent (see Intent.setAction()).
data

The data URI for the Intent (see Intent.setData()).

mimety
The MIME type for the Intent (see Intent.setType()).
pe
categori An iterable data structure containing strings that define categories for
the Intent (see Intent.addCategory()).
es
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.

compon The component for the Intent (see ComponentName). Using this argument
ent
will direct the Intent to a specific class within a specific Android

package.
flags

An iterable data structure containing flags that control how the Intent
is handled (see Intent.setFlags()).

MonkeyImage takeSnapshot ()

Captures the entire screen buffer of this device, yielding a screen capture of the current
display.
Returns

A MonkeyImage object containing the image of the current display.

void touch ( integer x, integer y, string type)

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
x
left of the screen in its current orientation.
y

The vertical position of the touch in actual device pixels, starting from the
top of the screen in its current orientation.

typ The type of key event to send. The allowed values are DOWN, UP, and
e DOWN_AND_UP.
void type (string message)

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 ()

Wakes the screen of this device.

Appendix

Table 1.Property variable names used with getProperty() and getSystemProperty().


Property
Group

Property

Description

Notes

build

board

Code name for the device's


system board

brand

The carrier or provider for


which the OS is customized.

device

The device design name.

fingerprint

A unique identifier for the


currently-running build.

host
ID

A changelist number or label.

model

The end-user-visible name for


the device.

product

The overall product name.

tags

Comma-separated tags that


describe the build, such as
"unsigned" and "debug".

type

The build type, such as


"user" or "eng".

user

CPU_ABI

The name of the native code


instruction set, in the form
CPU type plus ABI
convention.

manufacturer

The product/hardware
manufacturer.

The internal code used by the


source control system to
version.incremental
represent this version of the
software.
version.release

The user-visible name of this


version of the software.

version.sdk

The user-visible SDK version


associated with this version
of the OS.

version.codename

The current development


codename, or "REL" if this
version of the software has

See Build

been released.
width

The device's display width in


pixels.

height

The device's display height in


pixels.

display

density

The logical density of the


display. This is a factor that
scales DIP (DensityIndependent Pixel) units to
the device's resolution. DIP is
adjusted so that 1 DIP is
See
equivalent to one pixel on a DisplayMetrics for
160 pixel-per-inch display. For details.
example, on a 160-dpi
screen, density = 1.0, while
on a 120-dpi screen, density
= .75.

The value does not exactly follow


the real screen size, but is
adjusted to conform to large
changes in the display DPI. See
density for more details.
am.current
package

action

comp.class

comp.package

The Android package name of The am.current


the currently running
keys return
package.
information about
the currentlyThe current activity's action. running Activity.
This has the same format as
the name attribute of the
action element in a package
manifest.
The class name of the
component that started the
current Activity. See
comp.package for more
details.
The package name of the
component that started the
current Activity. A component
is specified by a package
name and the name of class

that the package contains.

clock

data

The data (if any) contained in


the Intent that started the
current Activity.

categories

The categories specified by


the Intent that started the
current Activity.

realtime

The number of milliseconds


since the device rebooted,
including deep-sleep time.

uptime

See SystemClock
The number of milliseconds
for more
since the device rebooted,
information.
not including deep-sleep time

millis

current time since the UNIX


epoch, in milliseconds.

Except as noted, this content is licensed under Creative Commons Attribution


2.5. For details and restrictions, see the Content License.

About Android | Legal | Support


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.
You do not need to create new instances of MonkeyImage. Instead, use
MonkeyDevice.takeSnapshot() to create a new instance from a screenshot. For example,
use:
newimage = MonkeyDevice.takeSnapshot()

Summary

Methods
convertToBytes (string format)
string

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.

getRawPixel (integer x, integer y)


tuple

Returns the single pixel at the image location (x,y), as an a


tuple of integer, in the form (a,r,g,b).
getRawPixelInt (integer x, integer y)

integer

Returns the single pixel at the image location (x,y), as a 32-bit


integer.
getSubImage (tuple rect)

MonkeyImage

Creates a new MonkeyImage object from a rectangular selection


of the current image.
sameAs (MonkeyImage other, float percent)

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".
writeToFile (string path, string format)

void

Writes the current image to the file specified by filename, in


the format specified by format.

Public Methods

string convertToBytes ( string format)

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
form The desired output format. All of the common raster output formats are
at supported. The default value is "png" (Portable Network Graphics).
tuple getRawPixel (integer x, integer y)

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
x
the orientation it had when the screenshot was taken.
y

The vertical position of the pixel, starting with 0 at the top of the screen in the
orientation it had 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.

tuple getRawPixelInt (integer x, integer y)

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
x
the orientation it had when the screenshot was taken.
y

The vertical position of the pixel, starting with 0 at the top of the screen in the
orientation it had 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.

MonkeyImage getSubImage (tuple rect)

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
rec of the region, and h specifies its height, both in units of pixels.
t

The image's orientation is the same as the screen orientation at the time the screenshot
was made.

Returns

A new MonkeyImage object containing the selection.

boolean sameAs ( MonkeyImage otherImage, float percent )

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.
perce A float in the range 0.0 to 1.0, inclusive, indicating the percentage of
nt pixels that need to be the same for the method to return true. The default

is 1.0, indicating that all the pixels must match.


Returns

Boolean true if the images match, or boolean false otherwise.

void writeToFile (string filename, string format)

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
form method tries to guess the format from the filename's extension. If no
at 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.

About Android | Legal | Support


MonkeyRunner

A monkeyrunner class that contains static utility methods.


Summary

Methods
alert (string message, string title, string okTitle)
void

Displays an alert dialog to the process running the current


program.
choice (string message, iterable choices, string title)

integer

Displays a dialog with a list of choices to the process running


the current program.
help (string format)

void

Displays the monkeyrunner API reference in a style similar to


that of Python's pydoc tool, using the specified format.

string

input (string message, string initialValue, string title, string


okTitle, string cancelTitle)

Displays a dialog that accepts input.


sleep (float seconds)
void

Pauses the current program for the specified number of


seconds.
waitForConnection (float timeout, string deviceId)

MonkeyDevice

Tries to make a connection between the monkeyrunner


backend and the specified device or emulator.

Public Methods

string alert ( string message, string title, string okTitle)

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.
title

The dialog's title. The default value is "Alert".

okTitle The text displayed in the dialog button. The default value is "OK".
integer choice (string message, iterable choices, string title)

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
messa
The prompt message displayed in the dialog.
ge
choice A Python iterable containing one or more objects that are displayed as
s
strings. The recommended form is an array of strings.
title

The dialog's title. The default is "Input".

Returns

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.

void help (string format)

Displays the monkeyrunner API reference in a style similar to that of Python's pydoc tool,
using the specified format.

Arguments
form The markup format to use in the output. The possible values are "text" for
at plain text or "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.
initialValu The initial value to display in the dialog. The default is an empty
e
string.
title
okTitle

The dialog's title. The default is "Input".


The text displayed in the okTitle button. The default is "OK".

cancelTitl
The text displayed in the cancelTitle button. The default is "Cancel".
e
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.

void sleep ( float seconds )

Pauses the current program for the specified number of seconds.


Arguments
seconds

The number of seconds to pause.

MonkeyDevice waitForConnection (float timeout, string deviceId)

Tries to make a connection between the monkeyrunner backend and the specified device or
emulator.
Arguments
timeo The number of seconds to wait for a connection. The default is to wait
ut forever.
devic A regular expression that specifies the serial number of the device or
eId emulator. See the 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.

About Android | Legal | Support

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.
ProGuard outputs the following files after it runs:
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


These files are located in the following directories:

<project_root>/bin/proguard

<project_root>/proguard

if you are using Ant.

if you are using Eclipse.

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:

a class that is referenced only in the AndroidManifest.xml file

a method called from JNI

dynamically referenced fields and methods

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:
-keep public class <MyClass>

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.

Decoding Obfuscated Stack Traces


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:
retrace.bat|retrace.sh [-verbose] mapping.txt [<stacktrace_file>]

For example:

retrace.bat -verbose mapping.txt obfuscated_trace.txt

If you do not specify a value for <stacktrace_file>, the retrace tool reads from standard
input.

Debugging considerations for published applications


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.

Adding New Sites


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:
1. Select Available Packages in the left panel.
2. Click Add Add-on Site and enter the URL of the repository.xml file. Click OK.

Any SDK packages available from the site will now be listed under a new item named User
Add-ons.

Troubleshooting
Problems connecting to the SDK repository
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 devices 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.

To run the Systrace user interface:


Using Eclipse
Using Android Studio
Using Device Monitor

Command Line Usage


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.
$ python systrace.py [options] [category1] [category2] ... [categoryN]

See the sections below for example Systrace sessions.

Android 4.3 and higher options


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
-h, --help
-o <FILE>
-t N, --time=N
-b N, --buf-size=N
-k <KFUNCS>
--ktrace=<KFUNCS>
-l, --list-categories

Description
Show the help message.
Write the HTML trace report to the specified file.
Trace activity for N seconds. The default value is 5 seconds.
Use a trace buffer size of N kilobytes. This option lets you
limit the total size of the data collected during a trace.
Trace the activity of specific kernel functions, specified in a
comma-separated list.
List the available tracing category tags. The available tags are:

gfx

- Graphics

input

view

webview

wm

- Window Manager

am

- Activity Manager

audio

- Audio

video

- Video

camera

hal

- Hardware Modules

res

- Resource Loading

dalvik

rs

sched

freq

membus

idle

- CPU Idle

disk

- Disk input and output

load

- CPU Load

sync

- Synchronization Manager

workq

- Input

- View
- WebView

- Camera

- Dalvik VM

- RenderScript
- CPU Scheduling

- CPU Frequency
- Memory Bus Utilization

- Kernel Workqueues

Note: Some trace categories are not supported on all devices.


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 commaseparated list of package names. The apps must contain tracing
instrumentation calls from the Trace class. For more
information, see Analyzing Display and Performance.
Link to the original CSS or JavaScript resources instead of
--link-assets
embedding them in the HTML trace report.
Create the interactive Systrace report from a file, instead of
--from-file=<FROM_FILE>
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.
-a <APP_NAME>
--app=<APP_NAME>

Android 4.2 and lower options


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
-h, --help
-o <FILE>
-t N, --time=N
-b N, --bufsize=N
-d, --disk
-f, --cpu-freq
-i, --cpu-idle
-l, --cpu-load
-s, --no-cpusched
-u, --busutilization
-w,

Description
Show the help message.
Write the HTML trace report to the specified file.
Trace activity for N seconds. The default value is 5 seconds.
Use a trace buffer size of N kilobytes. This option lets you limit the total
size of the data collected during a trace.
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
logged, so the initial frequency of the CPU when tracing starts is not
shown.
Trace CPU idle events.
Trace CPU load. This value is a percentage determined by the interactive
CPU frequency governor.
Prevent tracing of the CPU scheduler. This option allows for longer trace
times by reducing the rate of data flowing into the trace buffer.
Trace the bus utilization levels. This option requires root access on the
device.
Trace kernel work queues. This option requires root access on the device.

--workqueue

Set the enabled trace tags in a comma separated list. The available tags
are:

--settags=<TAGS>

gfx

input

view

webview

wm

- Window Manager

am

- Activity Manager

sync

audio

- Audio

video

- Video

camera

- Graphics
- Input

- View
- WebView

- Synchronization Manager

- 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.

Trace Viewing Shortcuts


The table below lists the keyboard shortcuts that are available while viewing a Systrace trace
HTML report.
Key
w
s
a
d
e
g

Description
Zoom into the trace timeline.
Zoom out of the trace timeline.
Pan left on the trace timeline.
Pan right on the trace timeline.
Center the trace timeline on the current mouse location.
Show grid at the start of the currently selected task.

Shift+g
Right Arrow
Left Arrow
Double Click
Shift+Double Click

Show grid at the end of the currently selected task.


Select the next event on the currently selected timeline.
Select the previous event on the currently selected timeline.
Zoom into the trace timeline.
Zoom out of the trace timeline.

Tracer for OpenGL ES


In this document
1. Running Tracer
2. Generating a Trace
3. Analyzing a Trace

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.
To run Tracer in Eclipse:
1. Start Eclipse and open a workspace that contains an Android project.
2. Activate the perspective for Tracer by choosing Window > Open Perspective >
Other...
3. Select Tracer for OpenGL ES and click OK.
To run Tracer in Device Monitor:
1. Start the Device Monitor tool.
2. Activate the perspective for Tracer by choosing Window > Open Perspective...

3. Select Tracer for OpenGL ES and click OK.

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.


To capture an OpenGL ES trace for an Android application:
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.
7. Select the desired Data Collection Options.
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.
8. Enter a Destination File for the trace output.
9. Click Trace to start the trace capture.
10. On the connected device, exercise the functions of your application you want to trace.
11. In the dialog box, Stop Tracing to complete the tracing run.

Analyzing a Trace
After you have generated a trace, you can load it for review and analysis.
To review a captured trace:
1. In Eclipse or Device Monitor, activate the Tracer for OpenGL ES perspective.
2. On the toolbar, click the trace load button (

).

3. After loading a trace, select a frame and review the OpenGL ES calls. Drawing
commands are highlighted in blue.
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:
adb shell uiautomator runtest <JARS> -c <CLASSES> [options]

Heres an example:
adb shell uiautomator runtest LaunchSettings.jar -c
com.uia.example.my.LaunchSettings

Command-line Options
The following table describes the subcommands and options for uiautomator.
Table 1. Command-line options for uiautomator
Subcommand
runtest

Option
<JARS>

Description
Required. The <JARS> argument is the name of one or more
JAR files that you deployed to the target device which
contain your uiautomator testcases. You can list more than
one JAR file by using a space as a separator.

Required (API 17 or lower).The <CLASSES> argument is a


list of test classes or test methods in <JARS> to run.
Each class or method must be fully qualified with the
package name, in one of these formats:

-c <CLASSES>

package_name.class_name

package_name.class_name#method_name

You can list multiple classes or methods by using a space as a


separator.
Note:This argument is not required for API 18 and higher. If
not specified, all test cases in <JARS> will be run.

--nohup

-e <NAME>
<VALUE>

Runs the test to completion on the device even if its parent


process is terminated (for example, if the device is
disconnected).
Specify other name-value pairs to be passed to test classes.
May be repeated.
Note: The -e options cannot be combined; you must prefix
each option with a separate -e flag.

-e debug
[true|false]

Wait for debugger to connect before starting.

dump [file]

Generate an XML file with a dump of the current UI


hierarchy. If a filepath is not specified, by default, the
generated dump file is stored on the device in this location
/storage/sdcard0/window_dump.xml.

-e
outputFormat
simple | -s

Enables less verbose JUnit style output.


Prints out accessibility events to the console until the
connection to the device is terminated

events

uiautomator API
The uiautomator API is bundled in the uiautomator.jar file under the <androidsdk>/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
com.android.uiautomator.core.UiCollectio 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.
Provides access to state information about
the device. You can also use this class to
com.android.uiautomator.core.UiDevice
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.UiScrollabl Provides support for searching for items
e
in a scrollable UI container.
Represents a query for one or more target
com.android.uiautomator.core.UiSelector
UI elements on a device screen.
com.android.uiautomator.core.Configurato Allows you to set key parameters for
r
running uiautomator tests.
n

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 tests.
com.android.uiautomator.testrunner.UiAutomatorTestCas
All uiautomator test
e
cases should extend this
class.

Exceptions
Exception

Description
Indicates when a a
com.android.uiautomator.core.UiObjectNotFoundExceptio UiSelector could not be
n
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.
About Android | Legal | Support
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()
Configurat
Retrieves a singleton instance of Configurator.
or
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)

Configurat Sets the timeout for waiting for an acknowledgment of generic


or
uiautomator actions, such as clicks, text setting, and menu
presses.
Configurat setKeyInjectionDelay(long delay)
or
Sets a delay between key presses when injecting text input.

setScrollAcknowledgmentTimeout(long timeout)
Configurat
Sets the timeout for waiting for an acknowledgement of an
or
uiautomtor scroll swipe action.
setWaitForIdleTimeout(long timeout)
Configurat
Sets the timeout for waiting for the user interface to go into an
or
idle state before starting a uiautomator action.
setWaitForSelectorTimeout(long timeout)
Configurat
Sets the timeout for waiting for a widget to become visible in
or
the user interface so that it can be matched by a selector.
[Expand]
Inherited Methods
From class java.lang.Object
Public Methods

public long getActionAcknowledgmentTimeout ()

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

current timeout in milliseconds

Since

Android API Level 18

public static Configurator getInstance ()

Retrieves a singleton instance of Configurator.


Returns

Configurator instance

Since

Android API Level 18

public long getKeyInjectionDelay ()

Gets the current delay between key presses when injecting text input. See setText(String)
Returns

current delay in milliseconds

Since

Android API Level 18

public long getScrollAcknowledgmentTimeout ()

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

current timeout in milliseconds

Since

Android API Level 18

public long getWaitForIdleTimeout ()

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

Current timeout value in milliseconds

Since

Android API Level 18

public long getWaitForSelectorTimeout ()

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

Current timeout value in milliseconds

Since

Android API Level 18

public Configurator setActionAcknowledgmentTimeout (long timeout)

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

Android API Level 18

public Configurator setKeyInjectionDelay (long delay)

Sets a delay between key presses when injecting text input. See setText(String)
Parameters
delay

Delay value in milliseconds

Returns

self

Since

Android API Level 18

public Configurator setScrollAcknowledgmentTimeout (long timeout)

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

Android API Level 18

public Configurator setWaitForIdleTimeout (long timeout)

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

Android API Level 18

public Configurator setWaitForSelectorTimeout (long timeout)

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

Android API Level 18

IAutomationSupport

Class Overview

Provides auxiliary support for running test cases


Summary

Public Methods
abstra sendStatus(int resultCode, Bundle status)
ct void Allows the running test cases to send out interim status
Public Methods

public abstract void sendStatus (int resultCode, Bundle status)

Allows the running test cases to send out interim status


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
IAutomationSup getAutomationSupport()
port
Provides support for running tests to report interim status
Bundle

getParams()
Get command line parameters.

UiDevice

void

getUiDevice()
Get current instance of UiDevice.
sleep(long ms)
Calls sleep(long) to sleep
[Expand]
Inherited Methods

From class junit.framework.TestCase


From class junit.framework.Assert
From class java.lang.Object
From interface junit.framework.Test
Public Constructors

public UiAutomatorTestCase ()
Public Methods

public IAutomationSupport getAutomationSupport ()

Provides support for running tests to report interim status


public Bundle getParams ()

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.
public UiDevice getUiDevice ()

Get current instance of UiDevice. Works similar to calling the static getInstance() from
anywhere in the test classes.
public void sleep (long ms)

Calls sleep(long) to sleep


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
getChildByDescription(UiSelector childPattern, String text)
UiObje
Searches for child UI element within the constraints of this
ct
UiSelector selector.
getChildByInstance(UiSelector childPattern, int instance)
UiObje
Searches for child UI element within the constraints of this
ct
UiSelector.
getChildByText(UiSelector childPattern, String text)
UiObje
Searches for child UI element within the constraints of this
ct
UiSelector.
getChildCount(UiSelector childPattern)
int

Counts child UI element instances matching the childPattern


argument.
[Expand]
Inherited Methods

From class com.android.uiautomator.core.UiObject


From class java.lang.Object
Public Constructors

public UiCollection (UiSelector selector)


Public Methods

public UiObject getChildByDescription (UiSelector childPattern, String


text)

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

instance that matched the search and not at the identifying child element that
matched the content description.
childPattern

Parameters
childPatter
UiSelector selector of the child pattern to match and return
n
text

String of the identifying child contents of of the childPattern

Returns

UiObject pointing at and instance of childPattern

Throws
UiObjectNotFoundException
public UiObject getChildByInstance (UiSelector childPattern, int
instance)

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
instance

int the desired matched instance of this childPattern

Returns

UiObject pointing at and instance of childPattern

Throws
UiObjectNotFoundException
public UiObject getChildByText (UiSelector childPattern, String text)

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
childPatter
UiSelector selector of the child pattern to match and return
n

text

String of the identifying child contents of of the childPattern

Returns

UiObject pointing at and instance of childPattern

Throws
UiObjectNotFoundException
public int getChildCount (UiSelector childPattern)

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
childPatter a UiSelector that represents the matching child UI elements to
n
count
Returns

the number of matched childPattern under the current UiCollection

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 or pressing the Home and Menu
buttons.

Summary
Public Methods
clearLastTraversedText()
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.
String
getCurrentActivityName()
This method is deprecated. The results returned should be considered
void

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.
boolean pressHome()

boolean
boolean
boolean
boolean
boolean
void
void
void
void
void
void
void
void
void
boolean
boolean

boolean

boolean
void

Simulates a short press on the HOME button.


pressKeyCode(int keyCode, int metaState)
Simulates a short press using a key code.
pressKeyCode(int keyCode)
Simulates a short press using a key code.
pressMenu()
Simulates a short press on the MENU button.
pressRecentApps()
Simulates a short press on the Recent Apps button.
pressSearch()
Simulates a short press on the SEARCH button.
registerWatcher(String name, UiWatcher watcher)
Registers a UiWatcher to run automatically when the testing framework is
unable to find a match using a UiSelector.
removeWatcher(String name)
Removes a previously registered UiWatcher.
resetWatcherTriggers()
Resets a UiWatcher that has been triggered.
runWatchers()
This method forces all registered watchers to run.
setCompressedLayoutHeirarchy(boolean compressed)
Enables or disables layout hierarchy compression.
setOrientationLeft()
Simulates orienting the device to the left and also freezes rotation by
disabling the sensors.
setOrientationNatural()
Simulates orienting the device into its natural orientation and also freezes
rotation by disabling the sensors.
setOrientationRight()
Simulates orienting the device to the right and also freezes rotation by
disabling the sensors.
sleep()
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)
Performs a swipe between points in the Point array.
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.
takeScreenshot(File storePath)
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
takeScreenshot(File storePath, float scale, int quality)
Take a screenshot of current window and store it as PNG The screenshot is
adjusted per screen rotation
unfreezeRotation()
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
public void clearLastTraversedText ()
Clears the text from the last UI traversal event. See getLastTraversedText().
public boolean click (int x, int y)
Perform a click at arbitrary coordinates specified by the user
Parameters

x
y

coordinate
coordinate

Returns

true if the click succeeded else false

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

startX
startY
endX
endY
steps

X-axis value for the starting coordinate


Y-axis value for the starting coordinate
X-axis value for the ending coordinate
Y-axis value for the ending coordinate
is the number of steps for the swipe action

Returns

true if swipe is performed, false if the operation fails or the coordinates are invalid

Since

Android API Level 18

public void dumpWindowHierarchy (String fileName)


Helper method used for debugging to dump the current window's layout hierarchy. The file
root location is /data/local/tmp
public void freezeRotation ()
Disables the sensors and freezes the device rotation at its current rotation state.
Throws

RemoteException
RemoteException
public String getCurrentActivityName ()
This method is deprecated.
The results returned should be considered unreliable
Retrieves the last activity to report accessibility events.
Returns

String name of activity

public String getCurrentPackageName ()


Retrieves the name of the last package to report accessibility events.
Returns

String name of package

public int getDisplayHeight ()


Gets the height of the display, in pixels. The size is adjusted based on the current orientation
of the display.
Returns

height in pixels or zero on failure

public int getDisplayRotation ()


Returns the current rotation of the display, as defined in Surface
Since

Android API Level 17

public Point getDisplaySizeDp ()


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

a Point containing the display size in dp

Since

Android API Level 18

public int getDisplayWidth ()


Gets the width of the display, in pixels. The width and height details are reported based on the
current orientation of the display.
Returns

width in pixels or zero on failure

public static UiDevice getInstance ()


Retrieves a singleton instance of UiDevice
Returns

UiDevice instance

public String getLastTraversedText ()


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

text of the last traversal event, else return an empty string

public String getProductName ()


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

product name of the device

Since

Android API Level 17

public boolean hasAnyWatcherTriggered ()


Checks if any registered UiWatcher have triggered. See registerWatcher(String,
UiWatcher) See hasWatcherTriggered(String)
public boolean hasWatcherTriggered (String watcherName)
Checks if a specific registered UiWatcher has triggered. See registerWatcher(String,
UiWatcher). If a UiWatcher runs and its checkForCondition() call returned true, then the
UiWatcher is considered triggered. This is helpful if a watcher is detecting errors from ANR
or crash dialogs and the test needs to know if a UiWatcher has been triggered.
Returns

true if triggered else false

public boolean isNaturalOrientation ()


Check if the device is in its natural orientation. This is determined by checking if the
orientation is at 0 or 180 degrees.
Returns

true if it is in natural orientation

Since

Android API Level 17

public boolean isScreenOn ()


Checks the power manager if the screen is ON.
Returns

true if the screen is ON else false

Throws

RemoteException
RemoteException
public boolean openNotification ()
Opens the notification shade.
Returns

true if successful, else return false

Since

Android API Level 18

public boolean openQuickSettings ()


Opens the Quick Settings shade.
Returns

true if successful, else return false

Since

Android API Level 18

public boolean pressBack ()


Simulates a short press on the BACK button.
Returns

true if successful, else return false

public boolean pressDPadCenter ()


Simulates a short press on the CENTER button.
Returns

true if successful, else return false

public boolean pressDPadDown ()


Simulates a short press on the DOWN button.

Returns

true if successful, else return false

public boolean pressDPadLeft ()


Simulates a short press on the LEFT button.
Returns

true if successful, else return false

public boolean pressDPadRight ()


Simulates a short press on the RIGHT button.
Returns

true if successful, else return false

public boolean pressDPadUp ()


Simulates a short press on the UP button.
Returns

true if successful, else return false

public boolean pressDelete ()


Simulates a short press on the DELETE key.
Returns

true if successful, else return false

public boolean pressEnter ()


Simulates a short press on the ENTER key.
Returns

true if successful, else return false

public boolean pressHome ()


Simulates a short press on the HOME button.
Returns

true if successful, else return false

public boolean pressKeyCode (int keyCode, int metaState)


Simulates a short press using a key code. See KeyEvent.
Parameters

keyCode the key code of the event.


metaState an integer in which each bit set to 1 represents a pressed meta key
Returns

true if successful, else return false

public boolean pressKeyCode (int keyCode)


Simulates a short press using a key code. See KeyEvent
Returns

true if successful, else return false

public boolean pressMenu ()


Simulates a short press on the MENU button.
Returns

true if successful, else return false

public boolean pressRecentApps ()


Simulates a short press on the Recent Apps button.
Returns

true if successful, else return false

Throws

RemoteException
RemoteException
public boolean pressSearch ()
Simulates a short press on the SEARCH button.
Returns

true if successful, else return false

public void registerWatcher (String name, UiWatcher watcher)


Registers a UiWatcher to run automatically when the testing framework is unable to find a
match using a UiSelector. See runWatchers()
Parameters

name
watcher

to register the UiWatcher


UiWatcher

public void removeWatcher (String name)


Removes a previously registered UiWatcher. See registerWatcher(String, UiWatcher)
Parameters

name

used to register the UiWatcher

public void resetWatcherTriggers ()


Resets a UiWatcher that has been triggered. If a UiWatcher runs and its
checkForCondition() call returned true, then the UiWatcher is considered triggered. See
registerWatcher(String, UiWatcher)

public void runWatchers ()


This method forces all registered watchers to run. See registerWatcher(String,
UiWatcher)

public void setCompressedLayoutHeirarchy (boolean compressed)


Enables or disables layout hierarchy compression. If compression is enabled, the layout
hierarchy derived from the Acessibility framework will only contain nodes that are important
for uiautomator testing. Any unnecessary surrounding layout nodes that make viewing and
searching the hierarchy inefficient are removed.
Parameters

compressed

true to enable compression; else, false to disable

Since

Android API Level 18

public void setOrientationLeft ()


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

Android API Level 17

public void setOrientationNatural ()


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

public void setOrientationRight ()


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

Android API Level 17

public void sleep ()


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
public boolean swipe (Point[] segments, int segmentSteps)

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

segments
segmentSteps

is Point array containing at least one Point object


steps to inject between two Points

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

steps

is the number of move steps sent to the system

Returns

false if the operation fails or the coordinates are invalid

public boolean takeScreenshot (File storePath)


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

storePath

where the PNG should be written to

Returns

true if screen shot is created successfully, false otherwise

Since

Android API Level 17

public boolean takeScreenshot (File storePath, float scale, int quality)


Take a screenshot of current window and store it as PNG The screenshot is adjusted per
screen rotation
Parameters

storePath
scale
quality

where the PNG should be written to


scale the screenshot down if needed; 1.0f for original size
quality of the PNG compression; range: 0-100

Returns

true if screen shot is created successfully, false otherwise

Since

Android API Level 17

public void unfreezeRotation ()


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)
Waits for the current application to idle.
Parameters

timeout

in milliseconds

public void waitForIdle ()


Waits for the current application to idle. Default wait timeout is 10 seconds
public boolean waitForWindowUpdate (String packageName, long timeout)
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

packageName
timeout

the specified window package name (can be null). If null, a window update
from any front-end window will end the wait
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

public void wakeUp ()


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(
g
long)
lon
WAIT_FOR_SELECTOR_POLL
g
lon WAIT_FOR_SELECTOR_TIME This constant is deprecated. use
setWaitForSelectorTimeout(long)
g OUT
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.
boolean clickAndWaitForNewWindow()
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.
getChildCount()
int
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
boolean isScrollable()

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
protected static final int FINGER_TOUCH_HALF_WIDTH

Constant Value: 20 (0x00000014)


protected static final int SWIPE_MARGIN_LIMIT
Constant Value: 5 (0x00000005)
protected static final long WAIT_FOR_EVENT_TMEOUT
This constant is deprecated.
use setScrollAcknowledgmentTimeout(long)
Constant Value: 3000 (0x0000000000000bb8)
protected static final long WAIT_FOR_SELECTOR_POLL
Constant Value: 1000 (0x00000000000003e8)
protected static final long WAIT_FOR_SELECTOR_TIMEOUT
This constant is deprecated.
use setWaitForSelectorTimeout(long)
Constant Value: 10000 (0x0000000000002710)
protected static final long WAIT_FOR_WINDOW_TMEOUT
Constant Value: 5500 (0x000000000000157c)

Public Constructors
public UiObject (UiSelector selector)
Constructs a UiObject to represent a view that matches the specified selector criteria.

Public Methods
public void clearTextField ()
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
public boolean click ()
Performs a click at the center of the visible bounds of the UI element represented by this
UiObject.
Returns

true id successful else false

Throws

UiObjectNotFoundException
public boolean clickAndWaitForNewWindow (long timeout)
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:
launching a new activity
bringing up a pop-up menu
bringing up a dialog
Parameters

timeout

timeout before giving up on waiting for a new window

Returns

true if the event was triggered, else false

Throws

UiObjectNotFoundException
public boolean clickAndWaitForNewWindow ()
Waits for window transitions that would typically take longer than the usual default timeouts.
See clickAndWaitForNewWindow(long)
Returns

true if the event was triggered, else false

Throws

UiObjectNotFoundException

public boolean clickBottomRight ()


Clicks the bottom and right corner of the UI element
Returns

true on success

Throws

UiObjectNotFoundException
public boolean clickTopLeft ()
Clicks the top and left corner of the UI element
Returns

true on success

Throws

UiObjectNotFoundException
public boolean dragTo (UiObject destObj, int steps)
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

destObj the destination UiObject.


steps usually 40 steps. You can increase or decrease the steps to change the speed.
Returns

true if successful

Throws

UiObjectNotFoundException
Since

Android API Level 18

public boolean dragTo (int destX, int destY, int steps)

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

destX the X-axis coordinate.


destY the Y-axis coordinate.
steps usually 40 steps. You can increase or decrease the steps to change the speed.
Returns

true if successful

Throws

UiObjectNotFoundException
Since

Android API Level 18

public boolean exists ()


Check if view exists. This methods performs a waitForExists(long) with zero
timeout. This basically returns immediately whether the view represented by this UiObject
exists or not. If you need to wait longer for this view, then see waitForExists(long).
Returns

true if the view represented by this UiObject does exist

public Rect getBounds ()


Returns the view's bounds property. See getVisibleBounds()
Returns

Rect

Throws

UiObjectNotFoundException
public UiObject getChild (UiSelector selector)
Creates a new UiObject for a child view that is under the present UiObject.
Parameters

selector

for child view to match

Returns

a new UiObject representing the child view

Throws

UiObjectNotFoundException
public int getChildCount ()
Counts the child views immediately under the present UiObject.
Returns

the count of child views.

Throws

UiObjectNotFoundException
public String getClassName ()
Retrieves the className property of the UI element.
Returns

class name of the current node represented by this UiObject

Throws

UiObjectNotFoundException

if no match was found

Since

Android API Level 18

public String getContentDescription ()


Reads the content_desc property of the UI element
Returns

value of node attribute "content_desc"

Throws

UiObjectNotFoundException

public UiObject getFromParent (UiSelector selector)


Creates a new UiObject for a sibling view or a child of the sibling view, relative to the
present UiObject.
Parameters

selector

for a sibling view or children of the sibling view

Returns

a new UiObject representing the matched view

Throws

UiObjectNotFoundException
public String getPackageName ()
Reads the view's package property
Returns

true if it is else false

Throws

UiObjectNotFoundException
public final UiSelector getSelector ()
Debugging helper. A test can dump the properties of a selector as a string to its logs if needed.
getSelector().toString();
Returns

UiSelector

public String getText ()


Reads the text property of the UI element
Returns

text value of the current node represented by this UiObject

Throws

UiObjectNotFoundException

if no match could be found

public Rect getVisibleBounds ()


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

Android API Level 17

public boolean isCheckable ()


Checks if the UI element's checkable property is currently true.
Returns

true if it is else false

Throws

UiObjectNotFoundException
public boolean isChecked ()
Check if the UI element's checked property is currently true
Returns

true if it is else false

Throws

UiObjectNotFoundException
public boolean isClickable ()
Checks if the UI element's clickable property is currently true.
Returns

true if it is else false

Throws

UiObjectNotFoundException
public boolean isEnabled ()
Checks if the UI element's enabled property is currently true.
Returns

true if it is else false

Throws

UiObjectNotFoundException
public boolean isFocusable ()
Check if the UI element's focusable property is currently true.
Returns

true if it is else false

Throws

UiObjectNotFoundException
public boolean isFocused ()
Check if the UI element's focused property is currently true
Returns

true if it is else false

Throws

UiObjectNotFoundException
public boolean isLongClickable ()
Check if the view's long-clickable property is currently true
Returns

true if it is else false

Throws

UiObjectNotFoundException
public boolean isScrollable ()
Check if the view's scrollable property is currently true
Returns

true if it is else false

Throws

UiObjectNotFoundException
public boolean isSelected ()
Checks if the UI element's selected property is currently true.
Returns

true if it is else false

Throws

UiObjectNotFoundException
public boolean longClick ()
Long clicks the center of the visible bounds of the UI element
Returns

true if operation was successful

Throws

UiObjectNotFoundException
public boolean longClickBottomRight ()
Long clicks bottom and right corner of the UI element
Returns

Throws

true if operation was successful

UiObjectNotFoundException
public boolean longClickTopLeft ()
Long clicks on the top and left corner of the UI element
Returns

true if operation was successful

Throws

UiObjectNotFoundException
public boolean performMultiPointerGesture (PointerCoords... touches)
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

represents the pointers' paths. Each MotionEvent.PointerCoords array


touches represents a different pointer. Each MotionEvent.PointerCoords in an array
element represents a touch point on a pointer's path.
Returns

true

if all touch events for this gesture are injected successfully, false otherwise

Since

Android API Level 18

public boolean performTwoPointerGesture (Point startPoint1, Point startPoint2, Point


endPoint1, Point endPoint2, int steps)
Generates a two-pointer gesture with arbitrary starting and ending points.
Parameters

startPoint1 start point of pointer 1


startPoint2 start point of pointer 2
endPoint1 end point of pointer 1
endPoint2 end point of pointer 2
steps
the number of steps for the gesture. Steps are injected about 5 milliseconds

apart, so 100 steps may take around 0.5 seconds to complete.


Returns

true

if all touch events for this gesture are injected successfully, false otherwise

Since

Android API Level 18

public boolean pinchIn (int percent, int steps)


Performs a two-pointer gesture, where each pointer moves diagonally toward the other, from
the edges to the center of 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

Android API Level 18

public boolean pinchOut (int percent, int steps)


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

Throws

true

if all touch events for this gesture are injected successfully, false otherwise

UiObjectNotFoundException
Since

Android API Level 18

public boolean setText (String text)


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

text

string to set

Returns

true if operation is successful

Throws

UiObjectNotFoundException
public boolean swipeDown (int steps)
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

steps

indicates the number of injected move steps into the system. Steps are injected about
5ms apart. So a 100 steps may take about 1/2 second to complete.

Returns

true if successful

Throws

UiObjectNotFoundException
public boolean swipeLeft (int steps)
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

steps

indicates the number of injected move steps into the system. Steps are injected about
5ms apart. So a 100 steps may take about 1/2 second to complete.

Returns

true if successful

Throws

UiObjectNotFoundException
public boolean swipeRight (int steps)
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

steps

indicates the number of injected move steps into the system. Steps are injected about
5ms apart. So a 100 steps may take about 1/2 second to complete.

Returns

true if successful

Throws

UiObjectNotFoundException
public boolean swipeUp (int steps)
Performs the swipe up action on the UiObject. See also:

scrollToBeginning(int)

scrollToEnd(int)

scrollBackward()

scrollForward()

Parameters

steps

indicates the number of injected move steps into the system. Steps are injected about
5ms apart. So a 100 steps may take about 1/2 second to complete.

Returns

true of successful

Throws

UiObjectNotFoundException
public boolean waitForExists (long timeout)
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

timeout

the amount of time to wait (in milliseconds)

Returns

true if the view is displayed, else false if timeout elapsed while waiting

public boolean waitUntilGone (long timeout)


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

timeout

time to wait (in milliseconds)

Returns

true if the element is gone before timeout elapsed, else false if timeout elapsed but a
matching element is still found.

Protected Methods
protected AccessibilityNodeInfo findAccessibilityNodeInfo (long timeout)
Finds a matching UI element in the accessibility hierarchy, by using the selector for this
UiObject.
Parameters

timeout

in milliseconds

Returns

AccessibilityNodeInfo if found else null

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(String detailMessage, Throwable throwable)
UiObjectNotFoundException(Throwable throwable)
[Expand]
Inherited Methods

From class java.lang.Throwable


From class java.lang.Object
Public Constructors

public UiObjectNotFoundException (String msg)


public UiObjectNotFoundException (String detailMessage, Throwable
throwable)
public UiObjectNotFoundException (Throwable throwable)
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
From class com.android.uiautomator.core.UiObject
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.

getChildByDescription(UiSelector childPattern, String text,


UiObject boolean allowScrollSearch)
Searches for a child element in the present scrollable container.
UiObject

getChildByDescription(UiSelector childPattern, String text)


Searches for a child element in the present scrollable container.
getChildByInstance(UiSelector childPattern, int instance)

UiObject Searches for a child element in the present scrollable container


that matches the selector you provided.
getChildByText(UiSelector childPattern, String text, boolean
UiObject allowScrollSearch)
Searches for a child element in the present scrollable container.
UiObject

getChildByText(UiSelector childPattern, String text)


Searches for a child element in the present scrollable container.
getMaxSearchSwipes()

int

Gets the maximum number of scrolls allowed when performing a


scroll action in search of a child element.
getSwipeDeadZonePercentage()

double

boolean

Returns the percentage of a widget's size that's considered as a


no-touch zone when swiping.
scrollBackward(int steps)
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.

boolean

scrollForward()

Performs a forward scroll with the default number of scroll steps


(55).
boolean

scrollForward(int steps)
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

boolean

boolean

boolean

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.
scrollToBeginning(int maxSwipes)
Scrolls to the beginning of a scrollable layout element.
scrollToBeginning(int maxSwipes, int steps)
Scrolls to the beginning of a scrollable layout element.
scrollToEnd(int maxSwipes, int steps)
Scrolls to the end of a scrollable layout element.
scrollToEnd(int maxSwipes)
Scrolls to the end of a scrollable layout element.

setAsHorizontalList()
UiScrolla
Set the direction of swipes to be horizontal when performing
ble
scroll actions.
setAsVerticalList()
UiScrolla
Set the direction of swipes to be vertical when performing scroll
ble
actions.
UiScrolla setMaxSearchSwipes(int swipes)
ble
Sets the maximum number of scrolls allowed when performing a

scroll action in search of a child element.


setSwipeDeadZonePercentage(double
UiScrolla swipeDeadZonePercentage)
ble
Sets the percentage of a widget's size that's considered as notouch zone when swiping.
Protected Methods
exists(UiSelector selector)
boolea
Used privately when performing swipe searches to decide if an
n
element has become visible or not.
[Expand]
Inherited Methods
From class com.android.uiautomator.core.UiCollection
From class com.android.uiautomator.core.UiObject
From class java.lang.Object
Public Constructors

public UiScrollable (UiSelector container)

Constructor.
Parameters
container a UiSelector selector to identify the scrollable layout element.
Public Methods

public boolean flingBackward ()

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

true if scrolled, and false if can't scroll anymore

Throws
UiObjectNotFoundException

public boolean flingForward ()

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

true if scrolled, false if can't scroll anymore

Throws
UiObjectNotFoundException
public boolean flingToBeginning (int maxSwipes)

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

true on scrolled else false

Throws
UiObjectNotFoundException
public boolean flingToEnd (int maxSwipes)

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

true on scrolled, else false

Throws
UiObjectNotFoundException
public UiObject getChildByDescription (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 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
text

Content-description to find in the children of the childPattern


match (may be a partial match)

allowScrollS
set to true if scrolling is allowed
earch
Returns

UiObject representing the child element that matches the search

conditions
Throws

UiObjectNotFoundException
public UiObject getChildByDescription (UiSelector childPattern, String
text)

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
childPatter
UiSelector for a child in a scollable layout element
n
text

Content-description to find in the children of the childPattern


match

Returns

UiObject representing the child element that matches the search

conditions
Throws

UiObjectNotFoundException

public UiObject getChildByInstance (UiSelector childPattern, int


instance)

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
childPatter
UiSelector for a child in a scollable layout element
n
instance

int number representing the occurance of a childPattern match

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
text

UiSelector selector for a child in a scrollable layout element

String to find in the children of the childPattern match

allowScrollSear
set to true if scrolling is allowed
ch
Returns

UiObject representing the child element that matches the search

conditions
Throws

UiObjectNotFoundException
public UiObject getChildByText (UiSelector childPattern, String text)

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
text

String to find in the children of the childPattern match

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

max the number of search swipes to perform until giving up

public double getSwipeDeadZonePercentage ()

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

a value between 0 and 1

public boolean scrollBackward (int steps)

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 rightto-left languages like Arabic and Hebrew.
Parameters
steps number of steps. Use this to control the speed of the scroll action.

Returns

true if scrolled, false if can't scroll anymore

Throws
UiObjectNotFoundException
public boolean scrollBackward ()

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

true if scrolled, and false if can't scroll anymore

Throws
UiObjectNotFoundException
public boolean scrollDescriptionIntoView (String text)

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
tex content-description to find within the contents of this scrollable layout
t element.
Returns

true if item is found; else, false

Throws
UiObjectNotFoundException
public boolean scrollForward ()

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

true if scrolled, false if can't scroll anymore

Throws
UiObjectNotFoundException
public boolean scrollForward (int steps)

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 rightto-left languages like Arabic and Hebrew.
Parameters
steps number of steps. Use this to control the speed of the scroll action
Returns

true if scrolled, false if can't scroll anymore

Throws
UiObjectNotFoundException
public boolean scrollIntoView (UiSelector selector)

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
public boolean scrollIntoView (UiObject obj)

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

true if item is found; else, false

Throws
UiObjectNotFoundException
public boolean scrollToBeginning (int maxSwipes)

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

true on scrolled else false

Throws
UiObjectNotFoundException
public boolean scrollToBeginning (int maxSwipes, int steps)

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

true on scrolled else false

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

true on scrolled else false

Throws
UiObjectNotFoundException
public boolean scrollToEnd (int maxSwipes)

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

true on scrolled, else false

Throws
UiObjectNotFoundException
public UiScrollable setAsHorizontalList ()

Set the direction of swipes to be horizontal when performing scroll actions.


Returns

reference to itself

public UiScrollable setAsVerticalList ()

Set the direction of swipes to be vertical when performing scroll actions.


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

public UiScrollable setSwipeDeadZonePercentage (double


swipeDeadZonePercentage)

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

protected boolean exists (UiSelector selector)

Used privately when performing swipe searches to decide if an element has become visible or
not.
Returns

true if found else false

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
UiSelect checkable(boolean val)
or
Set the search criteria to match widgets that are checkable.
checked(boolean val)
UiSelect
Set the search criteria to match widgets that are currently
or
checked (usually for checkboxes).
UiSelect childSelector(UiSelector selector)
or
Adds a child UiSelector criteria to this selector.
className(String className)
UiSelect
Set the search criteria to match the class property for a widget
or
(for example, "android.widget.Button").
className(Class<T> type)
<T>
UiSelect Set the search criteria to match the class property for a widget
or
(for example, "android.widget.Button").
classNameMatches(String regex)
UiSelect
Set the search criteria to match the class property for a widget,
or
using a regular expression.
UiSelect clickable(boolean val)
or
Set the search criteria to match widgets that are clickable.
description(String desc)
UiSelect
Set the search criteria to match the content-description property
or
for a widget.
descriptionContains(String desc)
UiSelect
Set the search criteria to match the content-description property
or
for a widget.
descriptionMatches(String regex)
UiSelect
Set the search criteria to match the content-description property
or
for a widget.
descriptionStartsWith(String desc)
UiSelect
Set the search criteria to match the content-description property
or
for a widget.

UiSelect enabled(boolean val)


or
Set the search criteria to match widgets that are enabled.
UiSelect focusable(boolean val)
or
Set the search criteria to match widgets that are focusable.
UiSelect focused(boolean val)
or
Set the search criteria to match widgets that have focus.
fromParent(UiSelector selector)
UiSelect
Adds a child UiSelector criteria to this selector which is used to
or
start search from the parent widget.
index(int index)
UiSelect
Set the search criteria to match the widget by its node index in
or
the layout hierarchy.
instance(int instance)
UiSelect
Set the search criteria to match the widget by its instance
or
number.
UiSelect longClickable(boolean val)
or
Set the search criteria to match widgets that are long-clickable.
packageName(String name)
UiSelect
Set the search criteria to match the package name of the
or
application that contains the widget.
packageNameMatches(String regex)
UiSelect
Set the search criteria to match the package name of the
or
application that contains the widget.
UiSelect resourceId(String id)
or
Set the search criteria to match the given resource ID.
resourceIdMatches(String regex)
UiSelect
Set the search criteria to match the resource ID of the widget,
or
using a regular expression.
UiSelect scrollable(boolean val)
or
Set the search criteria to match widgets that are scrollable.

selected(boolean val)
UiSelect
Set the search criteria to match widgets that are currently
or
selected.
text(String text)
UiSelect
Set the search criteria to match the visible text displayed in a
or
widget (for example, the text label to launch an app).
textContains(String text)
UiSelect
Set the search criteria to match the visible text in a widget where
or
the visible text must contain the string in your input argument.
textMatches(String regex)
UiSelect
Set the search criteria to match the visible text displayed in a
or
layout element, using a regular expression.
textStartsWith(String text)
UiSelect
Set the search criteria to match visible text in a widget that is
or
prefixed by the text parameter.
String

toString()
Protected Methods

UiSelect
cloneSelector()
or
[Expand]
Inherited Methods
From class java.lang.Object
Public Constructors

public UiSelector ()
Public Methods

public UiSelector checkable (boolean val)

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, contentdescription, 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

UiSelector with the specified search criteria

Since

Android API Level 18

public UiSelector checked (boolean val)

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

UiSelector with the specified search criteria

public UiSelector childSelector (UiSelector selector)

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

UiSelector with this added search criterion

public UiSelector className (String className)

Set the search criteria to match the class property for a widget (for example,
"android.widget.Button").
Parameters
className

Value to match

Returns

UiSelector with the specified search criteria

Since

Android API Level 17

public UiSelector className (Class<T> type)

Set the search criteria to match the class property for a widget (for example,
"android.widget.Button").
Parameters
type

type

Returns

UiSelector with the specified search criteria

public UiSelector classNameMatches (String regex)

Set the search criteria to match the class property for a widget, using a regular expression.
Parameters
regex

a regular expression

Returns

UiSelector with the specified search criteria

Since

Android API Level 17

public UiSelector clickable (boolean val)

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, contentdescription, 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

UiSelector with the specified search criteria

public UiSelector description (String desc)

Set the search criteria to match the content-description property for a widget. The contentdescription 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

UiSelector with the specified search criteria

public UiSelector descriptionContains (String desc)

Set the search criteria to match the content-description property for a widget. The contentdescription 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

UiSelector with the specified search criteria

public UiSelector descriptionMatches (String regex)

Set the search criteria to match the content-description property for a widget. The contentdescription 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

UiSelector with the specified search criteria

Since

Android API Level 17

public UiSelector descriptionStartsWith (String desc)

Set the search criteria to match the content-description property for a widget. The contentdescription 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

UiSelector with the specified search criteria

public UiSelector enabled (boolean val)

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, contentdescription, 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

UiSelector with the specified search criteria

public UiSelector focusable (boolean val)

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, contentdescription, 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

UiSelector with the specified search criteria

public UiSelector focused (boolean val)

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, contentdescription, 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

UiSelector with the specified search criteria

public UiSelector fromParent (UiSelector selector)

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

UiSelector with this added search criterion

public UiSelector index (int index)

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

UiSelector with the specified search criteria

public UiSelector instance (int instance)

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

UiSelector with the specified search criteria

public UiSelector longClickable (boolean val)

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, contentdescription, 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

UiSelector with the specified search criteria

Since

Android API Level 17

public UiSelector packageName (String name)

Set the search criteria to match the package name of the application that contains the widget.
Parameters
name

Value to match

Returns

UiSelector with the specified search criteria

public UiSelector packageNameMatches (String regex)

Set the search criteria to match the package name of the application that contains the widget.
Parameters
regex

a regular expression

Returns

UiSelector with the specified search criteria

Since

Android API Level 17

public UiSelector resourceId (String id)

Set the search criteria to match the given resource ID.


Parameters
id
Value to match
Returns

UiSelector with the specified search criteria

Since

Android API Level 18

public UiSelector resourceIdMatches (String regex)

Set the search criteria to match the resource ID of the widget, using a regular expression.
Parameters
regex

a regular expression

Returns

UiSelector with the specified search criteria

Since

Android API Level 18

public UiSelector scrollable (boolean val)

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, contentdescription, 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

UiSelector with the specified search criteria

public UiSelector selected (boolean val)

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, contentdescription, 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

UiSelector with the specified search criteria

public UiSelector text (String text)

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

UiSelector with the specified search criteria

public UiSelector textContains (String text)

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

UiSelector with the specified search criteria

public UiSelector textMatches (String regex)

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

UiSelector with the specified search criteria

Since

Android API Level 17

public UiSelector textStartsWith (String text)

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

UiSelector with the specified search criteria

public String toString ()


Protected Methods

protected UiSelector cloneSelector ()


Since

Android API Level 17

UiWatcher

Represents a conditional watcher on the target device. To learn how to register a conditional
watcher, see UiDevice.registerWatcher().
Summary

Public Methods
abstra checkForCondition()
ct
boolea The testing framework calls this handler method automatically
when the framework is unable to find a match using the UiSelector.
n
Public Methods

public abstract boolean checkForCondition ()

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

true to indicate a matched condition, or false if no matching condition is


found

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
To align infile.apk and save it as outfile.apk:
zipalign [-f] [-v] <alignment> infile.apk outfile.apk

To confirm the alignment of existing.apk:


zipalign -c -v <alignment> existing.apk

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:

-f

: overwrite existing outfile.zip

-v

: verbose output

-c

: confirm the alignment of the given file

Build System Overview


In this document
1. A Detailed Look at the Build Process

See also

Getting Started with Android Studio

Android Studio Basics

Migrating from Eclipse

Video
The New Android SDK Build System

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:

Customize, configure, and extend the build process.

Create multiple APKs for your app with different features using the same project and
modules.

Reuse code and resources across source sets.

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.

A Detailed Look at the Build Process


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:
Unable to execute dex: method ID not in [0, 0xffff]: 65536.

To avoid this error, see Building Apps with Over 65K Methods.

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.

Configuring Gradle Builds


In this document
1. Build Configuration Basics

1. Declare dependencies
2. Run ProGuard
3. Configure signing settings
2. Work with build variants
See also

Android Plugin for Gradle

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.
Build Configuration Basics

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:
apply plugin: 'com.android.application'
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.

android {...}

configures all the Android-specific build options:

The compileSdkVersion property specifies the compilation target.

The buildToolsVersion property specifies what version of the build tools to use. To
install several versions of the build tools, use the SDK Manager.
Note: Always use a build tools version whose major revision number is higher or
equal to that of your compilation target and target SDK.

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 configuration specified in the defaultConfig element applies to all build
variants, unless the configuration for a build variant overrides some of these values.

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.

Figure 1. Sync the project in Android Studio.


Declare dependencies

The app module in this example declares three dependencies:


...
dependencies {
// Module dependency
compile project(":lib")
// Remote binary dependency
compile 'com.android.support:appcompat-v7:19.0.1'

// Local binary dependency


compile fileTree(dir: 'libs', include: ['*.jar'])

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.
declares a dependency on the lib module of
BuildSystemExample. When you build the app module, the build system assembles and
includes the lib module.
compile project(":lib")

Remote binary dependencies

The app and lib modules both use the ActionBarActivity class from the Android Support
Library, so these modules depend on it.
declares a dependency on
version 19.0.1 of the Android Support Library by specifying its Maven coordinates. The
Android Support Library is available in the Android Repository package of the Android SDK.
If your SDK installation does not have this package, download and install it using the SDK
Manager.
compile 'com.android.support:appcompat-v7:19.0.1'

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.)
Local binary dependencies

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.
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.
compile fileTree(dir: 'libs', include: ['*.jar'])

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'
}
}
}
...
getDefaultProguardFile('proguard-android.txt') obtains the default ProGuard

settings from the Android SDK installation. Android Studio adds the module-specific rules
file proguard-rules.txt at the root of the module, where you can add custom ProGuard
rules.
Configure signing settings

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.
Work with build variants

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

To create different product versions of your app:

1. Define product flavors in the build file.


2. Create additional source directories for each flavor.
3. Add the flavor-specific sources to your project.

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.
Define product flavors in the build file

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.
Add additional source directories for each flavor

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

app/src/demo/res

app/src/demo/res/layout

app/src/demo/res/values

The resulting directory structure looks like figure 1.

Figure 1. New source directories for the demo flavor.


Add a new activity to each flavor

To add SecondActivity to the demo flavor:


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:
1. Drag activity_second.xml from app/src/main/res/layout and drop it inside
app/src/demo/res/layout.
2. Accept the default values on the window that appears and click OK.
3. Copy strings.xml from app/src/main/res into app/src/demo/res.

4. Replace the contents of the new copy of strings.xml with the following:

Now

<?xml version="1.0" encoding="utf-8"?>


<resources>
<string name="hello_world">Demo version only.</string>
</resources>
you add source folders and SecondActivity to the full flavor by making a copy of

demo

flavor:

the

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:


<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="hello_world">This is the full version!</string>
</resources>
From this point on, you could develop SecondActivity independently inside each

Note:
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.

Figure 2. The Build Variants panel.


Launch a flavor-specific activity from the main activity

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:
1. Edit activity_main.xml and add a new button to MainActivity:
<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:

4.

public void onButton2Clicked(View view) {


Intent intent = new Intent(this, SecondActivity.class);
startActivity(intent);
}
Edit the app's manifest to include a reference to SecondActivity:
<manifest ...>
<application ...>
...
<activity
android:name="com.buildsystemexample.app.SecondActivity"
android:label="@string/title_activity_second" >
</activity>
</application>
</manifest>

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.
Separate output folders are created for each build variant.

Android Plug-in for Gradle


In this document
1. Work with build variants

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.

Projects and modules build settings


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.

Project Build File


By default, the project-level Gradle file uses buildscript to define the Gradle repositories and
dependencies. This allows different projects to use different Gradle versions. Supported
repositories include JCenter, Maven Central, or Ivy. This example declares that the build
script uses the JCenter repository and a classpath dependency artifact that contains the
Android plugin for Gradle version 1.0.1.
buildscript {
repositories {
jcenter()
}
dependencies {
classpath 'com.android.tools.build:gradle:1.0.1'
// NOTE: Do not place your application dependencies here: they
belong

// in the individual module build.gradle files

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.

Module Build File


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.
apply plugin: 'com.android.application'
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
Builds the project output.
check
Runs checks and tests.
build
Runs both assemble and check.

clean
Performs the 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.

Figure 1: Gradle tab


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 inde