Docand-Reference-Series-Android-API19-Nov-Book6

Docand-Reference-Series-Android-API19-Nov-Book6
Portions of this Book are reproduced from work created and shared by the Android Open Source Project
and used according to terms described in the Creative Commons 2.5 Attribution License. The derivitive
website is devloper.android.com. The source url of the original document is included under each section
title. Each Section is covered by the aforementioned License. Code Samples are included under the
Apache 2.0 License. Each section has the approriate link, and associated license at the footer of the page.
The Creative Commons License & Apache License are available at the end of this book.
E&OE Errors and omissions excepted or excluded.
All other sections of the document, that are not attributed to other source organisations are under Copyright
© 2013 by Docand using the Creative Commons Attribution-NonCommercial 3.0 Unported License.
First Edition: October 2013
www.docand.com
2
Forward
The Docand reference series has been created for developers working within the world of Android™
application development. Taking them from there initial concepts through deployment to product delivery.
Packed with all the information possible, the font size has been chosen to keep the price low. Produced
using a print on demand service allows the book series to be kept up to date with the latest information.
The series titles have been named after the different areas of official documentation, giving the novice
developer through to evangelists a single point of reference.
Credit is given to all the people who created these documents under the Creative Commons License.
Docand does not take credit for the quality and pure quantity of information required to cover all the areas.
The series attempts to bring together the vast amount of documentation into a single cohesive source of
information for a given date, the books are derived from the same source at the same time, thus allowing
cross referencing between the books in the series possible.
3
Contents
1. Developer Tools .................................................. 7 4. Setting Up the ADT Bundle ............................... 12 2. 5. 6. 7. 8. 9. 10. 11. 12. 13. 14. 15. 16. 17. 18. 19. 20. 21. 22. Get the Android SDK......................................... 10 Setting Up an Existing IDE ................................ 13 23. Installing the Eclipse Plugin .............................. 14 Adding Platforms and Packages ....................... 18 Getting Started with Android Studio .................. 20 Updating from older versions ..................................21 Installing Android Studio .........................................21 Starting a Project .....................................................22 Revisions .................................................................22 Migrating from Eclipse ...................................... 26 Export from Eclipse .................................................26 Import into Android Studio .......................................26 Android Studio Tips and Tricks ......................... 27 Project Structure ......................................................27 Basic Operations .....................................................27 Keyboard Commands .............................................28 Exploring the SDK ............................................. 30 Available Packages .................................................30 Adding New Sites ....................................................32 Troubleshooting .......................................................32 Android NDK ..................................................... 33 Downloads ...............................................................34 System and Software Requirements .......................65 Getting Started with the NDK ..................................68 Contents of the NDK ................................................69 Introduction ....................................................... 74 Essential command line tools ..................................75 Other Third-Party Development Tools .....................76 Managing Virtual Devices ................................. 78 Managing AVDs with AVD Manager ................. 79 Creating an AVD ......................................................79 Managing AVDs from the Command Line ........ 83 Listing Targets .........................................................83 Creating AVDs .........................................................84 Moving an AVD ........................................................87 Deleting an AVD ......................................................87 Using the Emulator ........................................... 88 Overview ..................................................................89 Android Virtual Devices and the Emulator ...............89 Starting and Stopping the Emulator ........................89 Installing Applications on the Emulator ...................90 Using Hardware Acceleration .................................90 SD Card Emulation ..................................................95 Working with Emulator Disk Images ........................96 Emulator Networking ...............................................99 Using the Emulator Console ..................................102 Emulator Limitations ..............................................111 Troubleshooting Emulator Problems .....................111 Using Hardware Devices ................................ 112 Setting up a Device for Development ....................112 OEM USB Drivers ........................................... 116 Installing a USB Driver ...........................................116 OEM Drivers ..........................................................118 Managing Projects .......................................... 121 Android Projects ....................................................121 Library Projects ......................................................123 Test Projects ..........................................................125 Download the ADT Plugin ........................................14
Configure the ADT Plugin ........................................14
Download the ADT Translation Manager Plugin ......14
Troubleshooting ADT Installation .............................15
24. 25. Managing Projects from Eclipse with ADT ...... 127 Creating an Android Project ................................. 127 Setting up a Library Project .................................. 128 Referencing a library project ................................ 129 Managing Projects from the Command Line ... 132 Creating an Android Project ................................. 132 Updating a Project ................................................ 133 Setting up a Library Project .................................. 133 Referencing a Library Project ............................... 134 Using Code Templates ................................... 137 Application Templates .......................................... 137 Activity Templates ................................................. 140 Other Templates ................................................... 142 Building and Running ...................................... 143 A Detailed Look at the Build Process ................... 143 Building and Running from Eclipse with ADT.. 146 Running on the emulator ....................................... 146 Running on a device ............................................. 146 Creating a Run Configuration ............................... 147 Testing a Library Project ....................................... 126
26. Building and Running from the Command Line
149 27. 28. 29. 30. 31. 32. 33. 34. 35. 4
Testing ............................................................ 155 Testing Fundamentals .................................... 156 Test Structure ........................................................ 157 Test Projects ......................................................... 157 The Testing API ..................................................... 158 Running Tests ....................................................... 161 Seeing Test Results .............................................. 162 monkey and monkeyrunner .................................. 162 Working With Package names .............................. 163 What to Test .......................................................... 163 Next Steps ............................................................ 163 Testing from Eclipse with ADT ........................ 164 Creating a Test Project ......................................... 164 Creating a Test Package ...................................... 165 Running Tests ....................................................... 166 Testing from Other IDEs ................................. 171 Working with Test Projects .................................... 171 Creating a Test Package ...................................... 173 Running Tests ....................................................... 174 Using the am instrument Command ..................... 175 Activity Testing ................................................ 179 The Activity Testing API ........................................ 179 What To Test ......................................................... 180 Next Steps ............................................................ 181 Appendix: UI Testing Notes .................................. 181 Service Testing ............................................... 184 Service Design and Testing .................................. 184 ServiceTestCase ................................................... 184 Mock object classes ............................................. 185 What to Test .......................................................... 185 Content Provider Testing ................................ 186 Content Provider Design and Testing ................... 186 Content Provider Testing API ................................ 186 What To Test ......................................................... 187 Next Steps ............................................................ 187 Accessibility Testing Checklist ........................ 189 Testing Goals ........................................................ 189 Testing Requirements ........................................... 189 Testing Recommendations ................................... 190 Special Cases and Considerations....................... 190 Testing Accessibility Features .............................. 190 UI Testing ........................................................ 193 Building in Debug Mode ....................................... 149
Building in Release Mode ..................................... 150
Running on the Emulator ...................................... 151
Running on a Device ............................................ 152
Application Signing ............................................... 152
Ant Command Reference ..................................... 153
36. 37. 38. 39. 40. 41. 42. 43. 44. 45. What To Test ................................................... 203 Ideas for Testing ................................................... 203 Activity Testing Tutorial ................................... 205 Prerequisites ......................................................... 206 Installing the Tutorial Sample Code ...................... 206 Setting Up the Emulator ........................................ 206 Setting Up the Projects ......................................... 206 Creating the Test Case Class ............................... 210 Running the Tests and Seeing the Results ........... 220 Forcing Some Tests to Fail .................................... 223 Next Steps ............................................................. 225 Appendix ............................................................... 225 Debugging ....................................................... 229 Debugging Environment ....................................... 229 Debugging Tips .................................................... 230 Debugging from Eclipse with ADT................... 232 The Debug Perspective in Eclipse ........................ 232 The DDMS Perspective ......................................... 232 Debugging from Other IDEs ............................ 233 Starting a debugging environment ....................... 233 Using DDMS.................................................... 234 Running DDMS...................................................... 234 How DDMS Interacts with a Debugger ................. 234 Using DDMS.......................................................... 235 Reading and Writing Logs ............................... 240 The Log class ....................................................... 240 Using LogCat ........................................................ 240 Viewing stdout and stderr ..................................... 243 Debugging Web Apps .......................................... 243 Improving Your Code with lint ......................... 244 Overview ............................................................... 244 Running lint from Eclipse ...................................... 245 Running lint from the Command-Line ................... 245 Configuring lint ...................................................... 246 Optimizing Your UI .......................................... 250 Using Hierarchy Viewer......................................... 250 Using Pixel Perfect ................................................ 256 Using lint to Optimize Your UI ............................... 258 Profiling with Traceview and dmtracedump..... 259 Traceview Layout .................................................. 259 Creating Trace Files .............................................. 260 Copying Trace Files to a Host Machine ................ 261 Viewing Trace Files in Traceview .......................... 261 Using dmtracedump ............................................. 261 Traceview Known Issues....................................... 263 50. Preparing for Release ..................................... 284 Overview ............................................................... 193
Analyzing Your Application's UI ............................ 194
Preparing to Test ................................................... 195
Creating uiautomator Tests ................................... 197
Building and Deploying Your uiautomator Tests... 201
Running uiautomator Tests ................................... 201
Best Practices ....................................................... 202
51. 52. 53. 54. 55. 56. 57. 58. 59. 46. Analyzing Display and Performance with Systrace
264 60. 47. Investigating Your RAM Usage ....................... 269 Interpreting Log Messages ................................... 269 Viewing Heap Updates ......................................... 270 Tracking Allocations .............................................. 270 Viewing Overall Memory Allocations ..................... 271 Capturing a Heap Dump ....................................... 274 Triggering Memory Leaks ..................................... 277 48. Using the Dev Tools App ................................ 278 49. Publishing Overview ........................................ 279 Preparing Your Application for Release ................ 279 Releasing Your Application to Users .................... 280 Releasing through a web site................................ 282 User Opt-In for Apps from Unknown Sources ...... 283 61. Overview ............................................................... 264
Generating Traces ................................................ 265
Analyzing Traces................................................... 266
62. 63. 64. 65. 66. 67. 5
Versioning Your Applications .......................... 290 Setting Application Version ................................... 290 Specifying Your Application's System API
Requirements ........................................................ 291 Signing Your Applications ............................... 293 Signing Process .................................................... 293 Signing Strategies ................................................. 294 Basic Setup for Signing ......................................... 295 Signing in Debug Mode ........................................ 295 Signing in Release Mode ...................................... 296 Securing Your Private Key..................................... 301 Support Library ................................................ 302 Overview................................................................ 302 Support Library Features ................................. 310 v4 Support Library ................................................. 310 v7 Libraries ............................................................ 311 v8 Support Library ................................................. 312 v13 Support Library ............................................... 312 Support Library Setup ..................................... 314 Downloading the Support Libraries....................... 314 Choosing Support Libraries .................................. 315 Adding Support Libraries ...................................... 315 Using Support Library APIs ................................... 316 Code Samples ....................................................... 317 Tools Help ....................................................... 318 SDK Tools .............................................................. 318 Platform Tools ........................................................ 319 Android Debug Bridge ..................................... 320 Syntax .................................................................... 321 Commands ............................................................ 321 Querying for Emulator/Device Instances............... 324 Directing Commands to a Specific Emulator/Device
Instance ................................................................. 325 Installing an Application ........................................ 325 Forwarding Ports ................................................... 325 Copying Files to or from an Emulator/Device Instance
............................................................................... 325 Issuing Shell Commands....................................... 326 Enabling logcat logging ........................................ 335 Stopping the adb server........................................ 335 Android Developer Tools ................................. 337 SDK Tools Integration............................................ 337 Code Editors.......................................................... 338 Graphical Layout Editor......................................... 339 Layout Refactoring Support .................................. 344 android ............................................................ 346 Syntax .................................................................... 346 AVD Manager .................................................. 351 bmgr ................................................................ 352 Forcing a Backup Operation ................................. 352 Forcing a Restore Operation ................................. 352 Other Commands .................................................. 353 Device Monitor ................................................ 354 Usage .................................................................... 354 dmtracedump .................................................. 355 Draw 9-patch ................................................... 356 Android Emulator............................................. 358 Keyboard Commands ........................................... 358 Command Line Parameters................................... 359 etc1tool ............................................................ 366 Hierarchy Viewer ............................................. 367 Introduction ........................................................... 284
Gathering Materials and Resources...................... 285
Configuring Your Application for Release ............. 286
Building Your Application for Release................... 288
Preparing External Servers and Resources .......... 289
Testing Your Application for Release .................... 289
68. HPROF Converter ........................................... 368 88. UiDevice .......................................................... 439 89. UiObject .......................................................... 459 Summary ............................................................... 459 Constants .............................................................. 464 Public Constructors............................................... 465 Public Methods ..................................................... 465 Protected Methods................................................ 482 90. UiObjectNotFoundException ........................... 483 Summary ............................................................... 483 Public Constructors............................................... 484 91. UiScrollable ..................................................... 485 Summary ............................................................... 485 Public Constructors............................................... 494 Public Methods ..................................................... 494 Protected Methods................................................ 505 92. UiSelector ....................................................... 507 Summary ............................................................... 507 Public Constructors............................................... 511 Public Methods ..................................................... 511 Protected Methods................................................ 521 93. UiWatcher ....................................................... 522 Summary ............................................................... 522 Public Methods ..................................................... 522 94. zipalign ............................................................ 523 95. Revisions ........................................................ 524 96. SDK Tools ....................................................... 525 Revisions ............................................................... 525 97. ADT Plugin ...................................................... 542 Revisions ............................................................... 542 98. Platforms ......................................................... 564 Android 4.4 ........................................................... 564 Android 4.3 ........................................................... 564 Android 4.2 ........................................................... 565 Android 4.1 ........................................................... 566 Android 4.0.3 ........................................................ 566 Android 4.0 ........................................................... 567 Android 3.2 ........................................................... 568 Android 3.1 ........................................................... 568 Android 3.0 ........................................................... 569 Android 2.3.4 ........................................................ 569 Android 2.3.3 ........................................................ 569 Android 2.3 ........................................................... 570 Android 2.2 ........................................................... 570 99. Samples .......................................................... 572 100. Accessory Development Kit ............................ 573 101. Accessory Development Kit 2012 Guide ........ 574 Components ......................................................... 574 Using the Alarm Clock .......................................... 575 Playing Audio ........................................................ 576 Developing Accessories with ADK 2012 .............. 576 How the ADK Connects with Android Devices ..... 579 USB Audio Dock Implementation ......................... 583 102. Accessory Development Kit 2011 Guide ........ 585 ADK Components ................................................. 585 Getting Started with the ADK ................................ 586 How the ADK board implements the Android
Accessory protocol ............................................... 588 103. Creative Commons License ............................ 596 Creative Commons Attribution 3.0 Unported ........ 598 104. Apache License, Version 2.0 .......................... 601 69. JOBB............................................................... 369 70. 71. 72. 73. 74. 75. 76. 77. 78. 79. 80. 81. 82. 83. 84. 85. 86. 87. Summary ............................................................... 439
Public Methods ..................................................... 445
lint ................................................................... 371 Syntax ....................................................................371 Options ..................................................................371 Configuring Java and XML Source Files ...............373 logcat .............................................................. 374 mksdcard ........................................................ 376 UI/Application Exerciser Monkey .................... 377 Overview ................................................................377 Basic Use of the Monkey .......................................377 Command Options Reference ...............................377 monkeyrunner ................................................. 381 A Simple monkeyrunner Program ..........................381 The monkeyrunner API ..........................................382 Running monkeyrunner .........................................382 monkeyrunner Built-in Help ...................................383 Extending monkeyrunner with Plugins ..................383 MonkeyDevice ................................................ 385 Summary ................................................................385 Constants ...............................................................387 Public Methods ......................................................387 Appendix ...............................................................392 MonkeyImage ................................................. 396 Summary ................................................................396 Public Methods ......................................................397 MonkeyRunner ................................................ 400 Summary ................................................................400 Public Methods ......................................................400 ProGuard ........................................................ 403 Enabling ProGuard ................................................403 Configuring ProGuard ...........................................404 Decoding Obfuscated Stack Traces .....................404 SDK Manager ................................................. 406 Recommended Packages .....................................406 Systrace .......................................................... 408 Usage ....................................................................408 Options ..................................................................408 Trace Viewing Shortcuts ........................................409 Tracer for OpenGL ES .................................... 411 Running Tracer ......................................................411 Generating a Trace ................................................411 Analyzing a Trace ..................................................412 Traceview ........................................................ 414 uiautomator ..................................................... 415 Syntax ....................................................................415 Command-line Options ..........................................415 uiautomator API .....................................................416 Configurator .................................................... 418 Summary ................................................................418 Public Methods ......................................................420 IAutomationSupport ........................................ 425 Class Overview ......................................................425 Summary ................................................................425 Public Methods ......................................................425 UiAutomatorTestCase ..................................... 426 Class Overview ......................................................426 Summary ................................................................426 Public Constructors ...............................................430 Public Methods ......................................................430 UiCollection ..................................................... 432 Summary ................................................................432 Public Constructors ...............................................436 Public Methods ......................................................437 Usage ....................................................................369
Options ..................................................................369
6
Developer Tools
1.
Developer Tools
Content from developer.android.com/tools/index.html through their Creative Commons Attribution 2.5 license
The Android Developer Tools (ADT) plugin for Eclipse provides a professional-grade development
environment for building Android apps. It's a full Java IDE with advanced features to help you build, test,
debug, and package your Android apps.
Free, open-source, and runs on most major OS platforms.
To get started, download the Android SDK.
Full Java IDE
•
•
•
•
•
Android-specific refactoring, quick fixes, integrated navigation between Java and XML resources.
Enhanced XML editors for Android XML resources.
Static analysis tools to catch performance, usability, and correctness problems.
Build support for complex projects, command-line support for CI through Ant. Includes ProGuard
and app-signing.
Template-based wizard to create standard Android projects and components.
Graphical UI Builders
•
•
•
•
Build rich Android UI with drag and drop.
Visualize your UI on tablets, phones, and other devices. Switch themes, locales, even platform
versions instantly, without building.
Visual refactoring lets you extracts layout for inclusion, convert layouts, extract styles.
Editor support for working with custom UI components.
On-device Developer Options
•
•
•
Enable debugging over USB.
Quickly capture bug reports onto the device.
Show CPU usage on screen.
7
Content from developer.android.com/tools/index.html through their Creative Commons Attribution 2.5 license
Developer Tools
•
•
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 available, go to Settings > About phone
and tap Build number seven times. Return to the previous screen to find Developer options.
Develop on Hardware Devices
•
•
•
Use any commercial Android hardware device or multiple devices.
Deploy your app to connected devices directy from the IDE.
Live, on-device debugging, testing, and profiling.
Develop on Virtual Devices
•
•
•
Emulate any device. Use custom screen sizes, keyboards, and other hardware components.
Advanced hardware emulation, including camera, sensors, multitouch, telephony.
Develop and test for broad device compatibility.
Powerful Debugging
•
•
•
•
Full Java debugger with on-device debugging and Android-specific tools.
Built-in memory analysis, performance/CPU profiling, OpenGL ES tracing.
Graphical tools for debugging and optimizing UI, runtime inspecton of UI structure and
performance.
Runtime graphical analysis of your app's network bandwidth usage.
Testing
•
•
Fully instrumentated, scriptable test environment.
Integrated reports using standard test UI.
8
Content from developer.android.com/tools/index.html through their Creative Commons Attribution 2.5 license
Developer Tools
•
Create and run unit tests on hardware devices or emulator.
Native Development
•
•
Support for compiling and packaging existing code written in C or C++.
Support for packaging multiple architectures in a single binary, for broad compatibility.
9
Content from developer.android.com/tools/index.html through their Creative Commons Attribution 2.5 license
Get the Android SDK
2. Get the Android SDK
Get the Android SDK
Content from developer.android.com/sdk/index.html through their Creative Commons Attribution 2.5 license
If you're a new Android developer, we recommend you download the ADT Bundle to quickly start
developing apps. It includes the essential Android SDK components and a version of the Eclipse IDE with
built-in ADT (Android Developer Tools) to streamline your Android app development.
With a single download, the ADT Bundle includes everything you need to begin developing apps:
•
•
•
•
•
Eclipse + ADT plugin
Android SDK Tools
Android Platform-tools
The latest Android platform
The latest Android system image for the emulator
To get the ADT Bundle or stand-alone SDK Tools, please visit the web site at developer.android.com/sdk/
Choose the SDK package for your OS from the table below.
Android Studio Early Access Preview
A new Android development environment called Android Studio, based on IntelliJ IDEA, is now available
as an early access preview. For more information, see Getting Started with Android Studio.
If you prefer to use an existing version of Eclipse or another IDE, you can instead take a more customized
approach to installing the Android SDK. See the following instructions:
USE AN EXISTING IDE
10
Content from developer.android.com/sdk/index.html through their Creative Commons Attribution 2.5 license
SYSTEM REQUIREMENTS
DOWNLOAD FOR OTHER PLATFORMS
Platform
Package
Size
MD5 Checksum
Windows
32-bit
adt-bundle-windows-x8620131030.zip
503599460
bytes
cd490a531ec24667354f6473e999b988
Windows
64-bit
adt-bundle-windowsx86_64-20131030.zip
503735416
bytes
ddddbb1b9028015779d68dde01f96b14
Mac OS X
64-bit
adt-bundle-mac-x86_6420131030.zip
470386961
bytes
3e80e7a92b549029d91bdcf2ae82657f
Linux 32-bit adt-bundle-linux-x8620131030.zip
496876498
bytes
d389139ad9f59a43bdd34c94bc850509
Linux 64-bit adt-bundle-linux-x86_6420131030.zip
497171697
bytes
99b51a4f0526434b083701a896550b72
Platform Package
Size
Windows android-sdk_r22.3-windows.zip 108847452
32 & 64bytes
bit
installer_r22.3-windows.exe
(Recommended)
MD5 Checksum
9f0fe8c8884d6aee2b298fee203c62dc
88845794
bytes
ad50c4dd9e23cee65a1ed740ff3345fa
Mac OS android-sdk_r22.3-macosx.zip 74893875
X
bytes
32 & 64bit
ecde88ca1f05955826697848fcb4a9e7
Linux
android-sdk_r22.3-linux.tgz
32 & 64bit
6ae581a906d6420ad67176dff25a31cc
100968558
bytes
11
Content from developer.android.com/sdk/index.html through their Creative Commons Attribution 2.5 license
Setting Up the ADT Bundle
4. Setting Up the ADT Bundle
Content from developer.android.com/sdk/installing/bundle.html through their Creative Commons Attribution 2.5 license
The ADT Bundle provides everything you need to start developing apps, including a version of the Eclipse
IDE with built-in ADT (Android Developer Tools) to streamline your Android app development. If you
haven't already, go download the Android ADT Bundle. (If you downloaded the SDK Tools only, for use
with an existing IDE, you should instead read Setting Up an Existing IDE.)
Install the SDK and Eclipse IDE
• Unpack the ZIP file (named adt-bundle-<os_platform>.zip) and save it to an appropriate
location, such as a "Development" directory in your home directory.
• Open the adt-bundle-<os_platform>/eclipse/ directory and launch eclipse.
That's it! The IDE is already loaded with the Android Developer Tools plugin and the SDK is ready to go.
To start developing, read Building Your First App.
Caution: Do not move any of the files or directories from the adt-bundle-<os_platform>
directory. If you move the eclipse or sdk directory, ADT will not be able to locate the SDK and you'll
need to manually update the ADT preferences.
Additional information
As you continue developing apps, you may need to install additional versions of Android for the emulator
and other packages such as the library for Google Play In-app Billing. To install more packages, use the
SDK Manager.
Everything you need to develop Android apps is on this web site, including design guidelines, developer
training, API reference, and information about how you can distribute your app. For additional resources
about developing and distributing your app, see the Developer Support Resources.
12
Content from developer.android.com/sdk/installing/bundle.html through their Creative Commons Attribution 2.5 license
Setting Up an Existing IDE
5. Setting Up an Existing IDE
Content from developer.android.com/sdk/installing/index.html through their Creative Commons Attribution 2.5 license
You should have already downloaded the Android SDK Tools. (If you downloaded the ADT Bundle, you
should instead read Setting Up the ADT Bundle.)
The SDK Tools package is not the complete SDK environment. It includes only the core SDK tools, which
you can use to download the rest of the SDK packages (such as the latest system image).
Information for other platforms
13
Content from developer.android.com/sdk/installing/index.html through their Creative Commons Attribution 2.5 license
Installing the Eclipse Plugin
6. Installing the Eclipse Plugin
Content from developer.android.com/sdk/installing/installing-adt.html through their Creative Commons Attribution 2.5 license
Android offers a custom plugin for the Eclipse IDE, called Android Development Tools (ADT). This plugin
provides a powerful, integrated environment in which to develop Android apps. It extends the capabilities
of Eclipse to let you quickly set up new Android projects, build an app UI, debug your app, and export
signed (or unsigned) app packages (APKs) for distribution.
If you need to install Eclipse, you can download it from eclipse.org/downloads/.
Note: If you prefer to work in a different IDE, you do not need to install Eclipse or ADT. Instead, you can
directly use the SDK tools to build and debug your application.
Download the ADT Plugin
• Start Eclipse, then select Help > Install New Software.
• Click Add, in the top-right corner.
• In the Add Repository dialog that appears, enter "ADT Plugin" for the Name and the following URL for
the Location:
https://dl-ssl.google.com/android/eclipse/
•
• Click OK.
If you have trouble acquiring the plugin, try using "http" in the Location URL, instead of "https" (https is
preferred for security reasons).
• In the Available Software dialog, select the checkbox next to Developer Tools and click Next.
• In the next window, you'll see a list of the tools to be downloaded. Click Next.
• Read and accept the license agreements, then click Finish.
If you get a security warning saying that the authenticity or validity of the software can't be established,
click OK.
• When the installation completes, restart Eclipse.
Configure the ADT Plugin
Once Eclipse restarts, you must specify the location of your Android SDK directory:
• In the "Welcome to Android Development" window that appears, select Use existing SDKs.
• Browse and select the location of the Android SDK directory you recently downloaded and unpacked.
• Click Next.
Your Eclipse IDE is now set up to develop Android apps, but you need to add the latest SDK platform tools
and an Android platform to your environment. To get these packages for your SDK, continue to Adding
Platforms and Packages.
Download the ADT Translation
Manager Plugin
ADT Translation Manager Plugin is an Android
SDK Tools plugin that helps you work with strings
that you are localizing. It's designed to work with
the translation services built into the Google Play
Developer Console that let you quickly find and
App Translations in Google Play
Google Play App Translation Service is
available in the Developer Console to help
you localize your app for a global user base.
You can browse qualified vendors, get
estimates, upload strings for translation, and
then import the translations directly into your
app.
14
Content from developer.android.com/sdk/installing/installing-adt.html through their Creative Commons Attribution 2.5 license
Installing the Eclipse Plugin
purchase translations of your app from a list of pre-qualified vendors.
The plugin simplifies the management of strings during translation. It lets you easily export your default
strings and upload them directly to the Developer Console, from which you can get estimates or purchase
translations. When your translations are ready, the plugin lets you quickly download and import them back
into your project. During import, it moves all of the translated resources into the correct locations under
res/values, so that localization works instantly.
For more information about translation services in Google Play, see Purchase professional translations
through the Developer Console.
To install the ADT Translation Manager Plugin follow these steps:
• Install the ADT Plugin, as described above.
• In Eclipse, select Help > Install New Software.
• Click Add, in the top-right corner.
• In the Add Repository dialog that appears, enter a repository name for the Name and the following URL
for the Location:
https://dl.google.com/alt/
•
• Click OK.
• In the Available Software dialog, select the checkbox next to Android Developer Tools - Translation
Manager and click Next.
• In the next window, you'll see a list of the tools to be downloaded. Click Next.
• Read and accept the license agreements, then click Finish.
If you get a security warning saying that the authenticity or validity of the software can't be established,
click OK.
• When the installation completes, restart Eclipse.
Installation notes
•
•
•
•
•
The full ADT Plugin must be installed in your Eclipse environment before you install the ADT
Translation Manager Plugin.
ADT Translation Manager Plugin is designed for use with the translation services offered through
the Google Play Developer Console. It is not designed for general purpose import/export of
strings.
To use the plugin, you must set up a Developer Console account.
Currently, translation services are available through the Developer Console only as part of a pilot
program. To use the plugin, you must first sign up for the pilot program by visiting the Developer
Console.
If you downloaded ADT as part of the SDK ADT bundle, you may encounter an error when
attempting to download the ADT Translation Manager Plugin from the remote repository. In that
case, open the Install New Software, uncheck "Contact all update sites during install to find
required software" at the bottom and try again.
Troubleshooting ADT Installation
If you are having trouble downloading the ADT plugin after following the steps above, here are some
suggestions:
15
Content from developer.android.com/sdk/installing/installing-adt.html through their Creative Commons Attribution 2.5 license
Installing the Eclipse Plugin
•
If Eclipse can not find the remote update site containing the ADT plugin, try changing the remote
site URL to use http, rather than https. That is, set the Location for the remote site to:
http://dl-ssl.google.com/android/eclipse/
•
•
If you are behind a firewall (such as a corporate firewall), make sure that you have properly
configured your proxy settings in Eclipse. In Eclipse, you can configure proxy information from the
main Eclipse menu in Window (on Mac OS X, Eclipse) > Preferences > General > Network
Connections.
If you are still unable to use Eclipse to download the ADT plugin as a remote update site, you can
download the ADT zip file to your local machine and manually install it:
• Download the ADT Plugin zip file (do not unpack it):
Package
Size
MD5 Checksum
ADT-22.3.0.zip
14493723 bytes
0189080b23dfa0f866adafaaafcc34ab
• Start Eclipse, then select Help > Install New Software.
• Click Add, in the top-right corner.
• In the Add Repository dialog, click Archive.
• Select the downloaded ADT-22.3.0.zip file and click OK.
• Enter "ADT Plugin" for the name and click OK.
• In the Available Software dialog, select the checkbox next to Developer Tools and click Next.
• In the next window, you'll see a list of the tools to be downloaded. Click Next.
• Read and accept the license agreements, then click Finish.
If you get a security warning saying that the authenticity or validity of the software can't be established,
click OK.
• When the installation completes, restart Eclipse.
To update your plugin once you've installed using the zip file, you will have to follow these steps again
instead of the default update instructions.
Other install errors
Note that there are features of ADT that require some optional Eclipse packages (for example, WST). If
you encounter an error when installing ADT, your Eclipse installion might not include these packages. For
information about how to quickly add the necessary packages to your Eclipse installation, see the
troubleshooting topic ADT Installation Error: "requires plug-in org.eclipse.wst.sse.ui".
For Linux users
If you encounter this error when installing the ADT Plugin for Eclipse:
16
Content from developer.android.com/sdk/installing/installing-adt.html through their Creative Commons Attribution 2.5 license
Installing the Eclipse Plugin
An error occurred during provisioning.
Cannot connect to keystore.
JKS
...then your development machine lacks a suitable Java VM. Installing Sun Java 6 will resolve this issue
and you can then reinstall the ADT Plugin.
17
Content from developer.android.com/sdk/installing/installing-adt.html through their Creative Commons Attribution 2.5 license
Adding Platforms and Packages
7. Adding Platforms and Packages
Content from developer.android.com/sdk/installing/adding-packages.html through their Creative Commons Attribution 2.5 license
The Android SDK separates tools, platforms, and other components into packages you can download
using the Android SDK Manager. The original SDK package you've downloaded includes only the SDK
Tools. To develop an Android app, you also need to download at least one Android platform and the latest
SDK Platform-tools.
• Launch the SDK Manager.
If you've used the Windows installer to install the SDK tools, you should already have the Android SDK
Manager open. Otherwise, you can launch the Android SDK Manager in one of the following ways:
•
•
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.
• The SDK Manager shows all the SDK packages available for you to add to your Android SDK. As a
minimum configuration for your SDK, we recommend you install the following:
•
•
•
The latest Tools packages (check the Tools folder).
The latest version of Android (check the first Android folder).
The Android Support Library (open the Extras folder and check Android Support Library).
Once you've chosen your packages, click Install. The Android SDK Manager installs the selected
packages into your Android SDK environment.
With these packages installed, you're ready to start developing. To get started, read Building Your First
App.
Figure 1. The Android SDK Manager shows the SDK packages that are available, already installed, or for
which an update is available.
18
Content from developer.android.com/sdk/installing/adding-packages.html through their Creative Commons Attribution 2.5 license
Adding Platforms and Packages
Additional information
•
•
•
For more information about using the SDK Manager and some of the available packages, see the
SDK Manager document.
This web site provides all information you need to develop Android apps, including design
guidelines, developer training, API reference, and information about how you can distribute your
app. We recommend you begin by reading Building Your First App.
For additional resources about developing and distributing your app, see the Developer Support
Resources.
19
Content from developer.android.com/sdk/installing/adding-packages.html through their Creative Commons Attribution 2.5 license
Getting Started with Android Studio
8. Getting Started with Android Studio
Content from developer.android.com/sdk/installing/studio.html through their Creative Commons Attribution 2.5 license
EARLY ACCESS PREVIEW
This download includes:
•
•
•
•
Android Studio early access preview
All the Android SDK Tools to design, test, debug, and profile your app
The latest Android platform to compile your app
The latest Android system image to run your app in the emulator
Android Studio is a new Android development environment based on IntelliJ IDEA. Similar to Eclipse with
the ADT Plugin, Android Studio provides integrated Android developer tools for development and
debugging. On top of the capabilities you expect from IntelliJ, Android Studio offers:
•
•
•
•
•
•
•
Gradle-based build support.
Android-specific refactoring and quick fixes.
Lint tools to catch performance, usability, version compatibility and other problems.
ProGuard and app-signing capabilities.
Template-based wizards to create common Android designs and components.
A rich layout editor that allows you to drag-and-drop UI components, preview layouts on multiple
screen configurations, and much more.
Built-in support for Google Cloud Platform, making it easy to integrate Google Cloud Messaging
and App Engine as server-side components.
Caution: Android Studio is currently available as an early access preview. Several features are either
incomplete or not yet implemented and you may encounter bugs. If you are not comfortable using an
unfinished product, you may want to instead download (or continue to use) the ADT Bundle (Eclipse with
the ADT Plugin).
DOWNLOAD FOR OTHER PLATFORMS
20
Content from developer.android.com/sdk/installing/studio.html through their Creative Commons Attribution 2.5 license
Getting Started with Android Studio
Platform Package
Size
MD5 Checksum
Windows android-studio-bundle132.893413-windows.exe
484345454
bytes
14cbf0109a822688f4e2f886c0b0c85a
Mac OS android-studio-bundleX
132.893413-mac.dmg
463332508
bytes
0cd4ac59864890f7de57314bcc7ea5aa
Linux
487694946
bytes
9f1306100314b03ff5b691b94f154501
android-studio-bundle132.893413-linux.tgz
Updating from older versions
If you already have Android Studio installed, in most cases, you can upgrade to the latest version by
installing a patch. From within Android Studio, select Help > Check for updates (on Mac, Android Studio
> Check for updates) to see whether an update is available.
If an update is not available, follow the installation instructions below and replace your existing installation.
Caution: Replacing your existing installation of Android Studio will remove any additional SDK packages
you've installed, such as target platforms, system images, and sample apps. To preserve these, copy
them from your current SDK directory under Android Studio to a temporary location before installing the
update. Then move them back once the update is complete. If you fail to copy these packages, then you
can instead download them again through the Android SDK Manager.
Also note that due to the update to Android Gradle Plugin 0.6, you will encounter errors when opening
existing projects. See the Troubleshooting notes below for information about how to resolve them.
Installing Android Studio
• Download the Android Studio package from above.
• Install Android Studio and the SDK tools:
Windows:
• Launch the downloaded EXE file, android-studio-bundle-<version>.exe.
• Follow the setup wizard to install Android Studio.
Known issue: On some Windows systems, the launcher script does not find where Java is installed. If you
encounter this problem, you need to set an environment variable indicating the correct location.
Select Start menu > Computer > System Properties > Advanced System Properties. Then open
Advanced tab > Environment Variables and add a new system variable JAVA_HOME that points to
your JDK folder, for example C:\Program Files\Java\jdk1.7.0_21.
Mac OS X:
• Open the downloaded DMG file, android-studio-bundle-<version>.dmg.
• Drag and drop Android Studio into the Applications folder.
Known issue: Depending on your security settings, when you attempt to open Android Studio, you might
see a warning that says the package is damaged and should be moved to the trash. If this happens, go to
System Preferences > Security & Privacy and under Allow applications downloaded from, select
Anywhere. Then open Android Studio again.
Linux:
21
Content from developer.android.com/sdk/installing/studio.html through their Creative Commons Attribution 2.5 license
Getting Started with Android Studio
• Unpack the downloaded Tar file, android-studio-bundle-<version>.tgz, into an
appropriate location for your applications.
• To launch Android Studio, navigate to the android-studio/bin/ directory in a terminal and
execute studio.sh.
You may want to add android-studio/bin/ to your PATH environmental variable so that you can
start Android Studio from any directory.
That's it! You're ready to start developing apps with Android Studio.
Note: On Windows and Mac, the individual tools and other SDK packages are saved within the Android
Studio application directory. To access the tools directly, use a terminal to navigate into the application and
locate the sdk/ directory. For example:
Windows: \Users\<user>\AppData\Local\Android\android-studio\sdk\
Mac: /Applications/Android\ Studio.app/sdk/
For a list of some known issues, see tools.android.com/knownissues.
Starting a Project
When you launch Android Studio for the first time, you'll see a Welcome screen that offers several ways to
get started:
•
To start building a new app, click New Project.
This starts the New Project wizard, which helps you set up a project using an app template.
•
To import an existing Android app project, click Import Project.
Note: If you previously developed your Android project with Eclipse, you should first use the new
export feature in the ADT plugin to prepare your project with the new Gradle build system. For
more information, read Migrating from Eclipse.
For additional help using Android Studio, read Tips and Tricks.
As you continue developing apps, you may need to install additional versions of Android for the emulator
and other packages such as the Android Support Library. To install more packages, use the SDK
Manager, which you can open from Android Studio by clicking SDK Manager
in the toolbar.
Revisions
Android Studio v0.3.2 (Oct 2013)
•
See tools.android.com for a full list of changes.
Android Studio v0.2.x (July 2013)
•
•
Merged in the latest IntelliJ codebase changes. Includes fixes for issues reported by Studio users
such as tweaks to Linux font sizes and font rendering.
Android Gradle plug-in updated to 0.5.0.
22
Content from developer.android.com/sdk/installing/studio.html through their Creative Commons Attribution 2.5 license
Getting Started with Android Studio
Caution: This new version is not backwards compatible. When opening a project that uses an
older version of the plug-in, Studio will show an error stating Gradle <project_name> project
refresh failed. See Troubleshooting below for details.
The updated Gradle plug-in includes the following changes:
o
o
o
o
o
Fixed IDE model to contain the output file even if it's customized through the DSL. Also
fixed the DSL to get/set the output file on the variant object so that it's not necessary to
use variant.packageApplication or variant.zipAlign
Fixed dependency resolution so that we resolved the combination of (default config,
build types, flavor(s)) together instead of separately.
Fixed dependency for tests of library project to properly include all the dependencies of
the library itself.
Fixed case where two dependencies have the same leaf name.
Fixed issue where Proguard rules file cannot be applied on flavors.
All Gradle plugin release notes are available are here: http://tools.android.com/tech-docs/newbuild-system.
•
•
•
•
•
•
•
Gradle errors from aapt no longer point to merged output files in the build/ folder, they point back
to the real source locations.
Parallel Builds. It's now possible to use Gradle's parallel builds. Please be aware that parallel
builds are in "incubation" (see Gradle's documentation.) This feature is off by default. To enable it,
go to Preferences > Compiler and check the box Compile independent modules in parallel.
Further work on the new resource repository used for layout rendering, resource folding in the
editor, and more:
o Basic support for .aar library dependencies (e.g. using a library without a local copy of
the sources). Still not working for resource XML validation and navigation in source
editors.
o Cycle detection in resource references.
o Quick Documentation (F1), which can show all translations of the string under the caret,
will now also show all resource overlays from the various Gradle flavors and build types,
as well as libraries. They are listed in reverse resource overlay order, with strikethrough
on the versions of the string that are masked.
o Fixes to handle updating the merged resources when the set of module dependencies
change.
o XML rendering fixes to properly handle character entity declarations and XML and
unicode escapes.
Save screenshot support for the layout preview and layout editor windows.
Template bug fixes.
Lint bug fixes.
Various fixes for crash reports. Thank you, and keep filing crash reports!
Android Studio v0.1.x (May 2013)
•
Various bug fixes, including a fix for a common Windows installation issue.
23
Content from developer.android.com/sdk/installing/studio.html through their Creative Commons Attribution 2.5 license
Getting Started with Android Studio
Note: Periodic updates are pushed to Android Studio without requiring you to update from here. To
manually check for updates, select Help > Check for updates (on Mac, select Android Studio > Check
for updates).
Troubleshooting
Figure 1. Error dialog when opening an existing project.
Error: Gradle project refresh failed
Android Studio 0.2.0 has updated the Gradle plug-in to 0.5.0, which is not backwards compatible. When
opening a project that uses an older version of the plug-in, Studio will display the error shown in figure 1 in
the upper right corner of the IDE. To resolve the error, you must change the version of the Android Gradle
plug-in to 0.5.0.
• Click the link in the error dialog Search in build.gradle files. If the dialog is no longer visible, click
Event Log
in the bottom-right corner of the IDE, then click Search in build.gradle files.
• Double-click the line under the build.gradle usage. For example: classpath
'com.android.tools.build:gradle:0.4. This opens the project build.gradle file.
• Edit the classpath to change the gradle version to 0.5.+. For example:
dependencies {
classpath 'com.android.tools.build:gradle:0.5.+'
}
•
• Save the file and rebuild your project.
24
Content from developer.android.com/sdk/installing/studio.html through their Creative Commons Attribution 2.5 license
Getting Started with Android Studio
Figure 2. Error dialog when creating a new project or opening a project using the support library.
Error: Failed to import Gradle project
If, after updating to Android Studio 0.2.x and creating or opening a project, you receive an error stating
"Could not find any version that matches com.android.support:support-v4:13.0.+", then you must install the
Android Support Repository. This was likely caused because you're pointing Android Studio to an
external Android SDK location that does not have the new Maven repository included with Android Studio
0.2.x. This new Maven repository is used by the new build system for the Support Library, instead of using
the Support Library JAR files, so must be present in the SDK.
• Open the Android SDK Manager.
• Expand the Extras directory and install Android Support Repository.
If you've encountered other problems in Android Studio, look at the following page for possible resolutions
to known issues: http://tools.android.com/knownissues.
25
Content from developer.android.com/sdk/installing/studio.html through their Creative Commons Attribution 2.5 license
Migrating from Eclipse
9. Migrating from Eclipse
Content from developer.android.com/sdk/installing/migrate.html through their Creative Commons Attribution 2.5 license
If you've previously developed for Android using
Eclipse and would like to migrate to Android
Studio, you should export your projects from
Eclipse in order to generate Gradle build files. You
can then import your project into Android Studio.
See also
•
•
Eclipse Compatibility Mode
FAQ on Migrating
Export from Eclipse
• Update your Eclipse ADT Plugin (you must have version 22.0 or higher).
• In Eclipse, select File > Export.
• In the window that appears, open Android and select Generate Gradle build files.
• Select the project you want to export for Android Studio and click Finish.
Your selected project remains in the same location but now contains a build.gradle file and is ready
for Android Studio.
Import into Android Studio
• In Android Studio, close any projects currently open. You should see the Welcome to Android Studio
window.
• Click Import Project.
• Locate the project you exported from Eclipse, expand it, select the build.gradle file and click OK.
• In the following dialog, leave Use gradle wrapper selected and click OK. (You do not need to specify
the Gradle home.)
Now that your project is imported to Android Studio, read Tips and Tricks for some help getting started.
Note: It's possible to import an existing Android project to Android Studio even if you don't generate a
Gradle build file from Eclipse—Android Studio will successfully build and run projects using an existing Ant
build file. However, in order to take advantage of build variants and other advanced features in the future,
we strongly suggest that you generate a Gradle build file using the ADT plugin or write your own Gradle
build file for use with Android Studio. For more information about the Gradle build system, see the Gradle
Plugin User Guide.
26
Content from developer.android.com/sdk/installing/migrate.html through their Creative Commons Attribution 2.5 license
Android Studio Tips and Tricks
10.
Android Studio Tips and Tricks
Content from developer.android.com/sdk/installing/studio-tips.html through their Creative Commons Attribution 2.5 license
If you're unfamiliar with the IntelliJ IDEA interface,
you might be wondering how to accomplish some
common tasks in Android Studio. This page
provides some tips to help you get going.
See also
•
•
•
For complete user documentation for the IntelliJ
IDEA interface (upon which Android Studio is
based), refer to the IntelliJ IDEA documentation.
Eclipse Compatibility Mode
FAQ on Migrating
Adding a Backend to Your App In
Android Studio
Figure 1. Gradle project structure
Project Structure
When you create a new project in Android Studio (or migrate a project from Eclipse), you'll notice that the
project structure appears differently than you may be used to. As shown in figure 1, almost all your project
files are now inside the src/ directory, including resources and the manifest file.
The new project structure is due to the switch to a Gradle-based build system. This structure provides
more flexibility to the build process and will allow multiple build variants (a feature not yet fully
implemented). Everything still behaves as you expect, but some of the files have moved around. For the
most part, you should need to modify only the files under the src/ directory. More information about the
Gradle project structure is available in the Gradle Plugin User Guide.
Basic Operations
The following topics describe how to perform some basic development tasks with Android Studio.
Creating virtual devices
All the capabilities of the Android Virtual Device Manager are accessible directly from the Android Studio
interface. Click the Android Virtual Device Manager
in the toolbar to open it and create new virtual devices for running your app in the emulator.
Installing SDK updates
The SDK Manager is also accessible to download new Android tools, platforms, and libraries for your app.
Click the SDK Manager
in the toolbar to open it and check for updates.
Creating new files
27
Content from developer.android.com/sdk/installing/studio-tips.html through their Creative Commons Attribution 2.5 license
Android Studio Tips and Tricks
You can quickly add new code and resource files by clicking the appropriate directory in the Project pane
and pressing CTRL + N (CMD + 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 CTRL + N, 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.
Creating layouts
Android Studio offers an advanced layout editor that allows you to drag-and-drop widgets into your layout
and preview your layout while editing the XML.
While editing in the Text view, you can preview the layout on devices by opening the Preview pane
available on the right side of the window. Within the Preview pane, you can modify the preview by
changing various options at the top of the pane, including the preview device, layout theme, platform
version and more. To preview the layout on multiple devices simultaneously, select Preview All Screen
Sizes from the device drop-down.
You can switch to the graphical editor by clicking Design at the bottom of the window. While editing in the
Design view, you can show and hide the widgets available to drag-and-drop by clicking Palette on the left
side of the window. Clicking Designer on the right side of the window reveals a panel with a layout
hierarchy and a list of properties for each view in the layout.
Debugging
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.
Keyboard Commands
The following tables list keyboard shortcuts for common operations.
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
Android Studio Key Command
Command look-up (autocomplete command name)
CTRL + SHIFT + A
Project quick fix
ALT + ENTER
Reformat code
CTRL + ALT + L (Win)
OPTION + CMD + L (Mac)
Show docs for selected API
CTRL + Q (Win)
28
Content from developer.android.com/sdk/installing/studio-tips.html through their Creative Commons Attribution 2.5 license
Android Studio Tips and Tricks
F1 (Mac)
Show parameters for selected method
CTRL + P
Generate method
ALT + Insert (Win)
CMD + N (Mac)
Jump to source
F4 (Win)
CMD + down-arrow (Mac)
Delete line
CTRL + Y (Win)
CMD + Backspace (Mac)
Search by symbol name
CTRL + ALT + SHIFT + N (Win)
OPTION + CMD + O (Mac)
Table 2. Project and editor key commands
Action
Android Studio Key Command
Build
CTRL + F9 (Win)
CMD + F9 (Mac)
Build and run
SHIFT + F10 (Win)
CTRL + R (Mac)
Toggle project visibility
ALT + 1 (Win)
CMD + 1 (Mac)
Navigate open tabs
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.
29
Content from developer.android.com/sdk/installing/studio-tips.html through their Creative Commons Attribution 2.5 license
Exploring the SDK
11.
Exploring the SDK
Content from developer.android.com/sdk/exploring.html through their Creative Commons Attribution 2.5 license
The Android SDK is composed of modular packages that you can download separately using the Android
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. Simply follow the
procedures described in Adding Platforms and Packages.
There are several different packages available for the Android SDK. The table below describes most of the
available packages and where they're located once you download them.
Available Packages
Package
Description
File Location
SDK Tools
Contains tools for debugging and <sdk>/tools/
testing, plus other utilities that are
required to develop an app. If
you've just installed the SDK
starter package, then you already
have the latest version of this
package. Make sure you keep
this up to date.
<sdk>/platform-tools/
SDK Platform- Contains platform-dependent
tools
tools for developing and
debugging your application.
These tools support the latest
features of the Android platform
and are typically updated only
when a new platform becomes
available. These tools are always
backward compatible with older
platforms, but you must be sure
that you have the latest version of
these tools when you install a
new SDK platform.
Documentation An offline copy of the latest
documentation for the Android
platform APIs.
<sdk>/docs/
SDK Platform
<sdk>/platforms/<androidversion>/
There's one SDK Platform
available for each version of
Android. It includes an
android.jar file with a fully
compliant Android library. In
order to build an Android app,
you must specify an SDK
platform as your build target.
30
Content from developer.android.com/sdk/exploring.html through their Creative Commons Attribution 2.5 license
Exploring the SDK
System Images Each platform version offers one <sdk>/platforms/<androidor more different system images version>/
(such as for ARM and x86). The
Android emulator requires a
system image to operate. You
should always test your app on
the latest version of Android and
using the emulator with the latest
system image is a good way to
do so.
<sdk>/sources/
Sources for
Android SDK
A copy of the Android platform
source code that's useful for
stepping through the code while
debugging your app.
Samples for
SDK
A collection of sample apps that <sdk>/platforms/<androidversion>/samples/
demonstrate a variety of the
platform APIs. These are a great
resource to browse Android app
code. The API Demos app in
particular provides a huge
number of small demos you
should explore.
Google APIs
<sdk>/add-ons/
An SDK add-on that provides
both a platform you can use to
develop an app using special
Google APIs and a system image
for the emulator so you can test
your app using the Google APIs.
Android
Support
A static library you can include in <sdk>/extras/android/support/
your app sources in order to use
powerful APIs that aren't
available in the standard
platform. For example, the
support library contains versions
of the Fragment class that's
compatible with Android 1.6 and
higher (the class was originally
introduced in Android 3.0) and
the ViewPager APIs that allow
you to easily build a sideswipeable UI.
Google Play
Provides the static libraries and
samples that allow you to
<sdk>/extras/google/
31
Content from developer.android.com/sdk/exploring.html through their Creative Commons Attribution 2.5 license
Exploring the SDK
Billing
integrate billing services in your
app with Google Play.
Google Play
Licensing
Provides the static libraries and <sdk>/extras/google/
samples that allow you to perform
license verification for your app
when distributing with Google
Play.
The above table 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.
For example, there may be a dependency between the ADT Plugin for Eclipse and the SDK Tools
package. When you install the SDK Tools package, you should also upgrade to the required version of
ADT (if you are developing in Eclipse). In this case, the major version number for your ADT plugin should
always match the revision number of your SDK Tools (for example, ADT 8.x requires SDK Tools r8).
The development tools will notify you with debug 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 addons 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:
• Select Available Packages in the left panel.
• 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:
• With the Android SDK Manager window open, select "Settings" in the left pane.
• On the right, in the "Misc" section, check the checkbox labeled "Force https://... sources to be fetched
using http://..."
• Click Save & Apply.
32
Content from developer.android.com/sdk/exploring.html through their Creative Commons Attribution 2.5 license
Android NDK
12.
Android NDK
Content from developer.android.com/tools/sdk/ndk/index.html through their Creative Commons Attribution 2.5 license
Platform
Package
Size (Bytes) MD5 Checksum
Windows 32-bit
android-ndk-r9bwindows-x86.zip
455928388 cfb9402ea08a1554186e85ed28cb4593
android-ndk-r9bwindows-x86-legacytoolchains.zip
152568224 00c8373b53ad9475f1bab1de4219b877
android-ndk-r9bwindows-x86_64.zip
479012553 1ba6be7ebf4e9272d77031dd70f81e94
Windows 64-bit
android-ndk-r9b166961852 6eee9459986e8b7f1032d62831dd775b
windows-x86_64-legacytoolchains.zip
Mac OS X 32-bit android-ndk-r9b-darwin- 349307548 b5fa7aa3b9fca5a5b0c46bdd970d284b
x86.tar.bz2
android-ndk-r9b-darwin- 119394536 be0a07bcea3695f7d93cbd1b880d3f75
x86-legacytoolchains.tar.bz2
Mac OS X 64-bit android-ndk-r9b-darwin- 354748937 710d80b6ff807f03e585f9aacee3bf09
x86_64.tar.bz2
android-ndk-r9b-darwin- 122378495 19c696a5b690b040409c68b21e9fcf46
x86_64-legacytoolchains.tar.bz2
Linux 32-bit (x86) android-ndk-r9b-linuxx86.tar.bz2
android-ndk-r9b-linuxx86-legacytoolchains.tar.bz2
Linux 64-bit (x86) android-ndk-r9b-linuxx86_64.tar.bz2
361394055 d7f783deaeea6b60cb515d9427c01c2e
125676842 bfc7a1e6baf856b4348d57abffc761d2
366988131 56c0999a2683d6711591843217f943e0
33
Content from developer.android.com/tools/sdk/ndk/index.html through their Creative Commons Attribution 2.5 license
Android NDK
android-ndk-r9b-linuxx86_64-legacytoolchains.tar.bz2
127742633 f41017d5888a8dc210d1703dcdf1def7
The NDK is a toolset that allows you to implement
parts of your app using native-code languages
such as C and C++. For certain types of apps, this
can be helpful so you can reuse existing code
libraries written in these languages, but most apps
do not need the Android NDK.
In this section
• Downloads
• Revisions
• System and Software Requirements
• Installing the NDK
Before downloading the NDK, you should
understand that the NDK will not benefit most
apps. As a developer, you need to balance its
benefits against its drawbacks. Notably, using
native code on Android generally does not result
in a noticable performance improvement, but it
always increases your app complexity. In general,
you should only use the NDK if it is essential to
your app—never because you simply prefer to
program in C/C++.
• Getting Started with the NDK
• Using the NDK
• Contents of the NDK
• Development tools
• Documentation
• Sample apps
Typical good candidates for the NDK are self-contained, CPU-intensive operations that don't allocate much
memory, such as signal processing, physics simulation, and so on. When examining whether or not you
should develop in native code, think about your requirements and see if the Android framework APIs
provide the functionality that you need.
Downloads
With NDK revision 9 and higher, the release packages have been split to reduce download size. The first
download for each platform contains the default NDK toolchain. The second download contains legacy
NDK toolchains for that platform, which is only required if you are not using the current, recommended
toolchain for your NDK builds.
Revisions
The following sections provide information about releases of the NDK.
Android NDK, Revision 9b (October 2013)
Important changes:
•
•
•
•
Updated include/android/*h and math.h for all Android API levels up to 18,
including the addition of levels 13, 15, 16 and 17. For information on added APIs, see
commit messages for Changes 68012 and 68014. (Issues 47150, 58528, and 38423)
Added support for API level 19, including Renderscript binding.
Added support for -mhard-float in the existing armeabi-v7a ABI. For more
information and current restrictions on Clang, see tests/device/hardfloat/jni/Android.mk.
Migrated from GNU Compiler Collection (GCC) 4.8 to 4.8.2, and added diagnostic color
support. To enable diagnostic colors, set -fdiagnostics-color=auto, fdiagnostics-color=always, or export GCC_COLORS as shown below:
34
Content from developer.android.com/tools/sdk/ndk/index.html through their Creative Commons Attribution 2.5 license
Android NDK
GCC_COLORS='error=01;31:warning=01;35:note=01;36:caret=01;32:locus=01:quote=01'
For more information, see GCC Language Independent Options.
•
•
Added two new samples to demonstrate OpenGL ES 3.0 features: Teapot and MoreTeapots.
These samples run on devices with Android 4.1 (API level 16) and higher.
Deprecated GCC 4.7 and Clang 3.2 support, which will be removed in the next release.
Important bug fixes:
•
•
•
•
Fixed problem with ARM GCC 4.6 thumb2 failing to generate 16-bit relative jump
tables. (GCC Issue)
Fixed GCC 4.8 internal compiler error (ICE) on
g++.dg/cpp0x/lambda/lambda-defarg3.C. (Change 62770, GCC Issue)
Fixed a problem with Windows 32-bit *-gdb.exe executables failing to launch. (Issue
58975)
Fixed GCC 4.8 ICE when building bullet library. The error message is as follows:
internal compiler error: verify_flow_info failed
(Issue 58916, GCC Issue)
•
•
•
Modified GDB/ARM build to skip ARM.exidx data for unwinding in prologue code and added a
command (set arm exidx-unwinding) to control exidx-based stack unwinding. (Issue
55826)
Fixed Clang 3.3 MIPS compiler problem where HI and LO registers are incorrectly reused.
Fixed issue with MIPS 4.7 ICE in dbx_reg_number. The error message is as follows:
external/icu4c/i18n/decimfmt.cpp:1322:1:
internal compiler error: in dbx_reg_number, at dwarf2out.c:10185
(GCC Patch)
Other bug fixes:
•
Header fixes
o Fixed the ARM WCHAR_MIN and WCHAR_MAX to be unsigned according to
spec (the X86/MIPS versions are signed). Define
_WCHAR_IS_ALWAYS_SIGNED to restore old behavior. (Issue 57749)
o Fixed include/netinet/tcp.h to contain TCP_INFO state enum.
(Issue 38881)
o Fixed the cdefs_elh.h macro _C_LABEL_STRING to stop generating
warnings in the GCC 4.8 toolchain when using c++11 mode. (Issue 58135,
Issue 58652)
o Removed non-existent functions imaxabs and imaxdiv from header
inttypes.h.
35
Content from developer.android.com/tools/sdk/ndk/index.html through their Creative Commons Attribution 2.5 license
Android NDK
Fixed issue with pthread_exit() return values and pthread_self().
(Issue 60686)
o Added missing mkdtemp() function, which already exists in bionic header
stdlib.h.
Fixed problem building samples/gles3jni with Clang on Android API level 11.
Fixed MCLinker to allow multiple occurrences of the following options: -gcsections and --eh-frame-hdr.
Fixed MCLinker to accept the --no-warn-mismatch option.
Modified cpu-features option to not assume all VFPv4 devices support IDIV. Now
this option only adds IDIV to white-listed devices, including Nexus 4. (Issue 57637)
Fixed problem with android_native_app_glue.c erroneously logging errors on
event predispatch operations.
Fixed all operations on gabi++ terminate and unexpected_handler to be thread-safe.
Fixed several issues with Clang -integrated-as option so it can pass tests for
ssax-instructions and fenv.
Fixed GCC 4.6/4.7/4.8 compiler to pass the linker option --eh-frame-hdr even for
static executables. For more information, see the GCC patch.
Fixed extra apostrophe in CPU-ARCH-ABIS.html. For more information, see NDKDEPENDS.html. (Issue 60142)
Fixed extra quotes in ndk-build output on Windows. (Issue 60649)
Fixed Clang 3.3 to compile ARM's built-in, atomic operations such as
__atomic_fetch_add, __atomic_fetch_sub, and
__atomic_fetch_or.
Fixed Clang 3.3 ICE with customized vfprintf. (Clang issue)
o
•
•
•
•
•
•
•
•
•
•
•
•
Other changes:
•
Enabled OpenMP for all GCC builds. To use this feature, add the following flags to your
build settings:
LOCAL_CFLAGS += -fopenmp
LOCAL_LDFLAGS += -fopenmp
For code examples, see tests/device/test-openmp
•
•
•
•
•
•
•
•
Reduced the size of ld.mcld significantly (1.5MB vs. ld.bfd 3.5MB and ld.gold 7.5MB),
resulting in a speed improvement of approximately 20%.
Added LOCAL_CONLYFLAGS and APP_CONLYFLAGS to specify options applicable to C only
but not C++. The existing LOCAL_CFLAGS and APP_CFLAGS are also used for C++
compilation (to save trouble of specifying most options twice), so options such as -std=gnu99
may fail in g++ builds with a warning and clang++ builds with an error.
Added gabi++ array helper functions.
Modified GCC builds so that all libgcc.a files are built with -funwind-tables to allow
the stack to be unwound past previously blocked points, such as __aeabi_idiv0.
Added Ingenic MXU support in MIPS GCC4.6/4.7/4.8 with new -mmxu option.
Extended MIPS GCC4.6/4.7/4.8 -mldc1-sdc1 to control ldxc1/sdxc1 too
Added crazy linker. For more information, see
sources/android/crazy_linker/README.TXT.
Fixed bitmap-plasma to draw to full screen rather than a 200x200 pixel area.
36
Content from developer.android.com/tools/sdk/ndk/index.html through their Creative Commons Attribution 2.5 license
Android NDK
•
Reduced linux and darwin toolchain sizes by 25% by creating symlinks to identical files.
Android NDK, Revision 9 (July 2013)
Important changes:
•
•
•
Added support for Android 4.3 (API level 18). For more information, see STABLEAPIS.html and new code examples in samples/gles3jni/README.
Added headers and libraries for OpenGL ES 3.0, which is supported by Android 4.3 (API
level 18) and higher.
Added GNU Compiler Collection (GCC) 4.8 compiler to the NDK. Since GCC 4.6 is still
the default, you must explicitly enable this option:
o For ndk-build builds, export NDK_TOOLCHAIN_VERSION=4.8 or add
it in Application.mk.
o For standalone builds, use the --toolchain= option in makestandalone-toolchain.sh, for example:
--toolchain=arm-linux-androideabi-4.8
Note: The -Wunused-local-typedefs option is enabled by -Wall. Be sure to
add __attribute__((unused)) if you use compile-time asserts like
sources/cxx-stl/stlport/stlport/stl/config/features.h, line
#311. For more information, see Change 55460
Note: In the GCC 4.7 release and later, ARM compilers generate unaligned access code
by default for ARMv6 and higher build targets. You may need to add the -mnounaligned-access build option when building for kernels that do not support this
feature.
•
Added Clang 3.3 support. The NDK_TOOLCHAIN_VERSION=clang build option
now picks Clang 3.3 by default.
Note: Both GCC 4.4.3 and Clang 3.1 are deprecated, and will be removed from the next
NDK release.
•
•
•
Updated GNU Project Debugger (GDB) to support python 2.7.5.
Added MCLinker to support Windows hosts. Since ld.gold is the default where
available, you must add -fuse-ld=mcld in LOCAL_LDFLAGS or APP_LDFLAGS
to enable MCLinker.
Added ndk-depends tool which prints ELF library dependencies. For more
information, see NDK-DEPENDS.html. (Issue 53486)
Important bug fixes:
•
•
•
Fixed potential event handling issue in android_native_app_glue. (Issue
41755)
Fixed ARM/GCC-4.7 build to generate sufficient alignment for NEON load and store
instructions VST and VLD. (GCC Issue 57271)
Fixed a GCC 4.4.3/4.6/4.7 internal compiler error (ICE) for a constant negative index
value on a string literal. (Issue 54623)
37
Content from developer.android.com/tools/sdk/ndk/index.html through their Creative Commons Attribution 2.5 license
Android NDK
•
•
•
•
•
•
•
•
•
Fixed GCC 4.7 segmentation fault for constant initialization with an object address.
(Issue 56508)
Fixed GCC 4.6 ARM segmentation fault for -O values when using Boost 1.52.0. (Issue
42891)
Fixed libc.so and libc.a to support the wait4() function. (Issue 19854)
Updated the x86 libc.so and libc.a files to include the clone() function.
Fixed LOCAL_SHORT_COMMANDS bug where the linker.list file is empty or
not used.
Fixed GCC MIPS build on Mac OS to use CFI directives, without which ld.mcld -eh-frame-hdr fails frequently.
Fixed Clang 3.2 X86/MIPS internal compiler error in
llvm/lib/VMCore/Value.cpp. (Change 59021)
Fixed GCC 4.7 64-bit Windows assembler crash. (Error: out of memory
allocating 4294967280 bytes).
Updated ndk-gdb script so that the --start or --launch actions now wait for the
GNU Debug Server, so that it can more reliably hit breakpoints set early in the execution
path (such as breakpoints in JNI code). (Issue 41278)
Note: This feature requires jdb and produces warning about pending breakpoints.
Specify the --nowait option to restore previous behavior.
•
•
•
•
Fixed GDB crash when library list is empty.
Fixed GDB crash when using a stepi command past a bx pc or blx pc Thumb
instruction. (Issue 56962, Issue 36149)
Fixed MIPS gdbserver to look for DT_MIPS_RLD_MAP instead of DT_DEBUG.
(Issue 56586)
Fixed a circular dependency in the ndk-build script, for example: If A->B and B->B, then
B was dropped from build. (Issue 56690)
Other bug fixes:
•
•
•
•
•
•
•
•
•
•
Fixed the ndk-build script to enable you to specify a version of Clang as a command
line option (e.g., NDK_TOOLCHAIN_VERSION=clang3.2). Previously, only
specifying the version as an environment variable worked.
Fixed gabi++ size of _Unwind_Exception to be 24 for MIPS build targets when
using the Clang compiler. (Change 54141)
Fixed the ndk-build script to ensure that built libraries are actually removed from
projects that include prebuilt static libraries when using the ndk-build clean
command. (Change 54461, Change 54480)
Modified the NDK_ANALYZE=1 option to be less verbose.
Fixed gnu-libstdc++/Android.mk to include a backward/ path for builds
that use backward compability. (Issue 53404)
Fixed a problem where stlport new sometimes returned random values.
Fixed ndk-gdb to match the order of CPU_ABIS, not APP_ABIS. (Issue 54033)
Fixed a problem where the NDK 64-bit build on MacOSX choses the wrong path for
compiler. (Issue 53769)
Fixed build scripts to detect 64-bit Windows Vista. (Issue 54485)
Fixed x86 ntonl/swap32 error: invalid 'asm': operand number out
of range. (Issue 54465, Change 57242)
38
Content from developer.android.com/tools/sdk/ndk/index.html through their Creative Commons Attribution 2.5 license
Android NDK
•
•
•
•
•
•
•
•
•
•
Fixed ld.gold to merge string literals.
Fixed ld.gold to handle large symbol alignment.
Updated ld.gold to enable the --sort-section=name option.
Fixed GCC 4.4.3/4.6/4.7 to suppress the -export-dynamic option for statically
linked programs. GCC no longer adds an .interp section for statically linked
programs.
Fixed GCC 4.4.3 stlport compilation error about inconsistent typedef of
_Unwind_Control_Block. (Issue 54426)
Fixed awk scripts to handle AndroidManifest.xml files created on Windows
which may contain trailing \r characters and cause build errors. (Issue 42548)
Fixed make-standalone-toolchain.sh to probe the prebuilts/ directory
to detect if the host is 32 bit or 64 bit.
Fixed the Clang 3.2 -integrated-as option.
Fixed the Clang 3.2 ARM EHABI compact model pr1 and pr2 handler data.
Added Clang -mllvm -arm-enable-ehabi option to fix the following Clang
error:
clang: for the -arm-enable-ehabi option: may only occur zero or one times!
•
Fixed build failure when there is no uses-sdk element in application manifest. (Issue 57015)
Other changes:
•
•
•
•
•
Header Fixes
o Modified headers to make __set_errno an inlined function, since
__set_errno in errno.h is deprecated, and libc.so no longer
exports it.
o Modified elf.h to include stdint.h. (Issue 55443)
o Fixed sys/un.h to be included independently of other headers. (Issue
53646)
o Fixed all of the MotionEvent_getHistorical API family to take the
const AInputEvent* motion_event. (Issue 55873)
o Fixed malloc_usable_size to take const void*. (Issue 55725)
o Fixed stdint.h to be more compatible with C99. (Change 46821)
o Modified wchar.h to not redefine WCHAR_MAX and WCHAR_MIN
o Fixed <inttypes.h> declaration for pointer-related PRI and SCN macros.
(Issue 57218)
o Changed the sys/cdefs.h header so that __WCHAR_TYPE__ is 32-bit
for API levels less than 9, which means that wchat_t is 32-bit for all API
levels. To restore the previous behavior, define the _WCHAR_IS_8BIT
boolean variable. (Issue 57267)
Added more formatting in NDK docs/ and miscellaneous documentation fixes.
Added support for a thin archive technique when building static libraries. (Issue 40303)
Updated script make-standalone-toolchain.sh to support the stlport
library in addition to gnustl, when you specify the option --stl=stlport. For
more information, see STANDALONE-TOOLCHAIN.html.
Updated the make-standalone-toolchain.sh script so that the --llvmversion= option creates the $TOOLCHAIN_PREFIX-clang and
39
Content from developer.android.com/tools/sdk/ndk/index.html through their Creative Commons Attribution 2.5 license
Android NDK
•
•
•
•
•
$TOOLCHAIN_PREFIX-clang++ scripts in addition to clang and clang++, to
avoid using the host's clang and clang++ definitions by accident.
Added two flags to re-enable two optimizations in upstream Clang but disabled in NDK
for better compatibility with code compiled by GCC:
o Added a -fcxx-missing-return-semantics flag to re-enable
missing return semantics in Clang 3.2+. Normally, all paths should terminate
with a return statement for a value-returning function. If this is not the case,
clang inserts an undefined instruction (or trap in debug mode) at the path
without a return statement. If you are sure your code is correct, use this flag to
allow the optimizer to take advantage of the undefined behavior. If you are not
sure, do not use this flag. The caller may still receive a random incorrect value,
but the optimizer will not exploit it and make your code harder to debug.
o Added a -fglobal-ctor-const-promotion flag to re-enable
promoting global variables with static constructor to be constants. With this flag,
the global variable optimization pass of LLVM tries to evaluate the global
variables with static constructors and promote them to global constants.
Although this optimization is correct, it may cause some incompatability with
code compiled by GCC. For example, code may do const_cast to cast the
constant to mutable and modify it. In GCC, the variable is in read-write and the
code is run by accident. In Clang, the const variable is in read-only memory
and may cause your application to crash.
Added -mldc1-sdc1 to the MIPS GCC and Clang compilers. By default, compilers
align 8-byte objects properly and emit the ldc1 and sdc1 instructions to move them
around. If your app uses a custom allocator that does not always align with a new
object's 8-byte boundary in the same way as the default allocator, your app may crash
due to ldc1 and sdc1 operations on unaligned memory. In this case, use the -mnoldc1-sdc1 flag to workaround the problem.
Downgraded the event severity from warning to info if APP_PLATFORM_LEVEL is
larger than APP_MIN_PLATFORM_LEVEL. The APP_PLATFORM_LEVEL may be
lower than APP_PLATFORM in jni/Application.mk because the NDK does not
have headers for all levels. In this case, the actual level is shifted downwards. The
APP_MIN_PLATFORM_LEVEL is specified by the android:minSdkVersion in
your application's manifest. (Issue 39752)
Added the android_getCpuIdArm() and android_setCpuArm() methods
to cpu-features.c. This addition enables easier retrieval of the ARM CPUID
information. (Issue 53689)
Modified ndk-build to use GCC 4.7's as/ld for Clang compiling.
Note: In GCC 4.7, monotonic_clock and is_monotonic have been renamed
to steady_clock and is_steady, respectively.
•
•
•
Added the following new warnings to the ndk-build script:
o Added warnings if LOCAL_LDLIBS/LDFLAGS are used in static library
modules.
o Added a warning if a configuration has no module to build.
o Added a warning for non-system libraries being used in
LOCAL_LDLIBS/LDFLAGS of a shared library or executable modules.
Updated build scripts, so that if APP_MODULES is not defined and only static libraries
are listed in Android.mk, the script force-builds all of them. (Issue 53502)
Updated ndk-build to support absolute paths in LOCAL_SRC_FILES.
40
Content from developer.android.com/tools/sdk/ndk/index.html through their Creative Commons Attribution 2.5 license
Android NDK
•
•
•
•
•
•
•
Removed the *-gdbtui executables, which are duplicates of the *-gdb executables
with the -tui option enabled.
Updated the build scripts to warn you when the Edison Design Group (EDG) compiler
front-end turns _STLP_HAS_INCLUDE_NEXT back on. (Issue 53646)
Added the environment variable NDK_LIBS_OUT to allow overriding of the path for
libraries/gdbserver from the default $PROJECT/libs. For more
information, see OVERVIEW.html.
Changed ndk-build script defaults to compile code with format string protection Wformat -Werror=format-security. You may set
LOCAL_DISABLE_FORMAT_STRING_CHECKS=true to disable it. For more
information, see ANDROID-MK.html
Added STL pretty-print support in ndk-gdb-py. For more information, see NDKGDB.html.
Added tests based on the googletest frameworks.
Added a notification to the toolchain build script that warns you if the current shell is not
bash.
Android NDK, Revision 8e (March 2013)
Important changes:
•
•
•
•
•
Added 64-bit host toolchain set (package name suffix *-x86_64.*). For more
information, see CHANGES.HTML and NDK-BUILD.html.
Added Clang 3.2 compiler. GCC 4.6 is still the default. For information on using the
Clang compiler, see CHANGES.HTML.
Added static code analyzer for Linux/MacOSX hosts. For information on using the
analyzer, see CHANGES.HTML.
Added MCLinker for Linux/MacOSX hosts as an experimental feature. The ld.gold
linker is the default where available, so you must explicitly enable it. For more
information, see CHANGES.HTML.
Updated ndk-build to use topological sort for module dependencies, which means the
build automatically sorts out the order of libraries specified in
LOCAL_STATIC_LIBRARIES, LOCAL_WHOLE_STATIC_LIBRARIES and
LOCAL_SHARED_LIBRARIES. For more information, see CHANGES.HTML. (Issue
39378)
Important bug fixes:
•
•
•
•
•
•
•
Fixed build script to build all toolchains in -O2. Toolchains in previous releases were
incorrectly built without optimization.
Fixed build script which unconditionally builds Clang/llvm for MacOSX in 64-bit.
Fixed GCC 4.6/4.7 internal compiler error: gen_thumb_movhi_clobber at
config/arm/arm.md:5832. (Issue 52732)
Fixed build problem where GCC/ARM 4.6/4.7 fails to link code using 64-bit atomic builtin functions. (Issue 41297)
Fixed GCC 4.7 linker DIV usage mismatch errors. (Sourceware Issue)
Fixed GCC 4.7 internal compiler error
build_data_member_initialization, at cp/semantics.c:5790.
Fixed GCC 4.7 internal compiler error redirect_eh_edge_1, at treeeh.c:2214. (Issue 52909)
41
Content from developer.android.com/tools/sdk/ndk/index.html through their Creative Commons Attribution 2.5 license
Android NDK
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
Fixed a GCC 4.7 segfault. (GCC Issue)
Fixed <chrono> clock resolution and enabled steady_clock. (Issue 39680)
Fixed toolchain to enable _GLIBCXX_HAS_GTHREADS for GCC 4.7 libstdc++. (Issue
41770, Issue 41859)
Fixed problem with the X86 MXX/SSE code failing to link due to missing
posix_memalign. (Change 51872)
Fixed GCC4.7/X86 segmentation fault in i386.c, function
distance_non_agu_define_in_bb(). (Change 50383)
Fixed GCC4.7/X86 to restore earlier cmov behavior. (GCC Issue)
Fixed handling NULL return value of setlocale() in libstdc++/GCC4.7. (Issue
46718)
Fixed ld.gold runtime undefined reference to __exidx_start and
__exidx_start_end. (Change 52134)
Fixed Clang 3.1 internal compiler error when using Eigen library. (Issue 41246)
Fixed Clang 3.1 internal compiler error including <chrono> in C++11 mode. (Issue
39600)
Fixed Clang 3.1 internal compiler error when generating object code for a method call to
a uniform initialized rvalue. (Issue 41387)
Fixed Clang 3.1/X86 stack realignment. (Change 52154)
Fixed problem with GNU Debugger (GDB) SIGILL when debugging on Android 4.1.2.
(Issue 40941)
Fixed problem where GDB cannot set source:line breakpoints when symbols
contain long, indirect file paths. (Issue 42448)
Fixed GDB read_program_header for MIPS PIE executables. (Change 49592)
Fixed STLport segmentation fault in uncaught_exception(). (Change 50236)
Fixed STLport bus error in exception handling due to unaligned access of
DW_EH_PE_udata2, DW_EH_PE_udata4, and DW_EH_PE_udata8.
Fixed Gabi++ infinite recursion problem with nothrow new[] operator. (Issue
52833)
Fixed Gabi++ wrong offset to exception handler pointer. (Change 53446)
Removed Gabi++ redundant free on exception object (Change 53447)
Other bug fixes:
•
•
•
•
•
Fixed NDK headers:
o Removed redundant definitions of size_t, ssize_t, and ptrdiff_t.
o Fixed MIPS and ARM fenv.h header.
o Fixed stddef.h to not redefine offsetof since it already exists in the
toolchain.
o Fixed elf.h to contain Elf32_auxv_t and Elf64_auxv_t. (Issue
38441)
o Fixed the #ifdef C++ definitions in the
OpenSLES_AndroidConfiguration.h header file. (Issue 53163)
Fixed STLport to abort after out of memory error instead of silently exiting.
Fixed system and Gabi++ headers to be able to compile with API level 8 and lower.
Fixed cpufeatures to not parse /proc/self/auxv. (Issue 43055)
Fixed ld.gold to not depend on host libstdc++ and on Windows platforms, to not
depend on the libgcc_sjlj_1.dll library.
42
Content from developer.android.com/tools/sdk/ndk/index.html through their Creative Commons Attribution 2.5 license
Android NDK
•
•
•
•
•
•
•
•
•
•
•
Fixed Clang 3.1 which emits inconsistent register list in .vsave and fails assembler.
(Change 49930)
Fixed Clang 3.1 to be able to compile libgabi++ and pass the test-stlport tests for
MIPS build targets. (Change 51961)
Fixed Clang 3.1 to only enable exception by default for C++, not for C.
Fixed several issues in Clang 3.1 to pass most GNU exception tests.
Fixed scripts clang and clang++ in standalone NDK compiler to detect -cc1 and to
not specify -target when found.
Fixed ndk-build to observe NDK_APP_OUT set in Application.mk.
Fixed X86 libc.so and lib.a which were missing the sigsetjmp and
siglongjmp functions already declared in setjmp.h. (Issue 19851)
Patched GCC 4.4.3/4.6/4.7 libstdc++ to work with Clang in C++ 11. (Clang Issue)
Fixed cygwin path in argument passed to HOST_AWK.
Fixed ndk-build script warning in windows when running from project's JNI directory.
(Issue 40192)
Fixed problem where the ndk-build script does not build if makefile has trailing
whitespace in the LOCAL_PATH definition. (Issue 42841)
Other changes:
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
Enabled threading support in GCC/MIPS toolchain.
Updated GCC exception handling helpers __cxa_begin_cleanup and
__cxa_type_match to have default visibility from the previous hidden visibility in
GNU libstdc++. For more information, see CHANGES.HTML.
Updated build scripts so that Gabi++ and STLport static libraries are now built with
hidden visibility except for exception handling helpers.
Updated build so that STLport is built for ARM in Thumb mode.
Added support for std::set_new_handler in Gabi++. (Issue 52805)
Enabled FUTEX system call in GNU libstdc++.
Updated ndk-build so that it no longer copies prebuilt static library to a project's
obj/local/<abi>/ directory. (Issue 40302)
Removed __ARM_ARCH_5*__ from ARM toolchains/*/setup.mk script.
(Issue 21132)
Built additional GNU libstdc++ libraries in thumb for ARM.
Enabled MIPS floating-point madd/msub/nmadd/nmsub/recip/rsqrt
instructions with 32-bit FPU.
Enabled graphite loop optimizer in GCC 4.6 and 4.7 to allow more optimizations: fgraphite, -fgraphite-identity, -floop-block, -floop-flatten,
-floop-interchange, -floop-strip-mine, -floop-parallelizeall, and -ftree-loop-linear. (info)
Enabled polly for Clang 3.1 on Linux and Max OS X 32-bit hosts which analyzes and
optimizes memory access. (info)
Enabled -flto in GCC 4.7, 4.6, Clang 3.2 and Clang 3.1 on linux (Clang LTO via
LLVMgold.so). MIPS compiler targets are not supported because ld.gold is not
available.
Enabled --plugin and --plugin-opt for ld.gold in GCC 4.6/4.7.
Enabled --text-reorder for ld.gold in GCC 4.7.
Configured GNU libstdc++ with _GLIBCXX_USE_C99_MATH which undefines the
isinf script in the bionic header. For more information, see CHANGES.html.
43
Content from developer.android.com/tools/sdk/ndk/index.html through their Creative Commons Attribution 2.5 license
Android NDK
•
•
•
•
•
Added APP_LDFLAGS to the build scripts. For more information, see ANDROIDMK.html.
Updated build scripts to allow NDK_LOG=0 to disable the NDK_LOG.
Updated build scripts to allow NDK_HOST_32BIT=0 to disable the host developer
environment 32-bit toolchain.
Changed the default GCC/X86 flags -march= and -mtune= from pentiumpro
and generic to i686 and atom.
Enhanced toolchain build scripts:
o Fixed a race condition in build-gcc.sh for the mingw build type which
was preventing a significant amount of parallel build processing.
o Updated build-gabi++.sh and build-stlport.sh so they can now
run from the NDK package. (Issue 52835)
o Fixed run-tests.sh in the MSys utilities collection.
o Improved 64-bit host toolchain and Canadian Cross build support.
o Updated build-mingw64-toolchain.sh script to more recent version.
o Added option to build libgnustl_static.a and stlport_static.a
without hidden visibility.
Android NDK, Revision 8d (December 2012)
Important changes:
•
Added the GNU Compiler Collection (GCC) 4.7 compiler to the NDK. The GCC 4.6
compiler is still the default, so you must to explicitly enable the new version as follows:
o For ndk-build, export the NDK_TOOLCHAIN_VERSION=4.7 variable
or add it to Application.mk.
o For standalone builds, add the --toolchain= option to makestandalone-toolchain.sh, for example:
--toolchain=arm-linux-androideabi-4.7
Note: This feature is experimental. Please try it and report any issues.
•
Added stlport exception support via gabi++. Note that the new gabi++ depends on dlopen
and related code, meaning that:
o You can no longer build a static executable using the -static option or include
libstlport_static.a using APP_STL := stlport_static. (You can
still use the -static option with a standalone toolchain.) Compiling a dynamic
executable using include $(BUILD_EXECUTABLE) continues to work because
the compiler automatically adds the -ldl option.
o If your project links using -nostdlib and {-Wl,--no-undefined}, you must manually
include the -ldl option.
For more information, see CPLUSPLUS-SUPPORT.html.
Note: This feature is experimental and works better with the GCC 4.6/4.7 compilers than with
GCC 4.4.3 or Clang 3.1. Please try it and report any issues.
•
Added a -mstack-protector-guard= option for x86 to choose between a global default
path which is compatible with older Android C library (bionic) and a new tls path (%gs:20) for 44
Content from developer.android.com/tools/sdk/ndk/index.html through their Creative Commons Attribution 2.5 license
Android NDK
fstack-protector, -fstack-protector-all and -fstack-protectorstrong using the GCC 4.6 and higher compilers.
Note: The -mstack-protector-guard setting itself does not enable any -fstackprotector* options.
•
Added android_setCpu() function to sources/android/cpufeatures/cpufeatures.c for use when auto-detection via /proc is not possible in Android 4.1 and higher.
(Chromium Issue 164154)
Important bug fixes:
•
•
Fixed unnecessary rebuild of object files when using the ndk-build script. (Issue
39810)
Fixed a linker failure with the NDK 8c release for Mac OS X 10.6.x that produced the
following error:
dyld: lazy symbol binding failed: Symbol not found: _memmem
Referenced from: ...../arm-linux-androideabi/bin/ld
Expected in: /usr/lib/libSystem.B.dylib
This problem was caused by building on Mac OS X 10.7, which produced binaries that were not
compatible with Mac OS 10.6.x and the NDK.
•
•
•
•
•
•
•
•
•
•
Removed the -x c++ options from the Clang++ standalone build script. (Issue 39089)
Fixed issues using the NDK_TOOLCHAIN_VERSION=clang3.1 option in Cygwin. (Issue
39585)
Fixed the make-standalone-toolchain.sh script to allow generation of a standalone
toolchain using the Cygwin or MinGW environments. The resulting toolchain can be used in
Cygwin, MingGW or CMD.exe environments. (Issue 39915, Issue 39585)
Added missing SL_IID_ANDROIDBUFFERQUEUESOURCE option in android-14 builds for
ARM and X86. (Issue 40625)
Fixed x86 CPU detection for the ANDROID_CPU_X86_FEATURE_MOVBE feature. (Issue
39317)
Fixed an issue preventing the Standard Template Library (STL) from using C++ sources that do
not have a .cpp file extension.
Fixed GCC 4.6 ARM internal compiler error at reload1.c:1061. (Issue 20862)
Fixed GCC 4.4.3 ARM internal compiler error at emit-rtl.c:1954. (Issue 22336)
Fixed GCC 4.4.3 ARM internal compiler error at postreload.c:396. (Issue 22345)
Fixed problem with GCC 4.6/4.7 skipping lambda functions. (Issue 35933)
Other bug fixes:
•
NDK header file fixes:
o Fixed __WINT_TYPE__ and wint_t to be the same type.
o Corrected typo in android/bitmap.h. (Issue 15134)
o Corrected typo in errno.h.
45
Content from developer.android.com/tools/sdk/ndk/index.html through their Creative Commons Attribution 2.5 license
Android NDK
Added check for the presence of __STDC_VERSION__ in sys/cdefs.h.
(Issue 14627)
o Reorganized headers in byteswap.h and dirent.h.
o Fixed limits.h to include page.h which provides PAGE_SIZE settings.
(Issue 39983)
o Fixed return type of glGetAttribLocation() and
glGetUniformLocation() from int to GLint.
o Fixed __BYTE_ORDER constant for x86 builds. (Issue 39824)
Fixed ndk-build script to not overwrite -Os with -O2 for ARM builds.
Fixed build scripts to allow overwriting of HOST_AWK, HOST_SED, and HOST_MAKE
settings.
Fixed issue for ld.gold on fsck_msdos builds linking objects built by the Intel
C/C++ compiler (ICC).
Fixed ARM EHABI support in Clang to conform to specifications.
Fixed GNU Debugger (GDB) to shorten the time spent on walking the target's link map
during solib events. (Issue 38402)
Fixed missing libgcc.a file when linking shared libraries.
o
•
•
•
•
•
•
Other changes:
•
•
•
•
•
•
•
•
Backported 64-bit built-in atomic functions for ARM to GCC 4.6.
Added documentation for audio output latency, along with other documentation and
fixes.
Fixed debug builds with Clang so that non-void functions now raise a SIGILL signal for
paths without a return statement.
Updated make-standalone-toolchain.sh to accept the suffix -clang3.1
which is equivalent to adding --llvm-version=3.1 to the GCC 4.6 toolchain.
Updated GCC and Clang bug report URL to: http://source.android.com/source/reportbugs.html
Added ARM ELF support to llvm-objdump.
Suppressed treating c input as c++ warning for Clang builds.
Updated build so that only the 32-bit version of libiberty.a is built and placed in
lib32/.
Android NDK, Revision 8c (November 2012)
Important changes:
•
Added the Clang 3.1 compiler to the NDK. The GNU Compiler Collection (GCC) 4.6 is
still the default, so you must explicitly enable the Clang compiler option as follows:
o For ndk-build, export NDK_TOOLCHAIN_VERSION=clang3.1 or
add this environment variable setting to Application.mk.
o For standalone builds, add --llvm-version=3.1 to makestandalone-toolchain.sh and replace CC and CXX in your makefile
with <tool-path>/bin/clang and <tool-path>/bin/clang++.
See STANDALONE-TOOLCHAIN.html for details.
Note: This feature is experimental. Please try it and report any issues.
46
Content from developer.android.com/tools/sdk/ndk/index.html through their Creative Commons Attribution 2.5 license
Android NDK
•
•
•
Added Gold linker ld.gold for the Windows toolchain. Gold linker is also the default
for ARM and X86 on all hosts. You may override it to use the ld.bfd linker by adding
LOCAL_LDFLAGS += -fuse-ld=bfd to Android.mk, or by passing -fuseld=bfd to the g++/clang++ command line that does the linking.
Added checks for spaces in the NDK path to the ndk-build[.cmd] and ndk-gdb
scripts, to prevent build errors that are difficult to diagnose.
Made the following changes to API level handling:
o Modified build logic so that projects that specify android-10 through
android-13 in APP_PLATFORM, project.properties or
default.properties link against android-9 instead of android14.
o Updated build so that executables using android-16 (Jelly Bean) or higher are
compiled with the -fPIE option for position-independent executables (PIE). A
new APP_PIE option allows you to control this behavior. See
APPLICATION-MK.html for details.
Note: All API levels above 14 still link against platforms/android-14
and no new platforms/android-N have been added.
Modified ndk-build to provide warnings if the adjusted API level is larger
than android:minSdkVersion in the project's
AndroidManifest.xml.
Updated the cpu-features helper library to include more ARM-specific features.
See sources/android/cpufeatures/cpu-features.h for details.
Modified the long double on the X86 platform to be 8 bytes. This data type is now the
same size as a double, but is still treated as a distinct type.
Updated build for APP_ABI=armeabi-v7a:
o Modified this build type to pass the -march=armv7-a parameter to the
linker. This change ensures that v7-specific libraries and crt*.o are linked
correctly.
o Added -mfpu=vfpv3-d16 to ndk-build instead of the -mfpu=vfp
option used in previous releases.
o
•
•
•
Important bug fixes:
•
•
•
•
Fixed an issue where running make-standalone-toolchain.sh with root
privileges resulted in the stand alone tool chain being inaccessible to some users. (Issue
35279)
o All files and executables in the NDK release package are set to have read and
execute permissions for all.
o The ownership/group of libstdc++.a is now preserved when copied.
Removed redundant \r from Windows prebuilt echo.exe. The redundant \r caused
gdb.setup to fail in the GNU Debugger (GDB) because it incorrectly became part of
the path. (Issue 36054)
Fixed Windows parallel builds that sometimes failed due to timing issues in the hostmkdir implementation. (Issue 25875)
Fixed GCC 4.4.3 GNU libstdc++ to not merge typeinfo names by default. For
more details, see toolchain repo gcc/gcc-4.4.3/libstdc++v3/libsupc++/typeinfo. (Issue 22165)
47
Content from developer.android.com/tools/sdk/ndk/index.html through their Creative Commons Attribution 2.5 license
Android NDK
•
•
•
•
•
•
•
Fixed problem on null context in GCC 4.6
cp/mangle.c::write_unscoped_name, where GCC may crash when the
context is null and dereferenced in TREE_CODE.
Fixed GCC 4.4.3 crashes on ARM NEON-specific type definitions for floats. (Issue
34613)
Fixed the STLport internal _IteWrapper::operator*() implementation
where a stale stack location holding the dereferenced value was returned and caused
runtime crashes. (Issue 38630)
ARM-specific fixes:
o Fixed ARM GCC 4.4.3/4.6 g++ to not warn that the mangling of <va_list> was
changed in GCC 4.4. The workaround using the -Wno-psabi switch to avoid
this warning is no longer required.
o Fixed an issue when a project with .arm or .neon suffixes in
LOCAL_SRC_FILES also used APP_STL. With APP_STL, the ndkbuild script searches for C++ files in LOCAL_SRC_FILES before adding
STL header/lib paths to compilation. Modified ndk-build to filter out
.arm and .neon suffixes before the search, otherwise items in
LOCAL_SRC_FILES like myfile.cpp.arm.neon won't be compiled as
C++ code.
o Fixed binutils-2.21/ld.bfd to be capable of linking object from older
binutils without tag_FP_arch, which was producing assertion fail error
messages in GNU Binutils. (Issue 35209)
o Removed Unknown EABI object attribute 44 warning when binutils2.19/ld links prebuilt object by newer binutils-2.21
o Fixed an issue in GNU stdc++ compilation with both -mthumb and march=armv7-a, by modifying make-standalone-toolchain.sh
to populate headers/libs in sub-directory armv7-a/thumb. (Issue
35616)
o Fixed unresolvable R_ARM_THM_CALL relocation error. (Issue 35342)
o Fixed internal compiler error at reload1.c:3633, caused by the ARM
back-end expecting the wrong operand type when sign-extend from char.
(GCC Issue 50099)
o Fixed internal compiler error with negative shift amount. (GCC Issue)
Fixed -fstack-protector for X86, which is also the default for the ndk-build
x86 ABI target.
MIPS-specific fixes:
o Fixed STLport endian-ness by setting _STLP_LITTLE_ENDIAN to 1
when compiling MIPS libstlport_*.
o Fixed GCC __builtin_unreachable issue when compiling LLVM.
(GCC Issue 54369)
o Backported fix for cc1 compile process consuming 100% CPU. (GCC Issue
50380)
GNU Debugger-specific fixes:
o Disabled Python support in gdb-7.x at build, otherwise the gdb-7.x configure
function may pick up whatever Python version is available on the host and build
gdb with a hard-wired dependency on a specific version of Python. (Issue
36120)
o Fixed ndk-gdb when APP_ABI contains all and matchs none of the
known architectures. (Issue 35392)
o Fixed Windows pathname support, by keeping the : character if it looks like it
could be part of a Windows path starting with a drive letter. (GDB Issue 12843)
48
Content from developer.android.com/tools/sdk/ndk/index.html through their Creative Commons Attribution 2.5 license
Android NDK
o
o
o
o
o
Fixed adding of hardware breakpoint support for ARM in gdbserver. (GDB
Issue)
Added fix to only read the current solibs when the linker is consistent. This
change speeds up solib event handling. (Issue 37677)
Added fix to make repeated attempts to find solib breakpoints. GDB now
retries enable_break() during every call to svr4_current_sos()
until it succeeds. (Change 43563)
Fixed an issue where gdb would not stop on breakpoints placed in dlopened libraries. (Issue 34856)
Fixed SIGILL in dynamic linker when calling dlopen(), on system where
/system/bin/linker is stripped of symbols and
rtld_db_dlactivity() is implemented as Thumb, due to not
preserving LSB of sym_addr. (Issue 37147)
Other bug fixes:
•
•
•
•
Fixed NDK headers:
o Fixed arch-mips/include/asm/* code that was incorrectly removed
from original kernel. (Change 43335)
o Replaced struct member data __unused with __linux_unused in
linux/sysctl.h and linux/icmp.h to avoid conflict with #define
__unused in sys/cdefs.h.
o Fixed fenv.h for enclosed C functions with __BEGIN_DECLS and
__END_DECLS.
o Removed unimplemented functions in malloc.h.
o Fixed stdint.h defintion of uint64_t for ANSI compilers. (Issue 1952)
o Fixed preprocessor macros in <arch>/include/machine/*.
o Replaced link.h for MIPS with new version supporting all platforms.
o Removed linux-unistd.h
o Move GLibc-specific macros LONG_LONG_MIN, LONG_LONG_MAX and
ULONG_LONG_MAX from <pthread.h> to <limits.h>.
Fixed a buffer overflow in ndk-stack-parser.
Fixed _STLP_USE_EXCEPTIONS, when not defined, to omit all declarations and
uses of __Named_exception. Compiling and use of __Named_exception
settings only occurs when STLport is allowed to use exceptions.
Fixed building of Linux-only NDK packages without also building Windows code. Use the
following settings to perform this type of build:
./build/tools/make-release.sh --force --systems=linux-x86
•
Fixed libc.so so it does not export atexit() and __do_handler. These symbols are
exported for ARM builds by the system version of the C library to support legacy native libraries.
NDK-generated should never reference them directly. Instead, each shared library or executable
should embed its own version of these symbols, provided by crtbegin_*.o.
If your project is linked with the -nostdlib -Wl,--no-undefined options, you must
provide your own __dso_handle because crtbegin_so.o is not linked in this case. The
content of __dso_handle does not matter, as shown in the following example code:
49
Content from developer.android.com/tools/sdk/ndk/index.html through their Creative Commons Attribution 2.5 license
Android NDK
extern "C" {
extern void *__dso_handle __attribute__((__visibility__ ("hidden")));
void *__dso_handle;
}
•
•
•
•
•
Fixed symbol decoder for ARM used in objdump for plt entries to generate a more readable
form [email protected]
Removed the following symbols, introduced in GCC 4.6 libgcc.a, from the X86 platform
libc.so library: __aeabi_idiv0, __aeabi_ldiv0, __aeabi_unwind_cpp_pr1,
and __aeabi_unwind_cpp_pr2.
Removed unused .ctors, .dtors, and .eh_frame in MIPS crt*_so.S.
Updated ndk-gdb so that it only takes the last line of output for ndk-build DUMP_XXXX.
This change ensures that if Application.mk or Android.mk print something with
$(info ...) syntax, it does not get injected into the result of DUMP_XXXX. (More info)
Other changes:
•
•
Removed arch-x86 and arch-mips headers from platforms/android[3,4,5,8]. Those headers were incomplete, since both X86 and MIPS ABIs are only
supported at API 9 or higher.
Simplified c++ include path in standalone packages, as shown below. (Issue 35279)
<path>/arm-linux-androideabi/include/c++/4.6.x-google
to:
<path>/include/c++/4.6/
•
•
•
•
Fixed ndk-build to recognize more C++ file extensions by default: .cc .cp .cxx .cpp
.CPP .c++ .C. You may still use LOCAL_CPP_EXTENSION to overwrite these extension
settings.
Fixed an issue in samples/san-angeles that caused a black screen or freeze frame on relaunch.
Replaced deprecated APIs in NDK samples. (Issue 20017)
o hello-gl2 from android-5 to android-7
o native-activity from android-9 to android-10
o native-audio from android-9 to android-10
o native-plasma from android-9 to android-10
Added new branding for Android executables with a simpler scheme in section
.note.android.ident (defined in crtbegin_static/dynamic.o) so that
debugging tools can act accordingly. The structure member and values are defined as follows:
static const struct {
int32_t namesz; /* = 8, sizeof ("Android") */
int32_t descsz; /* = 1 * sizeof(int32_t) */
int32_t type;
/* = 1, ABI_NOTETYPE */
char name[sizeof "Android"]; /* = "Android" */
50
Content from developer.android.com/tools/sdk/ndk/index.html through their Creative Commons Attribution 2.5 license
Android NDK
int32_t android_api; /* = 3, 4, 5, 8, 9, 14 */
}
The previous branding options in section .note.ABI-tag are deprecated.
•
Added a new script run-tests-all.sh which calls run-tests.sh and
standalone/run.sh with various conditions. The script run-tests.sh runs without the
--abi option, and is enhanced to compile most of the tests for all supported ABIs and run on all
attached devices
Android NDK, Revision 8b (July 2012)
The main features of this release are a new GNU Compiler Collection (GCC) 4.6 toolchain and GNU
Debugger (GDB) 7.3.x which adds debugging support for the Android 4.1 (API Level 16) system image.
Important bug fixes:
•
•
•
•
•
•
Fixed LOCAL_SHORT_COMMANDS issues on Mac OS, Windows Cygwin
environments for static libraries. List file generation is faster, and it is not regenerated to
avoid repeated project rebuilds.
Fixed several issues in ndk-gdb:
o Updated tool to pass flags -e, -d and -s to adb more consistently.
o Updated tool to accept device serial names containing spaces.
o Updated tool to retrieve /system/bin/link information, so gdb on the
host can set a breakpoint in __dl_rtld_db_dlactivity and be aware
of linker activity (e.g., rescan solib symbols when dlopen() is called).
Fixed ndk-build clean on Windows, which was failing to remove
./libs/*/lib*.so.
Fixed ndk-build.cmd to return a non-zero ERRORLEVEL when make fails.
Fixed libc.so to stop incorrectly exporting the __exidx_start and
__exidx_end symbols.
Fixed SEGV when unwinding the stack past __libc_init for ARM and MIPS.
Important changes:
•
Added GCC 4.6 toolchain (binutils 2.21 with gold and GDB 7.3.x) to co-exist with
the original GCC 4.4.3 toolchain (binutils 2.19 and GDB 6.6).
o GCC 4.6 is now the default toolchain. You may set
NDK_TOOLCHAIN_VERSION=4.4.3 in Application.mk to select the
original one.
o Support for the gold linker is only available for ARM and x86 architectures on
Linux and Mac OS hosts. This support is disabled by default. Add
LOCAL_LDLIBS += -fuse-ld=gold in Android.mk to enable it.
o Programs compiled with -fPIE require the new GDB for debugging, including
binaries in Android 4.1 (API Level 16) system images.
o The binutils 2.21 ld tool contains back-ported fixes from version 2.22:
§ Fixed ld --gc-sections, which incorrectly retains zombie
references to external libraries. (more info).
§ Fixed ARM strip command to preserve the original p_align and
p_flags in GNU_RELRO section if they are valid. Without this fix,
programs built with -fPIE could not be debugged. (more info)
51
Content from developer.android.com/tools/sdk/ndk/index.html through their Creative Commons Attribution 2.5 license
Android NDK
•
o Disabled sincos() optimization for compatibility with older platforms.
Updated build options to enable the Never eXecute (NX) bit and relro/bind_now
protections by default:
o Added --noexecstack to assembler and -z noexecstack to linker
that provides NX protection against buffer overflow attacks by enabling NX bit
on stack and heap.
o Added -z relro and -z now to linker for hardening of internal data
sections after linking to guard against security vulnerabilities caused by
memory corruption. (more info: 1, 2)
o These features can be disabled using the following options:
o Disable NX protection by setting the --execstack option for the assembler
and -z execstack for the linker.
o Disable hardening of internal data by setting the -z norelro and -z
lazy options for the linker.
o Disable these protections in the NDK jni/Android.mk by setting the
following options:
LOCAL_DISABLE_NO_EXECUTE=true
DISABLE_RELRO=true
# disable "--noexecstack" and "-z noexecstack"
# disable "-z relro" and "-z now"
See docs/ANDROID-MK.html for more details.
•
Added branding for Android executables with the .note.ABI-tag section (in
crtbegin_static/dynamic.o) so that debugging tools can act accordingly. The
structure member and values are defined as follows:
static const struct {
int32_t namesz; /* = 4, sizeof ("GNU") */
int32_t descsz; /* = 6 * sizeof(int32_t) */
int32_t type;
/* = 1 */
char name[sizeof "GNU"]; /* = "GNU" */
int32_t os;
/* = 0 */
int32_t major;
/* = 2 */
int32_t minor;
/* = 6 */
int32_t teeny;
/* = 15 */
int32_t os_variant; /* = 1 */
int32_t android_api; /* = 3, 4, 5, 8, 9, 14 */
}
•
Other bug fixes:
•
•
•
•
•
Fixed mips-linux-gnu relocation truncated to fit R_MIPS_TLS_LDM issue. (more
info)
Fixed ld tool segfaults when using --gc-sections. (more info)
Fixed MIPS GOT_PAGE counting issue. (more info)
Fixed follow warning symbol link for mips_elf_count_got_symbols.
Fixed follow warning symbol link for mips_elf_allocate_lazy_stub.
52
Content from developer.android.com/tools/sdk/ndk/index.html through their Creative Commons Attribution 2.5 license
Android NDK
•
•
•
•
Moved MIPS .dynamic to the data segment, so that it is writable.
Replaced hard-coded values for symbols with correct segment sizes for MIPS.
Removed the -mno-shared option from the defaults in the MIPS toolchain. The
default for Android toolchain is -fPIC (or -fpic if supported). If you do not explicitly
specify -mshared, -fpic, -fPIC, -fpie, or -fPIE, the MIPS compiler adds mno-shared that turns off PIC. Fixed compiler not to add -mno-shared in this
case.
Fixed wrong package names in samples hello-jni and two-libs so that the
tests project underneath it can compile.
Other Changes:
•
•
•
Changed locations of binaries:
o Moved gdbserver from toolchain/<arch-osver>/prebuilt/gdbserver to prebuilt/android<arch>/gdbserver/gdbserver.
o Renamed x86 toolchain prefix from i686-android-linux- to i686linux-android-.
o Moved sources/cxx-stl/gnu-libstdc++/include and lib to
sources/cxx-stl/gnu-libstdc++/4.6 when compiled with GCC
4.6, or sources/cxx-stl/gnu-libstdc++/4.4.3 when compiled
with GCC 4.4.3.
o Moved libbfd.a and libintl.a from lib/ to lib32/.
Added and improved various scripts in the rebuild and test NDK toolchain:
o Added build-mingw64-toolchain.sh to generate a new Linuxhosted toolchain that generates Win32 and Win64 executables.
o Improved speed of download-toolchain-sources.sh by using the
clone command and only using checkout for the directories that are
needed to build the NDK toolchain binaries.
o Added build-host-gcc.sh and build-host-gdb.sh scripts.
o Added tests/check-release.sh to check the content of a given NDK
installation directory, or an existing NDK package.
o Rewrote the tests/standalone/run.sh standalone tests .
Removed if_dl.h header from all platforms and architectures. The AF_LINK and
sockaddr_dl elements it describes are specific to BSD (i.e., they don't exist in
Linux).
Android NDK, Revision 8 (May 2012)
This release of the NDK includes support for MIPS ABI and a few additional fixes.
New features:
•
Added support for the MIPS ABI, which allows you to generate machine code that runs
on compatible MIPS-based Android devices. Major features for MIPS include MIPSspecific toolchains, system headers, libraries and debugging support. For more details
regarding MIPS support, see docs/CPU-MIPS.html in the NDK package.
By default, code is generated for ARM-based devices. You can add mips to your
APP_ABI definition in your Application.mk file to build for MIPS platforms. For
example, the following line instructs ndk-build to build your code for three distinct
ABIs:
53
Content from developer.android.com/tools/sdk/ndk/index.html through their Creative Commons Attribution 2.5 license
Android NDK
APP_ABI := armeabi armeabi-v7a mips
Unless you rely on architecture-specific assembly sources, such as ARM assembly code, you should not
need to touch your Android.mk files to build MIPS machine code.
•
You can build a standalone MIPS toolchain using the --arch=mips option when calling
make-standalone-toolchain.sh. See docs/STANDALONE-TOOLCHAIN.html
for more details.
Note: To ensure that your applications are available to users only if their devices are capable of running
them, Google Play filters applications based on the instruction set information included in your application
? no action is needed on your part to enable the filtering. Additionally, the Android system itself also
checks your application at install time and allows the installation to continue only if the application provides
a library that is compiled for the device's CPU architecture.
Important bug fixes:
•
•
Fixed a typo in GAbi++ implementation where the result of dynamic_cast<D>(b)
of base class object b to derived class D is incorrectly adjusted in the opposite direction
from the base class. (Issue 28721)
Fixed an issue in which make-standalone-toolchain.sh fails to copy
libsupc++.*.
Other bug fixes:
•
Fixed ndk-build.cmd to ensure that ndk-build.cmd works correctly even if the
user has redefined the SHELL environment variable, which may be changed when
installing a variety of development tools in Windows environments.
Android NDK, Revision 7c (April 2012)
This release of the NDK includes an important fix for Tegra2-based devices, and a few additional fixes and
improvements:
Important bug fixes:
•
Fixed GNU STL armeabi-v7a binaries to not crash on non-NEON devices. The files
provided with NDK r7b were not configured properly, resulting in crashes on Tegra2based devices and others when trying to use certain floating-point functions (e.g., cosf,
sinf, expf).
Important changes:
•
•
Added support for custom output directories through the NDK_OUT environment
variable. When defined, this variable is used to store all intermediate generated files,
instead of $PROJECT_PATH/obj. The variable is also recognized by ndk-gdb.
Added support for building modules with hundreds or even thousands of source files by
defining LOCAL_SHORT_COMMANDS to true in your Android.mk.
54
Content from developer.android.com/tools/sdk/ndk/index.html through their Creative Commons Attribution 2.5 license
Android NDK
This change forces the NDK build system to put most linker or archiver options into list
files, as a work-around for command-line length limitations. See docs/ANDROIDMK.html for details.
Other bug fixes:
•
Fixed android_getCpuCount() implementation in the cpufeatures helper
library. On certain devices, where cores are enabled dynamically by the system, the
previous implementation would report the total number of active cores the first time the
function was called, rather than the total number of physically available cores.
Android NDK, Revision 7b (February 2012)
This release of the NDK includes fixes for native Windows builds, Cygwin and many other improvements:
Important bug fixes:
•
•
•
•
•
Updated sys/atomics.h to avoid correctness issues on some multi-core ARMbased devices. Rebuild your unmodified sources with this version of the NDK and this
problem should be completely eliminated. For more details, read docs/ANDROIDATOMICS.html.
Reverted to binutils 2.19 to fix debugging issues that appeared in NDK r7 (which
switched to binutils 2.20.1).
Fixed ndk-build on 32-bit Linux. A packaging error put a 64-bit version of the awk
executable under prebuilt/linux-x86/bin in NDK r7.
Fixed native Windows build (ndk-build.cmd). Other build modes were not affected.
The fixes include:
o Removed an infinite loop / stack overflow bug that happened when trying to call
ndk-build.cmd from a directory that was not the top of your project path
(e.g., in any sub-directory of it).
o Fixed a problem where the auto-generated dependency files were ignored. This
meant that updating a header didn't trigger recompilation of sources that
included it.
o Fixed a problem where special characters in files or paths, other than spaces
and quotes, were not correctly handled.
Fixed the standalone toolchain to generate proper binaries when using -lstdc++ (i.e.,
linking against the GNU libstdc++ C++ runtime). You should use lgnustl_shared if you want to link against the shared library version or lstdc++ for the static version.
See docs/STANDALONE-TOOLCHAIN.html for more details about this fix.
•
•
Fixed gnustl_shared on Cygwin. The linker complained that it couldn't find
libsupc++.a even though the file was at the right location.
Fixed Cygwin C++ link when not using any specific C++ runtime through APP_STL.
Other changes:
•
When your application uses the GNU libstdc++ runtime, the compiler will no longer
forcibly enable exceptions and RTTI. This change results in smaller code.
55
Content from developer.android.com/tools/sdk/ndk/index.html through their Creative Commons Attribution 2.5 license
Android NDK
If you need these features, you must do one of the following:
o
•
•
•
Enable exceptions and/or RTTI explicitly in your modules or
Application.mk. (recommended)
o Define APP_GNUSTL_FORCE_CPP_FEATURES to 'exceptions',
'rtti' or both in your Application.mk. See docs/APPLICATIONMK.html for more details.
ndk-gdb now works properly when your application has private services running in
independent processes. It debugs the main application process, instead of the first
process listed by ps, which is usually a service process.
Fixed a rare bug where NDK r7 would fail to honor the LOCAL_ARM_MODE value and
always compile certain source files (but not all) to 32-bit instructions.
STLport: Refresh the sources to match the Android platform version. This update
fixes a few minor bugs:
o Fixed instantiation of an incomplete type
o Fixed minor "==" versus "=" typo
o Used memmove instead of memcpy in string::assign
o Added better handling of IsNANorINF, IsINF, IsNegNAN, etc.
For complete details, see the commit log.
•
•
•
•
•
•
•
STLport: Removed 5 unnecessary static initializers from the library.
The GNU libstdc++ libraries for armeabi-v7a were mistakenly compiled for armeabi
instead. This change had no impact on correctness, but using the right ABI should
provide slightly better performance.
The cpu-features helper library was updated to report three optional x86 CPU
features (SSSE3, MOVBE and POPCNT). See docs/CPU-FEATURES.html for
more details.
docs/NDK-BUILD.html was updated to mention NDK_APPLICATION_MK
instead of NDK_APP_APPLICATION_MK to select a custom Application.mk
file.
Cygwin: ndk-build no longer creates an empty "NUL" file in the current directory
when invoked.
Cygwin: Added better automatic dependency detection. In the previous version, it didn't
work properly in the following cases:
o When the Cygwin drive prefix was not /cygdrive.
o When using drive-less mounts, for example, when Cygwin would translate
/home to \\server\subdir instead of C:\Some\Dir.
Cygwin: ndk-build does not try to use the native Windows tools under
$NDK/prebuilt/windows/bin with certain versions of Cygwin and/or GNU
Make.
Android NDK, Revision 7 (November 2011)
This release of the NDK includes new features to support the Android 4.0 platform as well as many other
additions and improvements:
New features
•
Added official NDK APIs for Android 4.0 (API level 14), which adds the following native
features to the platform:
56
Content from developer.android.com/tools/sdk/ndk/index.html through their Creative Commons Attribution 2.5 license
Android NDK
o
•
Added native multimedia API based on the Khronos Group OpenMAX AL?
1.0.1 standard. The new <OMXAL/OpenMAXAL.h> and
<OMXAL/OpenMAXAL_Android.h> headers allow applications targeting
API level 14 to perform multimedia output directly from native code by using a
new Android-specific buffer queue interface. For more details, see
docs/openmaxal/index.html and http://www.khronos.org/openmax/.
o Updated the native audio API based on the Khronos Group OpenSL ES 1.0.1?
standard. With API Level 14, you can now decode compressed audio (e.g.
MP3, AAC, Vorbis) to PCM. For more details, see
docs/opensles/index.html and http://www.khronos.org/opensles/.
Added CCache support. To speed up large rebuilds, define the NDK_CCACHE
environment variable to ccache (or the path to your ccache binary). When declared,
the NDK build system automatically uses CCache when compiling any source file. For
example:
export NDK_CCACHE=ccache
Note: CCache is not included in the NDK release so you must have it installed prior to using it. For more
information about CCache, see http://ccache.samba.org.
•
Added support for setting APP_ABI to all to indicate that you want to build your NDK modules
for all the ABIs supported by your given NDK release. This means that either one of the following
two lines in your Application.mk are equivalent with this release:
APP_ABI := all
APP_ABI := armeabi armeabi-v7a x86
This also works if you define APP_ABI when calling ndk-build from the command-line,
which is a quick way to check that your project builds for all supported ABIs without changing the
project's Application.mk file. For example:
ndk-build APP_ABI=all
•
•
•
Added a LOCAL_CPP_FEATURES variable in Android.mk that allows you to declare which
C++ features (RTTI or Exceptions) your module uses. This ensures that the final linking works
correctly if you have prebuilt modules that depend on these features. See docs/ANDROIDMK.html and docs/CPLUSPLUS-SUPPORT.html for more details.
Shortened paths to source and object files that are used in build commands. When invoking
$NDK/ndk-build from your project path, the paths to the source, object, and binary files that
are passed to the build commands are significantly shorter now, because they are passed relative
to the current directory. This is useful when building projects with a lot of source files, to avoid
limits on the maximum command line length supported by your host operating system. The
behavior is unchanged if you invoke ndk-build from a sub-directory of your project tree, or if
you define NDK_PROJECT_PATH to point to a specific directory.
Experimental features
57
Content from developer.android.com/tools/sdk/ndk/index.html through their Creative Commons Attribution 2.5 license
Android NDK
You can now build your NDK source files on Windows without Cygwin by calling the ndkbuild.cmd script from the command line from your project path. The script takes exactly the
same arguments as the original ndk-build script. The Windows NDK package comes with its
own prebuilt binaries for GNU Make, Awk and other tools required by the build. You should not
need to install anything else to get a working build system.
Important: ndk-gdb does not work on Windows, so you still need Cygwin to debug.
This feature is still experimental, so feel free to try it and report issues on the public bug database
or public forum. All samples and unit tests shipped with the NDK succesfully compile with this
feature.
Important bug fixes
•
•
•
Imported shared libraries are now installed by default to the target installation location
(libs/<abi>) if APP_MODULES is not defined in your Application.mk. For
example, if a top-level module foo imports a module bar, then both libfoo.so and
libbar.so are copied to the install location. Previously, only libfoo.so was
copied, unless you listed bar in your APP_MODULES too. If you define
APP_MODULES explicitly, the behavior is unchanged.
ndk-gdb now works correctly for activities with multiple categories in their MAIN intent
filters.
Static library imports are now properly transitive. For example, if a top-level module foo
imports static library bar that imports static library zoo, the libfoo.so will now be
linked against both libbar.a and libzoo.a.
Other changes
•
•
•
•
•
•
•
docs/NATIVE-ACTIVITY.HTML: Fixed typo. The minimum API level should be 9,
not 8 for native activities.
docs/STABLE-APIS.html: Added missing documentation listing EGL as a
supported stable API, starting from API level 9.
download-toolchain-sources.sh: Updated to download the toolchain
sources from android.googlesource.com, which is the new location for the AOSP
servers.
Added a new C++ support runtime named gabi++. More details about it are available
in the updated docs/CPLUSPLUS-SUPPORT.html.
Added a new C++ support runtime named gnustl_shared that corresponds to the
shared library version of GNU libstdc++ v3 (GPLv3 license). See more info at
docs/CPLUSPLUS-SUPPORT.html
Added support for RTTI in the STLport C++ runtimes (no support for exceptions).
Added support for multiple file extensions in LOCAL_CPP_EXTENSION. For example,
to compile both foo.cpp and bar.cxx as C++ sources, declare the following:
LOCAL_CPP_EXTENSION := .cpp .cxx
•
Removed many unwanted exported symbols from the link-time shared system libraries provided
by the NDK. This ensures that code generated with the standalone toolchain doesn't risk to
58
Content from developer.android.com/tools/sdk/ndk/index.html through their Creative Commons Attribution 2.5 license
Android NDK
•
accidentally depend on a non-stable ABI symbol (e.g. any libgcc.a symbol that changes each
time the toolchain used to build the platform is changed)
Refreshed the EGL and OpenGLES Khronos headers to support more extensions. Note that this
does not change the NDK ABIs for the corresponding libraries, because each extension must be
probed at runtime by the client application.
The extensions that are available depend on your actual device and GPU drivers, not the platform
version the device runs on. The header changes simply add new constants and types to make it
easier to use the extensions when they have been probed with eglGetProcAddress() or
glGetProcAddress(). The following list describes the newly supported extensions:
GLES 1.x
o
o
o
o
o
o
o
o
o
o
o
o
o
o
o
o
o
o
o
o
o
o
GL_OES_vertex_array_object
GL_OES_EGL_image_external
GL_APPLE_texture_2D_limited_npot
GL_EXT_blend_minmax
GL_EXT_discard_framebuffer
GL_EXT_multi_draw_arrays
GL_EXT_read_format_bgra
GL_EXT_texture_filter_anisotropic
GL_EXT_texture_format_BGRA8888
GL_EXT_texture_lod_bias
GL_IMG_read_format
GL_IMG_texture_compression_pvrtc
GL_IMG_texture_env_enhanced_fixed_function
GL_IMG_user_clip_plane
GL_IMG_multisampled_render_to_texture
GL_NV_fence
GL_QCOM_driver_control
GL_QCOM_extended_get
GL_QCOM_extended_get2
GL_QCOM_perfmon_global_mode
GL_QCOM_writeonly_rendering
GL_QCOM_tiled_rendering
GLES 2.0
o
o
o
o
o
o
o
o
o
o
o
o
o
o
o
GL_OES_element_index_uint
GL_OES_get_program_binary
GL_OES_mapbuffer
GL_OES_packed_depth_stencil
GL_OES_texture_3D
GL_OES_texture_float
GL_OES_texture_float_linear
GL_OES_texture_half_float_linear
GL_OES_texture_npot
GL_OES_vertex_array_object
GL_OES_EGL_image_external
GL_AMD_program_binary_Z400
GL_EXT_blend_minmax
GL_EXT_discard_framebuffer
GL_EXT_multi_draw_arrays
59
Content from developer.android.com/tools/sdk/ndk/index.html through their Creative Commons Attribution 2.5 license
Android NDK
o
o
o
o
o
o
o
o
o
o
o
o
o
o
GL_EXT_read_format_bgra
GL_EXT_texture_format_BGRA8888
GL_EXT_texture_compression_dxt1
GL_IMG_program_binary
GL_IMG_read_format
GL_IMG_shader_binary
GL_IMG_texture_compression_pvrtc
GL_IMG_multisampled_render_to_texture
GL_NV_coverage_sample
GL_NV_depth_nonlinear
GL_QCOM_extended_get
GL_QCOM_extended_get2
GL_QCOM_writeonly_rendering
GL_QCOM_tiled_rendering
o
o
EGL_ANDROID_recordable
EGL_NV_system_time
EGL
Android NDK, Revision 6b (August 2011)
This release of the NDK does not include any new features compared to r6. The r6b release addresses the
following issues in the r6 release:
Important bug fixes
•
•
•
•
•
•
•
Fixed the build when APP_ABI="armeabi x86" is used for multi-architecture
builds.
Fixed the location of prebuilt STLport binaries in the NDK release package. A bug in the
packaging script placed them in the wrong location.
Fixed atexit() usage in shared libraries with the x86standalone toolchain.
Fixed make-standalone-toolchain.sh --arch=x86. It used to fail to copy
the proper GNU libstdc++ binaries to the right location.
Fixed the standalone toolchain linker warnings about missing the definition and size for
the __dso_handle symbol (ARM only).
Fixed the inclusion order of $(SYSROOT)/usr/include for x86 builds. See the
bug for more information.
Fixed the definitions of ptrdiff_t and size_t in x86-specific systems when they
are used with the x86 standalone toolchain.
Android NDK, Revision 6 (July 2011)
This release of the NDK includes support for the x86 ABI and other minor changes. For detailed
information describing the changes in this release, read the CHANGES.HTML document included in the
NDK package.
General notes:
•
Adds support for the x86 ABI, which allows you to generate machine code that runs on
compatible x86-based Android devices. Major features for x86 include x86-specific
toolchains, system headers, libraries and debugging support. For all of the details
regarding x86 support, see docs/CPU-X86.html in the NDK package.
60
Content from developer.android.com/tools/sdk/ndk/index.html through their Creative Commons Attribution 2.5 license
Android NDK
By default, code is generated for ARM-based devices, but you can add x86 to your
APP_ABI definition in your Application.mk file to build for x86 platforms. For
example, the following line instructs ndk-build to build your code for three distinct
ABIs:
APP_ABI := armeabi armeabi-v7a x86
Unless you rely on ARM-based assembly sources, you shouldn't need to touch your Android.mk files
to build x86 machine code.
•
•
You can build a standalone x86 toolchain using the --toolchain=x86-4.4.3 option when
calling make-standalone-toolchain.sh. See docs/STANDALONETOOLCHAIN.html for more details.
The new ndk-stack tool lets you translate stack traces in logcat that are generated by
native code. The tool translates instruction addresses into a readable format that contains things
such as the function, source file, and line number corresponding to each stack frame. For more
information and a usage example, see docs/NDK-STACK.html.
Other changes:
arm-eabi-4.4.0, which had been deprecated since NDK r5, has been removed from the
NDK distribution.
Android NDK, Revision 5c (June 2011)
This release of the NDK does not include any new features compared to r5b. The r5c release addresses
the following problems in the r5b release:
Important bug fixes:
•
•
•
•
•
ndk-build: Fixed a rare bug that appeared when trying to perform parallel builds of
debuggable projects.
Fixed a typo that prevented LOCAL_WHOLE_STATIC_LIBRARIES to work correctly
with the new toolchain and added documentation for this in docs/ANDROIDMK.html.
Fixed a bug where code linked against gnustl_static crashed when run on
platform releases older than API level 8 (Android 2.2).
ndk-gdb: Fixed a bug that caused a segmentation fault when debugging Android 3.0
or newer devices.
<android/input.h>: Two functions that were introduced in API level 9 (Android
2.3) were incorrect and are fixed. While this breaks the source API, the binary interface
to the system is unchanged. The incorrect functions were missing a history_index
parameter, and the correct definitions are shown below:
float AMotionEvent_getHistoricalRawX(const AInputEvent* motion_event,
size_t pointer_index,
size_t history_index);
float AMotionEvent_getHistoricalRawY(const AInputEvent* motion_event,
size_t pointer_index,
size_t history_index);
61
Content from developer.android.com/tools/sdk/ndk/index.html through their Creative Commons Attribution 2.5 license
Android NDK
•
Updated the C library ARM binary for API level 9 (Android 2.3) to correctly expose at link time
new functions that were added in that API level (for example, pthread_rwlock_init).
Minor improvements and fixes:
•
•
•
•
•
•
•
•
•
Object files are now always linked in the order they appear in LOCAL_SRC_FILES.
This was not the case previously because the files were grouped by source extensions
instead.
When import-module fails, it now prints the list of directories that were searched.
This is useful to check that the NDK_MODULE_PATH definition used by the build
system is correct.
When import-module succeeds, it now prints the directory where the module was
found to the log (visible with NDK_LOG=1).
Increased the build speed of debuggable applications when there is a very large number
of include directories in the project.
ndk-gdb: Better detection of adb shell failures and improved error messages.
<pthread.h>: Fixed the definition of PTHREAD_RWLOCK_INITIALIZER for API
level 9 (Android 2.3) and higher.
Fixed an issue where a module could import itself, resulting in an infinite loop in GNU
Make.
Fixed a bug that caused the build to fail if LOCAL_ARM_NEON was set to true (typo in
build/core/build-binary.mk).
Fixed a bug that prevented the compilation of .s assembly files (.S files were okay).
Android NDK, Revision 5b (January 2011)
This release of the NDK does not include any new features compared to r5. The r5b release addresses the
following problems in the r5 release:
•
•
•
•
The r5 binaries required glibc 2.11, but the r5b binaries are generated with a special toolchain
that targets glibc 2.7 or higher instead. The Linux toolchain binaries now run on Ubuntu 8.04 or
higher.
Fixes a compiler bug in the arm-linux-androideabi-4.4.3 toolchain. The previous binary generated
invalid thumb instruction sequences when dealing with signed chars.
Adds missing documentation for the "gnustl_static" value for APP_STL, that allows you to link
against a static library version of GNU libstdc++.
The following ndk-build issues are fixed:
o A bug that created inconsistent dependency files when a compilation error occured on
Windows. This prevented a proper build after the error was fixed in the source code.
o A Cygwin-specific bug where using very short paths for the Android NDK installation or
the project path led to the generation of invalid dependency files. This made incremental
builds impossible.
o A typo that prevented the cpufeatures library from working correctly with the new NDK
toolchain.
o Builds in Cygwin are faster by avoiding calls to cygpath -m from GNU Make for
every source or object file, which caused problems with very large source trees. In case
this doesn't work properly, define NDK_USE_CYGPATH=1 in your environment to use
cygpath -m again.
o The Cygwin installation now notifies the user of invalid installation paths that contain
spaces. Previously, an invalid path would output an error that complained about an
incorrect version of GNU Make, even if the right one was installed.
62
Content from developer.android.com/tools/sdk/ndk/index.html through their Creative Commons Attribution 2.5 license
Android NDK
•
•
•
•
•
Fixed a typo that prevented the NDK_MODULE_PATH environment variable from working
properly when it contained multiple directories separated with a colon.
The prebuilt-common.sh script contains fixes to check the compiler for 64-bit generated
machine code, instead of relying on the host tag, which allows the 32-bit toolchain to rebuild
properly on Snow Leopard. The toolchain rebuild scripts now also support using a 32-bit host
toolchain.
A missing declaration for INET_ADDRSTRLEN was added to <netinet/in.h>.
Missing declarations for IN6_IS_ADDR_MC_NODELOCAL and
IN6_IS_ADDR_MC_GLOBAL were added to <netinet/in6.h>.
'asm' was replaced with '__asm__' in <asm/byteorder.h> to allow compilation with std=c99.
Android NDK, Revision 5 (December 2010)
This release of the NDK includes many new APIs, most of which are introduced to support the
development of games and similar applications that make extensive use of native code. Using the APIs,
developers have direct native access to events, audio, graphics and window management, assets, and
storage. Developers can also implement the Android application lifecycle in native code with help from the
new NativeActivity class. For detailed information describing the changes in this release, read the
CHANGES.HTML document included in the downloaded NDK package.
General notes:
•
•
•
•
•
•
Adds support for native activities, which allows you to implement the Android application
lifecycle in native code.
Adds native support for the following:
o Input subsystem (such as the keyboard and touch screen)
o Access to sensor data (accelerometer, compass, gyroscope, etc).
o Event loop APIs to wait for things such as input and sensor events.
o Window and surface subsystem
o Audio APIs based on the OpenSL ES standard that support playback and
recording as well as control over platform audio effects
o Access to assets packaged in an .apk file.
Includes a new toolchain (based on GCC 4.4.3), which generates better code, and can
also now be used as a standalone cross-compiler, for people who want to build their
stuff with ./configure && make. See docs/STANDALONE-TOOLCHAIN.html for
the details. The binaries for GCC 4.4.0 are still provided, but the 4.2.1 binaries were
removed.
Adds support for prebuilt static and shared libraries (docs/PREBUILTS.html) and module
exports and imports to make sharing and reuse of third-party modules much easier
(docs/IMPORT-MODULE.html explains why).
Provides a default C++ STL implementation (based on STLport) as a helper module. It
can be used either as a static or shared library (details and usage examples are in
sources/android/stlport/README). Prebuilt binaries for STLport (static or shared) and
GNU libstdc++ (static only) are also provided if you choose to compile against those
libraries instead of the default C++ STL implementation. C++ Exceptions and RTTI are
not supported in the default STL implementation. For more information, see
docs/CPLUSPLUS-SUPPORT.HTML.
Includes improvements to the cpufeatures helper library that improves reporting of
the CPU type (some devices previously reported ARMv7 CPU when the device really
was an ARMv6). We recommend developers that use this library to rebuild their
applications then upload to Google Play to benefit from the improvements.
63
Content from developer.android.com/tools/sdk/ndk/index.html through their Creative Commons Attribution 2.5 license
Android NDK
•
•
•
Adds an EGL library that lets you create and manage OpenGL ES textures and services.
Adds new sample applications, native-plasma and native-activity, to
demonstrate how to write a native activity.
Includes many bugfixes and other small improvements; see docs/CHANGES.html for a
more detailed list of changes.
Android NDK, Revision 4b (June 2010)
NDK r4b notes:
Includes fixes for several issues in the NDK build and debugging scripts — if you are using NDK
r4, we recommend downloading the NDK r4b build. For detailed information describing the
changes in this release, read the CHANGES.TXT document included in the downloaded NDK
package.
General notes:
•
•
•
•
•
•
•
•
Provides a simplified build system through the new ndk-build build command.
Adds support for easy native debugging of generated machine code on production
devices through the new ndk-gdb command.
Adds a new Android-specific ABI for ARM-based CPU architectures, armeabi-v7a.
The new ABI extends the existing armeabi ABI to include these CPU instruction set
extensions:
o Thumb-2 instructions
o VFP hardware FPU instructions (VFPv3-D16)
o Optional support for ARM Advanced SIMD (NEON) GCC intrinsics and VFPv3D32. Supported by devices such as Verizon Droid by Motorola, Google Nexus
One, and others.
Adds a new cpufeatures static library (with sources) that lets your app detect the
host device's CPU features at runtime. Specifically, applications can check for ARMv7-A
support, as well as VFPv3-D32 and NEON support, then provide separate code paths as
needed.
Adds a sample application, hello-neon, that illustrates how to use the
cpufeatures library to check CPU features and then provide an optimized code path
using NEON instrinsics, if supported by the CPU.
Lets you generate machine code for either or both of the instruction sets supported by
the NDK. For example, you can build for both ARMv5 and ARMv7-A architectures at the
same time and have everything stored to your application's final .apk.
To ensure that your applications are available to users only if their devices are capable
of running them, Google Play now filters applications based on the instruction set
information included in your application — no action is needed on your part to enable the
filtering. Additionally, the Android system itself also checks your application at install
time and allows the installation to continue only if the application provides a library that is
compiled for the device's CPU architecture.
Adds support for Android 2.2, including a new stable API for accessing the pixel buffers
of Bitmap objects from native code.
Android NDK, Revision 3 (March 2010)
General notes:
•
Adds OpenGL ES 2.0 native library support.
64
Content from developer.android.com/tools/sdk/ndk/index.html through their Creative Commons Attribution 2.5 license
Android NDK
•
•
Adds a sample application,hello-gl2, that illustrates the use of OpenGL ES 2.0
vertex and fragment shaders.
The toolchain binaries have been refreshed for this release with GCC 4.4.0, which
should generate slightly more compact and efficient machine code than the previous one
(4.2.1). The NDK also still provides the 4.2.1 binaries, which you can optionally use to
build your machine code.
Android NDK, Revision 2 (September 2009)
Originally released as "Android 1.6 NDK, Release 1".
General notes:
•
•
Adds OpenGL ES 1.1 native library support.
Adds a sample application, san-angeles, that renders 3D graphics through the
native OpenGL ES APIs, while managing activity lifecycle with a GLSurfaceView
object.
Android NDK, Revision 1 (June 2009)
Originally released as "Android 1.5 NDK, Release 1".
General notes:
•
•
Includes compiler support (GCC) for ARMv5TE instructions, including Thumb-1
instructions.
Includes system headers for stable native APIs, documentation, and sample
applications.
System and Software Requirements
The sections below describe the system and software requirements for using the Android NDK, as well as
platform compatibility considerations that affect appplications using libraries produced with the NDK.
The Android SDK
•
•
A complete Android SDK installation (including all dependencies) is required.
Android 1.5 SDK or later version is required.
Supported operating systems
•
•
•
Windows XP (32-bit) or Vista (32- or 64-bit)
Mac OS X 10.4.8 or later (x86 only)
Linux (32 or 64-bit; Ubuntu 8.04, or other Linux distributions using GLibc 2.7 or later)
Required development tools
•
•
For all development platforms, GNU Make 3.81 or later is required. Earlier versions of GNU Make
might work but have not been tested.
A recent version of awk (either GNU Awk or Nawk) is also required.
65
Content from developer.android.com/tools/sdk/ndk/index.html through their Creative Commons Attribution 2.5 license
Android NDK
•
For Windows, Cygwin 1.7 or higher is required. The NDK will not work with Cygwin 1.5
installations.
Android platform compatibility
•
The native libraries created by the Android NDK can only be used on devices running specific
minimum Android platform versions. The minimum required platform version depends on the CPU
architecture of the devices you are targeting. The following table details which Android platform
versions are compatible with native code developed for specific CPU architectures.
Native Code CPU Architecture Used
Compatible Android Platform(s)
ARM, ARM-NEON
Android 1.5 (API Level 3) and higher
x86
Android 2.3 (API Level 9) and higher
MIPS
Android 2.3 (API Level 9) and higher
•
These requirements mean you can use native libraries produced with the NDK in applications that
are deployable to ARM-based devices running Android 1.5 or later. If you are deploying native
libraries to x86 and MIPS-based devices, your application must target Android 2.3 or later.
•
To ensure compatibility, an application using a native library produced with the NDK must declare
a <uses-sdk> element in its manifest file, with an android:minSdkVersion attribute
value of "3" or higher. For example:
<manifest>
<uses-sdk android:minSdkVersion="3" />
...
</manifest>
•
•
If you use this NDK to create a native library that uses the OpenGL ES APIs, the application
containing the library can be deployed only to devices running the minimum platform versions
described in the table below. To ensure compatibility, make sure that your application declares
the proper android:minSdkVersion attribute value, as shown in the following table.
66
Content from developer.android.com/tools/sdk/ndk/index.html through their Creative Commons Attribution 2.5 license
Android NDK
OpenGL ES Version Compatible Android Platform(s) Required uses-sdk Attribute
Used
OpenGL ES 1.1
Android 1.6 (API Level 4) and
higher
android:minSdkVersion="
4"
OpenGL ES 2.0
Android 2.0 (API Level 5) and
higher
android:minSdkVersion="
5"
•
For more information about API Level and its relationship to Android platform versions, see
Android API Levels.
•
Additionally, an application using the OpenGL ES APIs should declare a <uses-feature>
element in its manifest, with an android:glEsVersion attribute that specifies the minimum
OpenGl ES version required by the application. This ensures that Google Play will show your
application only to users whose devices are capable of supporting your application. For example:
<manifest>
<uses-feature android:glEsVersion="0x00020000" />
...
</manifest>
For more information, see the <uses-feature> documentation.
•
If you use this NDK to create a native library that uses the API to access Android Bitmap pixel
buffers or utilizes native activities, the application containing the library can be deployed only to
devices running Android 2.2 (API level 8) or higher. To ensure compatibility, make sure that your
application declares <uses-sdk android:minSdkVersion="8" /> attribute value in
its manifest.
Installing the NDK
Installing the NDK on your development computer is straightforward and involves extracting the NDK from
its download package.
Before you get started make sure that you have downloaded the latest Android SDK and upgraded your
applications and environment as needed. The NDK is compatible with older platform versions but not older
versions of the SDK tools. Also, take a moment to review the System and Software Requirements for the
NDK, if you haven't already.
To install the NDK, follow these steps:
67
Content from developer.android.com/tools/sdk/ndk/index.html through their Creative Commons Attribution 2.5 license
Android NDK
• From the table at the top of this page, select the NDK package that is appropriate for your development
computer and download the package.
• Uncompress the NDK download package using tools available on your computer. When uncompressed,
the NDK files are contained in a directory called android-ndk-<version>. You can rename the
NDK directory if necessary and you can move it to any location on your computer. This documentation
refers to the NDK directory as <ndk>.
You are now ready to start working with the NDK.
Getting Started with the NDK
Once you've installed the NDK successfully, take a few minutes to read the documentation included in the
NDK. You can find the documentation in the <ndk>/docs/ directory. In particular, please read the
OVERVIEW.HTML document completely, so that you understand the intent of the NDK and how to use it.
If you used a previous version of the NDK, take a moment to review the list of NDK changes in the
CHANGES.HTML document.
Here's the general outline of how you work with the NDK tools:
• Place your native sources under <project>/jni/...
• Create <project>/jni/Android.mk to describe your native sources to the NDK build system
• Optional: Create <project>/jni/Application.mk.
• Build your native code by running the 'ndk-build' script from your project's directory. It is located in the
top-level NDK directory:
cd <project>
<ndk>/ndk-build
The build tools copy the stripped, shared libraries needed by your application to the proper location in the
application's project directory.
• Finally, compile your application using the SDK tools in the usual way. The SDK build tools will package
the shared libraries in the application's deployable .apk file.
For complete information on all of the steps listed above, please see the documentation included with the
NDK package.
Using the NDK
The Android framework provides two ways to use native code:
•
Write your application using the Android framework and use JNI to access the APIs provided by
the Android NDK. This technique allows you to take advantage of the convenience of the Android
framework, but still allows you to write native code when necessary. If you use this approach,
your application must target specific, minimum Android platform levels, see Android platform
compatibility for more information.
•
Write a native activity, which allows you to implement the lifecycle callbacks in native code. The
Android SDK provides the NativeActivity class, which is a convenience class that notifies
your native code of any activity lifecycle callbacks (onCreate(), onPause(),
onResume(), etc). You can implement the callbacks in your native code to handle these
events when they occur. Applications that use native activities must be run on Android 2.3 (API
Level 9) or later.
You cannot access features such as Services and Content Providers natively, so if you want to
use them or any other framework API, you can still write JNI code to do so.
68
Content from developer.android.com/tools/sdk/ndk/index.html through their Creative Commons Attribution 2.5 license
Android NDK
Contents of the NDK
The NDK contains the APIs, documentation, and sample applications that help you write your native code.
Specifically:
•
•
•
•
A set of tools and build files used to generate native code libraries from C and C++ sources
A way to embed the corresponding native libraries into an application package file (.apk) that
can be deployed on Android devices
A set of native system headers and libraries that will be supported in all future versions of the
Android platform, starting from Android 1.5. Applications that use native activities must be run on
Android 2.3 or later.
Documentation, samples, and tutorials
The latest release of the NDK supports the following instruction sets:
•
•
•
•
ARMv5TE, including Thumb-1 instructions (see docs/CPU-ARCH-ABIS.html for more
information)
ARMv7-A, including Thumb-2 and VFPv3-D16 instructions, with optional support for
NEON/VFPv3-D32 instructions (see docs/CPU-ARM-NEON.html for more information)
x86 instructions (see docs/CPU-X86.html for more information)
MIPS instructions (see docs/CPU-MIPS.html for more information)
ARMv5TE machine code will run on all ARM-based Android devices. ARMv7-A will run only on devices
such as the Verizon Droid or Google Nexus One that have a compatible CPU. The main difference
between the two instruction sets is that ARMv7-A supports hardware FPU, Thumb-2, and NEON
instructions. You can target either or both of the instruction sets — ARMv5TE is the default, but switching
to ARMv7-A is as easy as adding a single line to the application's Application.mk file, without
needing to change anything else in the file. You can also build for both architectures at the same time and
have everything stored in the final .apk. Complete information is provided in the CPU-ARCH-ABIS.HTML
in the NDK package.
The NDK provides stable headers for libc (the C library), libm (the Math library), OpenGL ES (3D graphics
library), the JNI interface, and other libraries, as listed in the Development tools section.
Development tools
The NDK includes a set of cross-toolchains (compilers, linkers, etc..) that can generate native ARM
binaries on Linux, OS X, and Windows (with Cygwin) platforms.
It provides a set of system headers for stable native APIs that are guaranteed to be supported in all later
releases of the platform:
•
•
•
•
•
•
•
•
•
•
libc (C library) headers
libm (math library) headers
JNI interface headers
libz (Zlib compression) headers
liblog (Android logging) header
OpenGL ES 1.1 and OpenGL ES 2.0 (3D graphics libraries) headers
libjnigraphics (Pixel buffer access) header (for Android 2.2 and above).
A Minimal set of headers for C++ support
OpenSL ES native audio libraries
Android native application APIS
69
Content from developer.android.com/tools/sdk/ndk/index.html through their Creative Commons Attribution 2.5 license
Android NDK
The NDK also provides a build system that lets you work efficiently with your sources, without having to
handle the toolchain/platform/CPU/ABI details. You create very short build files to describe which sources
to compile and which Android application will use them — the build system compiles the sources and
places the shared libraries directly in your application project.
Important: With the exception of the libraries listed above, native system libraries in the Android platform
are not stable and may change in future platform versions. Your applications should only make use of the
stable native system libraries provided in this NDK.
Documentation
The NDK package includes a set of documentation that describes the capabilities of the NDK and how to
use it to create shared libraries for your Android applications. In this release, the documentation is
provided only in the downloadable NDK package. You can find the documentation in the <ndk>/docs/
directory. Included are these files (partial listing):
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
INSTALL.HTML — describes how to install the NDK and configure it for your host system
OVERVIEW.HTML — provides an overview of the NDK capabilities and usage
ANDROID-MK.HTML — describes the use of the Android.mk file, which defines the native
sources you want to compile
APPLICATION-MK.HTML — describes the use of the Application.mk file, which describes the
native sources required by your Android application
CPLUSPLUS-SUPPORT.HTML — describes the C++ support provided in the Android NDK
CPU-ARCH-ABIS.HTML — a description of supported CPU architectures and how to target them.
CPU-FEATURES.HTML — a description of the cpufeatures static library that lets your
application code detect the target device's CPU family and the optional features at runtime.
CHANGES.HTML — a complete list of changes to the NDK across all releases.
DEVELOPMENT.HTML — describes how to modify the NDK and generate release packages for
it
HOWTO.HTML — information about common tasks associated with NDK development
IMPORT-MODULE.HTML — describes how to share and reuse modules
LICENSES.HTML — information about the various open source licenses that govern the Android
NDK
NATIVE-ACTIVITY.HTML — describes how to implement native activities
NDK-BUILD.HTML — describes the usage of the ndk-build script
NDK-GDB.HTML — describes how to use the native code debugger
PREBUILTS.HTML — information about how shared and static prebuilt libraries work
STANDALONE-TOOLCHAIN.HTML — describes how to use Android NDK toolchain as a
standalone compiler (still in beta).
SYSTEM-ISSUES.HTML — known issues in the Android system images that you should be
aware of, if you are developing using the NDK.
STABLE-APIS.HTML — a complete list of the stable APIs exposed by headers in the NDK.
Additionally, the package includes detailed information about the "bionic" C library provided with the
Android platform that you should be aware of, if you are developing using the NDK. You can find the
documentation in the <ndk>/docs/system/libc/ directory:
•
OVERVIEW.HTML — provides an overview of the "bionic" C library and the features it offers.
Sample apps
70
Content from developer.android.com/tools/sdk/ndk/index.html through their Creative Commons Attribution 2.5 license
Android NDK
The NDK includes sample applications that illustrate how to use native code in your Android applications:
•
•
•
•
•
•
•
•
hello-jni — a simple application that loads a string from a native method implemented in a
shared library and then displays it in the application UI.
two-libs — a simple application that loads a shared library dynamically and calls a native
method provided by the library. In this case, the method is implemented in a static library
imported by the shared library.
san-angeles — a simple application that renders 3D graphics through the native OpenGL ES
APIs, while managing activity lifecycle with a GLSurfaceView object.
hello-gl2 — a simple application that renders a triangle using OpenGL ES 2.0 vertex and
fragment shaders.
hello-neon — a simple application that shows how to use the cpufeatures library to
check CPU capabilities at runtime, then use NEON intrinsics if supported by the CPU.
Specifically, the application implements two versions of a tiny benchmark for a FIR filter loop, a C
version and a NEON-optimized version for devices that support it.
bitmap-plasma — a simple application that demonstrates how to access the pixel buffers of
Android Bitmap objects from native code, and uses this to generate an old-school "plasma"
effect.
native-activity — a simple application that demonstrates how to use the native-app-glue
static library to create a native activity
native-plasma — a version of bitmap-plasma implemented with a native activity.
For each sample, the NDK includes the corresponding C source code and the necessary Android.mk and
Application.mk files. There are located under <ndk>/samples/<name>/ and their source code can
be found under <ndk>/samples/<name>/jni/.
You can build the shared libraries for the sample apps by going into <ndk>/samples/<name>/ then
calling the ndk-build command. The generated shared libraries will be located under
<ndk>/samples/<name>/libs/armeabi/ for (ARMv5TE machine code) and/or
<ndk>/samples/<name>/libs/armeabi-v7a/ for (ARMv7 machine code).
Next, build the sample Android applications that use the shared libraries:
•
•
If you are developing in Eclipse with ADT, use the New Project Wizard to create a new Android
project for each sample, using the "Import from Existing Source" option and importing the source
from <ndk>/samples/<name>/. Then, set up an AVD, if necessary, and build/run the
application in the emulator.
If you are developing with Ant, use the android tool to create the build file for each of the
sample projects at <ndk>/samples/<name>/. Then set up an AVD, if necessary, build your
project in the usual way, and run it in the emulator.
For more information about developing with the Android SDK tools and what you need to do to create,
build, and run your applications, see the Overview section for developing on Android.
Exploring the hello-jni Sample
The hello-jni sample is a simple demonstration on how to use JNI from an Android application. The
HelloJni activity receives a string from a simple C function and displays it in a TextView.
The main components of the sample include:
•
The familiar basic structure of an Android application (an AndroidManifest.xml file, a
src/ and res directories, and a main activity)
71
Content from developer.android.com/tools/sdk/ndk/index.html through their Creative Commons Attribution 2.5 license
Android NDK
•
•
A jni/ directory that includes the implemented source file for the native code as well as the
Android.mk file
A tests/ directory that contains unit test code.
• Create a new project in Eclipse from the existing sample source or use the android tool to update the
project so it generates a build.xml file that you can use to build the sample.
•
•
•
•
•
•
•
•
•
In Eclipse:
Click File > New Android Project...
Select the Create project from existing source radio button.
Select any API level above Android 1.5.
In the Location field, click Browse... and select the <ndk-root>/samples/hello-jni
directory.
Click Finish.
On the command line:
Change to the <ndk-root>/samples/hello-jni directory.
Run the following command to generate a build.xml file:
android update project -p . -s
•
• Compile the native code using the ndk-build command.
cd <ndk-root>/samples/hello-jni
<ndk_root>/ndk-build
•
• Build and install the application as you would a normal Android application. If you are using Eclipse, run
the application to build and install it on a device. If you are using Ant, run the following commands from the
project directory:
ant debug
adb install bin/HelloJni-debug.apk
•
When you run the application on the device, the string Hello JNI should appear on your device. You
can explore the rest of the samples that are located in the <ndk-root>/samples directory for more
examples on how to use the JNI.
Exploring the native-activity Sample Application
The native-activity sample provided with the Android NDK demonstrates how to use the
android_native_app_glue static library. This static library makes creating a native activity easier by
providing you with an implementation that handles your callbacks in another thread, so you do not have to
worry about them blocking your main UI thread. The main parts of the sample are described below:
72
Content from developer.android.com/tools/sdk/ndk/index.html through their Creative Commons Attribution 2.5 license
Android NDK
•
•
The familiar basic structure of an Android application (an AndroidManifest.xml file, a
src/ and res directories). The AndroidManifest.xml declares that the application is native and
specifies the .so file of the native activity. See NativeActivity for the source or see the
<ndk_root>/platforms/samples/nativeactivity/AndroidManifest.xml file.
A jni/ directory contains the native activity, main.c, which uses the
android_native_app_glue.h interface to implement the activity. The Android.mk that
describes the native module to the build system also exists here.
To build this sample application:
• Create a new project in Eclipse from the existing sample source or use the android tool to update the
project so it generates a build.xml file that you can use to build the sample.
•
•
•
•
•
•
•
•
•
In Eclipse:
Click File > New Android Project...
Select the Create project from existing source radio button.
Select any API level above Android 2.3.
In the Location field, click Browse... and select the <ndk-root>/samples/nativeactivity directory.
Click Finish.
On the command line:
Change to the <ndk-root>/samples/native-activity directory.
Run the following command to generate a build.xml file:
android update project -p . -s
•
• Compile the native code using the ndk-build command.
cd <ndk-root>/platforms/samples/android-9/samples/native-activity
<ndk_root>/ndk-build
•
• Build and install the application as you would a normal Android application. If you are using Eclipse, run
the application to build and install it on a device. If you are using Ant, run the following commands in the
project directory, then run the application on the device:
ant debug
adb install bin/NativeActivity-debug.apk
•
73
Content from developer.android.com/tools/sdk/ndk/index.html through their Creative Commons Attribution 2.5 license
Introduction
13.
Introduction
Content from developer.android.com/tools/workflow/index.html through their Creative Commons Attribution 2.5 license
To develop apps for Android devices, you use a set of tools that are included in the Android SDK. Once
you've downloaded and installed the SDK, you can access these tools right from your Eclipse IDE, through
the ADT plugin, or from the command line. Developing with Eclipse 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 Eclipse.
Figure 1. The development process for Android applications.
The basic steps for developing applications (with or without Eclipse) are shown in figure 1. The
development steps encompass four development phases, which include:
74
Content from developer.android.com/tools/workflow/index.html through their Creative Commons Attribution 2.5 license
Introduction
•
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.
•
Development
During this phase you set up and develop your Android project, which contains all of the source
code and resource files for your application. For more information, see Create an Android project.
•
Debugging and Testing
During this phase you build your project into a debuggable .apk package that you can install
and run on the emulator or an Android-powered device. If you are using Eclipse, builds are
generated each time you project is saved. If you're using another IDE, you can build your project
using Ant and install it on a device using adb. For more information, see Build and run your
application.
Next, you debug your application using a JDWP-compliant debugger along with the debugging
and logging tools that are provided with the Android SDK. Eclipse already comes packaged with a
compatible debugger. 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 Eclipse, be familiar with all of the tools below, because you
will have to run them from the command line.
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:
Ant
To compile and build your Android project into an installable .apk file.
Keytool
75
Content from developer.android.com/tools/workflow/index.html through their Creative Commons Attribution 2.5 license
Introduction
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 Eclipse and ADT, tools such as adb and android are automatically called by Eclipse
and ADT 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 Eclipse, such as the adb shell commands. You might
also need to call Keytool and Jarsigner to sign your applications, but you can set up Eclipse to do this
automatically as well.
For more information on the tools provided with the Android SDK, see the Tools section of the
documentation.
Other Third-Party Development Tools
The tools described in this section are not developed by the Android SDK team. The Android Dev Guide
does not provide documentation for these tools. Please refer to the linked documents in each section for
documentation.
Developing in IntelliJ IDEA
IntelliJ IDEA is a powerful Java IDE from JetBrains that provides full-cycle Android development support in
both the free Community Edition and the Ultimate edition.
The IDE ensures compatibility with the latest Android SDK and offers a smart code editor with completion,
quick navigation between code and resources, a graphical debugger, unit testing support using Android
Testing Framework, and the ability to run applications in either the emulator or a USB-connected device.
Links:
76
Content from developer.android.com/tools/workflow/index.html through their Creative Commons Attribution 2.5 license
Introduction
•
•
•
IntelliJ IDEA official website
Android support in IntelliJ IDEA
IntelliJ IDEA Android Tutorials
77
Content from developer.android.com/tools/workflow/index.html through their Creative Commons Attribution 2.5 license
Managing Virtual Devices
14.
Managing Virtual Devices
Content from developer.android.com/tools/devices/index.html through their Creative Commons Attribution 2.5 license
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.
78
Content from developer.android.com/tools/devices/index.html through their Creative Commons Attribution 2.5 license
Managing AVDs with AVD Manager
15.
Managing AVDs with AVD Manager
Content from developer.android.com/tools/devices/managing-avds.html through their Creative Commons Attribution 2.5 license
The AVD Manager is an easy to use user
In this section
interface to manage your AVD (Android Virtual
• Creating an AVD
Device) configurations. An AVD is a device
configuration for the Android emulator that allows
• Hardware options
you to model different configurations of Androidpowered devices. When you start the AVD Manager in Eclipse or navigate to your SDK's tools/
directory and execute android avd. You will see the AVD Manager as shown in figure 1.
Figure 1. Screenshot of the AVD Manager.
From the main screen, you can create, delete, repair and start AVDs as well as see the details of each
AVD.
Creating an AVD
You can create as many AVDs as you would like to test on. It is recommended that you test your
applications on all API levels higher than the target API level for your application.
To create an AVD:
• Start the AVD Manager:
•
•
In Eclipse: select Window > AVD Manager, or click the AVD Manager icon in the Eclipse toolbar.
In other IDEs: Navigate to your SDK's tools/ directory and execute the android tool with no
arguments.
• In the Virtual Devices panel, you'll see a list of existing AVDs. Click New to create a new AVD. The
Create New AVD dialog appears.
79
Content from developer.android.com/tools/devices/managing-avds.html through their Creative Commons Attribution 2.5 license
Managing AVDs with AVD Manager
Figure 2. Screenshot of the Create AVD window
• Fill in the details for the AVD.
Give it a name, a platform target, an SD card size, and a skin (HVGA is default). You can also add specific
hardware features of the emulated device by clicking the New... button and selecting the feature. For a list
of hardware features, see Hardware options.
Note: Be sure to define a target for your AVD that satisfies your application's Build Target (the AVD
platform target must have an API Level equal to or greater than the API Level that your application
compiles against).
• Click Create AVD.
Your AVD is now ready and you can either close the AVD Manager, create more AVDs, or launch an
emulator with the AVD by selecting a device and clicking Start.
80
Content from developer.android.com/tools/devices/managing-avds.html through their Creative Commons Attribution 2.5 license
Managing AVDs with AVD Manager
Hardware options
If you are creating a new AVD, you can specify the following hardware options for the AVD to emulate:
Characteristic
Description
Property
Device ram size
The amount of physical RAM on the
device, in megabytes. Default value is
"96".
hw.ramSize
Touch-screen
support
Whether there is a touch screen or not on hw.touchScreen
the device. Default value is "yes".
Trackball support
Whether there is a trackball on the
device. Default value is "yes".
hw.trackBall
Keyboard support
Whether the device has a QWERTY
keyboard. Default value is "yes".
hw.keyboard
DPad support
Whether the device has DPad keys.
Default value is "yes".
hw.dPad
GSM modem
support
Whether there is a GSM modem in the
device. Default value is "yes".
hw.gsmModem
Camera support
Whether the device has a camera.
Default value is "no".
hw.camera
Maximum horizontal Default value is "640".
camera pixels
hw.camera.maxHorizontalPixels
Maximum vertical
camera pixels
Default value is "480".
hw.camera.maxVerticalPixels
GPS support
Whether there is a GPS in the device.
Default value is "yes".
hw.gps
Battery support
Whether the device can run on a battery. hw.battery
Default value is "yes".
Accelerometer
Whether there is an accelerometer in the hw.accelerometer
81
Content from developer.android.com/tools/devices/managing-avds.html through their Creative Commons Attribution 2.5 license
Managing AVDs with AVD Manager
device. Default value is "yes".
Audio recording
support
Whether the device can record audio.
Default value is "yes".
hw.audioInput
Audio playback
support
Whether the device can play audio.
Default value is "yes".
hw.audioOutput
SD Card support
Whether the device supports
insertion/removal of virtual SD Cards.
Default value is "yes".
hw.sdCard
Cache partition
support
Whether we use a /cache partition on the disk.cachePartition
device. Default value is "yes".
Cache partition size Default value is "66MB".
Abstracted LCD
density
disk.cachePartition.size
Sets the generalized density
hw.lcd.density
characteristic used by the AVD's screen.
Default value is "160".
82
Content from developer.android.com/tools/devices/managing-avds.html through their Creative Commons Attribution 2.5 license
Managing AVDs from the Command Line
16.
Managing AVDs from the Command Line
Content from developer.android.com/tools/devices/managing-avds-cmdline.html through their Creative Commons Attribution 2.5 license
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.
In this section
Listing Targets
• Customize the device resolution or density
• Listing Targets
• Creating AVDs
• Default location of AVD files
To generate a list of system image targets, use
this command:
• Setting hardware emulation options
• Moving an AVD
android list targets
• Updating an AVD
The android tool scans the
<sdk>/platforms/ and <sdk>/addons/ directories looking for valid system images
and then generates the list of targets. Here's an
example of the command output:
• Deleting an AVD
See also
• Building and Running from the Command
Line
• Using the Android Emulator
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
83
Content from developer.android.com/tools/devices/managing-avds-cmdline.html through their Creative Commons Attribution 2.5 license
Managing AVDs from the Command Line
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:
• 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
84
Content from developer.android.com/tools/devices/managing-avds-cmdline.html through their Creative Commons Attribution 2.5 license
Managing AVDs from the Command Line
•
• 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.
• Continue through the various profile settings until the tool asks you to specify "Abstracted LCD density"
(hw.lcd.density). Enter an appropriate value, such as "120" for a low-density screen, "160" for a medium
density screen, or "240" for a high-density screen.
• 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
Description
Property
Device ram size
The amount of physical RAM on the
device, in megabytes. Default value is
"96".
hw.ramSize
85
Content from developer.android.com/tools/devices/managing-avds-cmdline.html through their Creative Commons Attribution 2.5 license
Managing AVDs from the Command Line
Touch-screen
support
Whether there is a touch screen or not on hw.touchScreen
the device. Default value is "yes".
Trackball support
Whether there is a trackball on the
device. Default value is "yes".
hw.trackBall
Keyboard support
Whether the device has a QWERTY
keyboard. Default value is "yes".
hw.keyboard
DPad support
Whether the device has DPad keys.
Default value is "yes".
hw.dPad
GSM modem
support
Whether there is a GSM modem in the
device. Default value is "yes".
hw.gsmModem
Camera support
Whether the device has a camera.
Default value is "no".
hw.camera
Maximum horizontal Default value is "640".
camera pixels
hw.camera.maxHorizontalPixels
Maximum vertical
camera pixels
Default value is "480".
hw.camera.maxVerticalPixels
GPS support
Whether there is a GPS in the device.
Default value is "yes".
hw.gps
Battery support
Whether the device can run on a battery. hw.battery
Default value is "yes".
Accelerometer
Whether there is an accelerometer in the hw.accelerometer
device. Default value is "yes".
Audio recording
support
Whether the device can record audio.
Default value is "yes".
hw.audioInput
Audio playback
support
Whether the device can play audio.
Default value is "yes".
hw.audioOutput
SD Card support
Whether the device supports
insertion/removal of virtual SD Cards.
hw.sdCard
86
Content from developer.android.com/tools/devices/managing-avds-cmdline.html through their Creative Commons Attribution 2.5 license
Managing AVDs from the Command Line
Default value is "yes".
Cache partition
support
Whether we use a /cache partition on the disk.cachePartition
device. Default value is "yes".
Cache partition size Default value is "66MB".
disk.cachePartition.size
Abstracted LCD
density
Sets the generalized density
hw.lcd.density
characteristic used by the AVD's screen.
Default value is "160".
Trackball support
Whether there is a trackball present.
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.
87
Content from developer.android.com/tools/devices/managing-avds-cmdline.html through their Creative Commons Attribution 2.5 license
Using the Emulator
17.
Using the Emulator
Content from developer.android.com/tools/devices/emulator.html through
their Creative Commons Attribution 2.5 license
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.
In this section
• Overview
• Android Virtual Devices and the Emulator
• Starting and Stopping the Emulator
• Installing Applications on the Emulator
• Using Hardware Acceleration
• Configuring Graphics Acceleration
• Configuring Virtual Machine Acceleration
• SD Card Emulation
• Creating an SD card image
• Copying files to an SD card image
• Loading an SD card image
• Working with Emulator Disk Images
• Default image files
• Runtime images: user data and SD card
• Temporary images
• Emulator Networking
• Network Address Space
• Local Networking Limitations
• Using Network Redirection
• Configuring the Emulator's DNS Settings
• Using the Emulator with a Proxy
• Interconnecting Emulator Instances
• Sending a Voice Call or SMS to Another
Emulator Instance
• Using the Emulator Console
• Port Redirection
• Geo Location Provider Emulation
• Hardware Events Emulation
• Device Power Characteristics
• Network Status
• Network Delay Emulation
• Network Speed Emulation
• Telephony Emulation
• SMS Emulation
• VM State
• Emulator Window
• Terminating an Emulator Instance
• Emulator Limitations
• Troubleshooting Emulator Problems
See also
• Android Emulator
• Managing AVDs with AVD Manager
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.
88
Content from developer.android.com/tools/devices/emulator.html through their Creative Commons Attribution 2.5 license
Using the Emulator
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 Eclipse 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:
89
Content from developer.android.com/tools/devices/emulator.html through their Creative Commons Attribution 2.5 license
Using the Emulator
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.
If you are working in Eclipse, the ADT plugin for Eclipse installs your application and starts the emulator
automatically, when you run or debug the application. 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 Eclipse, 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 Eclipse or the ADT Plugin, 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:
90
Content from developer.android.com/tools/devices/emulator.html through their Creative Commons Attribution 2.5 license
Using the Emulator
• Make sure you have the required SDK components installed (listed above).
• 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.
• 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.
• 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.
• 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 Eclipse, run your Android application using an AVD with the
-gpu on option enabled:
In Eclipse, click your Android project folder and then select Run > Run Configurations...
In the left panel of the Run Configurations dialog, select your Android project run configuration
or create a new configuration.
Click the Target tab.
Select the AVD you created in the previous procedure.
In the Additional Emulator Command Line Options field, enter:
-gpu on
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 system’s 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)
91
Content from developer.android.com/tools/devices/emulator.html through their Creative Commons Attribution 2.5 license
Using the Emulator
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:
• 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.
• 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.
• Name the emulator instance and select any other configuration options.
• 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)
92
Content from developer.android.com/tools/devices/emulator.html through their Creative Commons Attribution 2.5 license
Using the Emulator
To install the virtualization driver:
• Start the Android SDK Manager, select Extras and then select Intel Hardware Accelerated Execution
Manager.
• After the download completes, execute
<sdk>/extras/intel/Hardware_Accelerated_Execution_Manager/IntelHAXM.
exe.
• Follow the on-screen instructions to complete installation.
• 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 Eclipse, run your Android application with an x86-based
AVD:
In Eclipse, click your Android project folder and then select Run > Run Configurations...
In the left panel of the Run Configurations dialog, select your Android project run configuration
or create a new configuration.
Click the Target tab.
Select the x86-based AVD you created previously.
Run your Android project using this run configuration.
You can adjust the amount of memory available to the Intel HAXM kernel extension by re-running its
installer.
You can stop using the virtualization driver by uninstalling it. Re-run the installer or use the Control Panel
to remove the software.
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
93
Content from developer.android.com/tools/devices/emulator.html through their Creative Commons Attribution 2.5 license
Using the Emulator
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:
• Start the Android SDK Manager, select Extras and then select Intel Hardware Accelerated Execution
Manager.
• After the download completes, execute
<sdk>/extras/intel/Hardware_Accelerated_Execution_Manager/IntelHAXM.
dmg.
• Double click the IntelHAXM.mpkg icon to begin installation.
• Follow the on-screen instructions to complete installation.
• 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 Eclipse, run your Android application with an x86-based
AVD:
In Eclipse, click your Android project folder and then select Run > Run Configurations...
In the left panel of the Run Configurations dialog, select your Android project run configuration
or create a new configuration.
Click the Target tab.
Select the x86-based AVD you created previously.
Run your Android project using this run configuration.
You can adjust the amount of memory available to the Intel HAXM kernel extension by re-running the
installer.
You can stop using the virtualization kernel driver by uninstalling it. Before removing it, shut down any
running x86 emulators. To unload the virtualization kernel driver, run the following command in a terminal
window:
94
Content from developer.android.com/tools/devices/emulator.html through their Creative Commons Attribution 2.5 license
Using the Emulator
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 Eclipse, run your Android application with an x86-based AVD
and include the KVM options:
In Eclipse, click your Android project folder and then select Run > Run Configurations...
In the left panel of the Run Configurations dialog, select your Android project run configuration
or create a new configuration.
Click the Target tab.
Select the x86-based AVD you created previously.
In the Additional Emulator Command Line Options field, enter:
-qemu -m 512 -enable-kvm
•
•
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.
95
Content from developer.android.com/tools/devices/emulator.html through their Creative Commons Attribution 2.5 license
Using the Emulator
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
96
Content from developer.android.com/tools/devices/emulator.html through their Creative Commons Attribution 2.5 license
Using the Emulator
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 readonly. 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
Description
Comments
userdata.img The initial user-data disk image 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.
97
Content from developer.android.com/tools/devices/emulator.html through their Creative Commons Attribution 2.5 license
Using the Emulator
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
Comments
userdata- An image to which the emulator
qemu.img
writes runtime user-data for a
unique user.
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.
sdcard.img An image representing an SD
card inserted into the emulated
device.
Override using -sdcard <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.
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.
98
Content from developer.android.com/tools/devices/emulator.html through their Creative Commons Attribution 2.5 license
Using the Emulator
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 /
10.0.2.6
Optional second, third and fourth DNS server (if any)
10.0.2.15
The emulated device's own network/ethernet interface
127.0.0.1
The emulated device's own loopback interface
99
Content from developer.android.com/tools/devices/emulator.html through their Creative Commons Attribution 2.5 license
Using the Emulator
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:
100
Content from developer.android.com/tools/devices/emulator.html through their Creative Commons Attribution 2.5 license
Using the Emulator
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 -http-proxy
<proxy> option when starting the emulator, to set up the appropriate redirection. In this case, you
specify proxy information in <proxy> in one of these formats:
http://<machineName>:<port>
or
http://<username>:<password>@<machineName>:<port>
The -http-proxy option forces the emulator to use the specified HTTP/HTTPS proxy for all outgoing
TCP connections. Redirection for UDP is not currently supported.
101
Content from developer.android.com/tools/devices/emulator.html through their Creative Commons Attribution 2.5 license
Using the Emulator
Alternatively, you can define the environment variable http_proxy to the value you want to use for
<proxy>. In this case, you do not need to specify a value for <proxy> in the -http-proxy
command — the emulator checks the value of the http_proxy environment variable at startup and
uses its value automatically, if defined.
You can use the -verbose-proxy option to diagnose proxy connection problems.
Interconnecting Emulator Instances
To allow one emulator instance to communicate with another, you must set up the necessary network
redirection as illustrated below.
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:
• Set up the server on B, listening to 10.0.2.15:<serverPort>
• On B's console, set up a redirection from A:localhost:<localPort> to
B:10.0.2.15:<serverPort>
• 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:
• Launch the dialer application on the originating emulator instance.
• 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>).
• 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,
102
Content from developer.android.com/tools/devices/emulator.html through their Creative Commons Attribution 2.5 license
Using the Emulator
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>
103
Content from developer.android.com/tools/devices/emulator.html through their Creative Commons Attribution 2.5 license
Using the Emulator
The redir command supports the subcommands listed in the table below.
Subcommand
Description
Comments
list
List the current port
redirection.
add <protocol>:<host- Add a new port redirection.
port>:<guest-port>
•
•
•
del <protocol>:<host- Delete 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
Description
Comments
fix <longitude>
<latitude>
[<altitude>]
Send a simple GPS fix to the
emulator instance.
Specify longitude and latitude in
decimal degrees. Specify altitude in
meters.
nmea <sentence>
Send an NMEA 0183 sentence
to the emulated device, as if it
were sent from an emulated
GPS modem.
<sentence> must begin with
'$GP'. Only '$GPGGA' and
'$GPRCM' sentences are 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.
104
Content from developer.android.com/tools/devices/emulator.html through their Creative Commons Attribution 2.5 license
Using the Emulator
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 listed in the table below.
Subcommand
Description
Comments
send
Send one or more events to You can use text names or
<type>:<code>:<value> the Android kernel.
integers for <type> and
[...]
<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>.
event text <message> Simulate keypresses to
The message must be a UTF-8
send the specified string of string. Unicode posts will be
characters as a message, 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>
105
Content from developer.android.com/tools/devices/emulator.html through their Creative Commons Attribution 2.5 license
Using the Emulator
The event command supports the subcommands listed in the table below.
Subcommand
Description Comments
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.
health
Set battery
<unknown|good|overheat|dead|overvoltage|failure> health
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
106
Content from developer.android.com/tools/devices/emulator.html through their Creative Commons Attribution 2.5 license
Using the Emulator
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
107
Content from developer.android.com/tools/devices/emulator.html through their Creative Commons Attribution 2.5 license
Using the Emulator
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
call
<phonenumber>
Simulate an inbound
phone call from
<phonenumber>.
Comments
108
Content from developer.android.com/tools/devices/emulator.html through their Creative Commons Attribution 2.5 license
Using the Emulator
accept
<phonenumber>
Accept an inbound call You can change a call's state to "active" only if
from <phonenumber> its current state is "waiting" or "held".
and change the call's
state "active".
busy
<phonenumber>
Close an outbound call You can change a call's state to "busy" only if
to <phonenumber> and its current state is "waiting".
change the call's state
to "busy".
cancel
<phonenumber>
Terminate an inbound
or outbound phone call
to/from
<phonenumber>.
data <state>
Change the state of the Supported <state> values are:
GPRS data connection
to <state>.
• unregistered -- No network
available
• home -- On local network, nonroaming
• roaming -- On roaming network
• searching -- Searching networks
• denied -- Emergency calls only
• off -- Same as 'unregistered'
• on -- same as 'home'
hold
Change the state of a
call to "held".
list
List all inbound and
outbound calls and
their states.
voice <state>
Change the state of the Supported <state> values are:
GPRS voice
connection to <state>.
• unregistered -- No network
available
• home -- On local network, nonroaming
• roaming -- On roaming network
• searching -- Searching networks
• denied -- Emergency calls only
• off -- Same as 'unregistered'
• on -- Same as 'home'
status
Report the current
You can change a call's state to "held" only if its
current state is "active" or "waiting".
Values are those described for the voice and
109
Content from developer.android.com/tools/devices/emulator.html through their Creative Commons Attribution 2.5 license
Using the Emulator
GSM voice/data state. data commands.
SMS Emulation
The Android emulator console lets you generate an SMS message and direct it to an emulator instance.
Once you connect to an emulator instance, you can generate an emulated incoming SMS using the
following command:
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 listed in the table below.
Subcommand
Description
Comments
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).
Emulator Window
You can use the window command to manage the emulator window. The syntax for this command is as
follows:
window <scale>
110
Content from developer.android.com/tools/devices/emulator.html through their Creative Commons Attribution 2.5 license
Using the Emulator
The vm command supports the subcommands listed in the table below.
Subcommand
Description
Comments
scale <scale>
Scale the emulator window.
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.
Terminating an Emulator Instance
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.
111
Content from developer.android.com/tools/devices/emulator.html through their Creative Commons Attribution 2.5 license
Using Hardware Devices
18.
Using Hardware Devices
Content from developer.android.com/tools/device.html through their Creative Commons Attribution 2.5 license
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.
In this section
• Setting up a Device for Development
• USB Vendor IDs
See also
• Google USB Driver
You can use any Android-powered device as an
environment for running, debugging, and testing
• OEM USB Drivers
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 Eclipse or from the command line with ADB. If you don't yet have a
device, check with the service providers in your area to determine which Android-powered devices are
available.
If you want a SIM-unlocked phone, then you might consider a Nexus phone. To find a place to purchase
the Nexus S and other Android-powered devices, visit google.com/phone.
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.
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:
• Declare your application as "debuggable" in your Android Manifest.
When using Eclipse, you can skip this step, because running your app directly from the Eclipse IDE
automatically enables debugging.
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 before you build for
release (your published application should usually not be debuggable).
• Enable USB debugging on your device.
•
•
On most devices running Android 3.2 or older, you can find the option under Settings >
Applications > Development.
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.
• Set up your system to detect your device.
•
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.
112
Content from developer.android.com/tools/device.html through their Creative Commons Attribution 2.5 license
Using Hardware Devices
•
•
•
If you're developing on Mac OS X, it just works. Skip this step.
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:
Log in as root and create this file: /etc/udev/rules.d/51-android.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.
•
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 Eclipse, 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
USB Vendor ID
Acer
0502
ASUS
0b05
113
Content from developer.android.com/tools/device.html through their Creative Commons Attribution 2.5 license
Using Hardware Devices
Dell
413c
Foxconn
0489
Fujitsu
04c5
Fujitsu Toshiba
04c5
Garmin-Asus
091e
Google
18d1
Haier
201E
Hisense
109b
HTC
0bb4
Huawei
12d1
K-Touch
24e3
KT Tech
2116
Kyocera
0482
Lenovo
17ef
LG
1004
Motorola
22b8
MTK
0e8d
NEC
0409
114
Content from developer.android.com/tools/device.html through their Creative Commons Attribution 2.5 license
Using Hardware Devices
Nook
2080
Nvidia
0955
OTGV
2257
Pantech
10a9
Pegatron
1d4d
Philips
0471
PMC-Sierra
04da
Qualcomm
05c6
SK Telesys
1f53
Samsung
04e8
Sharp
04dd
Sony
054c
Sony Ericsson
0fce
Teleepoch
2340
Toshiba
0930
ZTE
19d2
115
Content from developer.android.com/tools/device.html through their Creative Commons Attribution 2.5 license
OEM USB Drivers
19.
OEM USB Drivers
Content from developer.android.com/tools/extras/oem-usb.html through their Creative Commons Attribution 2.5 license
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.
In this section
• Installing a USB Driver
• Windows 7
• Windows XP
• Windows Vista
• OEM Drivers
See also
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.
• Using Hardware Devices
• Google USB Driver
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.
• Windows 7
• Windows XP
• 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:
• Connect your Android-powered device to your computer's USB port.
• Right-click on Computer from your desktop or Windows Explorer, and select Manage.
• Select Devices in the left pane.
• Locate and expand Other device in the right pane.
• Right-click the device name (such as Nexus S) and select Update Driver Software. This will launch the
Hardware Update Wizard.
• Select Browse my computer for driver software and click Next.
• Click Browse and locate the USB driver folder. (The Google USB Driver is located in
<sdk>\extras\google\usb_driver\.)
• Click Next to install the driver.
116
Content from developer.android.com/tools/extras/oem-usb.html through their Creative Commons Attribution 2.5 license
OEM USB Drivers
Or, to upgrade an existing Android USB driver on Windows 7 with the new driver:
• Connect your Android-powered device to your computer's USB port.
• Right-click on Computer from your desktop or Windows Explorer, and select Manage.
• Select Device Manager in the left pane of the Computer Management window.
• Locate and expand Android Phone in the right pane.
• Right-click Android Composite ADB Interface and select Update Driver. This will launch the Hardware
Update Wizard.
• Select Install from a list or specific location and click Next.
• Select Search for the best driver in these locations; un-check Search removable media; and check
Include this location in the search.
• Click Browse and locate the USB driver folder. (The Google USB Driver is located in
<sdk>\extras\google\usb_driver\.)
• Click Next to upgrade the driver.
Windows XP
To install the Android USB driver on Windows XP for the first time:
• Connect your Android-powered device to your computer's USB port. Windows will detect the device and
launch the Hardware Update Wizard.
• Select Install from a list or specific location and click Next.
• Select Search for the best driver in these locations; un-check Search removable media; and check
Include this location in the search.
• Click Browse and locate the USB driver folder. (The Google USB Driver is located in
<sdk>\extras\google\usb_driver\.)
• Click Next to install the driver.
Or, to upgrade an existing Android USB driver on Windows XP with the new driver:
• Connect your Android-powered device to your computer's USB port.
• Right-click on My Computer from your desktop or Windows Explorer, and select Manage.
• Select Device Manager in the left pane.
• Locate and expand Android Phone in the right pane.
• Right-click Android Composite ADB Interface and select Update Driver. This will launch the Hardware
Update Wizard.
• Select Install from a list or specific location and click Next.
• Select Search for the best driver in these locations; un-check Search removable media; and check
Include this location in the search.
• Click Browse and locate the USB driver folder. (The Google USB Driver is located in
<sdk>\extras\google\usb_driver\.)
• Click Next to upgrade the driver.
Windows Vista
To install the Android USB driver on Windows Vista for the first time:
• Connect your Android-powered device to your computer's USB port. Windows will detect the device and
launch the Found New Hardware wizard.
• Select Locate and install driver software.
117
Content from developer.android.com/tools/extras/oem-usb.html through their Creative Commons Attribution 2.5 license
OEM USB Drivers
• Select Don't search online.
• Select I don't have the disk. Show me other options.
• Select Browse my computer for driver software.
• 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.
• Click Next. Vista may prompt you to confirm the privilege elevation required for driver installation.
Confirm it.
• 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:
• Connect your Android-powered device to your computer's USB port.
• Right-click on Computer from your desktop or Windows Explorer, and select Manage.
• Select Device Manager in the left pane.
• Locate and expand ADB Interface in the right pane.
• Right-click on HTC Dream Composite ADB Interface, and select Update Driver Software.
• 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.
• 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.
• Click Next. Vista might prompt you to confirm the privilege elevation required for driver installation.
Confirm it.
• 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
Driver URL
Acer
http://www.acer.com/worldwide/support/mobile.html
ALCATEL ONE
http://www.alcatelonetouch.com/global-en/support/faq/usbdriver.html
TOUCH
Asus
http://support.asus.com/download/
Dell
http://support.dell.com/support/downloads/index.aspx?c=us&cs=19&l=en&s=dh
s&~ck=anavml
118
Content from developer.android.com/tools/extras/oem-usb.html through their Creative Commons Attribution 2.5 license
OEM USB Drivers
Foxconn
http://drivers.cmcs.com.tw/
Fujitsu
http://www.fmworld.net/product/phone/sp/android/develop/
Garmin-Asus
https://www.garminasus.com/en_US/support/pcsync/
Hisense
http://app.hismarttv.com/dss/resourcecontent.do?method=viewResourceDetail
&resourceId=16&type=5
HTC
http://www.htc.com
Click on the support tab to select your products/device. Different regions will
have different links.
Huawei
http://www.huaweidevice.com/worldwide/downloadCenter.do?method=index
Intel
http://www.intel.com/software/android
KT Tech
http://www.kttech.co.kr/cscenter/download05.asp for EV-S100 (Take)
Kyocera
http://www.kyocera-wireless.com/support/phone_drivers.htm
Lenovo
http://developer.lenovomm.com/developer/download.jsp
LGE
http://www.lg.com/us/mobile-phones/mobile-support/mobile-lg-mobile-phonesupport.jsp
Motorola
http://developer.motorola.com/docstools/USB_Drivers/
MTK
http://online.mediatek.com/Public%20Documents/MTK_Android_USB_Driver.zi
p
Oppo
http://www.oppo.com/index.php?q=software/view&sw_id=631
Pantech
http://www.isky.co.kr/cs/software/software.sky?fromUrl=index
Pegatron
http://www.pegatroncorp.com/download/New_Duke_PC_Driver_0705.zip (ZIP
download)
119
Content from developer.android.com/tools/extras/oem-usb.html through their Creative Commons Attribution 2.5 license
OEM USB Drivers
Samsung
http://www.samsung.com/us/support/downloads
Sharp
http://k-tai.sharp.co.jp/support/
SK Telesys
http://www.sk-w.com/service/wDownload/wDownload.jsp
Sony Mobile
http://developer.sonymobile.com/downloads/drivers/
Communications
Teleepoch
http://www.teleepoch.com/android.html
Toshiba
http://support.toshiba.com/sscontent?docId=4001814
Yulong Coolpad http://www.yulong.com/product/product/product/downloadList.html#downListUL
Xiaomi
http://www.xiaomi.com/c/driver/index.html
ZTE
http://support.zte.com.cn/support/news/NewsDetail.aspx?newsId=1000442
120
Content from developer.android.com/tools/extras/oem-usb.html through their Creative Commons Attribution 2.5 license
Managing Projects
20.
Managing Projects
Content from developer.android.com/tools/projects/index.html through their Creative Commons Attribution 2.5 license
Projects act as containers for storing things such
as code and resource files. The SDK tools expect
your projects to follow a specific structure so it can
compile and package your application correctly,
so it is highly recommended that you create them
with Eclipse and ADT or with the android tool
on the command line. There are three types of
projects, and they all share the same general
structure but differ in function:
In this section
• Android Projects
• Library Projects
• Development considerations
• Test Projects
• Testing a Library Project
Android Projects
An Android project is the container for your application's source code, resource files, and files
such as the Ant build and Android Manifest file. An application project is the main type of project
and the contents are eventually built into an .apk file that you install on a device.
Test Projects
These projects contain code to test your application projects and are built into applications that
run on a device.
Library Projects
These projects 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
projects cannot be installed onto a device, however, they are pulled into the .apk file at build
time.
When you use the Android development tools to create a new project, 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 the Eclipse plugin or the android tool to generate your project. As your application
grows in complexity, you might require new kinds of resources, directories, and files.
Android Projects
Android projects are the projects that eventually get built into an .apk file that you install onto a device.
They contain things such as application source code and resource files. Some are generated for you by
default, while others should be created if required. The following directories and files comprise an Android
project:
src/
Contains your stub Activity file, which is stored at
src/your/package/namespace/ActivityName.java. All other source code files (such as
.java or .aidl files) go here as well.
bin/
Output directory of the build. This is where you can find the final .apk file and other compiled
resources.
jni/
Contains native code sources developed using the Android NDK. For more information, see the
Android NDK documentation.
gen/
121
Content from developer.android.com/tools/projects/index.html through their Creative Commons Attribution 2.5 license
Managing Projects
Contains the Java files generated by ADT, such as your R.java file and interfaces created from
AIDL files.
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.
res/
Contains application resources, such as drawable files, layout files, and string values. 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 instead of in the assets/ directory only
differs in the way that 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 are compiled into many kinds of resource. 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 is defined within them 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.
libs/
Contains private libraries.
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
122
Content from developer.android.com/tools/projects/index.html through their Creative Commons Attribution 2.5 license
Managing Projects
project.properties
This file contains project settings, such as the build target. This file is integral to the project, so
maintain it in a source revision control system. To edit project properties in Eclipse, right-click the
project folder and select Properties.
local.properties
Customizable computer-specific properties for the build system. If you use Ant to build the project,
this contains 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. If you use Eclipse, this file is not used.
ant.properties
Customizable properties for the build system. You can edit this file to override default build
settings used by Ant and also provide 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. If you use Eclipse, this file is not used.
build.xml
The Ant build file for your project. This is only applicable for projects that you build with Ant.
Library Projects
An Android library project is a development project
that holds shared Android source code and
resources. Other Android application projects can
reference the library project and, at build time,
include its compiled sources in their .apk files.
Multiple application projects can reference the
same library project and any single application
project can reference multiple library projects.
Note: You need SDK Tools r14 or newer to use
the new library project feature that generates each
library project into its own JAR file. You can
download the tools and platforms using the
Android SDK Manager, as described in Exploring
the SDK.
Library project example code
The SDK includes an example application
called T ic T a cT o eM a in that shows how a
dependent application can use code and
resources from an Android Library project.
The TicTacToeMain application uses code
and resources from an example library project
called TicTacToeLib.
To download the sample applications and run
them as projects in your environment, use the
Android SDK Manager to download the
"Samples for SDK API 8" (or later) package
into your SDK.
For more information and to browse the code
If you have source code and resources that are
of the samples, see the TicTacToeMain
common to multiple Android projects, you can
application.
move them to a library project so that it is easier to
maintain across applications and versions. Here
are some common scenarios in which you could make use of library projects:
•
•
If you are developing multiple related applications that use some of the same components, you
move the redundant components out of their respective application projects and create a single,
reuseable set of the same components in a library project.
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 project. The two dependent projects,
with their different package names, will reference the library project and provide only the
difference between the two application versions.
Structurally, a library project is similar to a standard Android application project. For example, it includes a
manifest file at the project root, as well as src/, res/ and similar directories. The project can contain
123
Content from developer.android.com/tools/projects/index.html through their Creative Commons Attribution 2.5 license
Managing Projects
the same types of source code and resources as a standard Android project, stored in the same way. For
example, source code in the library project can access its own resources through its R class.
However, a library project differs from a standard Android application project in that you cannot compile it
directly to its own .apk and run it on an Android device. Similarly, you cannot export the library project 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 project, the SDK tools compile the library into a
temporary JAR file and uses it in the main project, 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 project 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 projects, 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 projects to your Android project, 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 projects can reference other library projects and can import an external library (JAR) in the normal
way.
Development considerations
As you develop your library project and dependent applications, keep the points listed below in mind:
•
Resource conflicts
Since the tools merge the resources of a library project with those of a dependent application
project, a given resource ID might be defined in both projects. 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 highestpriority 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 project (or is unique across all projects).
•
You cannot export a library project 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 project can include a JAR library
You can develop a library project that itself includes a JAR library, however you need to manually
edit the dependent application project's build path and add a path to the JAR file.
•
A library project can depend on an external JAR library
You can develop a library project 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 project
and the dependent application must declare the external library in their manifest files, in a
<uses-library> element.
•
Library projects cannot include raw assets
124
Content from developer.android.com/tools/projects/index.html through their Creative Commons Attribution 2.5 license
Managing Projects
The tools do not support the use of raw asset files (saved in the assets/ directory) in a library
project. Any asset resources used by an application must be stored in the assets/ directory of
the application project itself. However, resource files saved in the res/ directory are supported.
•
Platform version must be lower than or equal to the Android project
A library is compiled as part of the dependent application project, so the API used in the library
project must be compatible with the version of the Android library used to compile the application
project. In general, the library project should use an API level that is the same as — or lower than
— that used by the application. If the library project uses an API level that is higher than that of
the application, the application project 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) project, for instance.
•
No restriction on library package 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 project creates its own R class
When you build the dependent application project, library projects are compiled and merged with
the application project. Each library has its own R class, named according to the library's package
name. The R class generated from main project and the library project is created in all the
packages that are needed including the main project's package and the libraries' packages.
•
Library project storage location
There are no specific requirements on where you should store a library project, relative to a
dependent application project, as long as the application project can reference the library project
by a relative link. What is important is that the main project can reference the library project
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 file structure of a test project is the same as an Android project.
src/
Includes your test source files. Test projects do not require an Activity .java file, but can
include one.
gen/
This contains the Java files generated by ADT, such as your R.java file and interfaces created
from AIDL files.
assets/
This is empty. You can use it to store raw asset files.
res/
A folder for your application resources, such as drawable files, layout files, string values, etc. See
Application Resources.
AndroidManifest.xml
The Android Manifest for your project. See The AndroidManifest.xml File. Test Projects have a
special <instrumentation> element that connects the test project with the application
project.
project.properties
125
Content from developer.android.com/tools/projects/index.html through their Creative Commons Attribution 2.5 license
Managing Projects
This file contains project settings, such as the build target and links to the project being tested.
This file is integral to the project, so maintain it in a source revision control system. To edit project
properties in Eclipse, right-click the project folder and select Properties.
local.properties
Customizable computer-specific properties for the build system. If you use Ant to build the project,
this contains the path to the SDK installation. Because the content of the file is specific to the
local installation of the SDK, it should not be maintained in a Source Revision Control system. If
you use Eclipse, this file is not used.
ant.properties
Customizable properties for the build system. You can edit this file to override default build
settings used by Ant and provide the location to 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. If you use Eclipse, this file is not used.
build.xml
The Ant build file for your project. This is only applicable for projects that you build with Ant.
For more information, see the Testing section.
Testing a Library Project
There are two recommended ways of setting up testing on code and resources in a library project:
•
•
You can set up a test project that instruments an application project that depends on the library
project. You can then add tests to the project for library-specific features.
You can set up a standard application project that depends on the library and put the
instrumentation in that project. This lets you create a self-contained project that contains both the
tests/instrumentations and the code to test.
126
Content from developer.android.com/tools/projects/index.html through their Creative Commons Attribution 2.5 license
Managing Projects from Eclipse with ADT
21.
Managing Projects from Eclipse with ADT
Content from developer.android.com/tools/projects/projects-eclipse.html through their Creative Commons Attribution 2.5 license
Eclipse and the ADT plugin provide GUIs and
wizards to create all three types of projects
(Android project, Library project, and Test project):
In this section
• Creating an Android Project
• Setting up a Library Project
•
•
•
An Android project contains all of the files
• Referencing a Library Project
and resources that are needed to build a
See also
project into an .apk file for installation.
You need to create an Android project for
• Testing from Eclipse with ADT
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 Eclipse with ADT.
Creating an Android Project
The ADT plugin provides a New Project Wizard that you can use to quickly create a new Android project
(or a project from existing code). To create a new project:
• Select File > New > Project.
• Select Android > Android Application Project, and click Next.
• Enter the basic settings for the project:
•
•
•
•
•
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 Project Name. This text is used as the name of the folder where your project is created.
Enter a Package Name. 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 a Minimum Required SDK. This setting indicates the lowest version of the Android
platform that your application supports. This value sets the minSdkVersion attribute in the
<uses-sdk> element of your manifest file.
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'
manifest file.
Note: You can change the target SDK for your project at any time: Right-click the project in the
Package Explorer, select Properties, select Android and then check the desired Project Build
Target.
•
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.
127
Content from developer.android.com/tools/projects/projects-eclipse.html through their Creative Commons Attribution 2.5 license
Managing Projects from Eclipse with ADT
•
•
Select a Theme. This setting specifies which standard Android visual style is applied to your
application.
Click Next.
• In the Configure Project page, select the desired settings and click Next. Leave the Create activity
option checked so you can start your application with some essential components.
• In the Configure Launcher Icon page, create an icon and click Next.
• In the Create Activity page, select activity template and click Next. For more information about Android
code templates, see Using Code Templates.
• Click Finish and the wizard creates a new project according to the options you have chosen.
Tip: You can also start the New Project Wizard by clicking the New
icon in the toolbar.
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.
To create a new library project:
• Select File > New > Project.
• Select Android > Android Application Project, and click Next.
• Enter the basic settings for the project, including Application Name, Project Name, Package Name,
and SDK settings.
• In the Configure Project page, select the Mark this project as a library option to flag the project as a
library.
• Set the other options as desired and click Next.
• Follow the instructions to complete the wizard and create a new library project.
You can also convert an existing application project into a library. To do so, simply open the Properties for
the project and select the is Library checkbox, as shown in the figure below.
128
Content from developer.android.com/tools/projects/projects-eclipse.html through their Creative Commons Attribution 2.5 license
Managing Projects from Eclipse with ADT
Figure 1. Marking a project as an Android library.
To set the a project's properties to indicate that it is a library project:
• In the Package Explorer, right-click the library project and select Properties.
• In the Properties window, select the Android properties group in the left pane and locate the Library
properties in the right pane.
• Select the is Library check box and click Apply.
• Click OK to close the Properties window.
Once you create a library project or mark an existing project as a library, you can reference the library
project in other Android application projects. For more information, see the Referencing a library project
section.
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>
Referencing a library project
129
Content from developer.android.com/tools/projects/projects-eclipse.html through their Creative Commons Attribution 2.5 license
Managing Projects from Eclipse with ADT
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
Properties.
To add a reference to a library project, follow these steps:
• Make sure that both the project library and the application project that depends on it are in your
workspace. If one of the projects is missing, import it into your workspace.
• In the Package Explorer, right-click the dependent project and select Properties.
• In the Properties window, select the "Android" properties group at left and locate the Library properties
at right.
• Click Add to open the Project Selection dialog.
• From the list of available library projects, select a project and click OK.
• When the dialog closes, click Apply in the Properties window.
• Click OK to close the Properties window.
As soon as the Properties dialog closes, Eclipse rebuilds the project, including the contents of the library
project.
Figure 2 shows the Properties dialog that lets you add library references and move them up and down in
priority.
Figure 2. Adding a reference to a library project in the properties of an application project.
If you are adding references to multiple libraries, note that 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.
Declaring library components in the manifest file
130
Content from developer.android.com/tools/projects/projects-eclipse.html through their Creative Commons Attribution 2.5 license
Managing Projects from Eclipse with ADT
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.
131
Content from developer.android.com/tools/projects/projects-eclipse.html through their Creative Commons Attribution 2.5 license
Managing Projects from the Command Line
22.
Managing Projects from the Command Line
Content from developer.android.com/tools/projects/projects-cmdline.html through their Creative Commons Attribution 2.5 license
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.
•
•
•
In this section
• Creating an Android Project
• Updating a Project
• Setting up a Library Project
• Creating the manifest file
An Android project contains all of the files
• Updating a library project
and resources that are needed to build a
project into an .apk file for installation.
• Referencing a Library Project
You need to create an Android project for
• Declaring library components in the
any application that you want to
manifest file
eventually install on a device.
•
Building a dependent application
You can also designate an Android
project as a library project, which allows
See also
it to be shared with other projects that
• Testing from Other IDEs
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 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.
name 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.
path is the location of your project directory. If the directory does not exist, it will be created for
you.
activity 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.
132
Content from developer.android.com/tools/projects/projects-cmdline.html through their Creative Commons Attribution 2.5 license
Managing Projects from the Command Line
•
package 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 upgrading 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 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.
path is the location of your project directory.
name is the name for the project. This is optional—if 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
133
Content from developer.android.com/tools/projects/projects-cmdline.html through their Creative Commons Attribution 2.5 license
Managing Projects from the Command Line
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:
134
Content from developer.android.com/tools/projects/projects-cmdline.html through their Creative Commons Attribution 2.5 license
Managing Projects from the Command Line
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
135
Content from developer.android.com/tools/projects/projects-cmdline.html through their Creative Commons Attribution 2.5 license
Managing Projects from the Command Line
To build an application project that depends on one or more library projects, you can use the standard Ant
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.
136
Content from developer.android.com/tools/projects/projects-cmdline.html through their Creative Commons Attribution 2.5 license
Using Code Templates
23.
Using Code Templates
Content from developer.android.com/tools/projects/templates.html through their Creative Commons Attribution 2.5 license
The SDK tools provide templates for quickly
creating Android application projects with the
basic structure or for adding components to your
existing projects. 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:
•
•
•
In this section
• Application Templates
• BlankActivity Template
• Full Screen Activity Template
• Master Detail Flow Template
• Activity Templates
• Login Activity Template
• Settings Activity Template
• Other Templates
Application Templates
Activity Templates
Other Templates
Application Templates
Application templates create basic Android applications that you can immediately run and test on your
Android device. These templates are available when you create a new Android project, though you can
also use these templates to add new activities to an existing project.
To use Android application templates:
• In Eclipse, with the Android Development Tools (ADT) plugin installed, select File > New > Android.
• Select Android > Android Application Project, and click Next.
• Enter the settings for your application, including Application Name, Project Name, Package Name,
API level settings and presentation Theme, and click Next.
• Enter the project configuration options, and click Next.
• Optionally enter launcher icon settings, and click Next.
• In the Create Activity page, select an application template to use.
•
•
•
BlankActivity
FullScreenActivity
MasterDetailFlow
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
137
Content from developer.android.com/tools/projects/templates.html through their Creative Commons Attribution 2.5 license
Using Code Templates
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 for tab controls
Fragment objects for section content
Optional swipe gesture support based on the swipe view
design pattern, which extends FragmentPagerAdapter
to manage section fragments
138
Content from developer.android.com/tools/projects/templates.html through their Creative Commons Attribution 2.5 license
Using Code Templates
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 for section titles
Fragment objects for section content
FragmentPagerAdapter to manage section fragments
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 for list mode navigation
Fragment objects for section content
Full Screen Activity Template
Example
Description
139
Content from developer.android.com/tools/projects/templates.html through their Creative Commons Attribution 2.5 license
Using Code Templates
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:
•
•
SystemUiHider implementation that manages
hiding of the system user interface using a versioncompatible approach
Basic layout
Master Detail Flow Template
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:
• Right click the project folder of the Android application where you want to add an activity.
• Select New > Other...
• Select Android > Android Activity, and click Next.
140
Content from developer.android.com/tools/projects/templates.html through their Creative Commons Attribution 2.5 license
Using Code Templates
• Select an activity template, then follow the instructions to add it to your existing application.
•
•
•
•
•
LoginActivity
SettingsActivity
BlankActivity
FullScreenActivity
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 implementation for handing network
operations separately from the main user interface thread
Progress indicator during network operations
Settings Activity Template
Example
Description
141
Content from developer.android.com/tools/projects/templates.html through their Creative Commons Attribution 2.5 license
Using Code Templates
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:
• Right click the project folder of the Android application where you want to add a code component.
• Select New > Other...
• Select Android > Android Object, and click Next.
• Select an object template, then follow the instructions to add it to your existing application.
•
•
•
•
BroadcastReceiver
ContentProvider
Custom View
Service
142
Content from developer.android.com/tools/projects/templates.html through their Creative Commons Attribution 2.5 license
Building and Running
24.
Building and Running
Content from developer.android.com/tools/building/index.html through their Creative Commons Attribution 2.5 license
During the build process, your Android projects
In this section
are compiled and packaged into an .apk file, the
• A Detailed Look at the Build Process
container for your application binary. It 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.
If you are developing in Eclipse, the ADT plugin incrementally builds your project as you make changes to
the source code. Eclipse outputs an .apk file automatically to the bin folder of the project, so you do not
have to do anything extra to generate the .apk.
If you are developing in a non-Eclipse environment, you can build your project with the generated
build.xml Ant file that is in the project directory. The Ant file calls targets that automatically call the
build tools for you.
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 tools use 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.
Fortunately, Eclipse or your Ant build script signs the application for you in debug mode when you build
your application. You can also easily setup Eclipse or your Ant build to sign your application in release
mode as well. For more information on signing applications, see Signing Your Applications.
The following diagram depicts the components involved in building and running an application:
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 Eclipse, the complete build process is automatically done
periodically as you develop and save your code changes. If you are using other IDEs, this build process is
done every time you run the generated Ant build script for your project. It is useful, however, to understand
what is happening under the hood since much of the tools and processes are masked from you. The
following diagram depicts the different tools and processes that are involved in a build:
143
Content from developer.android.com/tools/building/index.html through their Creative Commons Attribution 2.5 license
Building and Running
The general process for a typical build is outlined below:
•
•
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.
144
Content from developer.android.com/tools/building/index.html through their Creative Commons Attribution 2.5 license
Building and Running
•
•
•
•
•
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 project 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.
145
Content from developer.android.com/tools/building/index.html through their Creative Commons Attribution 2.5 license
Building and Running from Eclipse with ADT
25.
Building and Running from Eclipse with ADT
Content from developer.android.com/tools/building/building-eclipse.html through their Creative Commons Attribution 2.5 license
Eclipse and ADT provide an environment where
most of the details of the build process are hidden
from you. By default, the build process constantly
runs in the background as you make changes to
your project.
In this section
• Running on an Emulator
• Running on a Device
• Creating a Run Configuration
When Eclipse automatically builds your
application, it enables debugging and signs the .apk with a debug key, by default. When you run the
application, Eclipse invokes ADB and installs your application to a device or emulator, so you do not have
to manually perform these tasks. Since most of the build process is taken care of by Eclipse, the following
topics show you how to run an application, which will automatically build your application as well.
To distribute your application, however, you must build your application in release mode and sign the
.apk file with your own private key.
This document shows you how to run your application on an emulator or a real device from Eclipse—all of
which is done using the debug version of your application. For more information about how to sign your
application with a private key for release, see Signing Your Applications
Running on the emulator
Before you can run your application on the Android Emulator, you must create an AVD.
To run (or debug) your application, select Run > Run (or Run > Debug) from the Eclipse menu bar. The
ADT plugin will automatically create a default run configuration for the project. Eclipse will then perform the
following:
• Compile the project (if there have been changes since the last build).
• Create a default run configuration (if one does not already exist for the project).
• 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 below.
If you run the application with the Debug option, the application will start in the "Waiting For Debugger"
mode. Once the debugger is attached, Eclipse opens the Debug perspective and starts the application's
main activity. Otherwise, if you run the application with the normal Run option, Eclipse installs the
application on the device and launches the main activity.
To set or change the run configuration used for your project, use the run configuration manager. 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:
146
Content from developer.android.com/tools/building/building-eclipse.html through their Creative Commons Attribution 2.5 license
Building and Running from Eclipse with ADT
•
•
Ensure that your application is debuggable by setting the android:debuggable attribute of
the <application> element to true. As of ADT 8.0, this is done by default when you build
in debug mode.
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 Eclipse menu bar.
Creating a Run Configuration
The run configuration specifies the project to run, the Activity to start, the emulator or connected device to
use, and so on. When you first run a project as an Android Application, ADT 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, you can
customize the run configuration or even create a new one.
To create or modify a run configuration, refer to the Eclipse documentation on how to create Run
configurations. The following steps highlight the important things you need to do for an Android project:
• Open the run configuration manager from the Run Menu.
• Expand the Android Application item and create a new configuration or open an existing one.
• With the Run Configuration selected, adjust your desired run configuration settings:
•
In the Android tab, specify the Project and Activity to launch.
•
In the 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).
You can 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.
Automatic and manual target modes
By default, a run configuration uses the automatic target mode in order to select an AVD. In this mode,
ADT will select an AVD for the application in the following manner:
• 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.
• 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.
147
Content from developer.android.com/tools/building/building-eclipse.html through their Creative Commons Attribution 2.5 license
Building and Running from Eclipse with ADT
• If there are no devices or emulators running that meet the requirements of the build target, ADT looks at
the available AVDs. If there is an AVD that matches the build target of the project, ADT chooses that AVD.
If the AVD versions are newer than the build target of the project, ADT chooses the oldest possible version
of an AVD that meets the project's build target requirement.
• If there are no suitable AVDs, the application is not installed 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.
148
Content from developer.android.com/tools/building/building-eclipse.html through their Creative Commons Attribution 2.5 license
Building and Running from the Command Line
26.
Building and Running from the Command Line
Content from developer.android.com/tools/building/building-cmdline.html through their Creative Commons Attribution 2.5 license
There are two ways to build your application using
the Ant build script: one for testing/debugging your
application — debug mode — and one for building
your final package for release — release mode.
Regardless of which way you build your
application, it must be signed before it can install
on an emulator or device—with a debug key when
building in debug mode and with your own private
key when building in release mode.
In this section
• Building in Debug Mode
• Building in Release Mode
• Build unsigned
• Build signed and aligned
• Once built and signed in release mode
• Running on the Emulator
Whether you're building in debug mode or release
• Running on a Device
mode, you need to use the Ant tool to compile and
• Application Signing
build your project. This will create the .apk file that
you can install on an emulator or device. When
• Ant Command Reference
you build in debug mode, the .apk file is
See also
automatically signed by the SDK tools with a
debug key, so it's instantly ready for installation
• Managing AVDs from the Command Line
onto an emulator or attached development device.
•
Using the Android Emulator
You cannot distribute an application that is signed
with a debug key. When you build in release
• Signing Your Applications
mode, the .apk file is unsigned, so you must
manually sign it with your own private key, using Keytool and Jarsigner.
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 Ant, you can obtain it from the Apache Ant 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.6.0_02
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 Ant to compile your project in debug mode:
149
Content from developer.android.com/tools/building/building-cmdline.html through their Creative Commons Attribution 2.5 license
Building and Running from the Command Line
ant debug
This creates your debug .apk file inside the project bin/ directory, named
<your_project_name>-debug.apk. The file is already signed with the debug key and has been
aligned with zipalign.
Each time you change a source file or resource, you must run Ant again in order to package up the latest
version of the application.
To install and run your application on an emulator, see the following 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 project directory.
• Use Ant to compile your project in release mode:
ant release
•
This creates your Android application .apk file inside the project bin/ directory, named
<your_project_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
project's ant.properties file. With this information provided, the build script will prompt you for your
keystore and alias password when you build in release mode and produce your final application package,
which will be ready for distribution.
Caution: Due to the way Ant handles input, the password that you enter during the build process will be
visible. If you are concerned about your keystore and alias password being visible on screen, then you
may prefer to perform the application signing manually, via Jarsigner (or a similar tool). To instead perform
the signing procedure manually, build unsigned and then continue with Signing Your Applications.
150
Content from developer.android.com/tools/building/building-cmdline.html through their Creative Commons Attribution 2.5 license
Building and Running from the Command Line
To specify your keystore and alias, open the project ant.properties file (found in the root of the
project directory) and add entries for key.store and key.alias. For example:
key.store=path/to/my.keystore
key.alias=mykeystore
Save your changes. Now you can build a signed .apk in release mode:
• Open a command-line and navigate to the root of your project directory.
• Use Ant to compile your project in release mode:
ant release
•
• 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 project bin/ directory, named
<your_project_name>-release.apk. This .apk file has been signed with the private key specified
in ant.properties 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:
• 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.
• 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 project bin/ 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.
151
Content from developer.android.com/tools/building/building-cmdline.html through their Creative Commons Attribution 2.5 license
Building and Running from the Command Line
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 platform-tools/
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).
152
Content from developer.android.com/tools/building/building-cmdline.html through their Creative Commons Attribution 2.5 license
Building and Running from the Command Line
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 compile 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.
The ADT plugin 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
Eclipse 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
exporting and signing your application with the ADT's Export Wizard.
Ant Command Reference
ant clean
Cleans the project. If you include the all target before clean (ant all clean), other
projects are also cleaned. For instance if you clean a test project, the tested project is also
cleaned.
ant debug
Builds a debug package. Works on application, library, and test projects and compiles
dependencies as needed.
ant emma debug
Builds a test project while building the tested project with instrumentation turned on. This is used
to run tests with code coverage enabled.
ant release
Builds a release package.
ant instrument
Builds an instrumented debug package. This is generally called automatically when building a test
project with code coverage enabled (with the emma target)
ant <build_target> install
Builds and installs a package. Using install by itself fails.
ant installd
Installs an already compiled debug package. This fails if the .apk is not already built.
ant installr
Installs an already compiled release package. This fails if the .apk is not already built.
ant installt
Installs an already compiled test package. Also installs the .apk of the tested application. This
fails if the .apk is not already built.
ant installi
Installs an already compiled instrumented package. This is generally not used manually as it's
called when installing a test package. This fails if the .apk is not already built.
ant test
Runs the tests (for test projects). The tested and test .apk files must be previously installed.
153
Content from developer.android.com/tools/building/building-cmdline.html through their Creative Commons Attribution 2.5 license
Building and Running from the Command Line
ant debug installt test
Builds a test project and the tested project, installs both .apk files, and runs the tests.
ant emma debug install test
Builds a test project and the tested project, installs both .apk files, and runs the tests with code
coverage enabled.
154
Content from developer.android.com/tools/building/building-cmdline.html through their Creative Commons Attribution 2.5 license
Testing
27.
Testing
Content from developer.android.com/tools/testing/index.html through their Creative Commons Attribution 2.5 license
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
you’re not allowed to do on that thread, and what the penalty is if you violate the policy. Implementationwise, 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 haven’t used it and, second, that this is an opportunity to lecture sternly on
one of my favorite subjects: performance improvement and profiling.
155
Content from developer.android.com/tools/testing/index.html through their Creative Commons Attribution 2.5 license
Testing Fundamentals
28.
Testing Fundamentals
Content from developer.android.com/tools/testing/testing_android.html through their Creative Commons Attribution 2.5 license
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:
•
•
•
•
•
In this section
• Test Structure
• Test Projects
• The Testing API
• JUnit
• Instrumentation
Android test suites are based on JUnit.
• Test case classes
You can use plain JUnit to test a class
that doesn't call the Android API, or
• Assertion classes
Android's JUnit extensions to test
• Mock object classes
Android components. If you're new to
• Running Tests
Android testing, you can start with
general-purpose test case classes such
• Seeing Test Results
as AndroidTestCase and then go on
• monkey and monkeyrunner
to use more sophisticated classes.
• Working With Package Names
The Android JUnit extensions provide
component-specific test case classes.
• What To Test
These classes provide helper methods
• Next Steps
for creating mock objects and methods
that help you control the lifecycle of a
Key classes
component.
• InstrumentationTestRunner
Test suites are contained in test
packages that are similar to main
• android.test
application packages, so you don't need
• android.test.mock
to learn a new set of tools or techniques
• junit.framework
for designing and building tests.
The SDK tools for building and tests are
Related tutorials
available in Eclipse with ADT, and also in
• Activity Testing Tutorial
command-line form for use with other
IDEs. These tools get information from
See also
the project of the application under test
• Testing from Eclipse with ADT
and use this information to automatically
create the build files, manifest file, and
• Testing from Other IDEs
directory structure for the test package.
• monkeyrunner
The SDK also provides monkeyrunner,
• UI/Application Exerciser Monkey
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:
156
Content from developer.android.com/tools/testing/testing_android.html through their Creative Commons Attribution 2.5 license
Testing Fundamentals
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.
157
Content from developer.android.com/tools/testing/testing_android.html through their Creative Commons Attribution 2.5 license
Testing Fundamentals
•
•
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
158
Content from developer.android.com/tools/testing/testing_android.html through their Creative Commons Attribution 2.5 license
Testing Fundamentals
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 Android-specific
setup, teardown, and helper methods.
AndroidTestCase
A useful general test case class, especially if you are just starting out with Android testing, is
AndroidTestCase. It extends both TestCase and Assert. It provides the JUnit-standard setUp()
and tearDown() methods, as well as all of JUnit's Assert methods. In addition, it provides methods for
testing permissions, and a method that guards against memory leaks by clearing out certain class
references.
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
159
Content from developer.android.com/tools/testing/testing_android.html through their Creative Commons Attribution 2.5 license
Testing Fundamentals
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.
160
Content from developer.android.com/tools/testing/testing_android.html through their Creative Commons Attribution 2.5 license
Testing Fundamentals
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
MockContentResolver 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).
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.
161
Content from developer.android.com/tools/testing/testing_android.html through their Creative Commons Attribution 2.5 license
Testing Fundamentals
InstrumentationTestRunner is the primary Android test runner class. It extends the JUnit test runner
framework and is also instrumented. It can run any of the test case classes provided by Android and
supports all possible types of testing.
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
162
Content from developer.android.com/tools/testing/testing_android.html through their Creative Commons Attribution 2.5 license
Testing Fundamentals
the API, you can write a wide range of large, powerful, and complex tests. You run programs that
use the API with the monkeyrunner command-line tool.
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.
163
Content from developer.android.com/tools/testing/testing_android.html through their Creative Commons Attribution 2.5 license
Testing from Eclipse with ADT
29.
Testing from Eclipse with ADT
Content from developer.android.com/tools/testing/testing_eclipse.html through their Creative Commons Attribution 2.5 license
This topic explains how create and run tests of
In this section
Android applications in Eclipse with ADT. Before
• Creating a Test Project
you read this topic, you should read about how to
create an Android application with the basic
• Creating a Test Package
processes for creating and running applications
• Running Tests
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:
• In Eclipse, select File > New > Other. This opens the Select a Wizard dialog.
• 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.
• 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.
164
Content from developer.android.com/tools/testing/testing_eclipse.html through their Creative Commons Attribution 2.5 license
Testing from Eclipse with ADT
The name becomes part of the suggested project path, but you can change this in the next step.
• 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.
• 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).
• In the Build Target panel, select the Android SDK platform that the application under test uses.
• 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:
• In the Project Explorer tab, open your test project, then open the src folder.
• 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.
• 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.
• 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.
• In the Superclass field, enter the name of the Android test case class you are extending. You can also
browse the available classes.
• In Which method stubs would you like to create?, unset all the options, then click Finish. You will set up
the constructor manually.
• 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
165
Content from developer.android.com/tools/testing/testing_eclipse.html through their Creative Commons Attribution 2.5 license
Testing from Eclipse with ADT
class' constructor. Each base test case class has its own constructor signature. Refer to the class
documentation in the documentation for android.test for more information.
To control your test environment, you will want to override the setUp() and tearDown() methods:
•
•
setUp(): This method is invoked before any of the test methods in the class. Use it to set up
the environment for the test (the test fixture. You can use setUp() to instantiate a new Intent
with the action ACTION_MAIN. You can then use this intent to start the Activity under test.
tearDown(): This method is invoked after all the test methods in the class. Use it to do
garbage collection and to reset the test fixture.
Another useful convention is to add the method testPreconditions() to your test class. Use this
method to test that the application under test is initialized correctly. If this test fails, you know that that the
initial conditions were in error. When this happens, further test results are suspect, regardless of whether
or not the tests succeeded.
The Resources tab contains an Activity Testing tutorial with more information about creating test classes
and methods.
Running Tests
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:
•
•
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
a nd r o id tool's "create test-project" option.
To see how to do this, read Testing in Other
IDEs.
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:
• In the Package Explorer, select the test project, then from the main menu, select Run > Run
Configurations.... The Run Configurations dialog appears.
166
Content from developer.android.com/tools/testing/testing_eclipse.html through their Creative Commons Attribution 2.5 license
Testing from Eclipse with ADT
• 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.
• 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.
• Now click the Target tab.
•
•
Optional: If you are using the emulator, click Automatic, then in the Android Virtual Device (AVD)
selection table, select an existing AVD.
In the Emulator Launch Parameters pane, set the Android emulator flags you want to use. These
are documented in the topic Android Emulator.
• 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.
• Optional: Add the configuration to the Run toolbar and the Favorites menu: in the Display in Favorites
pane click the checkbox next to Run.
• Optional: To add this configuration to the Debug menu and toolbar, click the checkbox next to Debug.
• 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.
• 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.
• 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:
[yyyy-mm-dd hh:mm:ss - testfile] Waiting
for HOME ('android.process.acore') to be
launched...
Message Examples
The examples shown in this section come
from the SpinnerTest sample test package,
which tests the Spinner sample application.
This test package is also featured in the
Activity Testing tutorial.
In the following description of these messages,
devicename is the name of the device or
emulator you are using to run the test, and port
is the port number for the device. The name and
port number are in the format used by the adb devices command. Also, testfile is the .apk
filename of the test package you are running, and appfile is the filename of the application under test.
•
If you are using an emulator and you have not yet started it, then Eclipse first starts the emulator.
When this is complete, you see the message:
HOME is up on device 'devicename-port'
•
If you have not already installed your test package, then you see the message:
167
Content from developer.android.com/tools/testing/testing_eclipse.html through their Creative Commons Attribution 2.5 license
Testing from Eclipse with ADT
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 12:44:40
[2010-07-01 12:44:40
'emulator-5554'
[2010-07-01 12:44:40
[2010-07-01 12:44:49
•
- MyTest] HOME is up on device 'emulator-5554'
- MyTest] Uploading MyTest.apk onto device
- MyTest] Installing MyTest.apk...
- 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 12:44:49
MyApp
[2010-07-01 12:44:49
'emulator-5554'
[2010-07-01 12:44:49
[2010-07-01 12:44:54
•
- MyTest] Project dependency found, installing:
- MyApp] Uploading MyApp.apk onto device
- MyApp] Installing MyApp.apk...
- MyApp] Success!
Next, you see the message Launching instrumentation instrumentation_class
on device devicename-port
instrumentation_class is the fully-qualified class name of the instrumentation test
runner you have specified (usually InstrumentationTestRunner.
•
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
168
Content from developer.android.com/tools/testing/testing_eclipse.html through their Creative Commons Attribution 2.5 license
Testing from Eclipse with ADT
[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.
169
Content from developer.android.com/tools/testing/testing_eclipse.html through their Creative Commons Attribution 2.5 license
Testing from Eclipse with ADT
Figure 2. Messages for a test failure.
170
Content from developer.android.com/tools/testing/testing_eclipse.html through their Creative Commons Attribution 2.5 license
Testing from Other IDEs
30.
Testing from Other IDEs
Content from developer.android.com/tools/testing/testing_otheride.html through their Creative Commons Attribution 2.5 license
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.
In this section
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.
• Running tests on a device or emulator
• Working with Test Projects
• Creating a test project
• Updating a test project
• Creating a Test Package
• Running Tests
• Quick build and run with Ant
• Using the Instrument Command
• Instrument options
• Instrument examples
Working with Test Projects
See Also
You use the android tool to create test
• Testing Fundamentals
projects. You also use android to convert
• Android Debug Bridge
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
-m,
Path to the project of
-the application under
main test, relative to the
test package
directory.
Description
For example, if the application under test is in
source/HelloAndroid, and you want to create the test
project in source/HelloAndroidTest, then the value of
--main should be ../HelloAndroid.
To learn more about choosing the location of test projects,
please read Testing Fundamentals.
-n,
Name that you want to
-give the test project.
name
-p,
Directory in which you The android tool creates the test project files and directory
-want to create the
structure in this directory. If the directory does not exist,
path new test project.
android creates it.
171
Content from developer.android.com/tools/testing/testing_otheride.html through their Creative Commons Attribution 2.5 license
Testing from Other IDEs
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 the tests in HelloAndroidTest should be run against the application with the Android
package name com.example.helloandroid.
o android:label="Tests for .HelloAndroid": specifies a user-readable
label for the instrumentation class. By default, the android tool gives it the value
"Tests for " plus the name of the main Activity of the application under test.
172
Content from developer.android.com/tools/testing/testing_otheride.html through their Creative Commons Attribution 2.5 license
Testing from Other IDEs
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
-m, - The path to the project For example, if the application under test is in
-main of the application
source/HelloAndroid, and the test project is in
under test, relative to source/HelloAndroidTest, then the value for --main
the test project
is ../HelloAndroid.
-p, - The of the test project. For example, if the test project is in
-path
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.
173
Content from developer.android.com/tools/testing/testing_otheride.html through their Creative Commons Attribution 2.5 license
Testing from Other IDEs
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:
• If necessary, rebuild your main application and test package.
• Install your test package and main application Android package files (.apk files) to your current
Android device or emulator
• 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.
174
Content from developer.android.com/tools/testing/testing_otheride.html through their Creative Commons Attribution 2.5 license
Testing from Other IDEs
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:
am instrument [flags] <test_package>/<runner_class>
The main input parameters to am instrument are described in the following table:
Parameter
Value
Description
<test_package> The Android package
name of the test
package.
The value of the package attribute of the
manifest element in the test package's
manifest file.
<runner_class> The class name of the
instrumented test
runner you are using.
This is usually
InstrumentationTestRunner.
The flags for am instrument are described in the following table:
Flag 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).
-e <test_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 section am
instrument options.
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:
175
Content from developer.android.com/tools/testing/testing_otheride.html through their Creative Commons Attribution 2.5 license
Testing from Other IDEs
-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
Value
Description
package
<Java_package_name> 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 executed.
Notice that this is not an Android package name; a
test package has a single Android package name
but may have several Java packages within it.
class
<class_name>
The fully-qualified Java class name for one of the
test case classes. Only this test case class is
executed.
<class_name>#method A fully-qualified test case class name, and one of its
name
methods. Only this method is executed. 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 re-formatted as test results.
176
Content from developer.android.com/tools/testing/testing_otheride.html through their Creative Commons Attribution 2.5 license
Testing from Other IDEs
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.
o FunctionTests, which contains the methods testCamera, testXVGA, and
testHardKeyboard.
o 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
177
Content from developer.android.com/tools/testing/testing_otheride.html through their Creative Commons Attribution 2.5 license
Testing from Other IDEs
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.FunctionTests#testCamera \
> com.android.demo.app.tests/android.test.InstrumentationTestRunner
You can find more examples of the command in the documentation for InstrumentationTestRunner.
178
Content from developer.android.com/tools/testing/testing_otheride.html through their Creative Commons Attribution 2.5 license
Activity Testing
31.
Activity Testing
Content from developer.android.com/tools/testing/activity_testing.html through their Creative Commons Attribution 2.5 license
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.
In this section
• The Activity Testing API
• ActivityInstrumentationTestCase2
• ActivityUnitTestCase
• SingleLaunchActivityTestCase
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.
• Mock objects and activity testing
The Activity Testing API
• Appendix: UI Testing Notes
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:
• Assertions for activity testing
• What to Test
• Next Steps
• Testing on the UI thread
• Turning off touch mode
• Unlocking the Emulator or Device
• Troubleshooting UI tests
Key Classes
• InstrumentationTestRunner
•
•
•
Lifecycle control: With instrumentation,
• ActivityInstrumentationTestCase2
you can start the activity under test,
• ActivityUnitTestCase
pause it, and destroy it, using methods
provided by the test case classes.
Related Tutorials
Dependency injection: Instrumentation
• Activity Testing Tutorial
allows you to create mock system
objects such as Contexts or Applications
See Also
and use them to run the activity under
• Testing from Eclipse with ADT
test. This helps you control the test
• Testing from Other IDEs
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
179
Content from developer.android.com/tools/testing/activity_testing.html through their Creative Commons Attribution 2.5 license
Activity Testing
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
ViewAsserts 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.
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.
180
Content from developer.android.com/tools/testing/activity_testing.html through their Creative Commons Attribution 2.5 license
Activity Testing
•
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:
181
Content from developer.android.com/tools/testing/activity_testing.html through their Creative Commons Attribution 2.5 license
Activity Testing
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
182
Content from developer.android.com/tools/testing/activity_testing.html through their Creative Commons Attribution 2.5 license
Activity Testing
<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 re-factor
your tests.
183
Content from developer.android.com/tools/testing/activity_testing.html through their Creative Commons Attribution 2.5 license
Service Testing
32.
Service Testing
Content from developer.android.com/tools/testing/service_testing.html through their Creative Commons Attribution 2.5 license
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
In this section
• Service Design and Testing
• ServiceTestCase
• Mock object classes
• What to Test
Key Classes
• InstrumentationTestRunner
• ServiceTestCase
• MockApplication
• RenamingDelegatingContext
Related Tutorials
• Activity Testing Tutorial
When you design a Service, you should consider
See Also
how your tests can examine the various states of
the Service lifecycle. If the lifecycle methods that
• Testing From Eclipse with ADT
start up your Service, such as onCreate() or
• Testing From Other IDEs
onStartCommand() do not normally set a global
variable to indicate that they were successful, you
may want to provide such a variable for testing purposes.
Most other testing is facilitated by the methods in the ServiceTestCase test case class. For example,
the getService() method returns a handle to the Service under test, which you can test to confirm that
the Service is running even at the end of your tests.
ServiceTestCase
ServiceTestCase extends the JUnit TestCase class with with methods for testing application
permissions and for controlling the application and Service under test. It also provides mock application
and Context objects that isolate your test from the rest of the system.
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.
184
Content from developer.android.com/tools/testing/service_testing.html through their Creative Commons Attribution 2.5 license
Service Testing
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
ServiceTestCase assumes that you will use a mock Context or mock Application (or both) for the test
environment. These objects isolate the test environment from the rest of the system. If you don't provide
your own instances of these objects before you start the Service, then ServiceTestCase will create its
own internal instances and inject them into the Service. You can override this behavior by creating and
injecting your own instances before starting the Service
To inject a mock Application object into the Service under test, first create a subclass of
MockApplication. MockApplication is a subclass of Application in which all the methods
throw an Exception, so to use it effectively you subclass it and override the methods you need. You then
inject it into the Service with the setApplication() method. This mock object allows you to control the
application values that the Service sees, and isolates it from the real system. In addition, any hidden
dependencies your Service has on its application reveal themselves as exceptions when you run the test.
You inject a mock Context into the Service under test with the setContext() method. The mock Context
classes you can use are described in more detail in Testing Fundamentals.
What to Test
The topic What To Test lists general considerations for testing Android components. Here are some
specific guidelines for testing a Service:
•
•
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.
185
Content from developer.android.com/tools/testing/service_testing.html through their Creative Commons Attribution 2.5 license
Content Provider Testing
33.
Content Provider Testing
Content from developer.android.com/tools/testing/contentprovider_testing.html through their Creative Commons Attribution 2.5 license
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.
In this section
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.
• What To Test
Content Provider Design and
Testing
• Content Provider Design and Testing
• The Content Provider Testing API
• ProviderTestCase2
• Mock object classes
• Next Steps
Key Classes
• InstrumentationTestRunner
• ProviderTestCase2
• IsolatedContext
• MockContentResolver
Related Tutorials
• Activity Testing Tutorial
In Android, content providers are viewed
See Also
externally as data APIs that provide tables of data,
• Testing Fundamentals
with their internals hidden from view. A content
provider may have many public constants, but it
• Testing From Eclipse with ADT
usually has few if any public methods and no
• Testing From Other IDEs
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
186
Content from developer.android.com/tools/testing/contentprovider_testing.html through their Creative Commons Attribution 2.5 license
Content Provider Testing
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
ProviderTestCase2 uses IsolatedContext and MockContentResolver, which are standard mock
object classes. To learn more about them, please read Testing Fundamentals.
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
187
Content from developer.android.com/tools/testing/contentprovider_testing.html through their Creative Commons Attribution 2.5 license
Content Provider Testing
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.
188
Content from developer.android.com/tools/testing/contentprovider_testing.html through their Creative Commons Attribution 2.5 license
Accessibility Testing Checklist
34.
Accessibility Testing Checklist
Content from developer.android.com/tools/testing/testing_accessibility.html through their Creative Commons Attribution 2.5 license
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:
•
•
In this section
• Testing Goals
• Testing Requirements
• Testing Recommendations
• Special Cases and Considerations
• Testing Accessibility Features
• Testing audible feedback
• Testing focus navigation
• Testing gesture navigation
See Also
• Accessibility Developer Checklist
• Android Design: Accessibility
• Making Applications Accessible
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.
• 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.
• 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.
• 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.
• 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.
• 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.
189
Content from developer.android.com/tools/testing/testing_accessibility.html through their Creative Commons Attribution 2.5 license
Accessibility Testing Checklist
• 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.
• 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.
• 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.
• Review developer special cases and considerations: Review the list of special cases for
accessibility development and test your application for the cases that apply.
• 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.
• 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:
• Launch the Settings application.
190
Content from developer.android.com/tools/testing/testing_accessibility.html through their Creative Commons Attribution 2.5 license
Accessibility Testing Checklist
• Navigate to the Accessibility category and select it.
• Select Accessibility to enable it.
• 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 Use 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:
• Launch the Settings application.
• Navigate to the Accessibility category and select it.
• 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.
• 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 Use Explore by Touch.
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 Dpad.
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.
191
Content from developer.android.com/tools/testing/testing_accessibility.html through their Creative Commons Attribution 2.5 license
Accessibility Testing Checklist
For more information about using Explore by Touch accessibility gestures, see Accessibility gestures.
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.
192
Content from developer.android.com/tools/testing/testing_accessibility.html through their Creative Commons Attribution 2.5 license
UI Testing
35.
UI Testing
Content from developer.android.com/tools/testing/testing_ui.html through their Creative Commons Attribution 2.5 license
In addition to unit testing the individual
components that make up your Android
application (such as activities, services, and
content providers), it is also important that you test
the behavior of your application’s user interface
(UI) when it is running on a device. UI testing
ensures that your application returns the correct
UI output in response to a sequence of user
actions on a device, such as entering keyboard
input or pressing toolbars, menus, dialogs,
images, and other UI controls.
Functional or black-box UI testing does not require
testers to know the internal implementation details
of the app, only its expected output when a user
performs a specific action or enters a specific
input. This approach allows for better separation
of development and testing roles in your
organization.
One common approach to UI testing is to run tests
manually and verify that the app is behaving as
expected. However, this approach can be timeconsuming, tedious, and error-prone. A more
efficient and reliable approach is to automate the
UI testing with a software testing framework.
Automated testing involves creating programs to
perform testing tasks (test cases) to cover specific
usage scenarios, and then using the testing
framework to run the test cases automatically and
in a repeatable manner.
Overview
The Android SDK provides the following tools to
support automated, functional UI testing on your
application:
•
•
In this section
• Overview
•
• Workflow
• Analyzing Your UI
• Preparing to Test
•
•
•
•
Load the App
Identify UI Components
Ensure Accessibility
Configure Development Environment
• Creating Tests
•
•
uiautomator API
Sample Test Case
• Building and Deploying Tests
• Running Tests
• Best Practices
Key classes
• IAutomationSupport
• UiAutomatorTestCase
• UiCollection
• UiDevice
• UiObject
• UiScrollable
• UiSelector
uiautomatorviewer - A GUI tool to
See Also
scan and analyze the UI components of
• uiautomator (reference)
an Android application.
uiautomator - A Java library
containing APIs to create customized functional UI tests, and an execution engine to automate
and run the tests.
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
193
Content from developer.android.com/tools/testing/testing_ui.html through their Creative Commons Attribution 2.5 license
UI Testing
Workflow for the the uiautomator testing framework
Here's a short overview of the steps required to automate UI testing:
• Prepare to test by installing the app on a test device, analyzing the app’s UI components, and ensuring
that your application is accessible by the test automation framework.
• Create automated tests to simulate specific user interactions on your application.
• Compile your test cases into a JAR file and install it on your test device along with your app.
• Run the tests and view the test results.
• 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 deviice.
To analyze the UI components of the application that you want to test:
• Connect your Android device to your development machine.
• Open a terminal window and navigate to <android-sdk>/tools/.
• Run the tool with this command:
194
Content from developer.android.com/tools/testing/testing_ui.html through their Creative Commons Attribution 2.5 license
UI Testing
$ uiautomatorviewer
•
• 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:
• Find the serial numbers for your connected devices by running this command:
$ adb devices
•
• 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.
• View the UI properties for your application:
•
•
Hover over the snapshot in the left-hand panel to see the UI components identified by the
uiautomatorviewer tool. You can view the component’s properties listed in the lower righthand panel, and the layout hierarchy in the upper right-hand panel.
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.
195
Content from developer.android.com/tools/testing/testing_ui.html through their Creative Commons Attribution 2.5 license
UI Testing
Identify the application’s 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 Application’s 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:
• Create a new Java project in Eclipse, and give your project a name that is relevant to the tests you’re
about to create (for example, "MyAppNameTests"). In the project, you will create the test cases that are
specific to the application that you want to test.
• From the Project Explorer, right-click on the new project that you created, then select Properties >
Java Build Path, and do the following:
• Click Add Library > JUnit then select JUnit3 to add JUnit support.
196
Content from developer.android.com/tools/testing/testing_ui.html through their Creative Commons Attribution 2.5 license
UI Testing
• 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. It’s also good
practice to start the test from the Home screen of the device. From the Home screen (or some other
starting location you’ve chosen in the target app), you can use the classes provided by the
uiautomator API to simulate user actions and to test specific UI components. For an example of how
to put together a uiautomator test case, see the sample test case.
uiautomator API
The uiautomator API is bundled in the uiautomator.jar file under the <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.
197
Content from developer.android.com/tools/testing/testing_ui.html through their Creative Commons Attribution 2.5 license
UI Testing
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:
198
Content from developer.android.com/tools/testing/testing_ui.html through their Creative Commons Attribution 2.5 license
UI Testing
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.
199
Content from developer.android.com/tools/testing/testing_ui.html through their Creative Commons Attribution 2.5 license
UI Testing
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();
// We’re 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 button’s
// 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());
}
200
Content from developer.android.com/tools/testing/testing_ui.html through their Creative Commons Attribution 2.5 license
UI Testing
}
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:
• 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.
• From the command line, set the ANDROID_HOME variable:
•
In Windows:
set ANDROID_HOME=<path_to_your_sdk>
•
•
In UNIX:
export ANDROID_HOME=<path_to_your_sdk>
•
• Go to the project directory where your build.xml file is located and build your test JAR.
ant build
•
• 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/
Here’s an example:
adb push ~/dev/workspace/LaunchSettings/bin/LaunchSettings.jar
/data/local/tmp/
•
Running uiautomator Tests
Here’s an example of how to run a test that is implemented in the LaunchSettings.jar file. The
tests are bundled in the com.uia.example.my package:
201
Content from developer.android.com/tools/testing/testing_ui.html through their Creative Commons Attribution 2.5 license
UI Testing
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.
202
Content from developer.android.com/tools/testing/testing_ui.html through their Creative Commons Attribution 2.5 license
What To Test
36.
What To Test
Content from developer.android.com/tools/testing/what_to_test.html through their Creative Commons Attribution 2.5 license
As you develop Android applications, knowing what to test is as important as knowing how to test. This
document lists some most common Android-related situations that you should consider when you test,
even at the unit test level. This is not an exhaustive list, and you consult the documentation for the features
that you use for more ideas. The android-developers Google Groups site is another resource for
information about testing.
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 re-start the
foreground Activity. You should consider testing the following:
•
•
Is the screen re-drawn correctly? Any custom UI code you have should handle changes in the
orientation.
Does the application maintain its state? The Activity should not lose anything that the user has
already entered into the UI. The application should not "forget" its place in the current transaction.
Change in configuration
A situation that is more general than a change in orientation is a change in the device's configuration, such
as a change in the availability of a keyboard or a change in system language.
A change in configuration also triggers the default behavior of destroying and then restarting the
foreground Activity. Besides testing that the application maintains the UI and its transaction state, you
should also test that the application updates itself to respond correctly to the new configuration.
Battery life
Mobile devices primarily run on battery power. A device has finite "battery budget", and when it is gone,
the device is useless until it is recharged. You need to write your application to minimize battery usage,
you need to test its battery performance, and you need to test the methods that manage battery usage.
Techniques for minimizing battery usage were presented at the 2010 Google I/O conference in the
presentation Coding for Life -- Battery Life, That Is. This presentation describes the impact on battery life
of various operations, and the ways you can design your application to minimize these impacts. When you
code your application to reduce battery usage, you also write the appropriate unit tests.
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 IP-based location awareness. It can also
wait for WiFi access before doing large data transfers, since WiFi transfers maximize battery usage
compared to transfers over 3G or EDGE.
203
Content from developer.android.com/tools/testing/what_to_test.html through their Creative Commons Attribution 2.5 license
What To Test
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.
204
Content from developer.android.com/tools/testing/what_to_test.html through their Creative Commons Attribution 2.5 license
Activity Testing Tutorial
37.
Activity Testing Tutorial
Content from developer.android.com/tools/testing/activity_test.html through their Creative Commons Attribution 2.5 license
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:
•
•
•
•
•
•
In this section
• Prerequisites
• Installing the Tutorial Sample Code
• Setting Up the Emulator
• Setting Up the Projects
• Creating the Test Case Class
• Adding the test case class file
• Adding the test case constructor
• Adding the setup method
• Adding an initial conditions test
• Adding a UI test
An Android test is itself an Android
• Adding state management tests
application that is linked to the
application under test by entries in its
• Running the Tests and Seeing the Results
AndroidManifest.xml file.
• Forcing Some Tests to Fail
Instead of Android components, an
• Next Steps
Android test application contains one or
more test cases. Each of these is a
Appendix
separate class definition.
• Installing the Completed Test Application
Android test case classes extend the
File
JUnit TestCase class.
• For Users Not Developing In Eclipse
Android test case classes for activities
extend JUnit and also connect you to the
See Also
application under test with
• Testing Fundamentals
instrumentation. You can send keystroke
or touch events directly to the UI.
• ActivityInstrumentationTestCase2
You choose an Android test case class
• Assert
based on the type of component
• InstrumentationTestRunner
(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.
205
Content from developer.android.com/tools/testing/activity_test.html through their Creative Commons Attribution 2.5 license
Activity Testing Tutorial
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-by-step. If you
want to run quickly through the tutorial, you can install the completed SpinnerTest application first,
and then follow the text. You may get more from the tutorial, however, if you create the test
application as you go. The instructions for installing the completed test application are in the
section Installing the Completed Test Application File.
The sample applications are described in more detail in the Samples topic. Follow the instructions to
download the version of the samples that's appropriate for the platform you're working with.
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:
206
Content from developer.android.com/tools/testing/activity_test.html through their Creative Commons Attribution 2.5 license
Activity Testing Tutorial
• In Eclipse, select File > New > Project > Android > Android Project, then click Next. The New
Android Project dialog appears.
• In the Project name text box, enter "SpinnerActivity". The Properties area is filled in automatically.
• In the Contents area, set "Create project from existing source".
• For Location, click Browse, navigate to the directory <SDK_path>/samples/android8/Spinner, then click Open. The directory name <SDK_path>/samples/android8/Spinner now appears in the Location text box.
• 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.
• In the Properties area, in the Min SDK Version:, enter "3".
• You should now see these values:
•
•
•
•
•
•
•
Project Name: "SpinnerActivity"
Create project from existing source: set
Location: "<SDK_path>/samples/android-8/Spinner"
Build Target: "API level of 3 or higher" (Target Name "Android 1.5 or higher")
Package name: (disabled, set to "com.android.example.spinner")
Create Activity: (disabled, set to ".SpinnerActivity")
Min SDK Version: "3"
The following screenshot summarizes these values:
207
Content from developer.android.com/tools/testing/activity_test.html through their Creative Commons Attribution 2.5 license
Activity Testing Tutorial
To create a new test project for the SpinnerTest application, follow these steps:
• Click Next. The New Android Test Project dialog appears.
• Set "Create a Test Project".
• Leave the other values unchanged. The result should be:
•
•
•
•
•
•
Create a Test Project: checked
Test Project Name: "SpinnerActivityTest"
Use default location: checked (this should contain the directory name
"workspace/SpinnerActivityTest").
Build Target: Use the same API level you used in the previous step.
Application name: "SpinnerActivityTest"
Package name: "com.android.example.spinner.test"
208
Content from developer.android.com/tools/testing/activity_test.html through their Creative Commons Attribution 2.5 license
Activity Testing Tutorial
•
Min SDK Version: "3"
The following screenshot summarizes these values:
• 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.
209
Content from developer.android.com/tools/testing/activity_test.html through their Creative Commons Attribution 2.5 license
Activity Testing Tutorial
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.
210
Content from developer.android.com/tools/testing/activity_test.html through their Creative Commons Attribution 2.5 license
Activity Testing Tutorial
•
•
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:
• In the Package Explorer, expand the test project SpinnerActivityTest if it is not open already.
• 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:
211
Content from developer.android.com/tools/testing/activity_test.html through their Creative Commons Attribution 2.5 license
Activity Testing Tutorial
The New Java Class wizard appears:
212
Content from developer.android.com/tools/testing/activity_test.html through their Creative Commons Attribution 2.5 license
Activity Testing Tutorial
• In the wizard, enter the following:
•
•
Name: "SpinnerActivityTest". This becomes the name of your test class.
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.
• You now have a new file SpinnerActivityTest.java in the project.
• 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
213
Content from developer.android.com/tools/testing/activity_test.html through their Creative Commons Attribution 2.5 license
Activity Testing Tutorial
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("com.android.example.spinner", SpinnerActivity.class);
} // end of SpinnerActivityTest constructor definition
This calls the superclass constructor with the Android package name
(com.android.example.spinner)and 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
214
Content from developer.android.com/tools/testing/activity_test.html through their Creative Commons Attribution 2.5 license
Activity Testing Tutorial
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 instrumentationbased 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 humancontrolled 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.
215
Content from developer.android.com/tools/testing/activity_test.html through their Creative Commons Attribution 2.5 license
Activity Testing Tutorial
To send key events to the UI of the application under test, you use the sendKeys() method. This method
does not have to run on the UI thread, since Android uses instrumentation to pass the key events to the
application under test.
The last part of the test compares the selection made by sending the key events to a pre-determined
value. This tests that the spinner is working as intended.
The following sections show you how to add the code for this test.
• 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;
•
• 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).
• 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 =
216
Content from developer.android.com/tools/testing/activity_test.html through their Creative Commons Attribution 2.5 license
Activity Testing Tutorial
(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.
217
Content from developer.android.com/tools/testing/activity_test.html through their Creative Commons Attribution 2.5 license
Activity Testing Tutorial
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:
• 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);
•
• Terminate the activity and restart it:
mActivity.finish();
mActivity = this.getActivity();
•
• Get the current spinner settings from the activity:
int currentPosition = mActivity.getSpinnerPosition();
String currentSelection = mActivity.getSpinnerSelection();
•
• 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;
218
Content from developer.android.com/tools/testing/activity_test.html through their Creative Commons Attribution 2.5 license
Activity Testing Tutorial
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:
• 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.
• 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();
•
• Set the spinner selection to a test value:
mActivity.setSpinnerPosition(TEST_STATE_PAUSE_POSITION);
mActivity.setSpinnerSelection(TEST_STATE_PAUSE_SELECTION);
•
• 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.
• 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.
• 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.
• Get the current state of the spinner:
int currentPosition = mActivity.getSpinnerPosition();
219
Content from developer.android.com/tools/testing/activity_test.html through their Creative Commons Attribution 2.5 license
Activity Testing Tutorial
String currentSelection = mActivity.getSpinnerSelection();
•
• 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";
•
• 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:
• In the Package Explorer, right-click the project SpinnerActivityTest at the top level, and then select Run
As > Android JUnit Test:
220
Content from developer.android.com/tools/testing/activity_test.html through their Creative Commons Attribution 2.5 license
Activity Testing Tutorial
• 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.
• The test application starts. You see a new tab for the JUnit view, next to the Package Explorer tab:
221
Content from developer.android.com/tools/testing/activity_test.html through their Creative Commons Attribution 2.5 license
Activity Testing Tutorial
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:
222
Content from developer.android.com/tools/testing/activity_test.html through their Creative Commons Attribution 2.5 license
Activity Testing Tutorial
•
•
•
•
•
Total time elapsed for the test application(labeled Finished after <x> seconds).
Number of runs (Runs:) - the number of tests in the entire test class.
Number of errors (Errors:) - the number of program errors and exceptions encountered during the
test run.
Number of failures (Failures:) - the number of test failures encountered during the test run. This is
the number of assertion failures. A test can fail even if the program does not encounter an error.
A progress bar. The progress bar extends from left to right as the tests run.
If all the tests succeed, the bar remains green. If a test fails, the bar turns from green to red.
•
A test method summary. Below the bar, you see a line for each class in the test application. To
look at the results for the individual methods in a test, click the arrow at the left to expand the line.
You see the name of each test method. To the right of the name, you see the time taken by the
test. You can look at the test's code by double-clicking its name.
The lower pane contains the failure trace. If all the tests are successful, this pane is empty. If some tests
fail, then if you highlight a failed test in the upper pane, the lower view contains a stack trace for the test.
This is demonstrated in the next section.
Note: If you run the test application and nothing seems to happen, look for the JUnit view. If you do not
see it, you may have run the test application as a regular Android application. Remember that you need to
run it as an Android JUnit application.
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:
• In Eclipse with ADT, go to the SpinnerActivity project and open the file SpinnerActivity.java.
• At the top of SpinnerActivity.java, at the end of the onCreate() method, find the following
line:
// mySpinner.setOnItemSelectedListener(null);
Remove the forward slash characters at the beginning of the line to uncomment the line. This sets the
listener callback to null:
mySpinner.setOnItemSelectedListener(null);
•
• The 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.
• Run the test, as described in the previous section Running the Tests and Seeing the Results.
223
Content from developer.android.com/tools/testing/activity_test.html through their Creative Commons Attribution 2.5 license
Activity Testing Tutorial
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:
• 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:
• 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.
224
Content from developer.android.com/tools/testing/activity_test.html through their Creative Commons Attribution 2.5 license
Activity Testing Tutorial
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, the base instrumentation class.
InstrumentationTestCase, the base instrumentation test case.
InstrumentationTestRunner, 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.
225
Content from developer.android.com/tools/testing/activity_test.html through their Creative Commons Attribution 2.5 license
Activity Testing Tutorial
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:
• Set up the projects for the application under test and the test application, as described in the section
section Setting Up the Projects.
• Set up the emulator, as described in the section Setting Up the Emulator.
• Add the test case class, as described in the section Adding the test case class file.
• Close Eclipse with ADT.
• Copy the file <SDK_path>/samples/android8/SpinnerTest/src/com/android/example/spinner/test/SpinnerActivityTe
st.java to the directory
workspace/SpinnerActivityTest/src/com/android/example/spinner/test/.
• Restart Eclipse with ADT.
• In Eclipse with ADT, re-build the project SpinnerActivityTest by selecting it in the Package
Explorer, right-clicking, and selecting Project > Clean.
• 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:
• 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:
•
•
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.
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.
• Navigate to the directory <SDK_path>/samples/android-8.
226
Content from developer.android.com/tools/testing/activity_test.html through their Creative Commons Attribution 2.5 license
Activity Testing Tutorial
• 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.
• 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.
• 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
•
• To create the test application, create a file SpinnerActivityTest.java in the directory
SpinnerActivityTest/src/com/android/example/spinner/test/.
• 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.
• 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
•
• In your device or emulator, check that both the main application SpinnerActivity and the test
application SpinnerActivityTest are installed.
• To run the test application, enter the following at the command line:
$ adb shell am instrument -w
227
Content from developer.android.com/tools/testing/activity_test.html through their Creative Commons Attribution 2.5 license
Activity Testing Tutorial
com.android.example.spinner.test/android.test.InstrumentationTestRunner
•
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(SpinnerActivityTest.jav
a:104)
at java.lang.reflect.Method.invokeNative(Native Method)
at android.test.InstrumentationTestCase.runMethod(InstrumentationTestCase.java:205)
at android.test.InstrumentationTestCase.runTest(InstrumentationTestCase.java:195)
at
android.test.ActivityInstrumentationTestCase2.runTest(ActivityInstrumentationTestCase2.java:17
5)
at android.test.AndroidTestRunner.runTest(AndroidTestRunner.java:169)
at android.test.AndroidTestRunner.runTest(AndroidTestRunner.java:154)
at android.test.InstrumentationTestRunner.onStart(InstrumentationTestRunner.java: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(SpinnerActivityTest.java:15
3)
at java.lang.reflect.Method.invokeNative(Native Method)
at android.test.InstrumentationTestCase.runMethod(InstrumentationTestCase.java:205)
at android.test.InstrumentationTestCase.runTest(InstrumentationTestCase.java:195)
at
android.test.ActivityInstrumentationTestCase2.runTest(ActivityInstrumentationTestCase2.java:17
5)
at android.test.AndroidTestRunner.runTest(AndroidTestRunner.java:169)
at android.test.AndroidTestRunner.runTest(AndroidTestRunner.java:154)
at android.test.InstrumentationTestRunner.onStart(InstrumentationTestRunner.java: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
228
Content from developer.android.com/tools/testing/activity_test.html through their Creative Commons Attribution 2.5 license
Debugging
38.
Debugging
Content from developer.android.com/tools/debugging/index.html through their Creative Commons Attribution 2.5 license
The Android SDK provides most of the tools that
In this section
you need to debug your applications. You need a
• Debugging Environment
JDWP-compliant debugger if you want to be able
to do things such as step through code, view
• Additional Debugging Tools
variable values, and pause execution of an
• Debugging Tips
application. If you are using Eclipse, a JDWPcompliant debugger is already included and there
is no setup required. If you are using another IDE, you can use the debugger that comes with it and attach
the debugger to a special port so it can communicate with the application VMs on your devices. The main
components that comprise a typical Android debugging environment are:
adb
adb acts as a middleman between a device and your development system. It provides various
device management capabilities, including moving and syncing files to the emulator, running a
UNIX shell on the device or emulator, and providing a general means to communicate with
connected emulators and devices.
Dalvik Debug Monitor Server
DDMS is a graphical program that communicates with your devices through adb. DDMS can
capture screenshots, gather thread and stack information, spoof incoming calls and SMS
messages, and has many other features.
Device or Android Virtual Device
Your application must run in a device or in an AVD so that it can be debugged. An adb device
daemon runs on the device or emulator and provides a means for the adb host daemon to
communicate with the device or emulator.
JDWP debugger
The Dalvik VM (Virtual Machine) supports the JDWP protocol to allow debuggers to attach to a
VM. Each application runs in a VM and exposes a unique port that you can attach a debugger to
via DDMS. If you want to debug multiple applications, attaching to each port might become
tedious, so DDMS provides a port forwarding feature that can forward a specific VM's debugging
port to port 8700. You can switch freely from application to application by highlighting it in the
Devices tab of DDMS. DDMS forwards the appropriate port to port 8700. Most modern Java IDEs
include a JDWP debugger, or you can use a command line debugger such as jdb.
Debugging Environment
Figure 1 shows how the various debugging tools work together in a typical debugging environment.
229
Content from developer.android.com/tools/debugging/index.html through their Creative Commons Attribution 2.5 license
Debugging
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
230
Content from developer.android.com/tools/debugging/index.html through their Creative Commons Attribution 2.5 license
Debugging
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.
231
Content from developer.android.com/tools/debugging/index.html through their Creative Commons Attribution 2.5 license
Debugging from Eclipse with ADT
39.
Debugging from Eclipse with ADT
Content from developer.android.com/tools/debugging/debugging-projects.html through their Creative Commons Attribution 2.5 license
If you are developing in Eclipse with the ADT
In this section
plugin, you can use the built-in Java Debugger,
• The Debug Perspective
along with DDMS, to debug your applications. To
access the debugger and DDMS, Eclipse displays
• The DDMS Perspective
the debugger and DDMS features as
perspectives, which are customized Eclipse views that display certain tabs and windows depending on the
perspective that you are in. Eclipse also takes care of starting the ADB host daemon for you, so you do not
have to run this manually.
The Debug Perspective in Eclipse
The Debug Perspective in Eclipse gives you access to the following tabs:
•
•
•
•
Debug - Displays previously and currently debugged Android applications and its currently
running threads
Variables - When breakpoints are set, displays variable values during code execution
Breakpoints - Displays a list of the set breakpoints in your application code
LogCat - Allows you to view system log messages in real time. The LogCat tab is also available in
the DDMS perspective.
You can access the Debug Perspective by clicking Window > Open Perspective > Debug. Refer to the
appropriate documentation for the Eclipse debugger for more information.
The DDMS Perspective
The DDMS Perspective in Eclipse lets you access all of the features of DDMS from within the Eclipse IDE.
The following sections of DDMS are available to you:
•
•
•
•
•
•
•
Devices - Shows the list of devices and AVDs that are connected to ADB.
Emulator Control - Lets you carry out device functions.
LogCat - Lets you view system log messages in real time.
Threads - Shows currently running threads within a VM.
Heap - Shows heap usage for a VM.
Allocation Tracker - Shows the memory allocation of objects.
File Explorer - Lets you explore the device's file system.
To access the DDMS perspective, go to Window > Open Perspective > DDMS. If DDMS does not
appear, go to Window > Open Perspective > Other ... and select DDMS from the Open Perspective
window that appears. For more information on using DDMS, see Using the Dalvik Debug Monitor Server.
232
Content from developer.android.com/tools/debugging/debugging-projects.html through their Creative Commons Attribution 2.5 license
Debugging from Other IDEs
40.
Debugging from Other IDEs
Content from developer.android.com/tools/debugging/debugging-projects-cmdline.html through their Creative Commons Attribution 2.5 license
If you are not using Eclipse to develop, you can
still take advantage of all the tools that the Android
SDK provides for debugging. A basic debugging
environment consists of:
In this section
• Starting a Debugging Environment
•
•
•
•
ADB
DDMS
Java Debugger
Configuring Your IDE to Attach to the
Debugging Port
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 Eclipse, 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:
• Load an AVD with the Android emulator or connect a device to your computer.
• 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.
• 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.
• 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 Eclipse 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.
233
Content from developer.android.com/tools/debugging/debugging-projects-cmdline.html through their Creative Commons Attribution 2.5 license
Using DDMS
41.
Using DDMS
Content from developer.android.com/tools/debugging/ddms.html through their Creative Commons Attribution 2.5 license
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.
In this section
• Running DDMS
• How DDMS Interacts with a Debugger
• Using DDMS
• Viewing heap usage for a process
• Tracking memory allocation of objects
• Working with an emulator or device's file
system
Running DDMS
• Examining thread information
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.
•
•
• Starting method profiling
• Using the Network Traffic tool
• Using LogCat
• Emulating phone operations and location
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.
234
Content from developer.android.com/tools/debugging/ddms.html through their Creative Commons Attribution 2.5 license
Using DDMS
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:
• In the Devices tab, select the process that you want to see the heap information for.
• Click the Update Heap button to enable heap information for the process.
235
Content from developer.android.com/tools/debugging/ddms.html through their Creative Commons Attribution 2.5 license
Using DDMS
• 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.
• 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:
• In the Devices tab, select the process that you want to enable allocation tracking for.
• 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.
• 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.
• To stop tracking or to clear the data and start over, click the Stop Tracking button.
• 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:
• In the Devices tab, select the emulator that you want to view the file system for.
• To copy a file from the device, locate the file in the File Explorer and click the Pull file button.
• 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.
• In the Devices tab, select the process that you want to examine the threads for.
• Click the Update Threads button.
• 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.
236
Content from developer.android.com/tools/debugging/ddms.html through their Creative Commons Attribution 2.5 license
Using DDMS
•
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:
• On the Devices tab, select the process that you want to enable method profiling for.
• Click the Start Method Profiling button.
• Interact with your application to start the methods that you want to profile.
• 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 battery-efficient. Generally,
you should look for short spikes that can be delayed, or that should cause a later transfer to be preempted.
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);
237
Content from developer.android.com/tools/debugging/ddms.html through their Creative Commons Attribution 2.5 license
Using DDMS
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
238
Content from developer.android.com/tools/debugging/ddms.html through their Creative Commons Attribution 2.5 license
Using DDMS
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.
239
Content from developer.android.com/tools/debugging/ddms.html through their Creative Commons Attribution 2.5 license
Reading and Writing Logs
42.
Reading and Writing Logs
Content from developer.android.com/tools/debugging/debugging-log.html through their Creative Commons Attribution 2.5 license
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.
In this section
• The Log class
• Starting LogCat
• Filtering Log Output
• Controlling Log Output Format
• Viewing Alternative Log Output Buffers
• Viewing stdout and stderr
The Log class
• Debugging Web Pages
Log is a logging class that you can utilize in your
code to print out messages to the LogCat. Common logging methods include:
•
•
•
•
•
v(String,
d(String,
i(String,
w(String,
e(String,
String) (verbose)
String) (debug)
String) (information)
String) (warning)
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:
240
Content from developer.android.com/tools/debugging/debugging-log.html through their Creative Commons Attribution 2.5 license
Reading and Writing Logs
-c
Clears (flushes) the entire log and exits.
-d
Dumps the log to the screen and exits.
Writes log message output to <filename>. The default is stdout.
f <filename>
-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.
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
o
o
o
o
o
o
V
D
I
W
E
F
S
—
—
—
—
—
—
—
Verbose (lowest priority)
Debug
Info
Warning
Error
Fatal
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...}
241
Content from developer.android.com/tools/debugging/debugging-log.html through their Creative Commons Attribution 2.5 license
Reading and Writing Logs
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 — Display priority/tag and PID of the process issuing the message (the default format).
process — Display PID only.
tag — Display the priority/tag only.
raw — Display the raw log message, with no other metadata fields.
time — Display the date, invocation time, priority/tag, and PID of the process issuing the
message.
threadtime — Display the date, invocation time, priority, tag, and the PID and TID of the
thread issuing the message.
long — Display all metadata fields and separate messages with blank lines.
When starting LogCat, you can specify the output format you want by using the -v option:
[adb] logcat [-v <format>]
242
Content from developer.android.com/tools/debugging/debugging-log.html through their Creative Commons Attribution 2.5 license
Reading and Writing Logs
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 — View the buffer that contains radio/telephony related messages.
events — View the buffer containing events-related messages.
main — 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.
243
Content from developer.android.com/tools/debugging/debugging-log.html through their Creative Commons Attribution 2.5 license
Improving Your Code with lint
43.
Improving Your Code with lint
Content from developer.android.com/tools/debugging/improving-w-lint.html through their Creative Commons Attribution 2.5 license
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.
In This Document
• Overview
• Running lint from Eclipse
• Running lint from the command-line
• Configuring lint
• Configuring lint in Eclipse
• Configuring the lint file
• Configuring lint checking in Java and XML
source files
See Also
Overview
• lint (reference)
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
244
Content from developer.android.com/tools/debugging/improving-w-lint.html through their Creative Commons Attribution 2.5 license
Improving Your Code with lint
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>
245
Content from developer.android.com/tools/debugging/improving-w-lint.html through their Creative Commons Attribution 2.5 license
Improving Your Code with lint
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.
246
Content from developer.android.com/tools/debugging/improving-w-lint.html through their Creative Commons Attribution 2.5 license
Improving Your Code with lint
Configuring lint in Eclipse
You can configure global, project-specific, and file-specific settings for lint from the Eclipse user
interface.
Global preferences
• Open Window > Preferences > Android > Lint Error Checking.
• 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
• 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.
• 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:
•
•
•
•
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.
247
Content from developer.android.com/tools/debugging/improving-w-lint.html through their Creative Commons Attribution 2.5 license
Improving Your Code with lint
<?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:
• Open the Java or XML file that has a lint warning or error in an Eclipse editor.
• 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.
• 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 ParserError issue in the
FeedProvider class:
@SuppressLint("ParserError")
public class FeedProvider extends ContentProvider {
To suppress checking for all lint issues in the Java file, use the all keyword, like this:
@SuppressLint("all")
Configuring lint checking in XML
248
Content from developer.android.com/tools/debugging/improving-w-lint.html through their Creative Commons Attribution 2.5 license
Improving Your Code with lint
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"
249
Content from developer.android.com/tools/debugging/improving-w-lint.html through their Creative Commons Attribution 2.5 license
Optimizing Your UI
44.
Optimizing Your UI
Content from developer.android.com/tools/debugging/debugging-ui.html through their Creative Commons Attribution 2.5 license
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.
In this section
• Using Hierarchy Viewer
• Running Hierarchy Viewer and choosing a
window
• About the View Hierarchy window
• Working with an individual View in Tree
View
• Debugging with View Hierarchy
• Optimizing with View Hierarchy
• Using Pixel Perfect
• About the Pixel Perfect window
• Working with Pixel Perfect overlays
• Using lint to optimize your UI
Related videos
Using Hierarchy Viewer
Running Hierarchy Viewer and choosing a window
To run Hierarchy Viewer, follow these steps:
• 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.
• If you have not done so already, install the application you want to work with.
• Run the application, and ensure that its UI is visible.
• From a terminal, launch hierarchyviewer from the <sdk>/tools/ directory.
• 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.
• 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.
250
Content from developer.android.com/tools/debugging/debugging-ui.html through their Creative Commons Attribution 2.5 license
Optimizing Your UI
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.
251
Content from developer.android.com/tools/debugging/debugging-ui.html through their Creative Commons Attribution 2.5 license
Optimizing Your UI
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
o
o
Bold red: The block represents the the View that is currently selected in Tree View.
Light red: The block represents the parent of the block outlined in bold red.
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.
252
Content from developer.android.com/tools/debugging/debugging-ui.html through their Creative Commons Attribution 2.5 license
Optimizing Your UI
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:
• View class: The View object's class.
• View object address: A pointer to View object.
• View object ID: The value of the android:id attribute.
• 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:
•
•
•
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.
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.
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.
• 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:
253
Content from developer.android.com/tools/debugging/debugging-ui.html through their Creative Commons Attribution 2.5 license
Optimizing Your UI
•
•
•
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.
254
Content from developer.android.com/tools/debugging/debugging-ui.html through their Creative Commons Attribution 2.5 license
Optimizing Your UI
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.
255
Content from developer.android.com/tools/debugging/debugging-ui.html through their Creative Commons Attribution 2.5 license
Optimizing Your UI
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.
256
Content from developer.android.com/tools/debugging/debugging-ui.html through their Creative Commons Attribution 2.5 license
Optimizing Your UI
When you select a pixel in the Loupe pane, you see the following information at the bottom of the
pane:
o
o
o
•
Pixel swatch: A rectangle filled with the same color as the pixel.
HTML color code: The hexadecimal RGB code corresponding to the pixel color
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.
257
Content from developer.android.com/tools/debugging/debugging-ui.html through their Creative Commons Attribution 2.5 license
Optimizing Your UI
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.
258
Content from developer.android.com/tools/debugging/debugging-ui.html through their Creative Commons Attribution 2.5 license
Profiling with Traceview and dmtracedump
45.
Profiling with Traceview and dmtracedump
Content from developer.android.com/tools/debugging/debugging-tracing.html through their Creative Commons Attribution 2.5 license
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.
In this section
Traceview Layout
• Creating Trace Files
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:
• Viewing Trace Files in Traceview
• Traceview Layout
• Timeline Panel
• Profile Panel
• Copying Trace Files to a Host Machine
• Using dmtracedump
• Traceview Known Issues
•
•
A timeline panel -- describes when each
thread and method started and stopped
A profile panel -- provides a summary of what happened inside a method
The sections below provide addition information about the traceview output panes.
Timeline Panel
Figure 1 shows a close up of the timeline panel. Each thread’s execution is shown in its own row, with time
increasing to the right. Each method is shown in another color (colors are reused in a round-robin fashion
starting with the methods that have the most inclusive time). The thin lines underneath the first row show
the extent (entry to exit) of all the calls to the selected method.
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.
259
Content from developer.android.com/tools/debugging/debugging-tracing.html through their Creative Commons Attribution 2.5 license
Profiling with Traceview and dmtracedump
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.
260
Content from developer.android.com/tools/debugging/debugging-tracing.html through their Creative Commons Attribution 2.5 license
Profiling with Traceview and dmtracedump
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-basename>.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
dmtracedump is a tool that gives you an alternate way of generating graphical call-stack diagrams from
trace log files. The tool uses the Graphviz Dot utility to create the graphical output, so you need to install
Graphviz before running dmtracedump.
The dmtracedump tool generates the call stack data as a tree diagram, with each call represented as a
node. It shows call flow (from parent node to child nodes) using arrows. The diagram below shows an
example of dmtracedump output.
261
Content from developer.android.com/tools/debugging/debugging-tracing.html through their Creative Commons Attribution 2.5 license
Profiling with Traceview and dmtracedump
Figure 3. Screenshot of dmtracedump
For each node, dmtracedump shows <ref> callname (<inc-ms>, <excms>,<numcalls>), where
<ref> -- Call reference number, as used in trace logs
<inc-ms> -- Inclusive elapsed time (milliseconds spent in method, including all child methods)
<exc-ms> -- Exclusive elapsed time (milliseconds spent in method, not including any child
methods)
<numcalls> -- Number of calls
•
•
•
•
The usage for dmtracedump is:
dmtracedump [-ho] [-s sortable] [-d trace-base-name] [-g outfile] <trace-base-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
Description
-d <tracebase-name>
Diff with this trace name
-g <outfile>
Generate output to <outfile>
-h
Turn on HTML output
262
Content from developer.android.com/tools/debugging/debugging-tracing.html through their Creative Commons Attribution 2.5 license
Profiling with Traceview and dmtracedump
-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%.
Traceview Known Issues
Threads
Traceview logging does not handle threads well, resulting in these two problems:
• If a thread exits during profiling, the thread name is not emitted;
• The VM reuses thread IDs. If a thread stops and another starts, they may get the same ID.
263
Content from developer.android.com/tools/debugging/debugging-tracing.html through their Creative Commons Attribution 2.5 license
Analyzing Display and Performance with Systrace
46.
Analyzing Display and Performance with Systrace
Content from developer.android.com/tools/debugging/systrace.html through their Creative Commons Attribution 2.5 license
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.
In this section
• Overview
• Generating Traces
• Limiting trace data
• Configuring trace data categories
• Running a trace
• Analyzing Traces
• Long running processes
• Interruptions in display execution
See also
• Systrace
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.
264
Content from developer.android.com/tools/debugging/systrace.html through their Creative Commons Attribution 2.5 license
Analyzing Display and Performance with Systrace
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. Setup 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 root access to the device, but most systrace log data only requires that the
device be enabled for developer debugging.
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 using the --set-tags option and the --disk, -cpu-freq, --cpu-idle, --cpu-load options.
Configuring trace data categories
To use systrace effectively, you must specify the types of processes you want to trace. The tool can
gather the following types of process information:
•
•
General system processes such as graphics, audio and input processes (selected using trace
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:
• Use the --set-tags option:
$> python systrace.py --set-tags=gfx,view,wm
•
• 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:
• On the device connected for tracing, navigate to: Settings > Developer options > Monitoring >
Enable traces.
• 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.
265
Content from developer.android.com/tools/debugging/systrace.html through their Creative Commons Attribution 2.5 license
Analyzing Display and Performance with Systrace
Running a trace
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:
• Make sure the device is connected through a USB cable and is enabled for debugging.
• 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
•
• On the device, execute any user actions you want be included in the trace.
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
266
Content from developer.android.com/tools/debugging/systrace.html through their Creative Commons Attribution 2.5 license
Analyzing Display and Performance with Systrace
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
267
Content from developer.android.com/tools/debugging/systrace.html through their Creative Commons Attribution 2.5 license
Analyzing Display and Performance with Systrace
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 smoothrunning, 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 reference page.
268
Content from developer.android.com/tools/debugging/systrace.html through their Creative Commons Attribution 2.5 license
Investigating Your RAM Usage
47.
Investigating Your RAM Usage
Content from developer.android.com/tools/debugging/debugging-memory.html through their Creative Commons Attribution 2.5 license
Because Android is designed for mobile devices,
you should always be careful about how much
random-access memory (RAM) your app uses.
Although Android’s Dalvik virtual machine
performs routine garbage collection, this doesn’t
mean you can ignore when and where your app
allocates and releases memory. In order to
provide a stable user experience that allows the
system to quickly switch between apps, it’s
important that your app does not needlessly
consume memory when the user is not interacting
with it.
In this section
• Interpreting Log Messages
• Viewing Heap Updates
• Tracking Allocations
• Viewing Overall Memory Allocations
• Capturing a Heap Dump
• Triggering Memory Leaks
See Also
Even if you follow all the best practices for
• Managing Your App's Memory
Managing Your App Memory during development
(which you should), you still might leak objects or
introduce other memory bugs. The only way to be certain your app is using as little memory as possible is
to analyze your app’s memory usage with tools. This guide shows you how to do that.
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
269
Content from developer.android.com/tools/debugging/debugging-memory.html through their Creative Commons Attribution 2.5 license
Investigating Your RAM Usage
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:
• Open the Device Monitor.
From your <sdk>/tools/ directory, launch the monitor tool.
• In the Debug Monitor window, select your app's process from the list on the left.
• Click Update Heap above the process list.
• 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
270
Content from developer.android.com/tools/debugging/debugging-memory.html through their Creative Commons Attribution 2.5 license
Investigating Your RAM Usage
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:
• Open the Device Monitor.
From your <sdk>/tools/ directory, launch the monitor tool.
• In the DDMS window, select your app's process in the left-side panel.
• In the right-side panel, select the Allocation Tracker tab.
• Click Start Tracking.
• Interact with your app to execute the code paths you want to analyze.
• 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:
271
Content from developer.android.com/tools/debugging/debugging-memory.html through their Creative Commons Attribution 2.5 license
Investigating Your RAM Usage
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 app’s process is destroyed. Generally, the most important portion
of this is “private dirty” RAM, which is the most expensive because it is used by only your process
and its contents exist only in RAM so can’t be paged to storage (because Android does not use
swap). All Dalvik and native heap allocations you make will be private dirty RAM; Dalvik and
native allocations you share with the Zygote process are shared dirty RAM.
Proportional Set Size (PSS)
This is a measurement of your app’s RAM use that takes into account sharing pages across
processes. Any RAM pages that are unique to your process directly contribute to its PSS value,
while pages that are shared with other processes contribute to the PSS value only in proportion to
the amount of sharing. For example, a page that is shared between two processes will contribute
half of its size to the PSS of each process.
A nice characteristic of the PSS measurement is that you can add up the PSS across all processes to
determine the actual memory being used by all processes. This means PSS is a good measure for the
actual RAM weight of a process and for comparison against the RAM use of other processes and the total
available RAM.
For example, below is the the output for Gmail’s process on a tablet device. There is a lot of information
here, but key points for discussion are listed below.
Note: The information you see may vary slightly from what is shown here, as some details of the output
differ across platform versions.
272
Content from developer.android.com/tools/debugging/debugging-memory.html through their Creative Commons Attribution 2.5 license
Investigating Your RAM Usage
** MEMINFO in pid 9953 [com.google.android.gm] **
Pss
Pss Shared Private Shared Private
Heap
Total
Clean
Dirty
Dirty
Clean
Clean
Size
------ ------ ------ ------ ------ ------ -----Native Heap
0
0
0
0
0
0
7800
Dalvik Heap
5110(3)
0
4136
4988(3)
0
0
9168
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
Heap
Heap
Alloc
Free
------ -----7637(6) 126
8958(6) 210
16595
336
Objects
Views:
AppContexts:
Assets:
Local Binders:
Death Recipients:
OpenSSL Sockets:
426
6(7)
2
64
0
1
ViewRootImpl:
Activities:
AssetManagers:
Proxy Binders:
3(8)
2(7)
2
34
SQL
MEMORY_USED:
PAGECACHE_OVERFLOW:
1739
1164
MALLOC_SIZE:
62
Generally, you should be concerned with only the Pss Total and Private Dirty columns. In
some cases, the Private Clean and Heap Alloc columns also offer interesting data. Here is
some more information about the different memory allocations (the rows) you should observe:
Dalvik Heap
The RAM used by Dalvik allocations in your app. The Pss Total includes all Zygote
allocations (weighted by their sharing across processes, as described in the PSS definition
above). The Private Dirty number is the actual RAM committed to only your app’s heap,
composed of your own allocations and any Zygote allocation pages that have been modified
since forking your app’s process from Zygote.
Note: On newer platform versions that have the Dalvik Other section, the Pss Total
and Private Dirty numbers for Dalvik Heap do not include Dalvik overhead such as the
just-in-time compilation (JIT) and garbage collection (GC) bookkeeping, whereas older versions
list it all combined under Dalvik.
The Heap Alloc is the amount of memory that the Dalvik and native heap allocators keep
track of for your app. This value is larger than Pss Total and Private Dirty because
your process was forked from Zygote and it includes allocations that your process shares with all
the others.
.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 app’s own
code. Generally, the actual mapped size will be much larger—the RAM here is only what currently
273
Content from developer.android.com/tools/debugging/debugging-memory.html through their Creative Commons Attribution 2.5 license
Investigating Your RAM Usage
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 can’t be garbage collected due to static
references on them, which is common. These objects often have a lot of other allocations
associated with them and so are a good way to track large memory leaks.
Note: A View or Drawable object also holds a reference to the Activity that it's from, so
holding a View or Drawable object can also lead to your app leaking an Activity.
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:
• Open the Device Monitor.
From your <sdk>/tools/ directory, launch the monitor tool.
• In the DDMS window, select your app's process in the left-side panel.
• Click Dump HPROF file, shown in figure 3.
• In the window that appears, name your HPROF file, select the save location, then click Save.
274
Content from developer.android.com/tools/debugging/debugging-memory.html through their Creative Commons Attribution 2.5 license
Investigating Your RAM Usage
Figure 3. The Device Monitor tool, showing the [1] Dump HPROF file button.
If you need to be more precise about when the dump is created, you can also create a heap dump at the
critical point in your app code by calling dumpHprofData().
The heap dump is provided in a format that's similar to, but not identical to one from the Java HPROF tool.
The major difference in an Android heap dump is due to the fact that there are a large number of
allocations in the Zygote process. But because the Zygote allocations are shared across all app
processes, they don’t matter very much to your own heap analysis.
To analyze your heap dump, you can use a standard tool like jhat or the Eclipse Memory Analyzer Tool
(MAT). However, first you'll need to convert the HPROF file from Android's format to the J2SE HPROF
format. You can do this using the hprof-conv tool provided in the <sdk>/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 converstion—it performs the conversion by default.
You can now load the converted file in MAT or another heap analysis tool that understands the J2SE
HPROF format.
When analyzing your heap, you should look for memory leaks caused by:
•
•
•
Long-lived references to an Activity, Context, View, Drawable, and other objects that may hold a
reference to the container Activity or Context.
Non-static inner classes (such as a Runnable, which can hold the Activity instance).
Caches that hold objects longer than necessary.
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.
275
Content from developer.android.com/tools/debugging/debugging-memory.html through their Creative Commons Attribution 2.5 license
Investigating Your RAM Usage
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:
• Create two HPROF files as described above, in Capturing a Heap Dump.
• Open the first HPROF file in MAT (File > Open Heap Dump).
• In the Navigation History view (if not visible, select Window > Navigation History), right-click on
Histogram and select Add to Compare Basket.
• Open the second HPROF file and repeat steps 2 and 3.
• Switch to the Compare Basket view and click Compare the Results (the red "!" icon in the top-right
corner of the view).
276
Content from developer.android.com/tools/debugging/debugging-memory.html through their Creative Commons Attribution 2.5 license
Investigating Your RAM Usage
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:
• 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.
• 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.
277
Content from developer.android.com/tools/debugging/debugging-memory.html through their Creative Commons Attribution 2.5 license
Using the Dev Tools App
48.
Using the Dev Tools App
Content from developer.android.com/tools/debugging/debugging-devtools.html through their Creative Commons Attribution 2.5 license
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.
278
Content from developer.android.com/tools/debugging/debugging-devtools.html through their Creative Commons Attribution 2.5 license
Publishing Overview
49.
Publishing Overview
Content from developer.android.com/tools/publishing/publishing_overview.html through their Creative Commons Attribution 2.5 license
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.
•
Quickview
You release the application to users.
•
Learn how to publish Android apps.
Find out how to prepare apps for
release.
Learn how to release apps to users.
In this section
• Preparing Your Application for Release
• Releasing Your Application to Users
See also
• Publishing on Google Play
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.
•
Building and signing a release version of your application.
279
Content from developer.android.com/tools/publishing/publishing_overview.html through their Creative Commons Attribution 2.5 license
Publishing Overview
The Android Development Tools (ADT) plugin and the Ant build script that are provided with the
Android SDK tools provide everything you need to build and sign a release version of your
application.
•
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:
280
Content from developer.android.com/tools/publishing/publishing_overview.html through their Creative Commons Attribution 2.5 license
Publishing Overview
•
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
281
Content from developer.android.com/tools/publishing/publishing_overview.html through their Creative Commons Attribution 2.5 license
Publishing Overview
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
282
Content from developer.android.com/tools/publishing/publishing_overview.html through their Creative Commons Attribution 2.5 license
Publishing Overview
transactions yourself and you will not be able to use Google Play's In-app Billing service to sell in-app
products. In addition, you will not be able to use the Licensing service to help prevent unauthorized
installation and use of your application.
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.
283
Content from developer.android.com/tools/publishing/publishing_overview.html through their Creative Commons Attribution 2.5 license
Preparing for Release
50.
Preparing for Release
Content from developer.android.com/tools/publishing/preparing.html through their Creative Commons Attribution 2.5 license
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.
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 section
• Introduction
• Gathering Materials and Resources
• Configuring Your Application
• Building Your Application
• Preparing External Servers and Resources
• Testing Your Application for Release
See also
This document summarizes the main tasks you
• Publishing Overview
need to perform to prepare your application for
release. The tasks that are described in this
• Signing Your Applications
document apply to all Android applications
• Launch Checklist for Google Play
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 releaseready 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
284
Content from developer.android.com/tools/publishing/preparing.html through their Creative Commons Attribution 2.5 license
Preparing for Release
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 Eclipse
and the ADT plugin or with the Ant build script (included with the Android SDK). For example, you can use
the Eclipse Export Wizard to compile, sign, and optimize your application all at once. You can also
configure the Ant build script to do the same when you build from the command line.
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
285
Content from developer.android.com/tools/publishing/preparing.html through their Creative Commons Attribution 2.5 license
Preparing for Release
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 Obtain a suitable private key.
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.
Clean up your project directories
286
Content from developer.android.com/tools/publishing/preparing.html through their Creative Commons Attribution 2.5 license
Preparing for Release
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 settings
Verify that the following manifest 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 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.
287
Content from developer.android.com/tools/publishing/preparing.html through their Creative Commons Attribution 2.5 license
Preparing for Release
•
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 fle 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 Eclipse with the ADT
plugin or you are using the Ant build script from the command line, you can automate the entire build
process.
Building with Eclipse
You can use the Eclipse Export Wizard to build a release-ready .apk file that is signed with your private
key and optimized. To learn how to run the Export Wizard, see Compile and sign with Eclipse ADT. The
Export Wizard compiles your application for release, signs your application with your private key, and
optimizes your application with the zipalign tool. The Export Wizard should run successfully if you have run
or debugged your application from Eclipse and you have no errors in your application (see Building and
Running from Eclipse with ADT for more information.
The Export Wizard 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, the Export Wizard will help you
generate one (see Signing Your Applications for more information about the signing process and signing
guidelines.
Building with Ant
You can use the Ant build script (included in the Android SDK) to build a release-ready .apk file that is
signed with your private key and optimized. To learn how to do this, see Building in Release Mode. This
build method assumes you have a certificate and private key suitable for signing your application. If you do
not have a suitable certificate and private key, the Export Wizard will help you generate one (see Signing
Your Applications for more information about the signing process and signing guidelines.
288
Content from developer.android.com/tools/publishing/preparing.html through their Creative Commons Attribution 2.5 license
Preparing for Release
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 handsetsized 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.
289
Content from developer.android.com/tools/publishing/preparing.html through their Creative Commons Attribution 2.5 license
Versioning Your Applications
51.
Versioning Your Applications
Content from developer.android.com/tools/publishing/versioning.html through their Creative Commons Attribution 2.5 license
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.
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 section
• Setting Application Version
• Specifying Your Application's System API
Requirements
See also
• Preparing to Publish Your Application
• Launch Checklist for Google Play
• The AndroidManifest.xml File
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:
•
android:versionCode — An integer value that represents the version of the application
code, relative to other versions.
The value is an integer so that other applications can programmatically evaluate it, for example to
check an upgrade or downgrade relationship. You can set the value to any integer you want,
however you should make sure that each successive release of your application uses a greater
value. The system does not enforce this behavior, but increasing the value with successive
releases is normative.
Typically, you would release the first version of your application with versionCode set to 1, then
monotonically increase the value with each release, regardless whether the release constitutes a
major or minor release. This means that the android:versionCode value does not
necessarily have a strong resemblance to the application release version that is visible to the
290
Content from developer.android.com/tools/publishing/versioning.html through their Creative Commons Attribution 2.5 license
Versioning Your Applications
user (see android:versionName, below). Applications and publishing services should not
display this version value to users.
•
android:versionName — A string value that represents the release version of the
application code, as it should be shown to users.
The value is a string so that you can describe the application version as a
<major>.<minor>.<point> string, or as any other type of absolute or relative version identifier.
As with android:versionCode, the system does not use this value for any internal
purpose, other than to enable applications to display it to users. Publishing services may also
extract the android:versionName value for display to users.
You define both of these version attributes in the <manifest> element of the manifest file.
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 — The minimum version of the Android platform on which the
application will run, specified by the platform's API Level identifier.
android:targetSdkVersion — 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.
android:maxSdkVersion — 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.
291
Content from developer.android.com/tools/publishing/versioning.html through their Creative Commons Attribution 2.5 license
Versioning Your Applications
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.
292
Content from developer.android.com/tools/publishing/versioning.html through their Creative Commons Attribution 2.5 license
Signing Your Applications
52.
Signing Your Applications
Content from developer.android.com/tools/publishing/app-signing.html through their Creative Commons Attribution 2.5 license
The Android system requires that all installed
applications be digitally signed with a certificate
whose private key is held by the application's
developer. The Android system uses the
certificate as a means of identifying the author of
an application and establishing trust relationships
between applications. The certificate is not used
to control which applications the user can install.
The certificate does not need to be signed by a
certificate authority: it is perfectly allowable, and
typical, for Android applications to use self-signed
certificates.
The important points to understand about signing
Android applications are:
•
•
•
•
•
•
•
Quickview
•
•
•
•
All Android apps must be signed
You can sign with a self-signed key
How you sign your apps is critical —
read this document carefully
Determine your signing strategy early
in the development process
In this section
• Signing Process
• Signing Strategies
• Basic Setup for Signing
All applications must be signed. The
• Signing in Debug Mode
system will not install an application on
• Signing Release Mode
an emulator or a device if it is not signed.
• Obtain a suitable private key
To test and debug your application, the
build tools sign your application with a
• Compile the application in release mode
special debug key that is created by the
• Sign your application with your private key
Android SDK build tools.
• Align the final APK package
When you are ready to release your
application for end-users, you must sign
• Compile and sign with Eclipse ADT
it with a suitable private key. You cannot
• Securing Your Private Key
publish an application that is signed with
the debug key generated by the SDK
See also
tools.
• Versioning Your Applications
You can use self-signed certificates to
• Preparing to Publish
sign your applications. No certificate
authority is needed.
The system tests a signer certificate's expiration date only at install time. If an application's signer
certificate expires after the application is installed, the application will continue to function
normally.
You can use standard tools — Keytool and Jarsigner — to generate keys and sign your
application .apk files.
After you sign your application for release, we recommend that you use the zipalign tool to
optimize the final APK package.
The Android system will not install or run an application that is not signed appropriately. This applies
wherever the Android system is run, whether on an actual device or on the emulator. For this reason, you
must set up signing for your application before you can run it or debug it on an emulator or device.
Signing Process
The Android build process signs your application differently depending on which build mode you use to
build your application. There are two build modes: debug mode and release mode. You use debug mode
when you are developing and testing your application. You use release mode when you want to build a
293
Content from developer.android.com/tools/publishing/app-signing.html through their Creative Commons Attribution 2.5 license
Signing Your Applications
release version of your application that you can distribute directly to users or publish on an application
marketplace such as Google Play.
When you build in debug mode the Android SDK build tools use the Keytool utility (included in the JDK) to
create a debug key. Because the SDK build tools created the debug key, they know the debug key's alias
and password. Each time you compile your application in debug mode, the build tools use the debug key
along with the Jarsigner utility (also included in the JDK) to sign your application's .apk file. Because the
alias and password are known to the SDK build tools, the tools don't need to prompt you for the debug
key's alias and password each time you compile.
When you build in release mode you use your own private key to sign your application. If you don't have a
private key, you can use the Keytool utility to create one for you. When you compile your application in
release mode, the build tools use your private key along with the Jarsigner utility to sign your application's
.apk file. Because the certificate and private key you use are your own, you must provide the password
for the keystore and key alias.
The debug signing process happens automatically when you run or debug your application using Eclipse
with the ADT plugin. Debug signing also happens automatically when you use the Ant build script with the
debug option. You can automate the release signing process by using the Eclipse Export Wizard or by
modifying the Ant build script and building with the release option.
Signing Strategies
Some aspects of application signing may affect how you approach the development of your application,
especially if you are planning to release multiple applications.
In general, the recommended strategy for all developers is to sign all of your applications with the same
certificate, throughout the expected lifespan of your applications. There are several reasons why you
should do so:
•
•
•
Application upgrade – As you release updates to your application, you must continue to sign the
updates with the same certificate or set of certificates, if you want users to be able to upgrade
seamlessly to the new version. When the system is installing an update to an application, it
compares the certificate(s) in the new version with those in the existing version. If the certificates
match exactly, including both the certificate data and order, then the system allows the update. If
you sign the new version without using matching certificates, you must also assign a different
package name to the application — in this case, the user installs the new version as a completely
new application.
Application modularity – The Android system allows applications that are 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 application in modules, and users
can update each of the modules independently if needed.
Code/data sharing through permissions – The Android system provides signature-based
permissions enforcement, so that an application can expose functionality to another application
that is signed with a specified certificate. By signing multiple applications with the same certificate
and using signature-based permissions checks, your applications can share code and data in a
secure manner.
Another important consideration in determining your signing strategy is how to set the validity period of the
key that you will use to sign your applications.
•
If you plan to support upgrades for a single application, you should ensure that your key has a
validity period that exceeds the expected lifespan of that application. 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.
294
Content from developer.android.com/tools/publishing/app-signing.html through their Creative Commons Attribution 2.5 license
Signing Your Applications
•
•
If you will sign multiple distinct applications with the same key, you should ensure that your key's
validity period exceeds the expected lifespan of all versions of all of the applications, including
dependent applications that may be added to the suite in the future.
If you plan to publish your application(s) on Google Play, the key you use to sign the
application(s) must have a validity period ending after 22 October 2033. Google Play enforces
this requirement to ensure that users can seamlessly upgrade applications when new versions
are available.
As you design your application, keep these points in mind and make sure to use a suitable certificate to
sign your applications.
Basic Setup for Signing
Before you begin, make sure that the Keytool utility and Jarsigner utility are available to the SDK build
tools. Both of these tools are available in the JDK. In most cases, you can tell the SDK build tools how to
find these utilities by setting your JAVA_HOME environment variable so it references a suitable JDK.
Alternatively, you can add the JDK version of Keytool and Jarsigner to your PATH variable.
If you are developing on a version of Linux that originally came with GNU Compiler for Java, make sure
that the system is using the JDK version of Keytool, rather than the gcj version. If Keytool is already in your
PATH, it might be pointing to a symlink at /usr/bin/keytool. In this case, check the symlink target
to be sure it points to the Keytool in the JDK.
Signing in Debug Mode
The Android build tools provide a debug signing mode that makes it easier for you to develop and debug
your application, while still meeting the Android system requirement for signing your APK. When using
debug mode to build your app, the SDK tools invoke Keytool to automatically create a debug keystore and
key. This debug key is then used to automatically sign the APK, so you do not need to sign the package
with your own key.
The SDK tools create the debug keystore/key with predetermined names/passwords:
•
•
•
•
•
Keystore name: "debug.keystore"
Keystore password: "android"
Key alias: "androiddebugkey"
Key password: "android"
CN: "CN=Android Debug,O=Android,C=US"
If necessary, you can change the location/name of the debug keystore/key or supply a custom debug
keystore/key to use. However, any custom debug keystore/key must use the same keystore/key names
and passwords as the default debug key (as described above). (To do so in Eclipse/ADT, go to Windows
> Preferences > Android > Build.)
Caution: You cannot release your application to the public when signed with the debug certificate.
Eclipse Users
If you are developing in Eclipse/ADT (and have set up Keytool and Jarsigner as described above in Basic
Setup for Signing), signing in debug mode is enabled by default. When you run or debug your application,
ADT signs the .apk file with the debug certificate, runs zipalign on the package, then installs it on
the selected emulator or connected device. No specific action on your part is needed, provided ADT has
access to Keytool.
Ant Users
295
Content from developer.android.com/tools/publishing/app-signing.html through their Creative Commons Attribution 2.5 license
Signing Your Applications
If you are using Ant to build your .apk file, debug signing mode is enabled by using the debug option
with the ant command (assuming that you are using a build.xml file generated by the android
tool). When you run ant debug to compile your app, the build script generates a keystore/key and signs
the APK for you. The script then also aligns the APK with the zipalign tool. No other action on your
part is needed. Read Building and Running Apps on the Command Line for more information.
Expiry of the Debug Certificate
The self-signed certificate used to sign your application in debug mode (the default on Eclipse/ADT and
Ant builds) will have an expiration date of 365 days from its creation date.
When the certificate expires, you will get a build error. On Ant builds, the error looks like this:
debug:
[echo] Packaging bin/samples-debug.apk, and signing it with a debug key...
[exec] Debug Certificate expired on 8/4/08 3:43 PM
In Eclipse/ADT, you will see a similar error in the Android console.
To fix this problem, simply delete the debug.keystore file. The default storage location for AVDs 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 in Release Mode
When your application is ready for release to other users, you must:
• Obtain a suitable private key
• Compile the application in release mode
• Sign your application with your private key
• Align the final APK package
If you are developing in Eclipse with the ADT plugin, you can use the Export Wizard to perform the
compile, sign, and align procedures. The Export Wizard even allows you to generate a new keystore and
private key in the process. So if you use Eclipse, you can skip to Compile and sign with Eclipse ADT.
1. Obtain a suitable private key
In preparation for signing your application, you must first ensure that you have a suitable private key with
which to sign. A suitable private key is one that:
•
•
•
Is in your possession
Represents the personal, corporate, or organizational entity to be identified with the application
Has a validity period that exceeds the expected lifespan of the application or application suite. A
validity period of more than 25 years is recommended.
If you plan to publish your application(s) on Google Play, note that a validity period ending after
22 October 2033 is a requirement. You can not upload an application if it is signed with a key
whose validity expires before that date.
296
Content from developer.android.com/tools/publishing/app-signing.html through their Creative Commons Attribution 2.5 license
Signing Your Applications
•
Is not the debug key generated by the Android SDK tools.
The key may be self-signed. If you do not have a suitable key, you must generate one using Keytool. Make
sure that you have Keytool available, as described in Basic Setup.
To generate a self-signed key with Keytool, use the keytool command and pass any of the options
listed below (and any others, as needed).
Warning: Keep your private key secure. Before you run Keytool, make sure to read Securing Your Private
Key for a discussion of how to keep your key secure and why doing so is critically important to you and to
users. In particular, when you are generating your key, you should select strong passwords for both the
keystore and key.
Warning: Keep the keystore file you generate with Keytool in a safe, secure place. You must use the
same key to sign future versions of your application. If you republish your app with a new key, Google Play
will consider it a new app. For more information on settings that must remain constant over the life of your
app, see the Android Developer Blog post Things That Cannot Change.
Keytool Option
Description
-genkey
Generate a key pair (public and private keys)
-v
Enable verbose output.
-alias <alias_name>
An alias for the key. Only the first 8 characters of the alias
are used.
-keyalg <alg>
The encryption algorithm to use when generating the key.
Both DSA and RSA are supported.
-keysize <size>
The size of each generated key (bits). If not supplied,
Keytool uses a default key size of 1024 bits. In general, we
recommend using a key size of 2048 bits or higher.
-dname <name>
A Distinguished Name that describes who created the key.
The value is used as the issuer and subject fields in the
self-signed certificate.
Note that you do not need to specify this option in the
command line. If not supplied, Jarsigner prompts you to
enter each of the Distinguished Name fields (CN, OU, and
so on).
-keypass <password>
The password for the key.
As a security precaution, do not include this option in your
command line. If not supplied, Keytool prompts you to enter
the password. In this way, your password is not stored in
your shell history.
-validity <valdays>
The validity period for the key, in days.
297
Content from developer.android.com/tools/publishing/app-signing.html through their Creative Commons Attribution 2.5 license
Signing Your Applications
Note: A value of 10000 or greater is recommended.
-keystore <keystorename>.keystore
A name for the keystore containing the private key.
-storepass <password>
A password for the keystore.
As a security precaution, do not include this option in your
command line. If not supplied, Keytool prompts you to enter
the password. In this way, your password is not stored in
your shell history.
Here's an example of a Keytool command that generates a private key:
$ keytool -genkey -v -keystore my-release-key.keystore
-alias alias_name -keyalg RSA -keysize 2048 -validity 10000
Running the example command above, Keytool prompts you to provide 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 and key are protected by the passwords you
entered. The keystore contains a single key, valid for 10000 days. The alias is a name that you — will use
later, to refer to this keystore when signing your application.
For more information about Keytool, see the documentation at
http://docs.oracle.com/javase/6/docs/technotes/tools/windows/keytool.html
2. Compile the application in release mode
In order to release your application to users, you must compile it in release mode. In release mode, the
compiled application is not signed by default and you will need to sign it with your private key.
Caution: You can not release your application unsigned, or signed with the debug key.
With Eclipse
To export an unsigned APK from Eclipse, right-click the project in the Package Explorer and select
Android Tools > Export Unsigned Application Package. Then specify the file location for the unsigned
APK. (Alternatively, open your AndroidManifest.xml file in Eclipse, select the Manifest tab, and
click Export an unsigned APK.)
Note that you can combine the compiling and signing steps with the Export Wizard. See Compiling and
signing with Eclipse ADT.
With Ant
If you are using Ant, you can enable release mode by using the release option with the ant command.
For example, if you are running Ant from the directory containing your build.xml file, the command
would look like this:
$ ant release
By default, the build script compiles the application APK without signing it. The output file in your project
bin/ will be <your_project_name>-unsigned.apk. Because the application APK is still unsigned,
you must manually sign it with your private key and then align it using zipalign.
However, the Ant build script can also perform the signing and aligning for you, if you have provided the
path to your keystore and the name of your key alias in the project's ant.properties file. With this
information provided, the build script will prompt you for your keystore and alias password when you
perform ant release, it will sign the package and then align it. The final output file in bin/ will
instead be <your_project_name>-release.apk. With these steps automated for you, you're able
298
Content from developer.android.com/tools/publishing/app-signing.html through their Creative Commons Attribution 2.5 license
Signing Your Applications
to skip the manual procedures below (steps 3 and 4). To learn how to specify your keystore and alias in
the ant.properties file, see Building and Running Apps on the Command Line.
3. Sign your application with your private key
When you have an application package that is ready to be signed, you can do sign it using the Jarsigner
tool. Make sure that you have Jarsigner available on your machine, as described in Basic Setup. Also,
make sure that the keystore containing your private key is available.
To sign your application, you run Jarsigner, referencing both the application's APK and the keystore
containing the private key with which to sign the APK. The table below shows the options you could use.
Jarsigner Option
Description
-keystore <keystorename>.keystore
The name of the keystore containing your private key.
-verbose
Enable verbose output.
-sigalg
The name of the signature algorithim to use in signing the
APK. Use the value SHA1withRSA.
-digestalg
The message digest algorithim to use in processing the
entries of an APK. Use the value SHA1.
-storepass <password>
The password for the keystore.
As a security precaution, do not include this option in your
command line unless you are working at a secure computer.
If not supplied, Jarsigner prompts you to enter the password.
In this way, your password is not stored in your shell history.
-keypass <password>
The password for the private key.
As a security precaution, do not include this option in your
command line unless you are working at a secure computer.
If not supplied, Jarsigner prompts you to enter the password.
In this way, your password is not stored in your shell history.
Here's how you would use Jarsigner to sign an application package called my_application.apk,
using the example keystore created above.
$ jarsigner -verbose -sigalg SHA1withRSA -digestalg SHA1 -keystore my-release-key.keystore
my_application.apk alias_name
Running the example command above, Jarsigner prompts you to provide passwords for the keystore and
key. It then modifies the APK in-place, meaning the APK is now signed. Note that you can sign an APK
multiple times with different keys.
Caution: As of JDK 7, the default signing algorithim has changed, requiring you to specify the signature
and digest algorithims (-sigalg and -digestalg) when you sign an APK.
To verify that your APK is signed, you can use a command like this:
299
Content from developer.android.com/tools/publishing/app-signing.html through their Creative Commons Attribution 2.5 license
Signing Your Applications
$ jarsigner -verify my_signed.apk
If the APK is signed properly, Jarsigner prints "jar verified". If you want more details, you can try one of
these commands:
$ jarsigner -verify -verbose my_application.apk
or
$ jarsigner -verify -verbose -certs my_application.apk
The command above, with the -certs option added, will show you the "CN=" line that describes who
created the key.
Note: If you see "CN=Android Debug", this means the APK was signed with the debug key generated by
the Android SDK. If you intend to release your application, you must sign it with your private key instead of
the debug key.
For more information about Jarsigner, see the documentation at
http://docs.oracle.com/javase/6/docs/technotes/tools/windows/jarsigner.html
4. Align the final APK package
Once you have signed the APK with your private key, run zipalign on the file. This tool ensures that all
uncompressed data starts with a particular byte alignment, relative to the start of the file. Ensuring
alignment at 4-byte boundaries provides a performance optimization when installed on a device. When
aligned, the Android system is able to read files with mmap(), even if they contain binary data with
alignment restrictions, rather than copying all of the data from the package. The benefit is a reduction in
the amount of RAM consumed by the running application.
The zipalign tool is provided with the Android SDK, inside the tools/ directory. To align your signed
APK, execute:
$ zipalign -v 4 your_project_name-unaligned.apk your_project_name.apk
The -v flag turns on verbose output (optional). 4 is the byte-alignment (don't use anything other than 4).
The first file argument is your signed .apk file (the input) and the second file is the destination .apk file
(the output). If you're overriding an existing APK, add the -f flag.
Caution: Your input APK must be signed with your private key before you optimize the package with
zipalign. If you sign it after using zipalign, it will undo the alignment.
For more information, read about the zipalign tool.
Compile and sign with Eclipse ADT
If you are using Eclipse with the ADT plugin, you can use the Export Wizard to export a signed APK (and
even create a new keystore, if necessary). The Export Wizard performs all the interaction with the Keytool
and Jarsigner for you, which allows you to sign the package using a GUI instead of performing the manual
procedures to compile, sign, and align, as discussed above. Once the wizard has compiled and signed
your package, it will also perfom package alignment with zipalign. Because the Export Wizard uses
both Keytool and Jarsigner, you should ensure that they are accessible on your computer, as described
above in the Basic Setup for Signing.
To create a signed and aligned APK in Eclipse:
• Select the project in the Package Explorer and select File > Export.
• Open the Android folder, select Export Android Application, and click Next.
300
Content from developer.android.com/tools/publishing/app-signing.html through their Creative Commons Attribution 2.5 license
Signing Your Applications
The Export Android Application wizard now starts, which will guide you through the process of signing your
application, including steps for selecting the private key with which to sign the APK (or creating a new
keystore and private key).
• Complete the Export Wizard and your application will be compiled, signed, aligned, and ready for
distribution.
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 applications that maliciously replace your authentic applications or corrupt them. Such a
person could also sign and distribute applications under your identity that attack other applications or the
system itself, or corrupt or steal user data.
Your private key is required for signing all future versions of your application. If you lose or misplace your
key, you will not be able to publish updates to your existing application. 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.
When you generate your key with Keytool, do not supply the -storepass and -keypass
options at the command line. If you do so, your passwords will be available in your shell history,
which any user on your computer could access.
Similarly, when signing your applications with Jarsigner, do not supply the -storepass and keypass options at the command line.
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 that you generate with the Keytool in a safe,
secure place.
In general, if you follow common-sense precautions when generating, using, and storing your key, it will
remain secure.
301
Content from developer.android.com/tools/publishing/app-signing.html through their Creative Commons Attribution 2.5 license
Support Library
53.
Support Library
Content from developer.android.com/tools/support-library/index.html through their Creative Commons Attribution 2.5 license
The Android Support Library package is a set of
code libraries that provide backward-compatible
versions of Android framework APIs as well as
features that are only available through the library
APIs. Each Support Library is backwardcompatible to a specific Android API level. This
design means that your applications can use the
libraries' features and still be compatible with
devices running Android 1.6 (API level 4) and up.
In this section
• Overview
• Revisions
See also
• Support Library Features
• Support Library Setup
This guide provides information about what features are enabled by the Support Libraries, how to use
them in your development environment and information about library releases.
Overview
Including the Support Libraries in your Android project is considered a best practice for application
developers, depending on the range of platform versions your app is targeting and the APIs that it uses.
Using the features the libraries provide can help you improve the look of your application, increase
performance and broaden the reach of your application to more users. If you use the Android code
template tools, you will notice that all the Android application templates include one or more of the Support
Libraries by default.
The Support Libraries each target a base Android API level and each provides a different set of features.
In order to effectively use the libraries, it is important to consider what features you want to support and
understand what features are supported by each library at what Android API level. To get started, review
the Support Library Features guide. After that, go to the Support Library Setup topic to learn how to
incorporate the Support Libraries into your application. For more details about Support Library APIs, see
the android.support packages in the API reference.
Revisions
This section provides details about the Support Library package releases.
Android Support Library, revision 19 (October 2013)
Changes for v4 support library:
•
•
•
•
Added support for external Storage APIs with the getObbDirs(),
getExternalFilesDirs(), getExternalCacheDirs(), and
getStorageState(). These helper methods always return a single file object on
devices running Android 4.3 (API level 18) and earlier. When running on Android 4.4
(API level 19) and higher, these methods may return more than one file object.
Added PrintHelper class that works with the Print APIs to print images with a
minimum of code.
Added drag-to-open user interface support for pop-up menus. For more information, see
PopupMenuCompat and ListPopupWindowCompat.
Improved accessibility support with the addition of a findFocus() method in
AccessibilityNodeProviderCompat and the getLiveRegion() method in
AccessibilityNodeInfoCompat.
302
Content from developer.android.com/tools/support-library/index.html through their Creative Commons Attribution 2.5 license
Support Library
•
•
•
Added helper class ScaleGestureDetectorCompat for accessing new scaling
gesture methods.
Fixed problem with ActionBarDrawerToggle in right-to-left language displays.
Modified AutoScrollHelper option to consume touch events or allow them to be
passed through to other views.
Changes for v7 mediarouter library:
•
•
Added support for media playback queuing, setting HTTP header values and media
playback duration.
Added explicit start, get, and end session actions for explicitly managing media playback
sessions with media router.
Android Support Library, revision 18 (July 2013)
Changes for v4 support library:
•
•
•
•
User interface
o Added BidiFormatter for handling text strings that combine right to left and
left to right-formatted text.
o Modified ViewPager to better handle cases where the pager has a measured
width of zero in the initial layout processing.
o Modified DrawerLayout and SlidingPaneLayout to not throw exceptions
for measurement while the project code is being edited.
Accessibility
o Added ExploreByTouchHelper to simplify the implementation of
accessibility for custom views.
o Fixed a problem with ViewPager incorrectly populating
TYPE_VIEW_SCROLLED accessibility events.
o Fixed a null pointer exception in ViewPager when populating an accessibility
event.
o Simplified AccessibilityNodeInfoCompat by changing CharSequence
inputs to String objects.
o Deprecated an AccessibilityRecordCompat constructor that used an
Object as input.
Media
o Added TransportMediator helper class to manage media transport control,
such as play, pause, skip and other media actions.
o Added DisplayManagerCompat for managing display output to one or more
device displays.
Other changes
o Added WakefulBroadcastReceiver helper class for implementing a
common pattern of detecting a device wakeup event and passing work off to a
Service while ensuring that the device does not go back to sleep before the
handoff is complete.
o Added two new APIs, commitContentChanged() and
rollbackContentChanged(), to AsyncTaskLoader to help deal with
background updates for data changes that are subsequently canceled.
New v7 appcompat library:
303
Content from developer.android.com/tools/support-library/index.html through their Creative Commons Attribution 2.5 license
Support Library
•
Added ActionBar to allow implementation of the action bar user interface design
pattern back to Android 2.1 (API level 7) and higher. Use of this class requires that you
implement your activity by extending the new ActionBarActivity class.
New v7 mediarouter library:
Added a new mediarouter library that provides support for the Google Cast developer preview.
The v7 mediarouter library APIs provide a means of controlling the routing of media channels and
streams from the current device to external screens, speakers, and other destination devices,
with compatibility back to Android 2.1 (API level 7). See V7 mediarouter library for more
information.
The v7 mediarouter library APIs introduced in Support Library r18 are subject to change in later
revisions of the Support Library. At this time, we recommend using the library only in connection
with the Google Cast developer preview.
Android Support Library, revision 13 (May 2013)
Changes for v4 support library:
•
•
•
•
•
•
•
•
•
Added DrawerLayout for creating a Navigation Drawer that can be pulled in from the
edge of a window.
Added SlidingPaneLayout widget for creating linked summary and detail views that
appropriately adapt to various screen sizes.
Added ActionBarDrawerToggle as a way to tie together the functions of
DrawerLayout and ActionBar.
Added ViewDragHelper as a new common component for dragging views within a
parent view.
Added ScrollerCompat to provide Scroller and OverScroller compatibility
support.
Added FileProvider to allow sharing of private files between applications.
Updated ViewPager to throw an exception if the associated PagerAdapter class is
modified without a call to notifyDataSetChanged().
Fixed an issue with ViewPager children drawing sort order.
Fixed GestureDetectorCompat to dispatch missing
onSingleTapConfirmed(MotionEvent) calls between tap timeout and long press
events.
New v7 gridlayout library:
•
•
Added GridLayout to provide support for the GridLayout layout object.
Added Space which can be used to create blank areas within a GridLayout layout
object.
Android Support Library, revision 12 (February 2013)
Changes for v4 support library:
•
•
Improved interaction behavior for ViewPager.
Fixed a bug that could cause ViewPager to select the wrong page.
304
Content from developer.android.com/tools/support-library/index.html through their Creative Commons Attribution 2.5 license
Support Library
•
•
Fixed use of removeView() method during layout for ViewPager.
Fixed issue with SearchViewCompat where using the back button to dismiss does not
clear the search text. This fix only applies to host API levels 14 and higher.
Android Support Library, revision 11 (November 2012)
Changes for v4 support library:
•
•
•
•
•
•
•
User Interface
o Added support for nested Fragment classes.
o Added improvements to FragmentManager debugging.
o Fixed problem in FragmentTabHost where fragment and tab interaction could
result in a ListView state loss.
o Fixed issue with user-visible hint in FragmentStatePagerAdapter.
o Added PageTransformer interface to ViewPager to allow applications to
supply a custom transition behavior for scrolling.
o Added new features and fixes to TaskStackBuilder from current release.
o Fixed PagerTitleStrip to correctly track the PagerAdapter currently in
use.
o Fixed display flickering, positioning, and text clipping problems with
PagerTitleStrip.
o Fixed PagerTabStrip to properly respect padding when drawing an
underline.
Accessibility
o Added support for new accessibility gesture and touch event types in
AccessibilityEventCompat.
o Added support for new accessibility APIs in ViewCompat.
o Added support for performAccessibilityAction() method to
ViewCompat.
Added support for gestures with GestureDetectorCompat.
Added support for performing atomic operations on files using a new AtomicFile
class.
Added support for the full set of make methods in IntentCompat.
Added trimToSize() method in LruCache utility class.
Updated ConnectivityManagerCompat to get NetworkInfo from a
CONNECTIVITY_ACTION broadcast.
Android Support Library, revision 10 (August 2012)
Changes for v4 support library:
•
Added support for notification features introduced in Android 4.1 (API level 16) with
additions to NotificationCompat.
Android Support Library, revision 9 (June 2012)
Changes for v4 support library:
•
User Interface Support
o Added PagerTabStrip support, providing enhanced functionality beyond
PagerTitleStrip.
305
Content from developer.android.com/tools/support-library/index.html through their Creative Commons Attribution 2.5 license
Support Library
o
•
•
Fixed various bugs for PagerTitleStrip and PagerTabStrip, including
setAllCaps option, title alignment, appearance improvements, minimum
width constraints and touch navigation issues.
o Added support for ViewPager page gutters, which helps the ViewPager class
provide paging support for content with a large horizontal scroll range, such as
a map.
o Fixed numerous bugs for ViewPager, including size and data set change
problems, page positioning, user interaction, scroll tracking and keyboard
navigation problems.
o Fixed many bugs for Fragment, including proper handling of
onActivityResult() when the target fragment no longer exists, dispatching
selection events to invisible fragments, improved
FragmentTransaction.replace() behavior and added better state
handling for fragments being moved out of view.
o Added support for the postOnAnimation() method in ViewCompat.
o Updated NavUtils to use Android 4.1 (API level 16) Up navigation
functionality when available.
Accessibility
o Updated accessibility support classes, including
AccessibilityNodeInfoCompat, to follow fixes made in Android 4.1 (API
level 16).
o Added support for accessibility scroll actions in ViewPager.
General improvements
o Updated TaskStackBuilder to reflect API changes in Android 4.1 (API level
16).
o Enhanced TaskStackBuilder to allow it to be used from a Service.
o Added support for EXTRA_HTML_TEXT to ShareCompat.
o Updated NotificationCompat.Builder to support the setNumber()
method.
o Added support in ConnectivityManagerCompat for the
isActiveNetworkMetered() method.
Android Support Library, revision 8 (April 2012)
Changes for v4 support library:
•
•
•
Fixed intent flags for PendingIntent objects generated by TaskStackBuilder.
Removed unused attributes from the gridlayout library projects to make sure the library
can be built with API level 7 and higher.
Added .classpath and .project files for the gridlayout library project.
Android Support Library, revision 7 (March 2012)
Changes for v4 support library:
•
•
Added ShareCompat, which provides helper classes for sending and receiving content
for social sharing applications, including new metadata for attributing shared data to the
source app. This class also provides compatible integration with the new
ShareActionProvider in Android 4.0.
Added NavUtils and TaskStackBuilder to provide support for implementing the
Android Design guidelines for navigation. These additions include a way to implement
the action bar's Up button across versions. For an example implementation of this
306
Content from developer.android.com/tools/support-library/index.html through their Creative Commons Attribution 2.5 license
Support Library
•
pattern, see the AppNavigation sample in
(<sdk>/samples/<platform>/AppNavigation).
Added NotificationCompat.Builder to provide a compatibility implementation of
Android 3.0's Notification.Builder helper class for creating standardized system
notifications.
Android Support Library, revision 6 (December 2011)
Note: Reference for support library APIs are now available with the framework references, for example:
android.support.v4.app.
Changes for v4 support library:
•
•
•
Changes to ViewPager:
o Added extra decorative view support for ViewPager. Decorative views may be
supplied as child views of a pager in XML layout.
o Added PagerAdapter.getPageTitle() to supply title strings for pages,
which defaults to no title for each page.
o Added PagerTitleStrip, a non-interactive title strip, that can be added as a
child of ViewPager. Developers can supply text appearance and color, as well
as layout sizing and gravity information.
o Updated PagerAdapter methods to take ViewGroup objects, rather than View
to avoid class casting in adapter implementations.
o Updated ViewPager to use Launcher-style fling behavior.
o Bug fixes for user interface interaction and test automation.
Support for Fragments:
o Changed setStartDeferred() method to
setUserVisibleHint(boolean).
o Added deferred start for off-screen pages to improve performance.
Support for Accessiblity APIs:
o Updated AccessibilityDelegateCompat methods to return empty lists
instead of null.
o Added new APIs needed by the v4 samples.
Android Support Library, revision 5 (December 2011)
Changes for v4 support library:
•
•
Support for Accessiblity APIs:
o Added AccessibilityDelegateCompat to support
View.AccessibilityDelegate.
o Added AccessibilityEventCompat to support AccessibilityEvent.
o Added AccessibilityManagerCompat to support
AccessibilityManager.
o Added AccessibilityNodeInfoCompat to support
AccessibilityNodeInfo.
o Added AccessibilityRecordCompat to support AccessibilityRecord.
o Added AccessibilityServiceInfoCompat to support
AccessibilityServiceInfo.
o Added ViewGroupCompat to support accessibility features in ViewGroup.
o Modified ViewCompat to support accessibility features in View.
Changes to ViewPager:
307
Content from developer.android.com/tools/support-library/index.html through their Creative Commons Attribution 2.5 license
Support Library
o
o
o
o
o
o
Added support for margins between pages. An optional Drawable can be
provided to fill the margins.
Added support for EdgeEffect.
Added support for keyboard navigation
Added support to control how many pages are kept to either side of the current
page.
Improved touch physics.
Bug fixes for user interface behavior.
Android Support Library, revision 4 (October 2011)
Changes for v4 support library:
•
•
•
•
•
Added EdgeEffectCompat to support EdgeEffect.
Added LocalBroadcastManager to allow applications to easily register for and
receive intents within a single application without broadcasting them globally.
Added support in ViewCompat to check for and set overscroll modes for Views on
Android 2.3 and later.
Changes to Fragment APIs:
o Added new APIs to control the visibility of new menus.
o Added custom animation APIs.
o Added APIs in FragmentActivity to retain custom, non-configuration
instance data.
o Various bug fixes.
Fixed a Loader bug that caused issues in canceling AsyncTasks when running on
Froyo and older versions of the platform. The support code now uses its own version of
AsyncTask to keep the same behavior on all platform versions.
Android Support Library, revision 3 (July 2011)
Changes for v4 support library:
•
•
•
•
•
Adds support for Fragment.SavedState
Adds MotionEventCompat to support newer MotionEvent APIs
Adds VelocityTrackerCompat to support a newer VelocityTracker APIs
Adds ViewConfigurationCompat to support a newer ViewConfiguration
APIs
All new APIs (available only in the support library) that allow you to create UIs with
horizontal paging, allowing users to swipe left and right between content views. Classes
to support this include:
o ViewPager: A ViewGroup that manages the layout for the child views,
which the user can swipe between.
o PagerAdapter: An adapter that populates the ViewPager with the views
that represent each page.
o FragmentPagerAdapter: An extension of PagerAdapter for flipping
between fragments.
o FragmentStatePagerAdapter: An extension of PagerAdapter for
flipping between fragments that uses the library's support for
Fragment.SavedState.
New v13 support library:
308
Content from developer.android.com/tools/support-library/index.html through their Creative Commons Attribution 2.5 license
Support Library
•
Includes the FragmentPagerAdapter and FragmentStatePagerAdapter
to support the horizontal paging.
These are exactly the same as the APIs added to the v4 support library, but rely on
other platform components in Android 3.2. Use this library instead of v4 if you're
developing for Android 3.2 and higher (all other APIs in the v4 library are already
available with API level 13).
Android Support Library, revision 2 (May 2011)
Changes for v4 library:
•
•
Support for fragment animations
Fix Fragment.onActivityResult() bug
Android Support Library, revision 1 (March 2011)
Initial release with the v4 library.
309
Content from developer.android.com/tools/support-library/index.html through their Creative Commons Attribution 2.5 license
Support Library Features
54.
Support Library Features
Content from developer.android.com/tools/support-library/features.html through their Creative Commons Attribution 2.5 license
The Android Support Library package contains
several libraries that can be included in your
application. Each of these libraries supports a
specific range of Android platform versions and
set of features.
This guide explains the important features and
version support provided by the Support Libraries
to help you decide which of them you should
include in your application. In general, we
recommend including the v4 support and v7
appcompat libraries, because they support a wide
range of Android versions and provide APIs for
recommended user interface patterns.
In this section
• v4 Support Library
• v7 Libraries
• v7 appcompat library
• v7 gridlayout library
• v7 mediarouter library
• v8 Support Library
• v13 Support Library
See also
• Support Library Revisions
In order to use any of the following libraries, you
• Support Library Setup
must download the library files to your Android
SDK installation. Follow the directions for
downloading the Support Libraries in Support Library Setup to complete this step. You must take additional
steps to include a specific Support Library in your application. See the end of each library section below for
important information on how to include the library in your application.
v4 Support Library
This library is designed to be used with Android 1.6 (API level 4) and higher. It includes the largest set of
APIs compared to the other libraries, including support for application components, user interface features,
accessibility, data handling, network connectivity, and programming utilities. Here are a few of the key
classes included in the v4 library:
•
•
•
App Components
o Fragment - Adds support encapsulation of user interface and functionality with
Fragments, enabling applications provide layouts that adjust between small and largescreen devices.
o NotificationCompat - Adds support for rich notification features.
o LocalBroadcastManager - Allows applications to easily register for and receive
intents within a single application without broadcasting them globally.
User Interface
o ViewPager - Adds a ViewGroup that manages the layout for the child views, which the
user can swipe between.
o PagerTitleStrip - Adds a non-interactive title strip, that can be added as a child of
ViewPager.
o PagerTabStrip - Adds a navigation widget for switching between paged views, that
can also be used with ViewPager.
o DrawerLayout - Adds support for creating a Navigation Drawer that can be pulled in
from the edge of a window.
o SlidingPaneLayout - Adds widget for creating linked summary and detail views that
appropriately adapt to various screen sizes.
Accessibility
o ExploreByTouchHelper - Adds a helper class for implementing accessibility support
for custom views.
310
Content from developer.android.com/tools/support-library/features.html through their Creative Commons Attribution 2.5 license
Support Library Features
o
o
o
o
•
AccessibilityEventCompat - Adds support for AccessibilityEvent. For more
information about implementing accessibility, see Accessibility.
AccessibilityNodeInfoCompat - Adds support for AccessibilityNodeInfo.
AccessibilityNodeProviderCompat - Adds support for
AccessibilityNodeProvider.
AccessibilityDelegateCompat - Adds support for
View.AccessibilityDelegate.
Content
o
o
Loader - Adds support for asynchronous loading of data. The library also provides
concrete implementations of this class, including CursorLoader and
AsyncTaskLoader.
FileProvider - Adds support for sharing of private files between applications.
There are many other APIs included in this library. For complete, detailed information about the v4 Support
Library APIs, see the android.support.v4 package in the API reference.
This library is located in the <sdk>/extras/android/support/v4/ directory after you download
the Android Support Libraries. This library does not contain user interface resources. To include it in your
application project, follow the instructions for adding libraries without resources.
The Gradle build script dependency identifier for this library is as follows:
com.android.support:support-v4:18.0.+
This dependency notation specifies the release version 18.0.0 or higher.
v7 Libraries
There are several libraries designed to be used with Android 2.1 (API level 7) and higher. These libraries
provide specific feature sets and can be included in your application independently from each other.
v7 appcompat library
This library adds support for the Action Bar user interface design pattern.
Note: This library depends on the v4 Support Library. If you are using Ant or Eclipse, make sure you
include the v4 Support Library as part of this library's classpath.
Here are a few of the key classes included in the v7 appcompat library:
•
•
•
ActionBar - Provides an implementation of the action bar user interface pattern. For more
information on using the Action Bar, see the Action Bar developer guide.
ActionBarActivity - Adds an application activity class that must be used as a base class for
activities that uses the Support Library action bar implementation.
ShareActionProvider - Adds support for a standardized sharing action (such as email or
posting to social applications) that can be included in an action bar.
This library is located in the <sdk>/extras/android/support/v7/appcompat/ directory
after you download the Android Support Libraries. This library contains user interface resources. To
include it in your application project, follow the instructions for adding libraries with resources.
The Gradle build script dependency identifier for this library is as follows:
com.android.support:appcompat-v7:18.0.+
This dependency notation specifies the release version 18.0.0 or higher.
311
Content from developer.android.com/tools/support-library/features.html through their Creative Commons Attribution 2.5 license
Support Library Features
v7 gridlayout library
This library adds support for the GridLayout class, which allows you to arrange user interface elements
using a grid of rectangular cells. For detailed information about the v7 gridlayout library APIs, see the
android.support.v7.widget package in the API reference.
This library is located in the <sdk>/extras/android/support/v7/gridlayout/ directory
after you download the Android Support Libraries. This library contains user interface resources. To
include it in your application project, follow the instructions for adding libraries with resources.
The Gradle build script dependency identifier for this library is as follows:
com.android.support:gridlayout-v7:18.0.+
This dependency notation specifies the release version 18.0.0 or higher.
v7 mediarouter library
This library provides MediaRouter, MediaRouteProvider, and related media classes that support the
Google Cast developer preview.
In general, the APIs in the v7 mediarouter library provide a means of controlling the routing of media
channels and streams from the current device to external screens, speakers, and other destination
devices. The library includes APIs for publishing app-specific media route providers, for discovering and
selecting destination devices, for checking media status, and more. For detailed information about the v7
mediarouter library APIs, see the android.support.v7.media package in the API reference.
The v7 mediarouter library is located in the
<sdk>/extras/android/support/v7/mediarouter/ directory after you download the
Android Support Library. It's provided as a library project with a dependency on the v7 appcompat library,
so you'll need to include both libraries in your build path when setting up your project. For more information
on how to set up your project, follow the instructions in adding libraries with resources. If you are
developing in Eclipse/ADT, make sure to include both the android-support-v7mediarouter.jar and android-support-v7-appcompat.jar files.
If you are using Android Studio, all you need to do is specify the Gradle build script dependency identifier
com.android.support:support-v7-mediarouter:<revision>, where "18.0.0" is the
minimum revision at which the library is available. For example:
com.android.support:mediarouter-v7:18.0.+
The v7 mediarouter library APIs introduced in Support Library r18 are subject to change in later revisions
of the Support Library. At this time, we recommend using the library only in connection with the Google
Cast developer preview.
v8 Support Library
This library is designed to be used with Android (API level 8) and higher. It adds support for the
RenderScript computation framework. These APIs are included in the
android.support.v8.renderscript package. You should be aware that the steps for including
these APIs in your application is very different from other support library APIs. For more information about
using these APIs in your application, see the RenderScript developer guide.
Note: Use of RenderScript with the support library is supported with the Android Eclipse plugin and Ant
build tools. It is not currently supported with Android Studio or Gradle-based builds.
v13 Support Library
312
Content from developer.android.com/tools/support-library/features.html through their Creative Commons Attribution 2.5 license
Support Library Features
This library is designed to be used for Android 3.2 (API level 13) and higher. It adds support for the
Fragment user interface pattern with the (FragmentCompat) class and additional fragment support
classes For more information about fragments, see the Fragments developer guide. For detailed
information about the v13 Support Library APIs, see the android.support.v13 package in the API
reference.
This library is located in the <sdk>/extras/android/support/v13/ directory after you
download the Android Support Libraries. This library does not contain user interface resources. To include
it in your application project, follow the instructions for adding libraries without resources.
The Gradle build script dependency identifier for this library is as follows:
com.android.support:support-v13:18.0.+
This dependency notation specifies the release version 18.0.0 or higher.
313
Content from developer.android.com/tools/support-library/features.html through their Creative Commons Attribution 2.5 license
Support Library Setup
55.
Support Library Setup
Content from developer.android.com/tools/support-library/setup.html through their Creative Commons Attribution 2.5 license
How you setup the Android Support Libraries in
your development project depends on what
features you want to use and what range of
Android platform versions you want to support
with your application.
This document guides you through downloading
the Support Library package and adding libraries
to your development environment.
Downloading the Support Libraries
The Android Support Library package is provided
as a supplemental download to the Android SDK
and is available through the Android SDK
Manager. Follow the instructions below to obtain
the Support Library files.
To download the Support Library through the SDK
Manager:
In this section
• Downloading the Support Library
• Choosing Support Libraries
• Adding Support Libraries
• Adding libraries without resources
• Adding libraries with resources
• Using Support Library APIs
• Manifest Declaration Changes
• Code Samples
See also
• Support Library Revisions
• Support Library Features
• Start the Android SDK Manager.
• In the SDK Manager window, scroll to the end of the Packages list, find the Extras folder and, if
necessary, expand to show its contents.
• Select the Android Support Library item.
Note: If you're developing with Android Studio, select and install the Android Support Repository item
instead.
• Click the Install packages... button.
314
Content from developer.android.com/tools/support-library/setup.html through their Creative Commons Attribution 2.5 license
Support Library Setup
Figure 1. The Android SDK Manager with the Android Support Library selected.
After downloading, the tool installs the Support Library files to your existing Android SDK directory. The
library files are located in the following subdirectory of your SDK:
<sdk>/extras/android/support/ directory.
Choosing Support Libraries
Before adding a Support Library to your application, decide what features you want to include and the
lowest Android versions you want to support. For more information on the features provided by the
different libraries, see Support Library Features.
Adding Support Libraries
In order to use a Support Library, you must modify your application's project's classpath dependencies
within your development environment. You must perform this procedure for each Support Library you want
to use.
Some Support Libraries contain resources beyond compiled code classes, such as images or XML files.
For example, the v7 appcompat and v7 gridlayout libraries include resources.
If you are not sure if a library contains resources, check the Support Library Features page. The following
sections describe how to add a Support Library with or without resources to your application project.
Adding libraries without resources
To add a Support Library without resources to your application project:
Using Eclipse
• Make sure you have downloaded the Android Support Library using the SDK Manager.
• Create a libs/ directory in the root of your application project.
• Copy the JAR file from your Android SDK installation directory (e.g.,
<sdk>/extras/android/support/v4/android-support-v4.jar) into your
application's project libs/ directory.
• Right click the JAR file and select Build Path > Add to Build Path.
Using Android Studio
• Make sure you have downloaded the Android Support Repository using the SDK Manager.
• Open the build.gradle file for your application.
• Add the support library to the dependencies section. For example, to add the v4 support library, add
the following lines:
dependencies {
...
compile "com.android.support:support-v4:18.0.+"
}
•
Adding libraries with resources
To add a Support Library with resources (such as v7 appcompat for action bar) to your application project:
Using Eclipse
Create a library project based on the support library code:
• Make sure you have downloaded the Android Support Library using the SDK Manager.
315
Content from developer.android.com/tools/support-library/setup.html through their Creative Commons Attribution 2.5 license
Support Library Setup
• Create a library project and ensure the required JAR files are included in the project's build path:
• Select File > Import.
• Select Existing Android Code Into Workspace and click Next.
• Browse to the SDK installation directory and then to the Support Library folder. For example, if you are
adding the appcompat project, browse to
<sdk>/extras/android/support/v7/appcompat/.
• Click Finish to import the project. For the v7 appcompat project, you should now see a new project titled
android-support-v7-appcompat.
• In the new library project, expand the libs/ folder, right-click each .jar file and select Build Path >
Add to Build Path. For example, when creating the the v7 appcompat project, add both the androidsupport-v4.jar and android-support-v7-appcompat.jar files to the build path.
• Right-click the library project folder and select Build Path > Configure Build Path.
• In the Order and Export tab, check the .jar files you just added to the build path, so they are
available to projects that depend on this library project. For example, the appcompat project requires
you to export both the android-support-v4.jar and android-support-v7appcompat.jar files.
• Uncheck Android Dependencies.
• Click OK to complete the changes.
You now have a library project for your selected Support Library that you can use with one or more
application projects.
Add the library to your application project:
• In the Project Explorer, right-click your project and select Properties.
• In the category panel on the left side of the dialog, select Android.
• In the Library pane, click the Add button.
• Select the library project and click OK. For example, the appcompat project should be listed as
android-support-v7-appcompat.
• In the properties window, click OK.
Using Android Studio
• Make sure you have downloaded the Android Support Repository using the SDK Manager.
• Open the build.gradle file for your application.
• Add the support library feature project identifier to the dependencies section. For example, to
include the appcompat project add compile "com.android.support:appcompatv7:18.0.+" to the dependencies section, as shown in the following example:
dependencies {
...
compile "com.android.support:appcompat-v7:18.0.+"
}
•
Using Support Library APIs
Support Library classes that provide support for existing framework APIs typically have the same name as
framework class but are located in the android.support class packages, or have a *Compat suffix.
316
Content from developer.android.com/tools/support-library/setup.html through their Creative Commons Attribution 2.5 license
Support Library Setup
Caution: When using classes from the Support Library, be certain you import the class from the
appropriate package. For example, when applying the ActionBar class:
•
•
android.support.v7.app.ActionBar when using the Support Library.
android.app.ActionBar when developing only for API level 11 or higher.
Note: After including the Support Library in your application project, we strongly recommend using the
ProGuard tool to prepare your application APK for release. In addition to protecting your source code, the
ProGuard tool also removes unused classes from any libraries you include in your application, which
keeps the download size of your application as small as possible. For more information, see ProGuard.
Further guidance for using some Support Library features is provided in the Android developer training
classes, guides and samples. For more information about the individual Support Library classes and
methods, see the android.support packages in the API reference.
Manifest Declaration Changes
If you are increasing the backward compatibility of your existing application to an earlier version of the
Android API with the Support Library, make sure to update your application's manifest. Specifically, you
should update the android:minSdkVersion element of the <uses-sdk> tag in the manifest to
the new, lower version number, as shown below:
<uses-sdk
android:minSdkVersion="7"
android:targetSdkVersion="17" />
This change tells Google Play that your application can be installed on devices with Android 2.1 (API level
7) and higher.
Note: If you are including the v4 support and v7 appcompat libraries in your application, you should
specify a minimum SDK version of "7" (and not "4"). The highest support library level you include in
your application determines the lowest API version in which it can operate.
Code Samples
Each Support Library includes code samples to help you get started using the support APIs. The code is
included in the download from the SDK Manager and is placed inside the Android SDK installation
directory, as listed below:
•
•
•
•
4v Samples: <sdk>/extras/android/support/samples/Support4Demos/
7v Samples: <sdk>/extras/android/support/samples/Support7Demos/
13v Samples: <sdk>/extras/android/support/samples/Support13Demos/
App Navigation:
<sdk>/extras/android/support/samples/SupportAppNavigation/
317
Content from developer.android.com/tools/support-library/setup.html through their Creative Commons Attribution 2.5 license
Tools Help
56.
Tools Help
Content from developer.android.com/tools/help/index.html through their Creative Commons Attribution 2.5 license
The Android SDK includes a variety of tools that help you develop mobile applications for the Android
platform. The tools are classified into two groups: SDK tools and platform tools. SDK tools are platform
independent and are required no matter which Android platform you are developing on. Platform tools are
customized to support the features of the latest Android platform.
SDK Tools
The SDK tools are installed with the SDK starter package and are periodically updated. The SDK tools are
required if you are developing Android applications. The most important SDK tools include the Android
SDK Manager (android sdk), the AVD Manager (android avd) the emulator (emulator), and
the Dalvik Debug Monitor Server (ddms). A short summary of some frequently-used SDK tools is provided
below.
android
Lets you manage AVDs, projects, and the installed components of the SDK.
Dalvik Debug Monitor Server (ddms)
Lets you debug Android applications.
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
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.
Android Emulator (emulator)
A QEMU-based device-emulation tool that you can use to design, debug, and test your
applications in an actual Android run-time environment.
Hierarchy Viewer (hierarchyviewer)
Lets you debug and optimize an Android application's user interface.
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.
layoutopt
Lets you quickly analyze your application's layouts in order to optimize them for efficiency.
mksdcard
Helps you create a disk image that you can use with the emulator, to simulate the presence of an
external storage card (such as an SD card).
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.
monkeyrunner
Provides an API for writing programs that control an Android device or emulator from outside of
Android code.
318
Content from developer.android.com/tools/help/index.html through their Creative Commons Attribution 2.5 license
Tools Help
ProGuard
Shrinks, optimizes, and obfuscates your code by removing unused code and renaming classes,
fields, and methods with semantically obscure names.
Systrace
Lets you analyze the execution of your application in the context of system processes, to help
diagnose display and performance issues.
sqlite3
Lets you access the SQLite data files created and used by Android applications.
traceview
Provides a graphical viewer for execution logs saved by your application.
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.
Platform Tools
The platform tools are typically updated every time you install a new SDK platform. Each update of the
platform tools is backward compatible with older platforms. Usually, you directly use only one of the
platform tools—the Android Debug Bridge (adb). Android Debug Bridge is a versatile tool that lets you
manage the state of an emulator instance or Android-powered device. You can also use it to install an
Android application (.apk) file on a device.
The other platform tools, such as aidl, aapt, dexdump, and dx, are typically called by the Android build
tools or Android Development Tools (ADT), so you rarely need to invoke these tools directly. As a general
rule, you should rely on the build tools or the ADT plugin to call them as needed.
Note: The Android SDK provides additional shell tools that can be accessed through adb, such as bmgr
and logcat.
319
Content from developer.android.com/tools/help/index.html through their Creative Commons Attribution 2.5 license
Android Debug Bridge
57.
Android Debug Bridge
Content from developer.android.com/tools/help/adb.html through their Creative Commons Attribution 2.5 license
Android Debug Bridge (adb) is a versatile
command line tool that lets you communicate with
an emulator instance or connected Androidpowered 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.
In this section
• Syntax
• Commands
• Querying for Emulator/Device Instances
• Directing Commands to a Specific
Emulator/Device Instance
• Installing an Application
• Forwarding Ports
• Copying Files to or from an
Emulator/Device Instance
• Issuing Shell Commands
• Using activity manager (am)
• Using package manager (pm)
• Examining sqlite3 databases from a remote
shell
• Recording a device screen
You can find the adb tool in
<sdk>/platform-tools/.
• UI/Application Exerciser Monkey
• Other shell commands
When you start an adb client, the client first
• Enabling logcat logging
checks whether there is an adb server process
already running. If there isn't, it starts the server
• Stopping the adb server
process. When the server starts, it binds to local
TCP port 5037 and listens for commands sent from adb clients—all adb clients use port 5037 to
communicate with the adb server.
The server then sets up connections to all running emulator/device instances. It locates emulator/device
instances by scanning odd-numbered ports in the range 5555 to 5585, the range used by
emulators/devices. Where the server finds an adb daemon, it sets up a connection to that port. Note that
each emulator/device instance acquires a pair of sequential ports — an even-numbered port for console
connections and an odd-numbered port for adb connections. For example:
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).
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
320
Content from developer.android.com/tools/help/adb.html through their Creative Commons Attribution 2.5 license
Android Debug Bridge
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.
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
Description
Comments
Target
Device
-d
Direct an adb command to the Returns an error if more than
only attached USB device.
one USB device is attached.
-e
Direct an adb command to the Returns an error if more than
only running emulator
one emulator instance is
instance.
running.
Direct an adb command a
See Directing Commands to
s <serialNumber specific emulator/device
a Specific Emulator/Device
>
instance, referred to by its adb- Instance.
assigned serial number (such
as "emulator-5556").
General
Debug
devices
Prints a list of all attached
emulator/device instances.
help
Prints a list of supported adb
commands.
version
Prints the adb version number.
See Querying for
Emulator/Device Instances
for more information.
logcat [option] Prints log data to the screen.
[filter-specs]
321
Content from developer.android.com/tools/help/adb.html through their Creative Commons Attribution 2.5 license
Android Debug Bridge
Data
bugreport
Prints dumpsys,
dumpstate, and logcat
data to the screen, for the
purposes of bug reporting.
jdwp
Prints a list of available JDWP You can use the forward
processes on a given device. jdwp:<pid> portforwarding specification to
connect to a specific JDWP
process. For example:
adb forward
tcp:8000 jdwp:472
jdb -attach
localhost:8000
install <pathto-apk>
Pushes an Android application
(specified as a full path to an
.apk file) to an
emulator/device.
pull <re Copies a specified file
mote> <l from an
ocal>
emulator/device
instance to your
development
computer.
push <lo Copies a specified file
cal> <re from your development
mote>
computer to an
emulator/device
instance.
forward <local> Forwards socket connections Port specifications can use
Ports and
<remote>
Networking
from a specified local port to a these schemes:
specified remote port on the
emulator/device instance.
• tcp:<portnum
>
• local:<UNIX
domain
socket name>
• dev:<charact
er device
name>
• jdwp:<pid>
322
Content from developer.android.com/tools/help/adb.html through their Creative Commons Attribution 2.5 license
Android Debug Bridge
ppp <tty> [parm Run PPP over USB.
]...
•
•
<tty> — the tty for
PPP stream. For
example
dev:/dev/omap_
csmi_ttyl.
[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
Prints the adb instance serial
number string.
get-state
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
You can prepend this
device is online — that is, until command to other adb
the instance state is device. 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-for-device
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-for-device
install <app>.apk
323
Content from developer.android.com/tools/help/adb.html through their Creative Commons Attribution 2.5 license
Android Debug Bridge
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.
Server
Shell
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.
See Issuing Shell
Commands for more
information.
shell [shellCom Issues a shell command in the
mand]
target emulator/device
instance and then exits the
remote 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.
o device — the instance is now connected to the adb server. Note that 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.
o no device — there is no emulator/device connected.
The output for each instance is formatted like this:
[serialNumber] [state]
Here's an example showing the devices command and its output:
324
Content from developer.android.com/tools/help/adb.html through their Creative Commons Attribution 2.5 license
Android Debug Bridge
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
325
Content from developer.android.com/tools/help/adb.html through their Creative Commons Attribution 2.5 license
Android Debug Bridge
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
Description
326
Content from developer.android.com/tools/help/adb.html through their Creative Commons Attribution 2.5 license
Android Debug Bridge
start [options] <INTENT>
Start an Activity specified by <INTENT>.
See the Specification for <INTENT> arguments.
Options are:
•
•
•
•
•
•
•
•
startservice [options]
<INTENT>
-D: Enable debugging.
-W: Wait for launch to complete.
--start-profiler <FILE>:
Start profiler and send results to
<FILE>.
-P <FILE>: Like --startprofiler, 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.
Options are:
•
--user <USER_ID> |
current: Specify which user to run
as; if not specified, then run as the
current user.
force-stop <PACKAGE>
Force stop everything associated with
<PACKAGE> (the app's package name).
kill [options] <PACKAGE>
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.
Options are:
•
--user <USER_ID> | all |
current: Specify user whose
processes to kill; all users if not
specified.
327
Content from developer.android.com/tools/help/adb.html through their Creative Commons Attribution 2.5 license
Android Debug Bridge
kill-all
Kill all background processes.
broadcast [options] <INTENT> Issue a broadcast intent.
See the Specification for <INTENT> arguments.
Options are:
•
instrument [options]
<COMPONENT>
[--user <USER_ID> | all |
current]: Specify which user to
send to; if not specified then send to all
users.
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>.
dumpheap [options] <PROCESS> Dump the heap of <PROCESS>, write to
<FILE>
<FILE>.
Options are:
•
--user
328
Content from developer.android.com/tools/help/adb.html through their Creative Commons Attribution 2.5 license
Android Debug Bridge
•
set-debug-app [options]
<PACKAGE>
[<USER_ID>|current]: When
supplying a process name, specify
user of process to dump; uses current
user if not specified.
-n: Dump native heap instead of
managed heap.
Set application <PACKAGE> to debug.
Options are:
•
•
-w: Wait for debugger when
application starts.
--persistent: Retain this value.
clear-debug-app
Clear the package previous set for debugging
with set-debug-app.
monitor [options]
Start monitoring for crashes or ANRs.
Options are:
•
--gdb: Start gdbserv on the given
port at crash/ANR.
screen-compat [on|off]
<PACKAGE>
Control screen compatibility mode of
<PACKAGE>.
display-size [reset|<WxH>]
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
329
Content from developer.android.com/tools/help/adb.html through their Creative Commons Attribution 2.5 license
Android Debug Bridge
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
list packages [options]
<FILTER>
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.
-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.
--user <USER_ID>: The user space
to query.
list permission-groups
Prints all known permission groups.
list permissions [options]
<GROUP>
Prints all known permissions, optionally only those in
<GROUP>.
Options:
•
•
•
•
•
list instrumentation
-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:
330
Content from developer.android.com/tools/help/adb.html through their Creative Commons Attribution 2.5 license
Android Debug Bridge
•
•
-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:
•
•
•
•
•
•
•
uninstall [options]
<PACKAGE>
-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.
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").
disable-user [options]
<PACKAGE_OR_COMPONENT>
Options:
•
grant <PACKAGE_PERMISSION>
--user <USER_ID>: The user to
disable.
Grant permissions to applications. Only optional
permissions the application has declared can be
331
Content from developer.android.com/tools/help/adb.html through their Creative Commons Attribution 2.5 license
Android Debug Bridge
granted.
revoke <PACKAGE_PERMISSION> Revoke permissions to applications. Only optional
permissions the application has declared can be
revoked.
set-install-location
<LOCATION>
Changes the default install location. Location values:
•
•
•
0: Auto—Let system decide the best
location.
1: Internal—install on internal device
storage.
2: External—install on external media.
Note: This is only intended for debugging; using this
can cause applications to break and other
undesireable behavior.
get-install-location
Returns the current install location. Return values:
•
•
•
0 [auto]: Lets system decide the best
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:
332
Content from developer.android.com/tools/help/adb.html through their Creative Commons Attribution 2.5 license
Android Debug Bridge
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
[email protected] $ screenrecord --verbose /sdcard/demo.mp4
(press Ctrl-C to stop)
[email protected] $ 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
Description
--help
Displays a usage summary.
333
Content from developer.android.com/tools/help/adb.html through their Creative Commons Attribution 2.5 license
Android Debug Bridge
--size <WIDTHxHEIGHT> Sets the video size, for example: 1280x720. The default
value is the device's main display resolution (if 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 system-level events. You can use
the Monkey to stress-test applications that you are developing, in a random yet repeatable manner.
The simplest way to use the monkey is with the following command, which launches your application and
sends 500 pseudo-random events to it.
adb shell monkey -v -p your.package.name 500
For more information about command options for Monkey, see the complete UI/Application Exerciser
Monkey documentation page.
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
Dumps system data to The Dalvik Debug Monitor
the screen.
Server (DDMS) tool offers
integrated debug
environment that you may
334
Content from developer.android.com/tools/help/adb.html through their Creative Commons Attribution 2.5 license
Android Debug Bridge
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.
335
Content from developer.android.com/tools/help/adb.html through their Creative Commons Attribution 2.5 license
Android Debug Bridge
To stop the adb server, use the kill-server command. You can then restart the server by issuing any
other adb command.
336
Content from developer.android.com/tools/help/adb.html through their Creative Commons Attribution 2.5 license
Android Developer Tools
58.
Android Developer Tools
Content from developer.android.com/tools/help/adt.html through their Creative Commons Attribution 2.5 license
ADT (Android Developer Tools) is a plugin for
Eclipse that provides a suite of tools that are
integrated with the Eclipse IDE. It offers you
access to many features that help you develop
Android applications quickly. ADT provides GUI
access to many of the command line SDK tools as
well as a UI design tool for rapid prototyping,
designing, and building of your application's user
interface.
Because ADT is a plugin for Eclipse, you get the
functionality of a well-established IDE, along with
Android-specific features that are bundled with
ADT. The following describes important features
of Eclipse and ADT:
Integrated Android project creation, building,
packaging, installation, and debugging
ADT integrates many development
workflow tasks into Eclipse, making it
easy for you to rapidly develop and test
your Android applications.
In this section
• SDK Tools Integration
• Code Editors
• Resource linking enhancements
• Graphical Layout Editor
• Canvas and outline view
• Palette
• Configuration chooser
• Layout Factoring Support
• Updating the ADT Plugin
Related videos
• Android Developer Tools Google I/O
Session
See also
• Android Tools change blog
SDK Tools integration
Many of the SDK tools are integrated into Eclipse's menus, perspectives, or as a part of
background processes ran by ADT.
Java programming language and XML editors
The Java programming language editor contains common IDE features such as compile time
syntax checking, auto-completion, and integrated documentation for the Android framework APIs.
ADT also provides custom XML editors that let you edit Android-specific XML files in a formbased UI. A graphical layout editor lets you design user interfaces with a drag and drop interface.
Integrated documentation for Android framework APIs
You can access documentation by hovering over classes, methods, or variables.
You can find the most up-to-date and more detailed information about changes and new features on the
Recent Changes page at the Android Tools Project site.
SDK Tools Integration
Many of the tools that you can start or run from
the command line are integrated into ADT. They
include:
•
•
Need help designing icons?
The Android Asset Studio is a web-based tool
that lets you generate icons from existing
images, clipart, or text. It also generates the
icons with different DPIs for different screen
sizes and types.
Traceview: Allows you to profile your
program's execution (Window > Open
Perspective > Traceview).
android: Provides access to the Android
SDK Manager and AVD Manager. Other android features such as creating or updating
projects (application and library) are integrated throughout the Eclipse IDE.
337
Content from developer.android.com/tools/help/adt.html through their Creative Commons Attribution 2.5 license
Android Developer Tools
•
•
•
•
•
Hierarchy Viewer: Allows you to visualize your application's view hierarchy to find inefficiencies
(Window > Open Perspective > Hierarchy Viewer).
Pixel Perfect: Allows you to closely examine your UI to help with designing and building. (Window
> Open Perspective > Pixel Perfect).
DDMS: Provides debugging features including: screen capturing, thread and heap information,
and logcat (Window > Open Perspective > DDMS).
adb: Provides access to a device from your development system. Some features of adb are
integrated into ADT such as project installation (Eclipse run menu), file transfer, device
enumeration, and logcat (DDMS). You must access the more advanced features of adb, such as
shell commands, from the command line.
ProGuard: Allows code obfuscation, shrinking, and optimization. ADT integrates ProGuard as part
of the build, if you enable it.
Code Editors
In addition to Eclipse's standard editor features, ADT provides custom XML editors to help you create and
edit Android manifests, resources, menus, and layouts in a form-based or graphical mode. Double-clicking
on an XML file in Eclipse's package explorer opens the appropriate XML editor.
Note: You can edit Android-specific XML files
(such as a layout or manifest) in both a graphical
mode and also an XML markup mode. You can
switch between these modes with the pair of tabs
at the bottom of each custom XML editor.
Google I/O Session Video
View the segment on the XML editors for
more information.
In addition, some special file types that don't have custom editors, such as drawables, animations, and
color files offer editing enhancements such as XML tag completion.
ADT provides the following custom, form-based XML editors:
Graphical Layout Editor
Edit and design your XML layout files with a drag and drop interface. The layout editor renders
your interface as well, offering you a preview as you design your layouts. This editor is invoked
when you open an XML file with a view declared (usually declared in res/layout. For more
information, see Graphical Layout Editor.
Android Manifest Editor
Edit Android manifests with a simple graphical interface. This editor is invoked when you open an
AndroidManifest.xml file.
Menu Editor
Edit menu groups and items with a simple graphical interface. This editor is invoked when you
open an XML file with a <menu> declared (usually located in the res/menu folder).
Resources Editor
Edit resources with a simple graphical interface. This editor is invoked when you open an XML file
with a <resources> tag declared.
XML Resources Editor
Edit XML resources with a simple graphical interface. This editor is invoked when you open an
XML file.
Resource linking enhancements
338
Content from developer.android.com/tools/help/adt.html through their Creative Commons Attribution 2.5 license
Android Developer Tools
In addition to the normal code editing features of Eclipse, ADT provides enhancements to the Android
development experience that allow you to quickly jump to declarations of various types of resources such
as strings or layout files. You can access these enhancements by holding down the control key and
clicking on the following items:
•
•
•
•
•
•
•
•
•
A resource identifier, such as R.id.button1, jumps to the XML definition of the view.
A declaration in the R.java file, such as public static final int
Button01=0x7f050000", jumps to the corresponding XML definition.
An activity or service definition in your manifest, such as <activity
android:name=".TestActivity">, jumps to the corresponding Java class. You can
jump from an activity definition (or service definition) into the corresponding Java class.
You can jump to any value definition (e.g. @string:foo), regardless of which XML file "foo" is
defined in.
Any file-based declaration, such as @layout/bar, opens the file.
Non-XML resources, such as @drawable/icon, launches Eclipse's default application for the
given file type, which in this case is an image.
@android namespace resources opens the resources found in the SDK install area.
Custom views in XML layouts, such as <foo.bar.MyView></foo.bar.MyView>, or
<view class="foo.bar.MyView">) jump to the corresponding custom view classes.
An XML attribute such as @android:string/ok or android.R.string.id in Java
code opens the file that declares the strings. The XML tab opens when doing this, not the formbased editor.
Graphical Layout Editor
ADT provides many features to allow you to design and build your application's user interface. Many of
these features are in the graphical layout editor, which you can access by opening one of your
application's XML layout files in Eclipse.
The graphical layout editor is the main screen that you use to visually design and build your UI. It is split up
into the following parts:
Canvas
In the middle of the editor is the canvas. It provides the rendered view of your layout and supports
dragging and dropping of UI widgets directly from the palette. You can select the platform version
used to render the items in the canvas. Each platform version has its own look and feel, which
might be the similar to or radically different from another platform version. The canvas renders the
appropriate look and feel for the currently selected platform version. This platform version does
not need to be the same as the version that your application targets.
The canvas also provides context-sensitive actions in the layout actions bar, such as adjusting
layout margins and orientation. The layout actions bar displays available actions depending on
the selected UI element in the canvas.
Outline
On the right side of the editor is the outline view. It displays a hierarchical view of your layout
where you can do things such as reorder of views. The outline view exposes similar functionality
as the canvas but displays your layout in an ordered list instead of a rendered preview.
Palette
On the left side of the editor is the palette. It provides a set of widgets that you can drag onto the
canvas. The palette shows rendered previews of the widgets for easy lookup of desired UI
widgets.
339
Content from developer.android.com/tools/help/adt.html through their Creative Commons Attribution 2.5 license
Android Developer Tools
Configuration Chooser
At the top of the editor is the configuration chooser. It provides options to change a layout's
rendering mode or screen type.
Figure 1. Graphical layout editor
Canvas and outline view
The canvas is the area where you can drag and
Google I/O Session Video
drop UI widgets from the palette to design your
View the segment on the canvas and outline
layout. The canvas offers a rendered preview of
view and the layout actions bar for more
your layout depending on factors such as the
information.
selected platform version, screen orientation, and
currently selected theme that you specify in the
configuration chooser. You can also drag and drop items into the outline view, which displays your layout
in a hierarchical list. The outline view exposes much of the same functionality as the canvas but offers
another method of organization that is beneficial for ordering and quickly selecting items. When you rightclick a specific item in the canvas or outline view, you can access a context-sensitive menu that lets you
modify the following attributes of the layout or view:
View and layout properties
When you right-click a view or layout in the canvas or outline view, it brings up a context-sensitive
menu that lets you set things such as:
•
•
•
•
•
ID of the view or layout
Text of the view
Layout width
Layout height
Properties such as alpha or clickable
Animation preview and creation
340
Content from developer.android.com/tools/help/adt.html through their Creative Commons Attribution 2.5 license
Android Developer Tools
If your layout or view is animated, you can preview the animation directly in the canvas (when you
select Android 3.0 or later as the platform version in the configuration chooser). Right-click an
item in the canvas and select Play Animation. If animation is not associated with item, an option
is available in the menu to create one.
View the segment on the animation features for more information.
Extract as Include
You can extract parts of a current layout into its own layout file, which you can then include in any
layout with a single line of XML. See Layout Refactoring Support for more information.
Other canvas features
The canvas has additional features not available in the outline view:
•
•
•
•
•
•
Edit views with the layout actions bar: The context-sensitive layout actions bar allows you to edit
how a view is laid out in your UI. The available actions depend on the currently selected view and
its parent layout. Some common actions include toggling the fill mode of the view and specifying
margins. For instance, if you select a Button in a LinearLayout, you see actions related to the
LinearLayout, such as a toggle to switch between horizontal and vertical layout, and a toggle
to control whether its children are aligned along their text baseline. You will also see toolbar
actions to control the individual layout attributes of the child, such as whether the child should
stretch out to match its parent's width and height, a dropdown action to set the child's layout
gravity, a button to open a margin editor, and a layout weight editor.
Edit a nested layout in its current context: If you are editing a layout that includes another layout,
you can edit the included layout in the layout that included it.
Preview drag and drop location: When you drag and drop a UI widget onto the canvas, ruler
markers appear showing you the approximate location of the UI widget depending on the type of
layout, such as RelativeLayout or LinearLayout.
Preview animations: You can preview view and layout animations when you select Android 2.1 or
later for the platform version in the configuration bar.
Render layouts in real-time: Layouts are rendered as accurately as possible according to the
platform version, including the appropriate system and action bars.
Support for fragments: Fragments can be rendered in the same screen as the layout that includes
the fragments.
341
Content from developer.android.com/tools/help/adt.html through their Creative Commons Attribution 2.5 license
Android Developer Tools
Figure 2. Canvas portion of the layout editor showing a rendered preview of an application
Figure 3. Outline view showing current layout's structure
Palette
The palette contains the UI widgets that you can
drag and drop onto the canvas and add to your
layout. The pallete categorizes the widgets and
shows rendered previews for easier lookup. The
main features of the palette include:
•
•
•
Google I/O Session Video
View the segment on the palette for more
information.
Different modes of rendered previews include: icons only, icons and text, tiny previews, small
previews, and previews (rendered in real size). Previews are only available for layouts rendered
with the latest revisions of Android 2.1 (API Level 7) or later.
Custom views in your project or library projects are added under custom views category.
Arrange UI widgets alphabetically or by category.
342
Content from developer.android.com/tools/help/adt.html through their Creative Commons Attribution 2.5 license
Android Developer Tools
Figure 4. Palette showing available UI widgets
Configuration chooser
The configuration chooser allows you to create
and configure different configurations of a layout
for different situations, such as one for landscape
and one for portrait mode. You can set the
following options for each configuration of a
layout:
•
•
•
•
•
Google I/O Session Video
View the segment on the configuration
chooser for more information.
Screen type combo box: Predefined screen settings for common device configurations. You can
also create your own by selecting Custom....
Screen orientation combo box: Portrait or Landscape screen orientation.
Theme combo box: Predefined themes or a custom theme that you have created.
Platform combo box: Platform version used to render the canvas and palette as well as displaying
appropriate themes.
Custom layout combo boxes: The locale, dock, and time of day combo boxes let you select
different versions of the same layout depending on the device's current state. You can create a
new version of a layout with the Create button.
343
Content from developer.android.com/tools/help/adt.html through their Creative Commons Attribution 2.5 license
Android Developer Tools
Figure 5. Configuration chooser
Layout Refactoring Support
In both the graphical and XML layout editor, there
are many features that help you quickly refactor
your layouts. The following list describes the major
refactoring support:
Google I/O Session Video
View the segment on refactoring features for a
rundown of the more important refactoring
features.
Change layout
This lets you change the layout on the fly and re-renders the canvas for you. You can apply this
refactoring to any layout and the layout is converted to the new type if possible. In many cases,
the opening and closing tags of the layout's XML element are changed along with things such as
ID attributes and their references. However, for some supported types, ADT attempts to preserve
the layout, such as changing a LinearLayout to a RelativeLayout.
Change widget
This lets you select one or more widgets and converts them to a new widget type. In addition to
changing the element name, it also removes any attributes that are not supported by the new
widget type and adds in any mandatory attributes required by the new widget type. If the current
ID of a widget includes the current widget type in its ID (such as a <Button> widget named
"button1"), then the ID is changed to match the new widget type and all references are
updated.
Extract as include
This lets you extract views inside of an existing layout into their own separate layout file. An
include tag that points to the newly created layout file is inserted into the existing layout file.
Right-click the view or layout and select Extract as Include....
Extract string
Extract strings from either XML or Java files into their own separate resource file.
Extract style
Extract style-related attributes from a layout and define them in a new styles.xml file. You
can select multiple views and this refactoring extracts all of the same styles into one style and
assigns that style to all the views that use it.
Wrap-in container
This lets you select one or more sibling elements and wrap them in a new container. This can be
applied to the root element as well, in which case the namespace declaration attributes will be
transferred to the new root. This refactoring also transfers layout_ attribute references to the
new root, For example, suppose you have a RelativeLayout. If other widgets have layout
constraints pointing to your widget, wrapping the widget causes these constraints to point to the
parent instead.
Quick Assistant
Provides refactoring suggestions depending on the current context. Press Ctrl-1 (or Cmd-1 on
Mac) in an editor, and Eclipse provides a list of possible refactorings depending on the context.
The Quick Assistant provides fast access to all of the above refactorings, where applicable. For
example, if you are editing an XML value and decide you want to extract it out as a string, place
the text cursor in the string and press Ctrl-1 to see the refactoring context menu.
Updating the ADT Plugin
344
Content from developer.android.com/tools/help/adt.html through their Creative Commons Attribution 2.5 license
Android Developer Tools
From time to time, a new revision of the ADT Plugin becomes available, with new features and bug fixes.
Generally, when a new revision of ADT is available, you should update to it as soon as convenient.
In some cases, a new revision of ADT will have a dependency on a specific revision of the Android SDK
Tools. If such dependencies exist, you will need to update the SDK Tools package of the SDK after
installing the new revision of ADT. To update the SDK Tools package, use the Android SDK Manager, as
described in Exploring the SDK.
To learn about new features of each ADT revision and also any dependencies on the SDK Tools, see the
listings in the Revisions section. To determine the version currently installed, open the Eclipse Installed
Software window using Help > Software Updates and refer to the version listed for "Android Development
Tools".
Follow the steps below to check whether an update is available and, if so, to install it.
• Select Help > Check for Updates.
If there are no updates available, a dialog will say so and you're done.
• If there are updates available, select Android DDMS, Android Development Tools, and Android
Hierarchy Viewer, then click Next.
• In the Update Details dialog, click Next.
• Read and accept the license agreement and then click Finish. This will download and install the latest
version of Android DDMS and Android Development Tools.
• Restart Eclipse.
If you encounter problems during the update, remove the existing ADT plugin from Eclipse, then perform a
fresh installation, using the instructions for Installing the ADT Plugin.
345
Content from developer.android.com/tools/help/adt.html through their Creative Commons Attribution 2.5 license
android
59.
android
Content from developer.android.com/tools/help/android.html through their Creative Commons Attribution 2.5 license
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
Description
Comments
avd
None
Launch the AVD
Manager
sdk
None
Launch the Android SDK
Manager
create
avd
-n <name>
The name for the AVD.
-t <targetID>
Target ID of the system Required
image to use with the
new AVD. To obtain a list
of available targets, use
android list
targets
Required
346
Content from developer.android.com/tools/help/android.html through their Creative Commons Attribution 2.5 license
android
-c
The path to the SD card
<path>|<size>[K|M] image to use with this
AVD or the size of a new
SD card image to create
for this AVD. For
example, -c
path/to/sdcard or
-c 1000M.
-f
Force creation of the
AVD
-p <path>
Path to the location at
which to create the
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 <targetID>
argument. For example,
-s HVGA-L
delete
avd
-n <name>
The name of the AVD to Required
delete
move
avd
-n <name>
The name of the AVD to Required
move
-p <path>
Path to the location at
which to create the
directory for this AVD's
files.
-r <new-name>
New name of the AVD if
you want to rename it
-n <name>
The name of the AVD to Required
update
347
Content from developer.android.com/tools/help/android.html through their Creative Commons Attribution 2.5 license
android
avd
move
Project actions and options
Action
Option
create -n <name>
project
-t <targetID>
Description
Comments
The name for the project Required
Target ID of the system Required
image to use with the
new AVD. To obtain a list
of available targets, use
android list
targets
-k
Package namespace
<path>|<size>[K|M]
Required
-a
Name for the default
Activity class
Required
-p <path>
Location of your project
directory
Required
update -n <name>
project
The name of the project
to update
-p <path>
Location path of the
project
Required
-l <library path> Location path of an
Android Library to add,
relative to the main
project
-s <subprojects>
Update any projects in
subfolders such as test
projects
-t <targetID>
Target id to set for the
project
348
Content from developer.android.com/tools/help/android.html through their Creative Commons Attribution 2.5 license
android
create -n <name>
testproject
-p <path>
The name of the project
Location path of the
project
Required
-m <main>
The name of the project Required
update -p <path>
testproject
Location path of the
Required
project to test, relative to
the new project
-m <main>
The main class of the
project to test
Required
create -k <packageName>
libproject
(Required) Package
name of the library
project
Required
-p <path>
Location path of the
project
Required
-t <targetID>
Target ID of the library
project
Required
-n <name>
The name of the project Required
update -p <path>
libproject
Location path of the
project
-l <libraryPath>
Location path of an
Android Library to add,
relative to the main
project
-t <name>
Target ID of the library
project
create -n <name>
uitest-
Required
The name of the UI test
project
349
Content from developer.android.com/tools/help/android.html through their Creative Commons Attribution 2.5 license
android
project
-t <name>
Target ID of the UI test
project
Required
-p <path>
Location path of the UI
test project
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.
350
Content from developer.android.com/tools/help/android.html through their Creative Commons Attribution 2.5 license
AVD Manager
60.
AVD Manager
Content from developer.android.com/tools/help/avd-manager.html through their Creative Commons Attribution 2.5 license
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 > AVD Manager, or click the AVD Manager icon in the Eclipse toolbar.
In other IDEs: Navigate to your SDK's tools/ directory and execute android avd.
For more information, see Managing AVDs with AVD Manager.
351
Content from developer.android.com/tools/help/avd-manager.html through their Creative Commons Attribution 2.5 license
bmgr
61.
bmgr
Content from developer.android.com/tools/help/bmgr.html through their Creative Commons Attribution 2.5 license
bmgr is a shell tool you can use to interact with
the Backup Manager on Android devices
supporting API Level 8 or greater. It provides
commands to induce backup and restore
operations so that you don't need to repeatedly
wipe data or take similar intrusive steps in order to
test your application's backup agent. These
commands are accessed via the adb shell.
In this section
• Forcing a Backup Operation
• Forcing a Restore Operation
• Other Commands
See also
• Data Backup
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>
<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:
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>
<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
352
Content from developer.android.com/tools/help/bmgr.html through their Creative Commons Attribution 2.5 license
bmgr
application's backup agent and invoke it for restore. This will happen even if your application is not
currently running.
Other Commands
Wiping data
The data for a single application can be erased from the active data set on demand. This is very useful
while you're developing a backup agent, in case bugs lead you to write corrupt data or saved state
information. You can wipe an application's data with the bmgr wipe command:
adb shell bmgr wipe <package>
<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.
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>
<boolean> is either true or false. This is equivalent to disabling or enabling backup in the device's
main Settings UI.
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).
353
Content from developer.android.com/tools/help/bmgr.html through their Creative Commons Attribution 2.5 license
Device Monitor
62.
Device Monitor
Content from developer.android.com/tools/help/monitor.html through their Creative Commons Attribution 2.5 license
Android Device Monitor is a stand-alone tool that
See also
provides a graphical user interface for several
• Investigating Your RAM Usage
Android application debugging and analysis tools.
The Monitor tool does not require installation of a
integrated development environment, such as Eclipse, and encapsulates the following tools:
•
•
•
•
•
DDMS
Tracer for OpenGL ES
Hierarchy Viewer
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.
354
Content from developer.android.com/tools/help/monitor.html through their Creative Commons Attribution 2.5 license
dmtracedump
63.
dmtracedump
Content from developer.android.com/tools/help/dmtracedump.html through their Creative Commons Attribution 2.5 license
dmtracedump is a tool that gives you an alternate way of generating graphical call-stack diagrams from
trace log files (instead of using Traceview).
This document is a reference to the available command line options. For more information on generating
trace logs, see Profiling with Traceview and dmtracedump.
The usage for dmtracedump is:
dmtracedump [-ho] [-s sortable] [-d trace-base-name] [-g outfile] <trace-base-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 <trace-base- Diff with this trace name
name>
-g <outfile>
Generate output to <outfile>
-h
Turn on HTML output
-o
Dump the trace file instead of profiling
-d <trace-base- URL base to the location of the sortable javascript file
name>
-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%.
355
Content from developer.android.com/tools/help/dmtracedump.html through their Creative Commons Attribution 2.5 license
Draw 9-patch
64.
Draw 9-patch
Content from developer.android.com/tools/help/draw9patch.html through their Creative Commons Attribution 2.5 license
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.
• From a terminal, launch the draw9patch application from your SDK /tools directory.
• 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.
• 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.
• 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.
356
Content from developer.android.com/tools/help/draw9patch.html through their Creative Commons Attribution 2.5 license
Draw 9-patch
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.
357
Content from developer.android.com/tools/help/draw9patch.html through their Creative Commons Attribution 2.5 license
Android Emulator
65.
Android Emulator
Content from developer.android.com/tools/help/emulator.html through their Creative Commons Attribution 2.5 license
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.
In this section
• Keyboard Commands
• Command Line Parameters
See also
• Using the Android Emulator
• Managing Virtual Devices
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
358
Content from developer.android.com/tools/help/emulator.html through their Creative Commons Attribution 2.5 license
Android Emulator
Camera button
Ctrl-KEYPAD_5, Ctrl-F3
Switch to previous layout orientation (for example,
portrait, landscape)
KEYPAD_7, Ctrl-F11
Switch to next layout orientation (for example, portrait,
landscape)
KEYPAD_9, Ctrl-F12
Toggle cell networking on/off
F8
Toggle code profiling
F9 (only with -trace startup option)
Toggle fullscreen mode
Alt-Enter
Toggle trackball mode
F6
Enter trackball mode temporarily (while key is pressed) Delete
DPad left/up/right/down
KEYPAD_4/8/6/2
DPad center click
KEYPAD_5
Onion alpha increase/decrease
KEYPAD_MULTIPLY(*) /
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 Option
AVD
Description
Comments
-avd
Required. Specifies the You must create an AVD configuration
<avd_name> AVD to load for this
before launching the emulator. For
or
emulator instance.
information, see Managing AVDs with AVD
359
Content from developer.android.com/tools/help/emulator.html through their Creative Commons Attribution 2.5 license
Android Emulator
@<avd_name>
Manager.
Disk
Use <filepath> as the
An absolute or relative path to the current
Images cache <file working cache partition working directory. If no cache file is
path>
image.
specified, the emulator's default behavior is
to use a temporary file instead.
For more information on disk images, use
-help-disk-images.
Use <filepath> as Optionally, you can specify a path relative
data <filep the working user-data to the current working directory. If -data
ath>
disk image.
is not used, the emulator looks for a file
named userdata-qemu.img in the
storage area of the AVD being used (see avd).
When resetting the
initdata <f user-data image
ilepath>
(through -wipedata), copy the
contents of this file to
the new user-data disk
image. By default, the
emulator copies the
<system>/userda
ta.img.
Optionally, you can specify a path relative
to the current working directory. See also wipe-data.
-nocache
See also -cache <file>.
Start the emulator
without a cache
partition.
For more information on disk images, use
-help-disk-images.
Use <filepath> as the
ramdisk <fi ramdisk image.
lepath>
Default value is
<system>/ramdisk.img.
Use <file> as the SD
sdcard <fil card image.
epath>
Default value is
<system>/sdcard.img.
Optionally, you can specify a path relative
to the current working directory. For more
information on disk images, use -helpdisk-images.
Optionally, you can specify a path relative
to the current working directory. For more
information on disk images, use -helpdisk-images.
-wipe-data Reset the current user- See also -initdata.
data disk image (that is, For more information on disk images, use
the file specified by -help-disk-images.
datadir and -data,
or the default file). The
emulator deletes all
data from the user data
image file, then copies
360
Content from developer.android.com/tools/help/emulator.html through their Creative Commons Attribution 2.5 license
Android Emulator
the contents of the file
at -inidata data to
the image file before
starting.
Debug
-debug
<tags>
Enable/disable debug
messages for the
specified debug tags.
<tags> is a space/comma/columnseparated list of debug component names.
Use -help-debug-tags to print a list
of debug component names that you can
use.
-debug<tag>
Enable/disable debug
messages for the
specified debug tag.
Use -help-debug-tags to print a list
of debug component names that you can
use in <tag>.
-debug-no- Disable debug
<tag>
messages for the
specified debug tag.
-logcat
<logtags>
Enable logcat output
with given tags.
If the environment variable
ANDROID_LOG_TAGS is defined and not
empty, its value will be used to enable
logcat output by default.
-shell
Create a root shell
console on the current
terminal.
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.
-shellEnable the root shell (as <device> must be a QEMU device type.
serial <dev in -shell and specify See the documentation for '-serial dev' at
ice>
the QEMU character
http://wiki.qemu.org/download/qemudoc.html for a list of device types.
device to use for
communication with the Here are some examples:
shell.
•
•
•
•
-showkernel
<name>
-shell-serial stdio is
identical to -shell
-shell-serial
tcp::4444,server,nowai
t lets you communicate 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.
Display kernel
messages.
361
Content from developer.android.com/tools/help/emulator.html through their Creative Commons Attribution 2.5 license
Android Emulator
-trace
<name>
Enable code profiling
(press F9 to start),
written to a specified
file.
-verbose
Enable verbose output. Equivalent to -debug-init.
You can define the default verbose output
options used by emulator instances in the
Android environment variable
ANDROID_VERBOSE. Define 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>.
Media
-audio
<backend>
Use the specified audio
backend.
-audio-in
<backend>
Use the specified audioinput backend.
-audio-out Use the specified audio<backend>
output backend.
-noaudio
Disable audio support in
the current emulator
instance.
-radio
<device>
Redirect radio modem
interface to a host
character device.
-useaudio
Enable audio support in Enabled by default.
the current emulator
instance.
Network -dns-server Use the specified DNS The value of <servers> must be a
<servers>
server(s).
comma-separated list of up to 4 DNS
server names or IP addresses.
-http-proxy Make all TCP
<proxy>
connections through a
specified HTTP/HTTPS
proxy
The value of <proxy> can be one of the
following:
http://<server>:<port>
http://<username>:<password>
@<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 variable and
362
Content from developer.android.com/tools/help/emulator.html through their Creative Commons Attribution 2.5 license
Android Emulator
automatically uses any value matching the
<proxy> format described above.
-netdelay
<delay>
Set network latency
emulation to <delay>.
-netfast
Shortcut for netspeed full netdelay none
-netspeed
<speed>
Set network speed
emulation to <speed>.
Default value is full. See the table in
Network Speed Emulation for supported
<speed> values.
-port
<port>
Set the console port
number for this
emulator instance to
<port>.
The console port number must be an even
integer between 5554 and 5584, inclusive.
<port>+1 must also be free and will be
reserved for ADB.
-reportconsole
<socket>
Report the assigned
console port for this
emulator instance to a
remote third party
before starting the
emulation.
<socket> must use one of these
formats:
Default value is none. See the table in
Network Delay Emulation for supported
<delay> values.
tcp:<port>[,server][,max=<se
conds>]
unix:<port>[,server][,max=<s
econds>]
Use -help-report-console
to view more information about this topic.
System -cpu-delay Slow down emulated
Supported values for <delay> are integers
<delay>
CPU speed by <delay> between 0 and 1000.
Note that the <delay> does not correlate to
clock speed or other absolute metrics — it
simply represents an abstract, relative
delay factor applied non-deterministically in
the emulator. Effective performance does
not always scale in direct relationship with
<delay> values.
-gps
<device>
Redirect NMEA GPS to Use this command to emulate an NMEAcharacter device.
compatible GPS unit connected to an
external character device or socket. The
format of <device> must be QEMUspecific serial device specification. See the
documentation for 'serial -dev' at
http://wiki.qemu.org/download/qemudoc.html.
-nojni
Disable JNI checks in
the Dalvik runtime.
-qemu
Pass arguments to the
qemu emulator
software.
Important: When using this option, make
sure it is the last option specified, since all
options after it are interpretted as qemuspecific options.
363
Content from developer.android.com/tools/help/emulator.html through their Creative Commons Attribution 2.5 license
Android Emulator
-qemu Enable KVM
enable-kvm acceleration of the
emulator virtual
machine.
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
Display qemu help.
-gpu on
Turn on graphics
acceleration for the
emulator.
-radio
<device>
Redirect radio mode to The format of <device> must be QEMUthe specified character specific serial device specification. See the
device.
documentation for 'serial -dev' at
http://wiki.qemu.org/download/qemudoc.html.
-timezone
Set the timezone for the
<timezone> emulated device to
<timezone>, instead of
the host's timezone.
-version
UI
This option is only available for emulators
using a system image with API Level 15,
revision 3 and higher. For more
information, see Using the Android
Emulator.
<timezone> must be specified in
zoneinfo format. For example:
"America/Los_Angeles"
"Europe/Paris"
Display the emulator's
version number.
-dpi-device Scale the resolution of
<dpi>
the emulator to match
the screen size of a
physical device.
The default value is 165. See also scale.
-no-bootanim
Disabling the boot animation can speed the
startup time for the emulator.
Disable the boot
animation during
emulator startup.
-no-window Disable the emulator's
graphical window
display.
-scale
<scale>
Scale the emulator
window.
-raw-keys
Disable Unicode
keyboard reversemapping.
-noskin
Don't use any emulator
skin.
<scale> is a number between 0.1 and 3
that represents the desired 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.
364
Content from developer.android.com/tools/help/emulator.html through their Creative Commons Attribution 2.5 license
Android Emulator
-keyset
<file>
Use the specified
The keyset file defines the list of key
keyset file instead of the bindings between the emulator and the
default.
host keyboard. For more information, use help-keyset to print information about
this topic.
-onion
<image>
Use overlay image over No support for JPEG. Only PNG is
screen.
supported.
-onionalpha
<percent>
Specify onion skin
translucency value (as
percent).
-onionSpecify onion skin
rotation
rotation.
<position>
Help
Default is 50.
<position> must be one of the values
0, 1, 2, 3.
-skin
<skinID>
This emulator option is Please set skin options using AVDs, rather
deprecated.
than by using this emulator option. Using
this option may yield unexpected and in
some cases misleading results, since the
density with which to render the 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.
-skindir
<dir>
This emulator option is See comments for -skin, above.
deprecated.
-help
Print a list of all
emulator options.
-help-all
Print help for all startup
options.
-help<option>
Print help for a specific
startup option.
-helpPrint a list of all tags for
debug-tags -debug <tags>.
-help-disk- Print help for using
images
emulator disk images.
-helpPrint help for emulator
environment environment variables.
-help-keys Print the current
mapping of keys.
-helpPrint help for defining a
keyset-file custom key mappings
file.
-helpvirtualdevice
Print help for Android
Virtual Device usage.
365
Content from developer.android.com/tools/help/emulator.html through their Creative Commons Attribution 2.5 license
etc1tool
66.
etc1tool
Content from developer.android.com/tools/help/etc1tool.html through their Creative Commons Attribution 2.5 license
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.
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.
--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).
366
Content from developer.android.com/tools/help/etc1tool.html through their Creative Commons Attribution 2.5 license
Hierarchy Viewer
67.
Hierarchy Viewer
Content from developer.android.com/tools/help/hierarchy-viewer.html through their Creative Commons Attribution 2.5 license
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
367
Content from developer.android.com/tools/help/hierarchy-viewer.html through their Creative Commons Attribution 2.5 license
HPROF Converter
68.
HPROF Converter
Content from developer.android.com/tools/help/hprof-conv.html through their Creative Commons Attribution 2.5 license
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.
368
Content from developer.android.com/tools/help/hprof-conv.html through their Creative Commons Attribution 2.5 license
JOBB
69.
JOBB
Content from developer.android.com/tools/help/jobb.html through their Creative Commons Attribution 2.5 license
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.
369
Content from developer.android.com/tools/help/jobb.html through their Creative Commons Attribution 2.5 license
JOBB
-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.
370
Content from developer.android.com/tools/help/jobb.html through their Creative Commons Attribution 2.5 license
lint
70.
lint
Content from developer.android.com/tools/help/lint.html through their Creative Commons Attribution 2.5 license
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.
In this section
• Syntax
• Options
• Configuring Java and XML Source Files
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
Comments
Checking --disable <list> Disable checking for a The <list> must be a commaspecific list of issues. separated list of lint issue IDs or
categories.
--enable <list>
Check for all the
The <list> must be a commadefault issues
separated list of lint issue IDs or
supported by lint as categories.
well as the specifically
enabled list of issues.
371
Content from developer.android.com/tools/help/lint.html through their Creative Commons Attribution 2.5 license
lint
--check <list>
Check for a specific list The <list> must be a commaof issues.
separated list of lint issue IDs or
categories.
-w or --nowarn
Only check for errors
and ignore warnings
-Wall
Check for all warnings,
including those that are
disabled by default
-Werror
Report all warnings as
errors
--config
<filename>
Use the specified
configuration file to
determine if issues are
enabled or disabled for
lint checking
If the project contains a
lint.xml file, the lint.xml
file will be used as the configuration
file by default.
Generate an HTML
report.
The report is saved in the output
file specified in the argument. The
HTML output includes code
snippets of the source code where
lint detected an issue, a verbose
description of the issue found, and
links to the source file.
Reporting --html
<filename>
--url
In the HTML output,
<filepath>=<url> replace a local path
prefix <filepath>
with a url prefix
<url>.
The --url option only applies
when you are generating an HTML
report with the --html option.
You can specify multiple
<filepath>=<url> mappings in the
argument by separating each
mapping with a comma.
To turn off linking to files, use -url none
--simplehtml
<filename>
Generate a simple
HTML report
The report is saved in the output
file specified in the argument.
--xml <filename> Generate an XML
report
The report is saved in the output
file specified in the argument.
--fullpath
Show the full file paths
in the lint checking
results.
372
Content from developer.android.com/tools/help/lint.html through their Creative Commons Attribution 2.5 license
lint
Help
--showall
Don't truncate long
messages or lists of
alternate locations.
--nolines
Don't include code
snippets from the
source files in the
output.
--exitcode
Set the exit code to 1 if
errors are found.
--quiet
Don't show the
progress indicator.
--help
List the command-line Use --help <topic> to see
arguments supported help information for a specific topic,
by the lint tool.
such as "suppress".
--list
List the ID and short
description for issues
that can be checked by
lint
--show
List the ID and verbose Use --show <ids> to see
description for issues descriptions for a specific list of
that can be checked by lint issue IDs.
lint
--version
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.
373
Content from developer.android.com/tools/help/lint.html through their Creative Commons Attribution 2.5 license
logcat
71.
logcat
Content from developer.android.com/tools/help/logcat.html through their Creative Commons Attribution 2.5 license
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 event 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.
Writes log message output to <filename>. The default is stdout.
f <filename>
-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.
374
Content from developer.android.com/tools/help/logcat.html through their Creative Commons Attribution 2.5 license
logcat
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.
375
Content from developer.android.com/tools/help/logcat.html through their Creative Commons Attribution 2.5 license
mksdcard
72.
mksdcard
Content from developer.android.com/tools/help/mksdcard.html through their Creative Commons Attribution 2.5 license
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
Option 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
376
Content from developer.android.com/tools/help/mksdcard.html through their Creative Commons Attribution 2.5 license
UI/Application Exerciser Monkey
73.
UI/Application Exerciser Monkey
Content from developer.android.com/tools/help/monkey.html through their Creative Commons Attribution 2.5 license
The Monkey is a program that runs on your emulator or device and generates pseudo-random streams of
user events such as clicks, touches, or gestures, as well as a number of system-level events. You can use
the Monkey to stress-test applications that you are developing, in a random yet repeatable manner.
Overview
The Monkey is a command-line tool that 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.
377
Content from developer.android.com/tools/help/monkey.html through their Creative Commons Attribution 2.5 license
UI/Application Exerciser Monkey
Category
Option
Description
General
--help
Prints a simple usage guide.
-v
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.
-s <seed>
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.
--throttle
<milliseconds>
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.
--pct-touch
<percent>
Adjust percentage of touch events. (Touch events are a
down-up event in a single place on the screen.)
--pct-motion
<percent>
Adjust percentage of motion events. (Motion events consist
of a down event somewhere on the screen, a series of
pseudo-random movements, and an up event.)
Events
--pct-trackball Adjust percentage of trackball events. (Trackball events
<percent>
consist of one or more random movements, sometimes
followed by a click.)
--pct-nav
<percent>
Adjust percentage of "basic" navigation events. (Navigation
events consist of up/down/left/right, as input from a
directional input device.)
--pct-majornav
<percent>
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.)
--pct-syskeys
<percent>
Adjust percentage of "system" key events. (These are keys
that are generally reserved for use by the system, such as
378
Content from developer.android.com/tools/help/monkey.html through their Creative Commons Attribution 2.5 license
UI/Application Exerciser Monkey
Home, Back, Start Call, End Call, or Volume controls.)
--pct-appswitch Adjust percentage of activity launches. At random intervals,
<percent>
the Monkey will issue a startActivity() call, as a way of
maximizing coverage of all activities within your package.
--pct-anyevent
<percent>
Constraints -p <allowedpackage-name>
-c <maincategory>
Adjust percentage of other types of events. This is a catchall for all other types of events such as keypresses, other
less-used 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
categories, the Monkey will select activities listed with the
category Intent.CATEGORY_LAUNCHER or
Intent.CATEGORY_MONKEY. To specify multiple
categories, use the -c option multiple times — one -c option
per category.
Debugging --dbg-no-events 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
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.
--hprof
If set, this option will generate profiling reports immediately
before and after the Monkey event sequence. This will
generate large (~5Mb) files in data/misc, so use with care.
See Traceview for more information on trace files.
--ignorecrashes
Normally, the Monkey will stop when the application crashes
or experiences any type of unhandled exception. If you
specify this option, the Monkey will continue to send events
to the system, until the count is completed.
379
Content from developer.android.com/tools/help/monkey.html through their Creative Commons Attribution 2.5 license
UI/Application Exerciser Monkey
--ignoretimeouts
Normally, the Monkey will stop when the application
experiences any type of timeout error such as a "Application
Not Responding" dialog. If you specify this option, the
Monkey will continue to send events to the system, until the
count is completed.
--ignoresecurityexceptions
Normally, the Monkey will stop when the application
experiences any type of permissions error, for example if it
attempts to launch an activity that requires certain
permissions. If you specify this option, the Monkey will
continue to send events to the system, until the count is
completed.
--kill-process- Normally, when the Monkey stops due to an error, the
after-error
application that failed will be left running. When this option is
set, it will signal the system to stop the process in which 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.
--monitornative-crashes
Watches for and reports crashes occurring in the Android
system native code. If --kill-process-after-error is set, the
system will stop.
--wait-dbg
Stops the Monkey from executing until a debugger is
attached to it.
380
Content from developer.android.com/tools/help/monkey.html through their Creative Commons Attribution 2.5 license
monkeyrunner
74.
monkeyrunner
Content from developer.android.com/tools/help/monkeyrunner_concepts.html through their Creative Commons Attribution 2.5 license
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.
In this section
• A Simple monkeyrunner Program
• The monkeyrunner API
• Running monkeyrunner
• monkeyrunner Built-in Help
• Extending monkeyrunner with Plugins
See Also
• Testing Fundamentals
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 pseudorandom 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.
381
Content from developer.android.com/tools/help/monkeyrunner_concepts.html through their Creative Commons Attribution 2.5 license
monkeyrunner
# 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 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.
MonkeyDevice: 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.
MonkeyImage: 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
382
Content from developer.android.com/tools/help/monkeyrunner_concepts.html through their Creative Commons Attribution 2.5 license
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
-plugin
<plugin_jar>
(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.
<program_filename> If you provide this argument, the monkeyrunner command
runs the 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>.
monkeyrunner Built-in Help
You can generate an API reference for monkeyrunner by running:
monkeyrunner help.py <format> <outfile>
The arguments are:
•
•
<format> is either text for plain text output or html for HTML output.
<outfile> 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).
383
Content from developer.android.com/tools/help/monkeyrunner_concepts.html through their Creative Commons Attribution 2.5 license
monkeyrunner
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;
}
}
384
Content from developer.android.com/tools/help/monkeyrunner_concepts.html through their Creative Commons Attribution 2.5 license
MonkeyDevice
75.
MonkeyDevice
Content from developer.android.com/tools/help/MonkeyDevice.html through their Creative Commons Attribution 2.5 license
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
string DOWN
Use this with the type argument of press() or touch() to send
a DOWN event.
string UP
Use this with the type argument of press() or touch() to send
an UP event.
string DOWN_AND_UP Use this with the type argument of press() or touch() to send
a DOWN event immediately followed by an 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.
void
drag (tuple start, tuple end, float duration, integer steps)
Simulates a drag gesture (touch, hold, and move) on this device's screen.
object
getProperty (string key)
Given the name of a system environment variable, returns its value for this
385
Content from developer.android.com/tools/help/MonkeyDevice.html through their Creative Commons Attribution 2.5 license
MonkeyDevice
device. The available variable names are listed in the detailed description of
this method.
object
getSystemProperty (string key)
. The API equivalent of adb shell getprop <key>. This is
provided for use by platform developers.
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.
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.
void
press (string name, dictionary type)
Sends the key event specified by type to the key specified by keycode.
void
reboot (string into)
Reboots this device into the bootloader specified by bootloadType.
void
removePackage (string package)
Deletes the specified package from this device, including its data and
cache.
object
shell (string cmd)
Executes an adb shell command and returns the result, if any.
void
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.
386
Content from developer.android.com/tools/help/MonkeyDevice.html through their Creative Commons Attribution 2.5 license
MonkeyDevice
MonkeyImage takeSnapshot()
Captures the entire screen buffer of this device, yielding a MonkeyImage
object containing a screen capture of the current display.
void
touch (integer x, integer y, integer type)
Sends a touch event specified by type to the screen location specified by x
and y.
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.
void
wake ()
Wakes the screen of this device.
Constants
string DOWN
press() or touch() value. Specifies that a DOWN event type should be sent to the device,
corresponding to pressing down on a key or touching the screen.
string UP
press() or touch() value. Specifies that an UP event type should be sent to the device, corresponding
to releasing a key or lifting up from the screen.
string DOWN_AND_UP
press(), touch() or type() value. Specifies that a DOWN event type followed by an UP event type
should be sent to the device, corresponding to typing a key or clicking the screen.
Public Methods
void broadcastIntent ( string uri, string action, string data, string mimetype, iterable
categories dictionary extras, component component, iterable flags)
Broadcasts an Intent to this device, as if the Intent were coming from an application. See Intent for more
information about the arguments.
Arguments
uri
The URI for the Intent. (see Intent.setData()).
387
Content from developer.android.com/tools/help/MonkeyDevice.html through their Creative Commons Attribution 2.5 license
MonkeyDevice
action
The action for this Intent (see Intent.setAction()).
data
The data URI for this Intent (see Intent.setData()).
mimetype The MIME type for the Intent (see Intent.setType()).
categories An iterable data structure containing strings that define categories for this Intent (see
Intent.addCategory()).
extras
A dictionary of extra data for this Intent (see Intent.putExtra() for an example).
The key for each dictionary item should be a string. The item's value can be any
simple or structured data type.
component The component for this Intent (see ComponentName). Using this argument 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()).
void drag ( tuple start, tuple end, float duration, integer steps)
Simulates a drag gesture (touch, hold, and move) on this device's screen.
Arguments
start
The starting point of the drag gesture, in the form of a tuple (x,y) where x and y are
integers.
end
The end point of the drag gesture, in the form of a tuple (x,y) where x and y are
integers.
duration The duration of the drag gesture in seconds. The default is 1.0 seconds.
steps
The number of steps to take when interpolating points. The default is 10.
object getProperty (string key)
Given the name of a system environment variable, returns its value for this device.
Arguments
key The name of the system environment variable. The available variable names are listed in
Table 1. Property variable names at the end of this topic.
388
Content from developer.android.com/tools/help/MonkeyDevice.html through their Creative Commons Attribution 2.5 license
MonkeyDevice
Returns
•
The value of the variable. The data format varies according to the variable requested.
object getSystemProperty (string key)
Synonym for getProperty().
Arguments
key The name of the system environment variable. The available variable names 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
The fully-qualified path and filename of the .apk file to install.
path
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
className The name of an Android component that is already installed on this device, in the
standard form packagename/classname, where packagename is the Android
package name of a .apk file on this device, and classname is the class name of an
Android component (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
389
Content from developer.android.com/tools/help/MonkeyDevice.html through their Creative Commons Attribution 2.5 license
MonkeyDevice
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
name The name of the keycode to send. See KeyEvent for a list of keycode names. 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
into The type of bootloader to reboot into. The allowed values are "bootloader", "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
390
Content from developer.android.com/tools/help/MonkeyDevice.html through their Creative Commons Attribution 2.5 license
MonkeyDevice
cmd The command to execute in the adb shell. The form of these commands is 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
uri
The URI for the Intent. (see Intent.setData()).
action
The action for the Intent (see Intent.setAction()).
data
The data URI for the Intent (see Intent.setData()).
mimetype The MIME type for the Intent (see Intent.setType()).
categories An iterable data structure containing strings that define categories for the Intent (see
Intent.addCategory()).
extras
A dictionary of extra data for the Intent (see Intent.putExtra() for an example).
The key for each dictionary item should be a string. The item's value can be any
simple or structured data type.
component The component for the Intent (see ComponentName). Using this argument 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)
391
Content from developer.android.com/tools/help/MonkeyDevice.html through their Creative Commons Attribution 2.5 license
MonkeyDevice
Sends a touch event specified by type to the screen location specified by x and y.
Arguments
x
The horizontal position of the touch in actual device pixels, starting from the 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.
type The type of key event to send. The allowed values are DOWN, UP, and 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 See Build
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.
392
Content from developer.android.com/tools/help/MonkeyDevice.html through their Creative Commons Attribution 2.5 license
MonkeyDevice
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.
version.incremental The internal code used by
the source control system to
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
393
Content from developer.android.com/tools/help/MonkeyDevice.html through their Creative Commons Attribution 2.5 license
MonkeyDevice
been released.
display
width
The device's display width
in pixels.
height
The device's display height
in pixels.
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
equivalent to one pixel on a
160 pixel-per-inch display.
For example, on a 160-dpi
screen, density = 1.0, while
on a 120-dpi screen, density
= .75.
See
DisplayMetrics
for details.
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
The Android package name The am.current
of the currently running
keys return
package.
information about the
currently-running
The current activity's action.
Activity.
This has the same format as
the name attribute of the
action element in a
package manifest.
comp.class
The class name of the
component that started the
current Activity. See
comp.package for more
details.
comp.package
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.
394
Content from developer.android.com/tools/help/MonkeyDevice.html through their Creative Commons Attribution 2.5 license
MonkeyDevice
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 See SystemClock
since the device rebooted, for more information.
including deep-sleep time.
uptime
The number of milliseconds
since the device rebooted,
not including deep-sleep
time
millis
current time since the UNIX
epoch, in milliseconds.
395
Content from developer.android.com/tools/help/MonkeyDevice.html through their Creative Commons Attribution 2.5 license
MonkeyImage
76.
MonkeyImage
Content from developer.android.com/tools/help/MonkeyImage.html through their Creative Commons Attribution 2.5 license
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
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.
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).
integer
getRawPixelInt (integer x, integer y)
Returns the single pixel at the image location (x,y), as a 32-bit integer.
MonkeyImage getSubImage (tuple rect)
Creates a new MonkeyImage object from a rectangular selection of the
current image.
boolean
sameAs (MonkeyImage other, 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".
void
writeToFile (string path, string format)
Writes the current image to the file specified by filename, in the format
specified by format.
396
Content from developer.android.com/tools/help/MonkeyImage.html through their Creative Commons Attribution 2.5 license
MonkeyImage
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
format The desired output format. All of the common raster output formats are 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
x The horizontal position of the pixel, starting with 0 at the left of the screen in 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
x The horizontal position of the pixel, starting with 0 at the left of the screen in 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
397
Content from developer.android.com/tools/help/MonkeyImage.html through their Creative Commons Attribution 2.5 license
MonkeyImage
•
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
rect A tuple (x, y, w, h) specifying the selection. x and y specify the 0-based pixel position of the
upper left-hand corner of the selection. w specifies the width of the region, and h specifies
its height, both in units of pixels.
The image's orientation is the same as the screen orientation at the time the screenshot
was made.
Returns
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.
percent A float in the range 0.0 to 1.0, inclusive, indicating the percentage of 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.
398
Content from developer.android.com/tools/help/MonkeyImage.html through their Creative Commons Attribution 2.5 license
MonkeyImage
format The output format to use for the file. If no format is provided, then the method tries to
guess the format from the filename's extension. If no extension is provided and no format
is specified, then the default format of "png" (Portable Network Graphics) is used.
399
Content from developer.android.com/tools/help/MonkeyImage.html through their Creative Commons Attribution 2.5 license
MonkeyRunner
77.
MonkeyRunner
Content from developer.android.com/tools/help/MonkeyRunner.html through their Creative Commons Attribution 2.5 license
A monkeyrunner class that contains static utility methods.
Summary
Methods
void
alert (string message, string title, string okTitle)
Displays an alert dialog to the process running the current program.
integer
choice (string message, iterable choices, string title)
Displays a dialog with a list of choices to the process running the current
program.
void
help (string format)
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.
void
sleep (float seconds)
Pauses the current program for the specified number of seconds.
MonkeyDevice waitForConnection (float timeout, string deviceId)
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
400
Content from developer.android.com/tools/help/MonkeyRunner.html through their Creative Commons Attribution 2.5 license
MonkeyRunner
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
message The prompt message displayed in the dialog.
choices A Python iterable containing one or more objects that are displayed as 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
format The markup format to use in the output. The possible values are "text" for 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.
401
Content from developer.android.com/tools/help/MonkeyRunner.html through their Creative Commons Attribution 2.5 license
MonkeyRunner
Arguments
message
The prompt message displayed in the dialog.
initialValue
The initial value to display in the dialog. The default is an empty string.
title
The dialog's title. The default is "Input".
okTitle
The text displayed in the okTitle button. The default is "OK".
cancelTitle
The text displayed in the cancelTitle button. The default is "Cancel".
Returns
•
If the user clicks the okTitle button, then the method returns the current value of the dialog's input
box. If the user clicks the cancelTitle button, the method returns an empty string.
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
timeout The number of seconds to wait for a connection. The default is to wait forever.
deviceId A regular expression that specifies the serial number of the device or 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.
402
Content from developer.android.com/tools/help/MonkeyRunner.html through their Creative Commons Attribution 2.5 license
ProGuard
78.
ProGuard
Content from developer.android.com/tools/help/proguard.html through their Creative Commons Attribution 2.5 license
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.
In this section
• Enabling ProGuard
• Configuring ProGuard
• Decoding Obfuscated Stack Traces
• Debugging considerations for published
applications
See also
• ProGuard Manual »
ProGuard is integrated into the Android build
• ProGuard ReTrace Manual »
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
403
Content from developer.android.com/tools/help/proguard.html through their Creative Commons Attribution 2.5 license
ProGuard
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 if you are using Ant.
<project_root>/proguard 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 section 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
404
Content from developer.android.com/tools/help/proguard.html through their Creative Commons Attribution 2.5 license
ProGuard
<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.
405
Content from developer.android.com/tools/help/proguard.html through their Creative Commons Attribution 2.5 license
SDK Manager
79.
SDK Manager
Content from developer.android.com/tools/help/sdk-manager.html through their Creative Commons Attribution 2.5 license
The Android SDK separates tools, platforms, and other components into packages you can download
using the SDK Manager.
You can launch the SDK Manager in one of the following ways:
•
•
•
From Eclipse (with ADT), select Window > 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.
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
406
Content from developer.android.com/tools/help/sdk-manager.html through their Creative Commons Attribution 2.5 license
SDK Manager
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.
407
Content from developer.android.com/tools/help/sdk-manager.html through their Creative Commons Attribution 2.5 license
Systrace
80.
Systrace
Content from developer.android.com/tools/help/systrace.html through their Creative Commons Attribution 2.5 license
The systrace tool helps analyze the performance of your application by capturing and displaying
execution times of your applications processes and other Android system processes. The tool combines
data from the Android kernel such as the CPU scheduler, disk activity and application threads to generate
an HTML report that shows an overall picture of an Android device’s system processes for a given period
of time.
The systrace tool is particularly useful in diagnosing display problems where an application is slow to
draw or stutters while displaying motion or animation. For more information on how to use systrace,
see Analyzing Display and Performance with Systrace.
Usage
In order to run systrace, the adb tool and Python must be 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 syntax for running systrace is as follows.
$> python systrace.py [options]
Here is an example execution run that sets trace tags and generates a trace from a connected Android
device.
$>
$>
$>
$>
$>
cd android-sdk/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
Options
The table below lists the command line options for systrace.
Option
Description
-o <FILE>
Write the HTML trace report to the specified file.
-t N, -time=N
Trace activity for N seconds. Default value is 5 seconds.
-b N, --buf- Use a trace buffer size of N kilobytes. This option lets you limit the total size
size=N
of the data collected during a trace.
-d, --disk
Trace disk input and output activity. This option requires root access on the
device.
-f, --cpu-
Trace CPU frequency changes. Only changes to the CPU frequency are
408
Content from developer.android.com/tools/help/systrace.html through their Creative Commons Attribution 2.5 license
Systrace
freq
logged, so the initial frequency of the CPU when tracing starts is not shown.
-i, --cpuidle
Trace CPU idle events.
-l, --cpuload
Trace CPU load. This value is a percentage determined by the interactive
CPU frequency governor.
-s, --nocpu-sched
Prevent tracing of the CPU scheduler. This option allows for longer trace
times by reducing the rate of data flowing into the trace buffer.
-w, -workqueue
Trace kernel work queues. This option requires root access on the device.
--settags=<TAGS>
Set the enabled trace tags in a comma separated list. The available tags
are:
•
•
•
•
•
•
•
•
•
•
gfx - Graphics
input - Input
view - View
webview - WebView
wm - Window Manager
am - Activity Manager
sync - Sync Manager
audio - Audio
video - Video
camera - Camera
Note: When setting trace tags from the command line, you must stop and
restart the framework ($> adb shell stop; adb shell
start) for the tag tracing changes to take effect.
--linkassets
Link to the original CSS or JS resources instead of embedding them in the
HTML trace report.
-h, --help
Show the help message.
You can set the trace tags for systrace with your device's user interface, 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
Description
409
Content from developer.android.com/tools/help/systrace.html through their Creative Commons Attribution 2.5 license
Systrace
w
Zoom into the trace timeline.
s
Zoom out of the trace timeline.
a
Pan left on the trace timeline.
d
Pan right on the trace timeline.
e
Center the trace timeline on the current mouse location.
g
Show grid at the start of the currently selected task.
Shift+g
Show grid at the end of the currently selected task.
Right Arrow
Select the next event on the currently selected timeline.
Left Arrow
Select the previous event on the currently selected timeline.
Double Click
Zoom into the trace timeline.
Shift+Double Click
Zoom out of the trace timeline.
410
Content from developer.android.com/tools/help/systrace.html through their Creative Commons Attribution 2.5 license
Tracer for OpenGL ES
81.
Tracer for OpenGL ES
Content from developer.android.com/tools/help/gltracer.html through their Creative Commons Attribution 2.5 license
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.
In this section
• Running Tracer
• Generating a Trace
• Analyzing a Trace
See also
• Tools
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:
• Start Eclipse and open a workspace that contains an Android project.
• Activate the perspective for Tracer by choosing Window > Open Perspective > Other...
• Select Tracer for OpenGL ES and click OK.
To run Tracer in Device Monitor:
• Start the Device Monitor tool.
• Activate the perspective for Tracer by choosing Window > Open Perspective...
• 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.
411
Content from developer.android.com/tools/help/gltracer.html through their Creative Commons Attribution 2.5 license
Tracer for OpenGL ES
Figure 1. Trace capture dialog box.
To capture an OpenGL ES trace for an Android application:
• Connect the Android device using a USB cable and make sure it is enabled for debugging. For more
information, see Using Hardware Devices.
• In Eclipse or Device Monitor, activate the Tracer for OpenGL ES perspective.
• On the toolbar, click the trace capture button (
).
• In the dialog box, select the Device to use for the trace.
• In the Application Package field, enter the full application package name containing the activity you
want to trace, for example: com.example.android.opengl
• 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.
• 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.
• Enter a Destination File for the trace output.
• Click Trace to start the trace capture.
• On the connected device, exercise the functions of your application you want to trace.
• 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:
• In Eclipse or Device Monitor, activate the Tracer for OpenGL ES perspective.
412
Content from developer.android.com/tools/help/gltracer.html through their Creative Commons Attribution 2.5 license
Tracer for OpenGL ES
• On the toolbar, click the trace load button (
).
• After loading a trace, select a frame and review the OpenGL ES calls. Drawing commands are
highlighted in blue.
413
Content from developer.android.com/tools/help/gltracer.html through their Creative Commons Attribution 2.5 license
Traceview
82.
Traceview
Content from developer.android.com/tools/help/traceview.html through their Creative Commons Attribution 2.5 license
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
414
Content from developer.android.com/tools/help/traceview.html through their Creative Commons Attribution 2.5 license
uiautomator
83.
uiautomator
Content from developer.android.com/tools/help/uiautomator/index.html through their Creative Commons Attribution 2.5 license
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.
In this section
•
•
•
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:
Syntax
Options
uiautomator API
o Classes
o Interfaces
o Exceptions
adb shell uiautomator runtest <JARS> -c <CLASSES> [options]
Here’s 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 Option
Description
runtest
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.
<JARS>
-c <CLASSES> 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:
•
•
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
415
Content from developer.android.com/tools/help/uiautomator/index.html through their Creative Commons Attribution 2.5 license
uiautomator
run.
--nohup
Runs the test to completion on the device even if its
parent process is terminated (for example, if the device
is disconnected).
-e <NAME>
<VALUE>
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
Wait for debugger to connect before starting.
[true|false]
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
Enables less verbose JUnit style output.
outputFormat
simple | -s
events
Prints out accessibility events to the console until the
connection to the device is terminated
uiautomator API
The uiautomator API is bundled in the uiautomator.jar file under the <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.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.
com.android.uiautomator.core.UiDevice
Provides access to state
information about the device.
You can also use this class
to simulate user actions on
the device, such as pressing
the d-pad hardware button or
pressing the Home and
Menu buttons.
416
Content from developer.android.com/tools/help/uiautomator/index.html through their Creative Commons Attribution 2.5 license
uiautomator
com.android.uiautomator.core.UiObject
Represents a user interface
(UI) element.
com.android.uiautomator.core.UiScrollable Provides support for
searching for items in a
scrollable UI container.
com.android.uiautomator.core.UiSelector
Represents a query for one
or more target UI elements
on a device screen.
com.android.uiautomator.core.Configurator Allows you to set key
parameters for running
uiautomator tests.
Interfaces
Interface
Description
com.android.uiautomator.core.UiWatcher
Represents a conditional
watcher on the target device.
com.android.uiautomator.testrunner.IAuto Provides auxiliary support for
mationSupport
running test cases.
com.android.uiautomator.testrunner.UiAut Defines an environment for
omatorTestCase
running multiple tests. All
uiautomator test cases
should extend this class.
Exceptions
Exception
Description
com.android.uiautomator.core.UiObjectNot Indicates when a a
FoundException
UiSelector could not be
matched to any UI element
displayed.
417
Content from developer.android.com/tools/help/uiautomator/index.html through their Creative Commons Attribution 2.5 license
Configurator
84.
Configurator
Content from developer.android.com/tools/help/uiautomator/Configurator.html through their Creative Commons Attribution 2.5 license
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
long
getActionAcknowledgmentTimeout()
Gets the current timeout for waiting for an acknowledgment of generic
uiautomator actions, such as clicks, text setting, and menu presses.
static
getInstance()
Configurator
Retrieves a singleton instance of Configurator.
long
getKeyInjectionDelay()
Gets the current delay between key presses when injecting text input.
long
getScrollAcknowledgmentTimeout()
Gets the timeout for waiting for an acknowledgement of an uiautomtor scroll
swipe action.
long
getWaitForIdleTimeout()
Gets the current timeout used for waiting for the user interface to go into an
idle state.
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.
Configurator setActionAcknowledgmentTimeout(long timeout)
Sets the timeout for waiting for an acknowledgment of generic uiautomator
418
Content from developer.android.com/tools/help/uiautomator/Configurator.html through their Creative Commons Attribution 2.5 license
Configurator
actions, such as clicks, text setting, and menu presses.
Configurator setKeyInjectionDelay(long delay)
Sets a delay between key presses when injecting text input.
Configurator setScrollAcknowledgmentTimeout(long timeout)
Sets the timeout for waiting for an acknowledgement of an uiautomtor scroll
swipe action.
Configurator setWaitForIdleTimeout(long timeout)
Sets the timeout for waiting for the user interface to go into an idle state before
starting a uiautomator action.
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.
[Expand]
Inherited Methods
From class java.lang.Object
Object
clone()
boolean equals(Object arg0)
void
finalize()
final
getClass()
Class<?>
int
hashCode()
final void notify()
final void notifyAll()
419
Content from developer.android.com/tools/help/uiautomator/Configurator.html through their Creative Commons Attribution 2.5 license
Configurator
String
toString()
final void wait()
final void wait(long arg0, int arg1)
final void wait(long arg0)
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
420
Content from developer.android.com/tools/help/uiautomator/Configurator.html through their Creative Commons Attribution 2.5 license
Configurator
•
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
421
Content from developer.android.com/tools/help/uiautomator/Configurator.html through their Creative Commons Attribution 2.5 license
Configurator
•
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)
422
Content from developer.android.com/tools/help/uiautomator/Configurator.html through their Creative Commons Attribution 2.5 license
Configurator
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.
423
Content from developer.android.com/tools/help/uiautomator/Configurator.html through their Creative Commons Attribution 2.5 license
Configurator
Parameters
timeout
Timeout value in milliseconds.
Returns
•
self
Since
•
Android API Level 18
424
Content from developer.android.com/tools/help/uiautomator/Configurator.html through their Creative Commons Attribution 2.5 license
IAutomationSupport
85.
IAutomationSupport
Content from developer.android.com/tools/help/uiautomator/IAutomationSupport.html through their Creative Commons Attribution 2.5 license
Class Overview
Provides auxiliary support for running test cases
Summary
Public Methods
abstract sendStatus(int resultCode, Bundle status)
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
425
Content from developer.android.com/tools/help/uiautomator/IAutomationSupport.html through their Creative Commons Attribution 2.5 license
UiAutomatorTestCase
86.
UiAutomatorTestCase
Content from developer.android.com/tools/help/uiautomator/UiAutomatorTestCase.html through their Creative Commons Attribution 2.5 license
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
IAutomationSupport getAutomationSupport()
Provides support for running tests to report interim status
Bundle
getParams()
Get command line parameters.
UiDevice
getUiDevice()
Get current instance of UiDevice.
void
sleep(long ms)
Calls sleep(long) to sleep
[Expand]
Inherited Methods
From class junit.framework.TestCase
int
countTestCases()
426
Content from developer.android.com/tools/help/uiautomator/UiAutomatorTestCase.html through their Creative Commons Attribution 2.5 license
UiAutomatorTestCase
String
getName()
TestResult run()
void
run(TestResult arg0)
void
runBare()
void
setName(String arg0)
String
toString()
From class junit.framework.Assert
static assertEquals(short arg0, short arg1)
void
static assertEquals(String arg0, int arg1, int arg2)
void
static assertEquals(String arg0, short arg1, short arg2)
void
static assertEquals(char arg0, char arg1)
void
static assertEquals(String arg0, String arg1, String arg2)
void
static assertEquals(int arg0, int arg1)
void
static assertEquals(String arg0, double arg1, double arg2, double arg3)
void
static assertEquals(String arg0, long arg1, long arg2)
void
static assertEquals(byte arg0, byte arg1)
427
Content from developer.android.com/tools/help/uiautomator/UiAutomatorTestCase.html through their Creative Commons Attribution 2.5 license
UiAutomatorTestCase
void
static assertEquals(Object arg0, Object arg1)
void
static assertEquals(boolean arg0, boolean arg1)
void
static assertEquals(String arg0, float arg1, float arg2, float arg3)
void
static assertEquals(String arg0, boolean arg1, boolean arg2)
void
static assertEquals(String arg0, String arg1)
void
static assertEquals(float arg0, float arg1, float arg2)
void
static assertEquals(String arg0, byte arg1, byte arg2)
void
static assertEquals(double arg0, double arg1, double arg2)
void
static assertEquals(String arg0, char arg1, char arg2)
void
static assertEquals(String arg0, Object arg1, Object arg2)
void
static assertEquals(long arg0, long arg1)
void
static assertFalse(String arg0, boolean arg1)
void
static assertFalse(boolean arg0)
void
428
Content from developer.android.com/tools/help/uiautomator/UiAutomatorTestCase.html through their Creative Commons Attribution 2.5 license
UiAutomatorTestCase
static assertNotNull(String arg0, Object arg1)
void
static assertNotNull(Object arg0)
void
static assertNotSame(Object arg0, Object arg1)
void
static assertNotSame(String arg0, Object arg1, Object arg2)
void
static assertNull(Object arg0)
void
static assertNull(String arg0, Object arg1)
void
static assertSame(Object arg0, Object arg1)
void
static assertSame(String arg0, Object arg1, Object arg2)
void
static assertTrue(String arg0, boolean arg1)
void
static assertTrue(boolean arg0)
void
static fail(String arg0)
void
static fail()
void
static failNotEquals(String arg0, Object arg1, Object arg2)
void
static failNotSame(String arg0, Object arg1, Object arg2)
429
Content from developer.android.com/tools/help/uiautomator/UiAutomatorTestCase.html through their Creative Commons Attribution 2.5 license
UiAutomatorTestCase
void
static failSame(String arg0)
void
static format(String arg0, Object arg1, Object arg2)
String
From class java.lang.Object
boolean equals(Object arg0)
final
getClass()
Class<?>
int
hashCode()
final void notify()
final void notifyAll()
String
toString()
final void wait()
final void wait(long arg0, int arg1)
final void wait(long arg0)
From interface junit.framework.Test
abstract countTestCases()
int
abstract run(TestResult arg0)
void
Public Constructors
public UiAutomatorTestCase ()
Public Methods
430
Content from developer.android.com/tools/help/uiautomator/UiAutomatorTestCase.html through their Creative Commons Attribution 2.5 license
UiAutomatorTestCase
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.
431
Content from developer.android.com/tools/help/uiautomator/UiAutomatorTestCase.html through their Creative Commons Attribution 2.5 license
UiCollection
87.
UiCollection
Content from developer.android.com/tools/help/uiautomator/UiCollection.html through their Creative Commons Attribution 2.5 license
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
UiObject getChildByDescription(UiSelector childPattern, String text)
Searches for child UI element within the constraints of this UiSelector selector.
UiObject getChildByInstance(UiSelector childPattern, int instance)
Searches for child UI element within the constraints of this UiSelector.
UiObject getChildByText(UiSelector childPattern, String text)
Searches for child UI element within the constraints of this UiSelector.
int
getChildCount(UiSelector childPattern)
Counts child UI element instances matching the childPattern argument.
[Expand]
Inherited Methods
From class com.android.uiautomator.core.UiObject
void
clearTextField()
Clears the existing text contents in an editable field.
boolean
click()
Performs a click at the center of the visible bounds of the UI element
represented by this UiObject.
432
Content from developer.android.com/tools/help/uiautomator/UiCollection.html through their Creative Commons Attribution 2.5 license
UiCollection
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.
boolean
clickAndWaitForNewWindow()
See clickAndWaitForNewWindow(long) This method is intended to
reliably wait for window transitions that would typically take longer than the
usual default timeouts.
boolean
clickBottomRight()
Clicks the bottom and right corner of the UI element
boolean
clickTopLeft()
Clicks the top and left corner of the UI element
boolean
exists()
Check if UI element exists.
Rect
getBounds()
Returns the UI element's bounds property.
UiObject getChild(UiSelector selector)
Creates a new UiObject representing a child UI element of the element
currently represented by this UiObject.
int
getChildCount()
Counts the child UI elements immediately under the UI element currently
represented by this UiObject.
String
getContentDescription()
Reads the content_desc property of the UI element
UiObject getFromParent(UiSelector selector)
433
Content from developer.android.com/tools/help/uiautomator/UiCollection.html through their Creative Commons Attribution 2.5 license
UiCollection
Creates a new UiObject representing a child UI element from the parent
element currently represented by this object.
String
getPackageName()
Reads the UI element's package property
final
getSelector()
UiSelector
Debugging helper.
String
getText()
Reads the text property of the UI element
Rect
getVisibleBounds()
Returns the visible bounds of the UI element.
boolean
isCheckable()
Check if the UI element's checkable property is currently true
boolean
isChecked()
Check if the UI element's checked property is currently true
boolean
isClickable()
Check if the UI element's clickable property is currently true
boolean
isEnabled()
Check if the UI element's enabled property is currently true
boolean
isFocusable()
Check if the UI element's focusable property is currently true
434
Content from developer.android.com/tools/help/uiautomator/UiCollection.html through their Creative Commons Attribution 2.5 license
UiCollection
boolean
isFocused()
Check if the UI element's focused property is currently true
boolean
isLongClickable()
Check if the UI element's long-clickable property is currently true
boolean
isScrollable()
Check if the UI element's scrollable property is currently true
boolean
isSelected()
Check if the UI element's selected property is currently true
boolean
longClick()
Long clicks the center of the visible bounds of the UI element
boolean
longClickBottomRight()
Long clicks bottom and right corner of the UI element
boolean
longClickTopLeft()
Long clicks on the top and left corner of the UI element
boolean
setText(String text)
Sets the text in an editable field, after clearing the field's content.
boolean
swipeDown(int steps)
Perform the action on the UI element that is represented by this object,
Also see #scrollToBeginning(int), #scrollToEnd(int), #scrollBackward(),
#scrollForward().
boolean
swipeLeft(int steps)
Perform the action on the UI element that is represented by this object.
435
Content from developer.android.com/tools/help/uiautomator/UiCollection.html through their Creative Commons Attribution 2.5 license
UiCollection
boolean
swipeRight(int steps)
Perform the action on the UI element that is represented by this object.
boolean
swipeUp(int steps)
Perform the action on the UI element that is represented by this UiObject.
boolean
waitForExists(long timeout)
Waits a specified length of time for a UI element to become visible.
boolean
waitUntilGone(long timeout)
Waits a specified length of time for a UI element to become undetectable.
From class java.lang.Object
boolean equals(Object arg0)
final
getClass()
Class<?>
int
hashCode()
final void notify()
final void notifyAll()
String
toString()
final void wait()
final void wait(long arg0, int arg1)
final void wait(long arg0)
Public Constructors
public UiCollection (UiSelector selector)
436
Content from developer.android.com/tools/help/uiautomator/UiCollection.html through their Creative Commons Attribution 2.5 license
UiCollection
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 childPattern instance that
matched the search and not at the identifying child element that matched the content description.
Parameters
childPattern
UiSelector selector of the child pattern to match and return
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
437
Content from developer.android.com/tools/help/uiautomator/UiCollection.html through their Creative Commons Attribution 2.5 license
UiCollection
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
childPattern
UiSelector selector of the child pattern to match and return
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
childPattern a UiSelector that represents the matching child UI elements to count
Returns
•
the number of matched childPattern under the current UiCollection
438
Content from developer.android.com/tools/help/uiautomator/UiCollection.html through their Creative Commons Attribution 2.5 license
UiDevice
88.
UiDevice
Content from developer.android.com/tools/help/uiautomator/UiDevice.html through their Creative Commons Attribution 2.5 license
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
void
clearLastTraversedText()
Clears the text from the last UI traversal event.
boolean click(int x, int y)
Perform a click at arbitrary coordinates specified by the user
boolean drag(int startX, int startY, int endX, int endY, int steps)
Performs a swipe from one coordinate to another coordinate.
void
dumpWindowHierarchy(String fileName)
Helper method used for debugging to dump the current window's layout hierarchy.
void
freezeRotation()
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 unreliable
String
getCurrentPackageName()
Retrieves the name of the last package to report accessibility events.
int
getDisplayHeight()
Gets the height of the display, in pixels.
int
getDisplayRotation()
439
Content from developer.android.com/tools/help/uiautomator/UiDevice.html through their Creative Commons Attribution 2.5 license
UiDevice
Returns the current rotation of the display, as defined in Surface
Point
getDisplaySizeDp()
Returns the display size in dp (device-independent pixel) The returned display
size is adjusted per screen rotation.
int
getDisplayWidth()
Gets the width of the display, in pixels.
static
getInstance()
UiDevice
Retrieves a singleton instance of UiDevice
String
getLastTraversedText()
Retrieves the text from the last UI traversal event received.
String
getProductName()
Retrieves the product name of the device.
boolean hasAnyWatcherTriggered()
Checks if any registered UiWatcher have triggered.
boolean hasWatcherTriggered(String watcherName)
Checks if a specific registered UiWatcher has triggered.
boolean isNaturalOrientation()
Check if the device is in its natural orientation.
boolean isScreenOn()
Checks the power manager if the screen is ON.
boolean openNotification()
Opens the notification shade.
440
Content from developer.android.com/tools/help/uiautomator/UiDevice.html through their Creative Commons Attribution 2.5 license
UiDevice
boolean openQuickSettings()
Opens the Quick Settings shade.
boolean pressBack()
Simulates a short press on the BACK button.
boolean pressDPadCenter()
Simulates a short press on the CENTER button.
boolean pressDPadDown()
Simulates a short press on the DOWN button.
boolean pressDPadLeft()
Simulates a short press on the LEFT button.
boolean pressDPadRight()
Simulates a short press on the RIGHT button.
boolean pressDPadUp()
Simulates a short press on the UP button.
boolean pressDelete()
Simulates a short press on the DELETE key.
boolean pressEnter()
Simulates a short press on the ENTER key.
boolean pressHome()
Simulates a short press on the HOME button.
boolean pressKeyCode(int keyCode, int metaState)
441
Content from developer.android.com/tools/help/uiautomator/UiDevice.html through their Creative Commons Attribution 2.5 license
UiDevice
Simulates a short press using a key code.
boolean pressKeyCode(int keyCode)
Simulates a short press using a key code.
boolean pressMenu()
Simulates a short press on the MENU button.
boolean pressRecentApps()
Simulates a short press on the Recent Apps button.
boolean pressSearch()
Simulates a short press on the SEARCH button.
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.
void
removeWatcher(String name)
Removes a previously registered UiWatcher.
void
resetWatcherTriggers()
Resets a UiWatcher that has been triggered.
void
runWatchers()
This method forces all registered watchers to run.
void
setCompressedLayoutHeirarchy(boolean compressed)
Enables or disables layout hierarchy compression.
void
setOrientationLeft()
Simulates orienting the device to the left and also freezes rotation by disabling the
442
Content from developer.android.com/tools/help/uiautomator/UiDevice.html through their Creative Commons Attribution 2.5 license
UiDevice
sensors.
void
setOrientationNatural()
Simulates orienting the device into its natural orientation and also freezes rotation
by disabling the sensors.
void
setOrientationRight()
Simulates orienting the device to the right and also freezes rotation by disabling
the sensors.
void
sleep()
This method simply presses the power button if the screen is ON else it does
nothing if the screen is already OFF.
boolean swipe(Point[] segments, int segmentSteps)
Performs a swipe between points in the Point array.
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.
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
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
void
unfreezeRotation()
Re-enables the sensors and un-freezes the device rotation allowing its contents to
rotate with the device physical rotation.
void
waitForIdle(long timeout)
443
Content from developer.android.com/tools/help/uiautomator/UiDevice.html through their Creative Commons Attribution 2.5 license
UiDevice
Waits for the current application to idle.
void
waitForIdle()
Waits for the current application to idle.
boolean waitForWindowUpdate(String packageName, long timeout)
Waits for a window content update event to occur.
void
wakeUp()
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
Object
clone()
boolean equals(Object arg0)
void
finalize()
final
getClass()
Class<?>
int
hashCode()
final void notify()
final void notifyAll()
String
toString()
final void wait()
444
Content from developer.android.com/tools/help/uiautomator/UiDevice.html through their Creative Commons Attribution 2.5 license
UiDevice
final void wait(long arg0, int arg1)
final void wait(long arg0)
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
coordinate
y
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
X-axis value for the starting coordinate
startY
Y-axis value for the starting coordinate
endX
X-axis value for the ending coordinate
445
Content from developer.android.com/tools/help/uiautomator/UiDevice.html through their Creative Commons Attribution 2.5 license
UiDevice
endY
Y-axis value for the ending coordinate
steps
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.
446
Content from developer.android.com/tools/help/uiautomator/UiDevice.html through their Creative Commons Attribution 2.5 license
UiDevice
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 ()
447
Content from developer.android.com/tools/help/uiautomator/UiDevice.html through their Creative Commons Attribution 2.5 license
UiDevice
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
448
Content from developer.android.com/tools/help/uiautomator/UiDevice.html through their Creative Commons Attribution 2.5 license
UiDevice
•
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 ()
449
Content from developer.android.com/tools/help/uiautomator/UiDevice.html through their Creative Commons Attribution 2.5 license
UiDevice
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 ()
450
Content from developer.android.com/tools/help/uiautomator/UiDevice.html through their Creative Commons Attribution 2.5 license
UiDevice
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
451
Content from developer.android.com/tools/help/uiautomator/UiDevice.html through their Creative Commons Attribution 2.5 license
UiDevice
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 ()
452
Content from developer.android.com/tools/help/uiautomator/UiDevice.html through their Creative Commons Attribution 2.5 license
UiDevice
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
to register the UiWatcher
watcher
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.
453
Content from developer.android.com/tools/help/uiautomator/UiDevice.html through their Creative Commons Attribution 2.5 license
UiDevice
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 ()
454
Content from developer.android.com/tools/help/uiautomator/UiDevice.html through their Creative Commons Attribution 2.5 license
UiDevice
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
is Point array containing at least one Point object
segmentSteps
steps to inject between two Points
Returns
•
true on success
455
Content from developer.android.com/tools/help/uiautomator/UiDevice.html through their Creative Commons Attribution 2.5 license
UiDevice
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
where the PNG should be written to
scale
scale the screenshot down if needed; 1.0f for original size
456
Content from developer.android.com/tools/help/uiautomator/UiDevice.html through their Creative Commons Attribution 2.5 license
UiDevice
quality
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
457
Content from developer.android.com/tools/help/uiautomator/UiDevice.html through their Creative Commons Attribution 2.5 license
UiDevice
packageName the specified window package name (can be null). If null, a window update
from any front-end window will end the wait
timeout
the timeout for the wait
Returns
•
true if a window update occurred, false if timeout has elapsed or if the current window does not
have the specified package name
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
458
Content from developer.android.com/tools/help/uiautomator/UiDevice.html through their Creative Commons Attribution 2.5 license
UiObject
89.
UiObject
Content from developer.android.com/tools/help/uiautomator/UiObject.html through their Creative Commons Attribution 2.5 license
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
int
FINGER_TOUCH_HALF_WIDTH
int
SWIPE_MARGIN_LIMIT
long WAIT_FOR_EVENT_TMEOUT
This constant is deprecated. use
setScrollAcknowledgmentTimeout(long)
long WAIT_FOR_SELECTOR_POLL
long WAIT_FOR_SELECTOR_TIMEOUT This constant is deprecated. use
setWaitForSelectorTimeout(long)
long WAIT_FOR_WINDOW_TMEOUT
Public Constructors
UiObject(UiSelector selector)
Constructs a UiObject to represent a view that matches the specified selector criteria.
Public Methods
void
clearTextField()
Clears the existing text contents in an editable field.
boolean
click()
Performs a click at the center of the visible bounds of the UI element
represented by this UiObject.
459
Content from developer.android.com/tools/help/uiautomator/UiObject.html through their Creative Commons Attribution 2.5 license
UiObject
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.
boolean
clickAndWaitForNewWindow()
Waits for window transitions that would typically take longer than the usual
default timeouts.
boolean
clickBottomRight()
Clicks the bottom and right corner of the UI element
boolean
clickTopLeft()
Clicks the top and left corner of the UI element
boolean
dragTo(UiObject destObj, int steps)
Drags this object to a destination UiObject.
boolean
dragTo(int destX, int destY, int steps)
Drags this object to arbitrary coordinates.
boolean
exists()
Check if view exists.
Rect
getBounds()
Returns the view's bounds property.
UiObject getChild(UiSelector selector)
Creates a new UiObject for a child view that is under the present UiObject.
int
getChildCount()
Counts the child views immediately under the present UiObject.
460
Content from developer.android.com/tools/help/uiautomator/UiObject.html through their Creative Commons Attribution 2.5 license
UiObject
String
getClassName()
Retrieves the className property of the UI element.
String
getContentDescription()
Reads the content_desc property of the UI element
UiObject getFromParent(UiSelector selector)
Creates a new UiObject for a sibling view or a child of the sibling view, relative to
the present UiObject.
String
getPackageName()
Reads the view's package property
final
getSelector()
UiSelector
Debugging helper.
String
getText()
Reads the text property of the UI element
Rect
getVisibleBounds()
Returns the visible bounds of the view.
boolean
isCheckable()
Checks if the UI element's checkable property is currently true.
boolean
isChecked()
Check if the UI element's checked property is currently true
boolean
isClickable()
Checks if the UI element's clickable property is currently true.
461
Content from developer.android.com/tools/help/uiautomator/UiObject.html through their Creative Commons Attribution 2.5 license
UiObject
boolean
isEnabled()
Checks if the UI element's enabled property is currently true.
boolean
isFocusable()
Check if the UI element's focusable property is currently true.
boolean
isFocused()
Check if the UI element's focused property is currently true
boolean
isLongClickable()
Check if the view's long-clickable property is currently true
boolean
isScrollable()
Check if the view's scrollable property is currently true
boolean
isSelected()
Checks if the UI element's selected property is currently true.
boolean
longClick()
Long clicks the center of the visible bounds of the UI element
boolean
longClickBottomRight()
Long clicks bottom and right corner of the UI element
boolean
longClickTopLeft()
Long clicks on the top and left corner of the UI element
boolean
performMultiPointerGesture(PointerCoords... touches)
Performs a multi-touch gesture.
boolean
performTwoPointerGesture(Point startPoint1, Point startPoint2, Point endPoint1,
462
Content from developer.android.com/tools/help/uiautomator/UiObject.html through their Creative Commons Attribution 2.5 license
UiObject
Point endPoint2, int steps)
Generates a two-pointer gesture with arbitrary starting and ending points.
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 .
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.
boolean
setText(String text)
Sets the text in an editable field, after clearing the field's content.
boolean
swipeDown(int steps)
Performs the swipe down action on the UiObject.
boolean
swipeLeft(int steps)
Performs the swipe left action on the UiObject.
boolean
swipeRight(int steps)
Performs the swipe right action on the UiObject.
boolean
swipeUp(int steps)
Performs the swipe up action on the UiObject.
boolean
waitForExists(long timeout)
Waits a specified length of time for a view to become visible.
boolean
waitUntilGone(long timeout)
Waits a specified length of time for a view to become undetectable.
463
Content from developer.android.com/tools/help/uiautomator/UiObject.html through their Creative Commons Attribution 2.5 license
UiObject
Protected Methods
AccessibilityNodeInfo findAccessibilityNodeInfo(long timeout)
Finds a matching UI element in the accessibility hierarchy, by using
the selector for this UiObject.
[Expand]
Inherited Methods
From class java.lang.Object
Object
clone()
boolean equals(Object arg0)
void
finalize()
final
getClass()
Class<?>
int
hashCode()
final void notify()
final void notifyAll()
String
toString()
final void wait()
final void wait(long arg0, int arg1)
final void wait(long arg0)
Constants
protected static final int FINGER_TOUCH_HALF_WIDTH
464
Content from developer.android.com/tools/help/uiautomator/UiObject.html through their Creative Commons Attribution 2.5 license
UiObject
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
465
Content from developer.android.com/tools/help/uiautomator/UiObject.html through their Creative Commons Attribution 2.5 license
UiObject
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 ()
466
Content from developer.android.com/tools/help/uiautomator/UiObject.html through their Creative Commons Attribution 2.5 license
UiObject
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.
467
Content from developer.android.com/tools/help/uiautomator/UiObject.html through their Creative Commons Attribution 2.5 license
UiObject
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
468
Content from developer.android.com/tools/help/uiautomator/UiObject.html through their Creative Commons Attribution 2.5 license
UiObject
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
469
Content from developer.android.com/tools/help/uiautomator/UiObject.html through their Creative Commons Attribution 2.5 license
UiObject
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"
470
Content from developer.android.com/tools/help/uiautomator/UiObject.html through their Creative Commons Attribution 2.5 license
UiObject
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
471
Content from developer.android.com/tools/help/uiautomator/UiObject.html through their Creative Commons Attribution 2.5 license
UiObject
•
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
472
Content from developer.android.com/tools/help/uiautomator/UiObject.html through their Creative Commons Attribution 2.5 license
UiObject
•
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
473
Content from developer.android.com/tools/help/uiautomator/UiObject.html through their Creative Commons Attribution 2.5 license
UiObject
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
474
Content from developer.android.com/tools/help/uiautomator/UiObject.html through their Creative Commons Attribution 2.5 license
UiObject
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
475
Content from developer.android.com/tools/help/uiautomator/UiObject.html through their Creative Commons Attribution 2.5 license
UiObject
Returns
•
true if operation was successful
Throws
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
touches represents the pointers' paths. Each MotionEvent.PointerCoords array
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
476
Content from developer.android.com/tools/help/uiautomator/UiObject.html through their Creative Commons Attribution 2.5 license
UiObject
•
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
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.
477
Content from developer.android.com/tools/help/uiautomator/UiObject.html through their Creative Commons Attribution 2.5 license
UiObject
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
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
•
Throws
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
478
Content from developer.android.com/tools/help/uiautomator/UiObject.html through their Creative Commons Attribution 2.5 license
UiObject
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
479
Content from developer.android.com/tools/help/uiautomator/UiObject.html through their Creative Commons Attribution 2.5 license
UiObject
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
480
Content from developer.android.com/tools/help/uiautomator/UiObject.html through their Creative Commons Attribution 2.5 license
UiObject
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
481
Content from developer.android.com/tools/help/uiautomator/UiObject.html through their Creative Commons Attribution 2.5 license
UiObject
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
482
Content from developer.android.com/tools/help/uiautomator/UiObject.html through their Creative Commons Attribution 2.5 license
UiObjectNotFoundException
90.
UiObjectNotFoundException
Content from developer.android.com/tools/help/uiautomator/UiObjectNotFoundException.html through their Creative Commons Attribution 2.5 license
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
synchronized
Throwable
fillInStackTrace()
Throwable
getCause()
String
getLocalizedMessage()
String
getMessage()
StackTraceElement[] getStackTrace()
synchronized
Throwable
initCause(Throwable arg0)
void
printStackTrace(PrintWriter arg0)
void
printStackTrace(PrintStream arg0)
void
printStackTrace()
483
Content from developer.android.com/tools/help/uiautomator/UiObjectNotFoundException.html through their Creative Commons Attribution 2.5 license
UiObjectNotFoundException
void
setStackTrace(StackTraceElement[] arg0)
String
toString()
From class java.lang.Object
boolean equals(Object arg0)
final
getClass()
Class<?>
int
hashCode()
final void notify()
final void notifyAll()
String
toString()
final void wait()
final void wait(long arg0, int arg1)
final void wait(long arg0)
Public Constructors
public UiObjectNotFoundException (String msg)
public UiObjectNotFoundException (String detailMessage, Throwable
throwable)
public UiObjectNotFoundException (Throwable throwable)
484
Content from developer.android.com/tools/help/uiautomator/UiObjectNotFoundException.html through their Creative Commons Attribution 2.5 license
UiScrollable
91. UiScrollable
Content from developer.android.com/tools/help/uiautomator/UiScrollable.html through their Creative Commons Attribution 2.5 license
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
int
FINGER_TOUCH_HALF_WIDTH
int
SWIPE_MARGIN_LIMIT
long WAIT_FOR_EVENT_TMEOUT
This constant is deprecated. use
setScrollAcknowledgmentTimeout(long)
long WAIT_FOR_SELECTOR_POLL
long WAIT_FOR_SELECTOR_TIMEOUT This constant is deprecated. use
setWaitForSelectorTimeout(long)
long WAIT_FOR_WINDOW_TMEOUT
Public Constructors
UiScrollable(UiSelector container)
Constructor.
Public Methods
boolean
flingBackward()
Performs a backwards fling action with the default number of fling steps (5).
boolean
flingForward()
485
Content from developer.android.com/tools/help/uiautomator/UiScrollable.html through their Creative Commons Attribution 2.5 license
UiScrollable
Performs a forward fling with the default number of fling steps (5).
boolean
flingToBeginning(int maxSwipes)
Performs a fling gesture to reach the beginning of a scrollable layout element.
boolean
flingToEnd(int maxSwipes)
Performs a fling gesture to reach the end of a scrollable layout element.
UiObject
getChildByDescription(UiSelector childPattern, String text, 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.
UiObject
getChildByInstance(UiSelector childPattern, int instance)
Searches for a child element in the present scrollable container that matches
the selector you provided.
UiObject
getChildByText(UiSelector childPattern, String text, boolean 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.
int
getMaxSearchSwipes()
Gets the maximum number of scrolls allowed when performing a scroll action
in search of a child element.
double
getSwipeDeadZonePercentage()
Returns the percentage of a widget's size that's considered as a no-touch zone
when swiping.
486
Content from developer.android.com/tools/help/uiautomator/UiScrollable.html through their Creative Commons Attribution 2.5 license
UiScrollable
boolean
scrollBackward(int steps)
Performs a backward scroll.
boolean
scrollBackward()
Performs a backward scroll with the default number of scroll steps (55).
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.
boolean
scrollForward()
Performs a forward scroll with the default number of scroll steps (55).
boolean
scrollForward(int steps)
Performs a forward scroll.
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.
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.
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.
boolean
scrollToBeginning(int maxSwipes)
Scrolls to the beginning of a scrollable layout element.
boolean
scrollToBeginning(int maxSwipes, int steps)
487
Content from developer.android.com/tools/help/uiautomator/UiScrollable.html through their Creative Commons Attribution 2.5 license
UiScrollable
Scrolls to the beginning of a scrollable layout element.
boolean
scrollToEnd(int maxSwipes, int steps)
Scrolls to the end of a scrollable layout element.
boolean
scrollToEnd(int maxSwipes)
Scrolls to the end of a scrollable layout element.
UiScrollable setAsHorizontalList()
Set the direction of swipes to be horizontal when performing scroll actions.
UiScrollable setAsVerticalList()
Set the direction of swipes to be vertical when performing scroll actions.
UiScrollable setMaxSearchSwipes(int swipes)
Sets the maximum number of scrolls allowed when performing a scroll action in
search of a child element.
UiScrollable setSwipeDeadZonePercentage(double swipeDeadZonePercentage)
Sets the percentage of a widget's size that's considered as no-touch zone
when swiping.
Protected Methods
boolean exists(UiSelector selector)
Used privately when performing swipe searches to decide if an element has
become visible or not.
[Expand]
Inherited Methods
From class com.android.uiautomator.core.UiCollection
UiObject getChildByDescription(UiSelector childPattern, String text)
488
Content from developer.android.com/tools/help/uiautomator/UiScrollable.html through their Creative Commons Attribution 2.5 license
UiScrollable
Searches for child UI element within the constraints of this UiCollection
UiSelector selector.
UiObject getChildByInstance(UiSelector childPattern, int instance)
Searches for child UI element within the constraints of this UiCollection
UiSelector selector.
UiObject getChildByText(UiSelector childPattern, String text)
Searches for child UI element within the constraints of this UiCollection
UiSelector selector.
int
getChildCount(UiSelector childPattern)
Counts child UI element instances matching the childPattern
argument.
From class com.android.uiautomator.core.UiObject
void
clearTextField()
Clears the existing text contents in an editable field.
boolean
click()
Performs a click at the center of the visible bounds of the UI
element represented by this UiObject.
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.
boolean
clickAndWaitForNewWindow()
Waits for window transitions that would typically take longer
than the usual default timeouts.
boolean
clickBottomRight()
Clicks the bottom and right corner of the UI element
489
Content from developer.android.com/tools/help/uiautomator/UiScrollable.html through their Creative Commons Attribution 2.5 license
UiScrollable
boolean
clickTopLeft()
Clicks the top and left corner of the UI element
boolean
dragTo(UiObject destObj, int steps)
Drags this object to a destination UiObject.
boolean
dragTo(int destX, int destY, int steps)
Drags this object to arbitrary coordinates.
boolean
exists()
Check if view exists.
AccessibilityNodeInfo findAccessibilityNodeInfo(long timeout)
Finds a matching UI element in the accessibility hierarchy, by
using the selector for this UiObject.
Rect
getBounds()
Returns the view's bounds property.
UiObject
getChild(UiSelector selector)
Creates a new UiObject for a child view that is under the
present UiObject.
int
getChildCount()
Counts the child views immediately under the present UiObject.
String
getClassName()
Retrieves the className property of the UI element.
String
getContentDescription()
Reads the content_desc property of the UI element
490
Content from developer.android.com/tools/help/uiautomator/UiScrollable.html through their Creative Commons Attribution 2.5 license
UiScrollable
UiObject
getFromParent(UiSelector selector)
Creates a new UiObject for a sibling view or a child of the
sibling view, relative to the present UiObject.
String
getPackageName()
Reads the view's package property
final UiSelector
getSelector()
Debugging helper.
String
getText()
Reads the text property of the UI element
Rect
getVisibleBounds()
Returns the visible bounds of the view.
boolean
isCheckable()
Checks if the UI element's checkable property is currently
true.
boolean
isChecked()
Check if the UI element's checked property is currently true
boolean
isClickable()
Checks if the UI element's clickable property is currently
true.
boolean
isEnabled()
Checks if the UI element's enabled property is currently true.
boolean
isFocusable()
Check if the UI element's focusable property is currently
491
Content from developer.android.com/tools/help/uiautomator/UiScrollable.html through their Creative Commons Attribution 2.5 license
UiScrollable
true.
boolean
isFocused()
Check if the UI element's focused property is currently true
boolean
isLongClickable()
Check if the view's long-clickable property is currently
true
boolean
isScrollable()
Check if the view's scrollable property is currently true
boolean
isSelected()
Checks if the UI element's selected property is currently
true.
boolean
longClick()
Long clicks the center of the visible bounds of the UI element
boolean
longClickBottomRight()
Long clicks bottom and right corner of the UI element
boolean
longClickTopLeft()
Long clicks on the top and left corner of the UI element
boolean
performMultiPointerGesture(PointerCoords... touches)
Performs a multi-touch gesture.
boolean
performTwoPointerGesture(Point startPoint1, Point startPoint2,
Point endPoint1, Point endPoint2, int steps)
Generates a two-pointer gesture with arbitrary starting and
ending points.
492
Content from developer.android.com/tools/help/uiautomator/UiScrollable.html through their Creative Commons Attribution 2.5 license
UiScrollable
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 .
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.
boolean
setText(String text)
Sets the text in an editable field, after clearing the field's
content.
boolean
swipeDown(int steps)
Performs the swipe down action on the UiObject.
boolean
swipeLeft(int steps)
Performs the swipe left action on the UiObject.
boolean
swipeRight(int steps)
Performs the swipe right action on the UiObject.
boolean
swipeUp(int steps)
Performs the swipe up action on the UiObject.
boolean
waitForExists(long timeout)
Waits a specified length of time for a view to become visible.
boolean
waitUntilGone(long timeout)
Waits a specified length of time for a view to become
undetectable.
From class java.lang.Object
493
Content from developer.android.com/tools/help/uiautomator/UiScrollable.html through their Creative Commons Attribution 2.5 license
UiScrollable
Object
clone()
boolean equals(Object arg0)
void
finalize()
final
getClass()
Class<?>
int
hashCode()
final void notify()
final void notifyAll()
String
toString()
final void wait()
final void wait(long arg0, int arg1)
final void wait(long arg0)
Public Constructors
public UiScrollable (UiSelector container)
Constructor.
Parameters
container
a UiSelector selector to identify the scrollable layout element.
Public Methods
public boolean flingBackward ()
494
Content from developer.android.com/tools/help/uiautomator/UiScrollable.html through their Creative Commons Attribution 2.5 license
UiScrollable
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 rightto-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-toleft 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
495
Content from developer.android.com/tools/help/uiautomator/UiScrollable.html through their Creative Commons Attribution 2.5 license
UiScrollable
public boolean flingToEnd (int maxSwipes)
Performs a fling gesture to reach the end of a scrollable layout element. The end can be at the bottommost 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)
allowScrollSearch set to true if scrolling is allowed
Returns
•
UiObject representing the child element that matches the search conditions
Throws
UiObjectNotFoundException
496
Content from developer.android.com/tools/help/uiautomator/UiScrollable.html through their Creative Commons Attribution 2.5 license
UiScrollable
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
childPattern UiSelector for a child in a scollable layout element
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
childPattern
UiSelector for a child in a scollable layout element
instance
int number representing the occurance of a childPattern match
Returns
•
UiObject representing the child element that matches the search conditions
Throws
497
Content from developer.android.com/tools/help/uiautomator/UiScrollable.html through their Creative Commons Attribution 2.5 license
UiScrollable
UiObjectNotFoundException
public UiObject getChildByText (UiSelector childPattern, String text,
boolean allowScrollSearch)
Searches for a child element in the present scrollable container. The search first looks for a child element
that matches the selector you provided, then looks for the text in its children elements. If both search
conditions are fulfilled, the method returns a {@ link UiObject} representing the element matching the
selector (not the child element in its subhierarchy containing the text).
Parameters
childPattern
UiSelector selector for a child in a scrollable layout element
text
String to find in the children of the childPattern match
allowScrollSearch
set to true if scrolling is allowed
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
498
Content from developer.android.com/tools/help/uiautomator/UiScrollable.html through their Creative Commons Attribution 2.5 license
UiScrollable
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 notouch 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 right-to-left languages like Arabic and Hebrew.
Parameters
steps
number of steps. Use this to control the speed of the scroll action.
499
Content from developer.android.com/tools/help/uiautomator/UiScrollable.html through their Creative Commons Attribution 2.5 license
UiScrollable
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
text content-description to find within the contents of this scrollable layout element.
Returns
•
true if item is found; else, false
Throws
UiObjectNotFoundException
500
Content from developer.android.com/tools/help/uiautomator/UiScrollable.html through their Creative Commons Attribution 2.5 license
UiScrollable
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 right-to-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
501
Content from developer.android.com/tools/help/uiautomator/UiScrollable.html through their Creative Commons Attribution 2.5 license
UiScrollable
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
UiObject
obj
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
502
Content from developer.android.com/tools/help/uiautomator/UiScrollable.html through their Creative Commons Attribution 2.5 license
UiScrollable
•
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)
503
Content from developer.android.com/tools/help/uiautomator/UiScrollable.html through their Creative Commons Attribution 2.5 license
UiScrollable
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 ()
504
Content from developer.android.com/tools/help/uiautomator/UiScrollable.html through their Creative Commons Attribution 2.5 license
UiScrollable
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.
505
Content from developer.android.com/tools/help/uiautomator/UiScrollable.html through their Creative Commons Attribution 2.5 license
UiScrollable
Returns
•
true if found else false
506
Content from developer.android.com/tools/help/uiautomator/UiScrollable.html through their Creative Commons Attribution 2.5 license
UiSelector
92.
UiSelector
Content from developer.android.com/tools/help/uiautomator/UiSelector.html through their Creative Commons Attribution 2.5 license
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
UiSelector checkable(boolean val)
Set the search criteria to match widgets that are checkable.
UiSelector checked(boolean val)
Set the search criteria to match widgets that are currently checked (usually for
checkboxes).
UiSelector childSelector(UiSelector selector)
Adds a child UiSelector criteria to this selector.
UiSelector className(String className)
Set the search criteria to match the class property for a widget (for example,
"android.widget.Button").
<T>
className(Class<T> type)
UiSelector
Set the search criteria to match the class property for a widget (for example,
"android.widget.Button").
UiSelector classNameMatches(String regex)
Set the search criteria to match the class property for a widget, using a regular
expression.
UiSelector clickable(boolean val)
507
Content from developer.android.com/tools/help/uiautomator/UiSelector.html through their Creative Commons Attribution 2.5 license
UiSelector
Set the search criteria to match widgets that are clickable.
UiSelector description(String desc)
Set the search criteria to match the content-description property for a widget.
UiSelector descriptionContains(String desc)
Set the search criteria to match the content-description property for a widget.
UiSelector descriptionMatches(String regex)
Set the search criteria to match the content-description property for a widget.
UiSelector descriptionStartsWith(String desc)
Set the search criteria to match the content-description property for a widget.
UiSelector enabled(boolean val)
Set the search criteria to match widgets that are enabled.
UiSelector focusable(boolean val)
Set the search criteria to match widgets that are focusable.
UiSelector focused(boolean val)
Set the search criteria to match widgets that have focus.
UiSelector fromParent(UiSelector selector)
Adds a child UiSelector criteria to this selector which is used to start search from
the parent widget.
UiSelector index(int index)
Set the search criteria to match the widget by its node index in the layout
hierarchy.
UiSelector instance(int instance)
508
Content from developer.android.com/tools/help/uiautomator/UiSelector.html through their Creative Commons Attribution 2.5 license
UiSelector
Set the search criteria to match the widget by its instance number.
UiSelector longClickable(boolean val)
Set the search criteria to match widgets that are long-clickable.
UiSelector packageName(String name)
Set the search criteria to match the package name of the application that
contains the widget.
UiSelector packageNameMatches(String regex)
Set the search criteria to match the package name of the application that
contains the widget.
UiSelector resourceId(String id)
Set the search criteria to match the given resource ID.
UiSelector resourceIdMatches(String regex)
Set the search criteria to match the resource ID of the widget, using a regular
expression.http://blog.bettersoftwaretesting.com/
UiSelector scrollable(boolean val)
Set the search criteria to match widgets that are scrollable.
UiSelector selected(boolean val)
Set the search criteria to match widgets that are currently selected.
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).
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.
509
Content from developer.android.com/tools/help/uiautomator/UiSelector.html through their Creative Commons Attribution 2.5 license
UiSelector
UiSelector textMatches(String regex)
Set the search criteria to match the visible text displayed in a layout element,
using a regular expression.
UiSelector textStartsWith(String text)
Set the search criteria to match visible text in a widget that is prefixed by the text
parameter.
String
toString()
Protected Methods
UiSelector cloneSelector()
[Expand]
Inherited Methods
From class java.lang.Object
Object
clone()
boolean equals(Object arg0)
void
finalize()
final
getClass()
Class<?>
int
hashCode()
final void notify()
final void notifyAll()
String
toString()
510
Content from developer.android.com/tools/help/uiautomator/UiSelector.html through their Creative Commons Attribution 2.5 license
UiSelector
final void wait()
final void wait(long arg0, int arg1)
final void wait(long arg0)
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, 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
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
511
Content from developer.android.com/tools/help/uiautomator/UiSelector.html through their Creative Commons Attribution 2.5 license
UiSelector
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
512
Content from developer.android.com/tools/help/uiautomator/UiSelector.html through their Creative Commons Attribution 2.5 license
UiSelector
•
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, 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 description (String desc)
Set the search criteria to match the content-description property for a widget. The content-description is
typically used by the Android Accessibility framework to provide an audio prompt for the widget when the
widget is selected. The content-description for the widget must match exactly with the string in your input
argument. Matching is case-sensitive.
Parameters
513
Content from developer.android.com/tools/help/uiautomator/UiSelector.html through their Creative Commons Attribution 2.5 license
UiSelector
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 content-description is
typically used by the Android Accessibility framework to provide an audio prompt for the widget when the
widget is selected. The content-description for the widget must contain the string in your input argument.
Matching is case-insensitive.
Parameters
desc
Value to match
Returns
•
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 content-description is
typically used by the Android Accessibility framework to provide an audio prompt for the widget when the
widget is selected. The content-description for the widget must match exactly with the string in your input
argument.
Parameters
regex
a regular expression
Returns
•
UiSelector with the specified search criteria
Since
•
Android API Level 17
public UiSelector descriptionStartsWith (String desc)
514
Content from developer.android.com/tools/help/uiautomator/UiSelector.html through their Creative Commons Attribution 2.5 license
UiSelector
Set the search criteria to match the content-description property for a widget. The content-description is
typically used by the Android Accessibility framework to provide an audio prompt for the widget when the
widget is selected. The content-description for the widget must start with the string in your input argument.
Matching is case-insensitive.
Parameters
desc
Value to match
Returns
•
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, 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 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, 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
515
Content from developer.android.com/tools/help/uiautomator/UiSelector.html through their Creative Commons Attribution 2.5 license
UiSelector
•
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, 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 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)
516
Content from developer.android.com/tools/help/uiautomator/UiSelector.html through their Creative Commons Attribution 2.5 license
UiSelector
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, 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
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
517
Content from developer.android.com/tools/help/uiautomator/UiSelector.html through their Creative Commons Attribution 2.5 license
UiSelector
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.http://blog.bettersoftwaretesting.com/
Parameters
518
Content from developer.android.com/tools/help/uiautomator/UiSelector.html through their Creative Commons Attribution 2.5 license
UiSelector
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, 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 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, 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 text (String text)
519
Content from developer.android.com/tools/help/uiautomator/UiSelector.html through their Creative Commons Attribution 2.5 license
UiSelector
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
520
Content from developer.android.com/tools/help/uiautomator/UiSelector.html through their Creative Commons Attribution 2.5 license
UiSelector
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
521
Content from developer.android.com/tools/help/uiautomator/UiSelector.html through their Creative Commons Attribution 2.5 license
UiWatcher
93.
UiWatcher
Content from developer.android.com/tools/help/uiautomator/UiWatcher.html through their Creative Commons Attribution 2.5 license
Represents a conditional watcher on the target device. To learn how to register a conditional watcher, see
UiDevice.registerWatcher().
Summary
Public Methods
abstract checkForCondition()
boolean
The testing framework calls this handler method automatically when the framework
is unable to find a match using the UiSelector.
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
522
Content from developer.android.com/tools/help/uiautomator/UiWatcher.html through their Creative Commons Attribution 2.5 license
zipalign
94.
zipalign
Content from developer.android.com/tools/help/zipalign.html through their Creative Commons Attribution 2.5 license
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
523
Content from developer.android.com/tools/help/zipalign.html through their Creative Commons Attribution 2.5 license
Revisions
95.
Revisions
Content from developer.android.com/tools/revisions/index.html through their Creative Commons Attribution 2.5 license
The Android SDK is composed of individual packages that may undergo an update at their own schedule,
so some have their own set of release notes. You can find information about some of the packages in this
section, including the core SDK Tools and the latest Platforms.
524
Content from developer.android.com/tools/revisions/index.html through their Creative Commons Attribution 2.5 license
SDK Tools
96.
SDK Tools
Content from developer.android.com/tools/sdk/tools-notes.html through their Creative Commons Attribution 2.5 license
SDK Tools is a downloadable component for the Android SDK. It includes the complete set of development
and debugging tools for the Android SDK.
If you are new to the Android SDK, the SDK starter package installs the latest revision of the SDK Tools in
the <sdk>/tools directory.
If you are already using the SDK and you want to update to the latest version of the SDK Tools, use the
Android SDK Manager to get the update, rather than downloading a new SDK starter package. For more
information about how to update, see Exploring the SDK.
Revisions
The sections below provide notes about successive releases of the SDK Tools, as denoted by revision
number. To determine what revision of the SDK Tools you are using, refer to the "Installed Packages"
listing in the Android SDK Manager.
For a summary of all known issues in SDK Tools, see http://tools.android.com/knownissues.
SDK Tools, Revision 22.3 (October 2013)
Dependencies:
•
•
•
Android SDK Platform-tools revision 18 or later.
If you are developing in Eclipse with ADT, note that this version of SDK Tools is
designed for use with ADT 22.3.0 and later. If you haven't already, update your ADT
Plugin to 22.3.0.
If you are developing outside Eclipse, you must have Apache Ant 1.8 or later.
General Notes:
•
•
Added support for Android 4.4 (API level 19).
Fixed a number of minor bugs in the SDK and build system.
SDK Tools, Revision 22.2.1 (September 2013)
Dependencies:
•
•
•
Android SDK Platform-tools revision 16 or later.
If you are developing in Eclipse with ADT, note that this version of SDK Tools is
designed for use with ADT 22.2.1 and later. If you haven't already, update your ADT
Plugin to 22.2.1.
If you are developing outside Eclipse, you must have Apache Ant 1.8 or later.
General Notes:
•
•
Fixed problem with templates that causes the new project wizard to hang. (Issue 60149)
Fixed crash when using the lint command line tool because of mis-matched library
dependency. (Issue 60190)
SDK Tools, Revision 22.2 (September 2013)
Dependencies:
525
Content from developer.android.com/tools/sdk/tools-notes.html through their Creative Commons Attribution 2.5 license
SDK Tools
•
•
•
Android SDK Platform-tools revision 16 or later.
If you are developing in Eclipse with ADT, note that this version of SDK Tools is
designed for use with ADT 22.2 and later. If you haven't already, update your ADT
Plugin to 22.2.
If you are developing outside Eclipse, you must have Apache Ant 1.8 or later.
General Notes:
•
•
•
•
•
Updated build tools to allow use of RenderScript on older versions of Android using new
features in the Support Library.
Moved the Systrace tool to the >sdk</platform-tools/ directory.
Modified Tracer for OpenGL ES to support OpenGL ES 3.0.
Lint
o Fixed problem with lint not detecting custom namespaces. (Issue 55673)
o Fixed problem with the XML report including invalid characters. (Issue 56205)
o Fixed command-line execution of lint to work in headless mode to support
execution by build servers. (Issue 55820)
Improved support for path names with spaces in the Windows command-line tools.
SDK Tools, Revision 22.0.5 (July 2013)
Dependencies:
•
•
•
•
Android SDK Platform-tools revision 16 or later.
If you are developing in Eclipse with the ADT Plugin, note that this version of SDK Tools
is designed for use with ADT 22.0.5 and later. If you haven't already, update ADT to
22.0.5.
If you are using Android Studio, note that this version of the SDK Tools is designed to
work with Android Studio 0.2.x and later.
If you are developing without an integrated development environment (IDE), you must
have Apache Ant 1.8 or later.
General Notes:
•
•
•
•
Fixed RenderScript compilation issue for Windows platforms with ant.
Updated Systrace to work with the Android 4.3 platform image.
Fixed packaging of RenderScript compiler.
Build tools 18.0.0 is obsolete and 18.0.1 should be used instead.
SDK Tools, Revision 22.0.4 (July 2013)
Dependencies:
•
•
•
Android SDK Platform-tools revision 16 or later.
If you are developing in Eclipse with the ADT Plugin, note that this version of SDK Tools
is designed for use with ADT 22.0.4 and later. If you haven't already, update ADT to
22.0.4.
If you are using Android Studio, note that this version of the SDK Tools is designed to
work with Android Studio 0.2.x and later.
526
Content from developer.android.com/tools/sdk/tools-notes.html through their Creative Commons Attribution 2.5 license
SDK Tools
•
If you are developing without an integrated development environment (IDE), you must
have Apache Ant 1.8 or later.
General Notes:
•
Fixed problem with compiling RenderScript code.
SDK Tools, Revision 22.0.1 (May 2013)
Dependencies:
•
•
•
Android SDK Platform-tools revision 16 or later.
If you are developing in Eclipse with ADT, note that this version of SDK Tools is
designed for use with ADT 22.0.1 and later. If you haven't already, update your ADT
Plugin to 22.0.1.
If you are developing outside Eclipse, you must have Apache Ant 1.8 or later.
General Notes:
•
•
•
•
Fixed issue with Lint ServiceCast check and fully qualified class names. (Issue 55403)
Fixed crash issue with Lint ArraySizeDetector check. (Issue 54887)
Fixed a problem with the monkeyrunner tool failing to import standard python classes.
(Issue 55632)
Fixed a problem with DDMS monitor not opening heap and network statistics views due
to a class not found exception. (Issue 55394)
SDK Tools, Revision 22 (May 2013)
Dependencies:
•
•
•
Android SDK Platform-tools revision 16 or later.
If you are developing in Eclipse with ADT, note that this version of SDK Tools is
designed for use with ADT 22.0.0 and later. If you haven't already, update your ADT
Plugin to 22.0.0.
If you are developing outside Eclipse, you must have Apache Ant 1.8 or later.
General Notes:
•
•
•
•
Changed the structure of the SDK by adding a new build tool SDK Component, which is
based on the existing platform-tools component. This change decouples the build tools
versions from the IDE versions, allowing updates to the tools without requiring an IDE
update.
Updated tools to allow libraries to share the same package name as the applications
that use them.
Updated draw9patch tool to allow easier changing of markers.
Added new Lint checks, including checks for layout consistency, RelativeLayout
siblings, Parcel creator, JavaScript interfaces, Service casting, quantity strings,
manifest typos, orientation tags in layouts, overlapping names for 9-patches and images,
and class existence checks.
527
Content from developer.android.com/tools/sdk/tools-notes.html through their Creative Commons Attribution 2.5 license
SDK Tools
•
•
Updated build tools to sign applications using the BouncyCastle library instead of relying
on Sun JVM specific APIs.
Released some of the Android tools into Maven Central to assist third-party tool
developers. The following tools are available in the repository: manifest-merger,
common/sdk_common, ddmlib, dvlib, layoutlib_api, sdklib, and
lint.
Bug fixes:
•
Fixed a number of minor bugs in the SDK and build system.
SDK Tools, Revision 21.1 (February 2013)
Dependencies:
•
•
•
Android SDK Platform-tools revision 16 or later.
If you are developing in Eclipse with ADT, note that this version of SDK Tools is
designed for use with ADT 21.1.0 and later. If you haven't already, update your ADT
Plugin to 21.1.0.
If you are developing outside Eclipse, you must have Apache Ant 1.8 or later.
General Notes:
•
•
•
Improved error reporting in dx when dex merging fails in the build system.
Added more than 15 new Lint checks, including checks for overriding older APIs, XML
resource problems, graphic asset issues and manifest tags.
Added new aapt feature to compile resources.
SDK Tools, Revision 21.0.1 (December 2012)
Dependencies:
•
•
•
Android SDK Platform-tools revision 16 or later.
If you are developing in Eclipse with ADT, note that this version of SDK Tools is
designed for use with ADT 21.0.1 and later. If you haven't already, update your ADT
Plugin to 21.0.1.
If you are developing outside Eclipse, you must have Apache Ant 1.8 or later.
General Notes:
•
Build
o
o
Updated build to detect and handle package name conflicts between an
application and the libraries it depends on. Libraries cannot share package
names unless all of them share the same package name. (Issue 40152, Issue
40273)
Added a flag to disable dex merging to deal with cases where merging could
generate a broken dex file. If this happens to your project, add the following
setting to your project.properties file:
dex.disable.merger=true This setting causes the build system to
revert to the older, slower dex processing that does not pre-dex libraries.
528
Content from developer.android.com/tools/sdk/tools-notes.html through their Creative Commons Attribution 2.5 license
SDK Tools
•
RenderScript
o Added support for Filterscript compilation.
o Added new project setting to control the RenderScript compilation target
separately from an Android project. Adding the following line to a
project.properties file causes RenderScript code to be compiled for
Android API Level 17, while the containing application can target a different
(lower) API level:
renderscript.target = 17
Previously, the RenderScript compilation target was tied to the android:minSdkVersion setting in
the manifest. (Issue 40487)
Bug fixes:
•
•
•
•
•
Lint
Corrected check for 0px values in style XML elements. (Issue 39601)
Fixed incorrect flagging of formatting strings. (Issue 39758)
Fixed problem where tools:ignore directive in the manifest file was
ignored by the Lint tool. (Issue 40136)
o Fixed problem with flagging a wakelock release inside a conditional. (Issue
40424)
o Fixed incorrect reporting of missing layout_width and layout_height
XML fields. (Issue 38958)
o Fixed handling of custom namespace attributes.
o Added fixes for filtering out library project warnings.
o Removed warnings about missing classes before a build.
Fixed problem with UI Automator Viewer execution script where Android tools directory
is not set.
Fixed problem with the SDK Manager so that it auto-selects the most recently released
platform on startup.
Fixed Java finding script to look for the currently supported version of Java (1.6 or
higher).
Fixed the SDK Manager launcher in the ADT bundle so that it can properly launch the
SDK Manager program when it is placed at the root of the bundle.
o
o
o
SDK Tools, Revision 21 (November 2012)
Dependencies:
•
•
•
Android SDK Platform-tools revision 16 or later.
If you are developing in Eclipse with ADT, note that this version of SDK Tools is
designed for use with ADT 21.0.0 and later. If you haven't already, update your ADT
Plugin to 21.0.0.
If you are developing outside Eclipse, you must have Apache Ant 1.8 or later.
General Notes:
•
Build System
529
Content from developer.android.com/tools/sdk/tools-notes.html through their Creative Commons Attribution 2.5 license
SDK Tools
o
Added a flag that sets jumbo mode for DEX files, which allows a larger number
of strings in the DEX files. Enable this mode by adding the following line to the
project.properties file of your project:
set dex.force.jumbo=true
•
•
•
•
•
•
•
Improved the build time by pre-dexing libraries (both JAR files and library projects).
Updated the build to generate R resource classes for library projects with only the IDs needed by
the libraries, reducing the risk of hitting DEX file limits for fields and methods.
Improved the build so that several editing features (code completion, resource chooser, go to
declaration) properly handle library project resources.
Lint
o
Added over 25 new lint rules for resources, locale settings, layout files, incorrect use of
SparseArray and PowerManager.WakeLock and manifest issues.
o Updated reporting to include errors in library projects if the library project is in the list of
projects to be checked.
o Added a new lint target to the Ant build system for easier integration with continuous
build systems.
o Added new --sources and --classpath arguments to point to sources with
different directory structures.
o Improved the XML export function to support the Jenkins Lint plugin.
o Added support for class file flow analysis.
Android Virtual Devices (AVD)
o Added new Device Definitions tab in the AVD Manager for configuring standard size
and Nexus virtual devices.
o Improved emulators so that they launch with a skin that is dynamically generated and
reflects the actual hardware configured in the AVD Manager.
o Improved support for developing Android apps on MIPS-based devices with new MIPS
System Images for Android Virtual Devices.
Added jobb tool for creating and encrypting APK Expansion Files. (more info)
Improved the Android JUnit test runner to allow a test to be run on all connected devices
simultaneously.
Bug fixes:
•
Fixed manifest merger to properly adapt library classes in the merged manifest.
SDK Tools, Revision 20.0.3 (August 2012)
Dependencies:
•
•
•
Android SDK Platform-tools revision 12 or later.
If you are developing in Eclipse with ADT, note that this version of SDK Tools is
designed for use with ADT 20.0.3 and later. If you haven't already, update your ADT
Plugin to 20.0.3.
If you are developing outside Eclipse, you must have Apache Ant 1.8 or later.
530
Content from developer.android.com/tools/sdk/tools-notes.html through their Creative Commons Attribution 2.5 license
SDK Tools
Bug fixes:
•
Fixed problem with cached download lists in SDK Manager.
SDK Tools, Revision 20.0.1 (July 2012)
Dependencies:
•
•
•
Android SDK Platform-tools revision 12 or later.
If you are developing in Eclipse with ADT, note that this version of SDK Tools is
designed for use with ADT 20.0.1 and later. If you haven't already, update your ADT
Plugin to 20.0.1.
If you are developing outside Eclipse, you must have Apache Ant 1.8 or later.
Bug fixes:
•
•
•
•
•
•
Fixed wrong check on build state that forced repetitive Java code recompilation.
Fixed problems with running more than one emulator and running multiple emulators
with GPU acceleration.
Improved resize algorithm for better rendering on scaled emulator windows.
Fixed a bug in the lint check for unprotected broadcast receivers to ignore
unprotected receivers for default Androi