android sdk developing

139
In this document Creating an Android Project Creating an AVD Running Your Application Running on the emulator Running on a device Creating a Custom Run Configuration Setting Up Application Signing Working with Library Projects Development requirements Setting up a library project Referencing a library project Development considerations Eclipse Tips Developing In Eclipse, with ADT The Android Development Tools (ADT) plugin for Eclipse adds powerful extensions to the Eclipse integrated development environment. It allows you to create and debug Android applications easier and faster. If you use Eclipse, the ADT plugin gives you an incredible boost in developing Android applications: It gives you access to other Android development tools from inside the Eclipse IDE. For example, ADT lets you access the many capabilities of the DDMS tool: take screenshots, manage port-forwarding, set breakpoints, and view thread and process information directly from Eclipse. It provides a New Project Wizard, which helps you quickly create and set up all of the basic files you'll need for a new Android application. It automates and simplifies the process of building your Android application. It provides an Android code editor that helps you write valid XML for your Android manifest and resource files. It will even export your project into a signed APK, which can be distributed to users. To begin developing Android applications in the Eclipse IDE with ADT, you first need to download the Eclipse IDE and then download and install the ADT plugin. To do so, follow the steps given in Installing the ADT Plugin. If you are already developing applications using a version of ADT earlier than 0.9, make sure to upgrade to the latest version before continuing. See the guide to Updating Your ADT Plugin. Note: This guide assumes you are using the latest version of the ADT plugin. While most of the information covered also applies to previous versions, if you are using an older version, you may want to consult this document from the set of documentation included in your SDK package (instead of the online version). 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. 1. Select Android > Android Project, and click Next. 2. Select the contents for the project: 3. Enter a Project Name. This will be the name of the folder where your project is created. Under Contents, select Create new project in workspace. Select your project workspace location. Under Target, select an Android target to be used as the project's Build Target. The Build Target specifies which Android platform you'd like your application built against. Page 1 of 12 Developing In Eclipse, with ADT | Android Developers 9/7/2010 file://V:\android-sdk-windows\docs\guide\developing\eclipse-adt.html

Upload: smartsm78

Post on 03-Nov-2014

74 views

Category:

Documents


4 download

TRANSCRIPT

Page 1: Android Sdk Developing

In this documentCreating an Android Project

Creating an AVD

Running Your Application

Running on the emulator

Running on a device

Creating a Custom Run Configuration

Setting Up Application Signing

Working with Library Projects

Development requirements

Setting up a library project

Referencing a library project

Development considerations

Eclipse Tips

Developing In Eclipse, with ADT

The Android Development Tools (ADT) plugin for Eclipse adds powerful extensions to the Eclipse integrated development environment. It allows you to create and debug Android applications easier and faster. If you use Eclipse, the ADT plugin gives you an incredible boost in developing Android applications:

It gives you access to other Android development tools from inside the Eclipse IDE. For example, ADT lets you access the many capabilities of the DDMS tool: take screenshots, manage port-forwarding, set breakpoints, and view thread and process information directly from Eclipse.

It provides a New Project Wizard, which helps you quickly create and set up all of the basic files you'll need for a new Android application.

It automates and simplifies the process of building your Android application.•

It provides an Android code editor that helps you write valid XML for your Android manifest and resource files.•

It will even export your project into a signed APK, which can be distributed to users.•

To begin developing Android applications in the Eclipse IDE with ADT, you first need to download the Eclipse IDE and then download and install the ADT plugin. To do so, follow the steps given in Installing the ADT Plugin.

If you are already developing applications using a version of ADT earlier than 0.9, make sure to upgrade to the latest version before continuing. See the guide to Updating Your ADT Plugin.

Note: This guide assumes you are using the latest version of the ADT plugin. While most of the information covered also applies to previous versions, if you are using an older version, you may want to consult this document from the set of documentation included in your SDK package (instead of the online version).

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

Select Android > Android Project, and click Next.2.

Select the contents for the project: 3.

Enter a Project Name. This will be the name of the folder where your project is created.◦

Under Contents, select Create new project in workspace. Select your project workspace location.◦

Under Target, select an Android target to be used as the project's Build Target. The Build Target specifies which Android platform you'd like your application built against.

Page 1 of 12Developing In Eclipse, with ADT | Android Developers

9/7/2010file://V:\android-sdk-windows\docs\guide\developing\eclipse-adt.html

Page 2: Android Sdk Developing

Unless you know that you'll be using new APIs introduced in the latest SDK, you should select a target with the lowest platform version possible.

Note: You can change your the Build Target for your project at any time: Right-click the project in the Package Explorer, select Properties, select Android and then check the desired Project Target.

Under Properties, fill in all necessary fields. ◦

Enter an Application name. This is the human-readable title for your application — the name that will appear on the Android device.

Enter a Package name. This is the package namespace (following the same rules as for packages in the Java programming language) where all your source code will reside.

Select Create Activity (optional, of course, but common) and enter a name for your main Activity class.■

Enter a Min SDK Version. This is an integer that indicates the minimum API Level required to properly run your application. Entering this here automatically sets the minSdkVersion attribute in the <uses-sdk> of your Android Manifest file. If you're unsure of the appropriate API Level to use, copy the API Level listed for the Build Target you selected in the Target tab.

Click Finish.4.

Tip: You can also start the New Project Wizard from the New icon in the toolbar.

Once you complete the New Project Wizard, ADT creates the following folders and files in your new project:

src/Includes your stub Activity Java file. All other Java files for your application go here.

<Android Version>/ (e.g., Android 1.1/)Includes the android.jar file that your application will build against. This is determined by the build target that you have chosen in the New Project Wizard.

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.xmlThe Android Manifest for your project. See The AndroidManifest.xml File.

default.propertiesThis file contains project settings, such as the build target. This files is integral to the project, as such, it should be maintained in a Source Revision Control system. It should never be edited manually — to edit project properties, right-click the project folder and select "Properties".

Creating an AVD

An Android Virtual Device (AVD) is a device configuration for the emulator that allows you to model real world devices. In order to run an instance of the emulator, you must create an AVD.

To create an AVD from Eclipse:

Page 2 of 12Developing In Eclipse, with ADT | Android Developers

9/7/2010file://V:\android-sdk-windows\docs\guide\developing\eclipse-adt.html

Page 3: Android Sdk Developing

Use the Emulator to Test Different Configurations

Create multiple AVDs that each define a different device configuration with which your application is compatible, then launch each AVD into a new emulator from the SDK and AVD Manager. Set the target mode in your app's run configuration to manual, so that when you run your application, you can select from the available virtual devices.

Select Window > Android SDK and AVD Manager, or click the Android SDK and AVD Manager icon in the Eclipse toolbar.

1.

In the Virtual Devices panel, you'll see a list of existing AVDs. Click New to create a new AVD.2.

Fill in the details for the AVD. 3.

Give it a name, a platform target, an SD card size, and a skin (HVGA is default).

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

Your AVD is now ready and you can either close the SDK and AVD Manager, create more AVDs, or launch an emulator with the AVD by selecting a device and clicking Start.

For more information about AVDs, read the Android Virtual Devices documentation.

Running Your Application

Running your application from Eclipse will usually require just a couple clicks, whether you're running it on the emulator or on an attached device. The information below describes how to get set up and run your application from Eclipse.

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 launch configuration for the project. Eclipse will then perform the following:

Compile the project (if there have been changes since the last build).1.

Create a default launch configuration (if one does not already exist for the project).2.

Install and start the application on an emulator (or device), based on the Deployment Target defined by the run configuration.

3.

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 debugging, the application will start in the "Waiting For Debugger" mode. Once the debugger is attached, Eclipse will open the Debug perspective.

To set or change the launch configuration used for your project, use the launch configuration manager. See Creating a Launch Configuration for 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 1.5 (API Level 3) platform, you should create an AVD for each platform equal to and greater than 1.5 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:

Page 3 of 12Developing In Eclipse, with ADT | Android Developers

9/7/2010file://V:\android-sdk-windows\docs\guide\developing\eclipse-adt.html

Page 4: Android Sdk Developing

Declare your application as debuggable in your manifest•

Enable USB Debugging on your device•

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

Read Setting up a Device for Development 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 launch configuration or even create a new.

To create or modify a launch configuration, follow these steps as appropriate for your Eclipse version:

Open the run configuration manager. 1.

In Eclipse 3.3 (Europa), select Run > Open Run Dialog (or Open Debug Dialog) ◦

In Eclipse 3.4 (Ganymede), select Run > Run Configurations (or Debug Configurations) ◦

Expand the Android Application item and create a new configuration or open an existing one. 2.

To create a new configuration: ◦

Select Android Application and click the New launch configuration icon above the list (or, right-click Android Application and click New).

1.

Enter a Name for your configuration.2.

In the Android tab, browse and select the project you'd like to run with the configuration.3.

To open an existing configuration, select the configuration name from the list nested below Android Application.

Adjust your desired launch configuration settings. 3.

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.

1.

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.

2.

If there are no devices or emulators running that meet the requirements of the build target, ADT looks at the available AVDs. If one meets the requirements of the build target, the AVD is used to launch a new emulator, upon which the application is installed and run.

3.

Page 4 of 12Developing In Eclipse, with ADT | Android Developers

9/7/2010file://V:\android-sdk-windows\docs\guide\developing\eclipse-adt.html

Page 5: Android Sdk Developing

Library project example code

The SDK includes an example application called TicTacToeMain that shows how a dependent application can use code and resources from an Android Library 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 and AVD Manager to download the "Samples for SDK API 8" component into your SDK.

For more information and to browse the code of the samples, see the TicTacToeMain application.

If all else fails, the application will not be run and you will see a console error warning you that there is no existing AVD that meets the build target requirements.

4.

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.

Signing your Applications

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 an actual device. There are two ways to do this: with a debug key (for immediate testing on an emulator or development device) or with a private key (for application distribution).

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

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

If you have source code and resources that are common to multiple application projects, you can 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 the same types of source code

Page 5 of 12Developing In Eclipse, with ADT | Android Developers

9/7/2010file://V:\android-sdk-windows\docs\guide\developing\eclipse-adt.html

Page 6: Android Sdk Developing

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 an standard Android application project in that you cannot compile it directly to its own .apk or run it on the Android platform. 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 from a dependent application's build path, then building that application.

When you build an application that depends on a library project, the SDK tools compile the library and merge its sources with those in the main project, then use 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.

ADT lets you add references to library projects and set their relative priority from the application project's Properties. As shown in Figure 2, below, once you've added a reference to a library project, you can use the Up and Down controls to change the ordering, with the library listed at the top getting the higher priority. 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 project cannot itself reference another library project and that, at build time, library projects are not merged with each other before being merged with the application. However, note that a library can import an external library (JAR) in the normal way.

The sections below describe how to use ADT to set up and manage library your projects. Once you've set up your library projects and moved code into them, you can import library classes and resources to your application in the normal way.

Development requirements

Android library projects are a build-time construct, so you can use them to build a final application .apk that targets any API level and is compiled against any version of the Android library.

However, to use library projects, you need to update your development environment to use the latest tools and platforms, since older releases of the tools and platforms do not support building with library projects. Specifically, you need to download and install the versions listed below:

Table 1. Minimum versions of SDK tools and plaforms on which you can develop library projects.

Component Minimum Version

SDK Tools r6 (or higher)

Android 2.2 platform r1 (or higher)

Android 2.1 platform r2 (or higher)

Android 2.0.1 platform not supported

Android 2.0 platform not supported

Android 1.6 platform r3 (or higher)

Android 1.5 platform r4 (or higher)

ADT Plugin 0.9.7 (or higher)

Page 6 of 12Developing In Eclipse, with ADT | Android Developers

9/7/2010file://V:\android-sdk-windows\docs\guide\developing\eclipse-adt.html

Page 7: Android Sdk Developing

You can download the tools and platforms using the Android SDK and AVD Manager, as described in Adding SDK Components. To install or update ADT, use the Eclipse Updater as described in ADT Plugin for Eclipse.

Setting up a library project

A library project is a standard Android project, so you can create a new one in the same way as you would a new application project. Specifically, you can use the New Project Wizard, as described in Creating an Android Project, above.

When you are creating the library project, you can select any application name, package, and set other fields as needed, as shown in the diagram below. Click Finish to create the project in the workspace.

Next, set the project's Properties to indicate that it is a library project:

In the Package Explorer, right-click the library project and select Properties.1.

In the Properties window, select the "Android" properties group at left and locate the Library properties at right. 2.

Select the "is Library" checkbox and click Apply.3.

Click OK to close the Properties window.4.

The new project is now marked as a library project. You can begin moving source code and resources into it, as described in the sections below.

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. Other application projects can now reference the existing project as a library project.

Figure 1. Marking a project as an Android library project.

Page 7 of 12Developing In Eclipse, with ADT | Android Developers

9/7/2010file://V:\android-sdk-windows\docs\guide\developing\eclipse-adt.html

Page 8: Android Sdk Developing

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 from an application

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:

In the Package Explorer, right-click the dependent project and select Properties.1.

In the Properties window, select the "Android" properties group at left and locate the Library properties at right.2.

Click Add to open the Project Selection dialog. 3.

From the list of available library projects, select a project and click OK.4.

When the dialog closes, click Apply in the Properties window.5.

Click OK to close the Properties window.6.

As soon as the Properties dialog closes, Eclipse rebuilds the project, including the contents of the library project.

The figure below shows the Properties dialog that lets you add library references and move them up and down in priority.

Page 8 of 12Developing In Eclipse, with ADT | Android Developers

9/7/2010file://V:\android-sdk-windows\docs\guide\developing\eclipse-adt.html

Page 9: Android Sdk Developing

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

Page 9 of 12Developing In Eclipse, with ADT | Android Developers

9/7/2010file://V:\android-sdk-windows\docs\guide\developing\eclipse-adt.html

Page 10: Android Sdk Developing

... </manifest>

For more information about the manifest file, see the documentation for AndroidManifest.xml.

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 highest-priority library taking precedence.

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

No export of library project to JAR

A library cannot be distributed as a binary file (such as a jar file). This is because the library project is compiled by the main project to use the correct resource IDs.

One library project cannot reference another

A library cannot depend on another library.

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 their manifest files, in a <uses-library> element.

Library project can not include AIDL files

The tools do not support the use of AIDL files in a library project. Any AIDL files used by an application must be stored in the application project itself.

Library project can not include raw assets

The tools do not support the use of raw asset files in a library project. Any asset resources used by an application must be stored in the assets/ directory of the application project itself.

Targeting different Android platform versions in library project and application 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 fail to compile. It is perfectly acceptable to

Page 10 of 12Developing In Eclipse, with ADT | Android Developers

9/7/2010file://V:\android-sdk-windows\docs\guide\developing\eclipse-adt.html

Page 11: Android Sdk Developing

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 name

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

Multiple R classes in gen/ folder of application project

When you build the dependent application project, the code of any libraries is compiled and merged to the application project. Each library has its own R class, named according to the library's package name. The R class generated from the resources of the main project and of the library is created in all the packages that are needed including the main project’s package and the libraries’ packages.

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

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. You can place the library project What is important is that the main project can reference the library project through a relative link.

Eclipse Tips

Executing arbitrary Java expressions in Eclipse

You can execute arbitrary code when paused at a breakpoint in Eclipse. For example, when in a function with a String argument called "zip", you can get information about packages and call class methods. You can also invoke arbitrary static methods: for example, entering android.os.Debug.startMethodTracing() will start dmTrace.

Open a code execution window, select Window > Show View > Display from the main menu to open the Display window, a simple text editor. Type your expression, highlight the text, and click the 'J' icon (or CTRL + SHIFT + D) to run your code. The code runs in the context of the selected thread, which must be stopped at a breakpoint or single-step point. (If you suspend the thread manually, you have to single-step once; this doesn't work if the thread is in Object.wait().)

If you are currently paused on a breakpoint, you can simply highlight and execute a piece of source code by pressing CTRL + SHIFT + D.

You can highlight a block of text within the same scope by pressing ALT +SHIFT + UP ARROW to select larger and larger enclosing blocks, or DOWN ARROW to select smaller blocks.

Here are a few sample inputs and responses in Eclipse using the Display window.

Page 11 of 12Developing In Eclipse, with ADT | Android Developers

9/7/2010file://V:\android-sdk-windows\docs\guide\developing\eclipse-adt.html

Page 12: Android Sdk Developing

↑ Go to top

Input Response

zip (java.lang.String) /work/device/out/linux-x86-debug/android/app/android_sdk.zip

zip.endsWith(".zip")

(boolean) true

zip.endsWith(".jar")

(boolean) false

You can also execute arbitrary code when not debugging by using a scrapbook page. Search the Eclipse documentation for "scrapbook".

Running DDMS Manually

Although the recommended way to debug is to use the ADT plugin, you can manually run DDMS and configure Eclipse to debug on port 8700. (Note: Be sure that you have first started DDMS).

Except as noted, this content is licensed under Apache 2.0. For details and restrictions, see the Content License. Android 2.2 r1 - 14 May 2010 15:20 Site Terms of Service - Privacy Policy - Brand Guidelines

Page 12 of 12Developing In Eclipse, with ADT | Android Developers

9/7/2010file://V:\android-sdk-windows\docs\guide\developing\eclipse-adt.html

Page 13: Android Sdk Developing

In this documentCreating an Android Project

Preparing to Sign Your Application

Building Your Application

Building in debug mode

Building in release mode

Creating an AVD

Running Your Application

Running on the emulator

Running on a device

Working with Library Projects

Development requirements

Setting up a library project

Referencing a library project

Building a dependent application project

Development considerations

Attaching a Debugger to Your Application

See alsoandroid Tool

Android Emulator

Android Debug Bridge

Developing In Other IDEs

The recommended way to develop an Android application is to use Eclipse with the ADT plugin. The ADT plugin provides editing, building, debugging, and .apk packaging and signing functionality integrated right into the IDE.

However, if you'd rather develop your application in another IDE, such as IntelliJ, or in a basic editor, such as Emacs, you can do that instead. The SDK includes all the tools you need to set up an Android project, build it, debug it and then package it for distribution. This document is your guide to using these tools.

Essential Tools

When developing in IDEs or editors other than Eclipse, you'll require familiarity with the following Android SDK tools:

androidTo create/update Android projects and to create/move/delete AVDs.

Android EmulatorTo run your Android applications on an emulated Android platform.

Android Debug BridgeTo interface with your emulator or connected device (install apps, shell the device, issue commands, etc.).

In addition to the above tools, included with the SDK, you'll use the following open source and third-party tools:

AntTo compile and build your Android project into an installable .apk file.

KeytoolTo generate a keystore and private key, used to sign your .apk file.

Jarsigner (or similar signing tool)To sign your .apk file with a private key generated by keytool.

In the topics that follow, you'll be introduced to each of these tools as necessary. For more advanced operations, please read the respective documentation for each tool.

Page 1 of 13Developing In Other IDEs | Android Developers

9/7/2010file://V:\android-sdk-windows\docs\guide\developing\other-ide.html

Page 14: Android Sdk Developing

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.

Creating a new Project

If you're starting a new project, use the android create project command to generate all the necessary files and folders.

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

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

The tool generates the following files and directories:

AndroidManifest.xml - The application manifest file, synced to the specified Activity class for the project.•

build.xml - Build file for Ant.•

default.properties - Properties for the build system. Do not modify this file.•

build.properties - Customizable properties for the build system. You can edit this file to override default build settings used by Ant and provide a pointer to your keystore and key alias so that the build tools can sign your application when built in release mode.

src/your/package/namespace/ActivityName.java - The Activity class you specified during project creation.•

bin/ - Output directory for the build script.•

gen/ - Holds Ant-generated files, such as R.java. •

Page 2 of 13Developing In Other IDEs | Android Developers

9/7/2010file://V:\android-sdk-windows\docs\guide\developing\other-ide.html

Page 15: Android Sdk Developing

libs/ - Holds private libraries.•

res/ - Holds project resources.•

src/ - Holds source code.•

tests/ - Holds a duplicate of all-of-the-above, for testing purposes.•

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 tools/ directory — to send your application to the emulator (discussed later). So you need access between your project solution and the tools/ folder.

Caution: You should refrain from moving the location of the SDK directory, because this will break the build scripts. (They will need to be manually updated to reflect the new SDK location before they will work again.)

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

Preparing to Sign Your Application

As you begin developing Android applications, understand that all Android applications must be digitally signed before the system will install them on an emulator or device. There are two ways to do this: with a debug key (for immediate testing on an emulator or development device) or with a private key (for application distribution).

The Android build tools help you get started by automatically signing your .apk files with a debug key at build time. This means that you can 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.

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.

Page 3 of 13Developing In Other IDEs | Android Developers

9/7/2010file://V:\android-sdk-windows\docs\guide\developing\other-ide.html

Page 16: Android Sdk Developing

Building Your Application

There are two ways to build your application: one for testing/debugging your application — debug mode — and one for building your final package for release — release mode. As described in the previous section, your application must be signed before it can be installed on an emulator or device.

Whether you're building in debug mode or release mode, you need to use the Ant tool to compile and build your project. This will create the .apk file that is installed onto the emulator or device. When you build in debug mode, the .apk file is automatically signed by the SDK tools with a debug key, so it's instantly ready for installation (but only onto an emulator or attached development device). When you build in release 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. However, you can (and should) also test your application in release mode. Debug mode simply allows you to run your application without manually signing the application.

To build in debug mode:

Open a command-line and navigate to the root of your project directory.1.

Use Ant to compile your project in debug mode: 2.

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

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

Page 4 of 13Developing In Other IDEs | Android Developers

9/7/2010file://V:\android-sdk-windows\docs\guide\developing\other-ide.html

Page 17: Android Sdk Developing

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

Use Ant to compile your project in release mode: 2.

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.

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

To specify your keystore and alias, open the project build.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.1.

Use Ant to compile your project in release mode: 2.

ant release

When prompted, enter you keystore and alias passwords. 3.

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 build.properties and aligned with zipalign. It's ready for installation and distribution.

Page 5 of 13Developing In Other IDEs | Android Developers

9/7/2010file://V:\android-sdk-windows\docs\guide\developing\other-ide.html

Page 18: Android Sdk Developing

Use the Emulator to Test Different Configurations

Create multiple AVDs that each define a different device configuration with which your application is compatible, then launch each AVD into a new emulator from the SDK and AVD Manager. Set the target mode in your app's run configuration to manual, so that when you run your application, you can select from the available virtual devices.

Once built and signed in release mode

Once you have signed your application with a private key, you can install it on an emulator or device as discussed in the following section about Running Your Application. 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.)

Creating an AVD

An Android Virtual Device (AVD) is a device configuration for the emulator that allows you to model real world devices. In order to run an instance of the emulator, you must create an AVD.

To create an AVD using the SDK tools:

Navigate to your SDK's tools/ directory and execute the android tool with no arguments: 1.

android

This will launch the SDK and AVD Manager GUI.

In the Virtual Devices panel, you'll see a list of existing AVDs. Click New to create a new AVD.2.

Fill in the details for the AVD. 3.

Give it a name, a platform target, an SD card size, and a skin (HVGA is default).

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

Your AVD is now ready and you can either close the AVD Manager, create more AVDs, or launch an emulator with the AVD by clicking Start.

For more information about AVDs, read the Android Virtual Devices documentation.

Running Your Application

Running your application on a virtual or real device takes just a couple steps. Remember to first build your application.

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 SDK and AVD Manager and launch a virtual device

1.

From your SDK's tools/ directory, execute the android tool with no arguments:

android

Page 6 of 13Developing In Other IDEs | Android Developers

9/7/2010file://V:\android-sdk-windows\docs\guide\developing\other-ide.html

Page 19: Android Sdk Developing

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

Install your application 2.

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.

If you don't see your application on the emulator. Try closing the emulator and launching the virtual device again from the SDK and AVD Manager. Sometimes when you install an Activity 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 1.5 (API Level 3) platform, you should create an AVD for each platform equal to and greater than 1.5 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:

Declare your application as debuggable in your manifest•

Enable USB Debugging on your device•

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

Page 7 of 13Developing In Other IDEs | Android Developers

9/7/2010file://V:\android-sdk-windows\docs\guide\developing\other-ide.html

Page 20: Android Sdk Developing

Library project example code

The SDK includes an example application called TicTacToeMain that shows how a dependent application can use code and resources from an Android Library 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 and AVD Manager to download the "Samples for SDK API 8" component into your SDK.

For more information and to browse the code of the samples, see the TicTacToeMain application.

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

If you have source code and resources that are common to multiple application projects, you can 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 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 an standard Android application project in that you cannot compile it directly to its own .apk or run it on the Android platform. 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 from a dependent application's build path, then building that application.

When you build an application that depends on a library project, the SDK tools compile the library and merge its sources with those in the main project, then use 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've have added references, the tools let you set their relative priority by editing the application project's build properties. At build time, the tools merge the libraries with the application one at a time, starting from the lowest priority to the highest.

Note that a library project cannot itself reference another library project and that, at build time, library projects are not merged with each other before being merged with the application. However, note that a library can import an external library (JAR) in the normal way.

The sections below describe how to use ADT to set up and manage library your projects. Once you've set up your library projects and moved code into them, you can import library classes and resources to your application in the normal way.

Page 8 of 13Developing In Other IDEs | Android Developers

9/7/2010file://V:\android-sdk-windows\docs\guide\developing\other-ide.html

Page 21: Android Sdk Developing

Development requirements

Android library projects are a build-time construct, so you can use them to build a final application .apk that targets any API level and is compiled against any version of the Android library.

However, to use library projects, you need to update your development environment to use the latest tools and platforms, since older releases of the tools and platforms do not support building with library projects. Specifically, you need to download and install the versions listed below:

Table 1. Minimum versions of SDK tools and plaforms on which you can develop library projects.

Component Minimum Version

SDK Tools r6 (or higher)

Android 2.2 platform r1 (or higher)

Android 2.1 platform r2 (or higher)

Android 2.0.1 platform not supported

Android 2.0 platform not supported

Android 1.6 platform r3 (or higher)

Android 1.5 platform r4 (or higher)

ADT Plugin 0.9.7 (or higher)

You can download the tools and platforms using the Android SDK and AVD Manager, as described in Adding SDK Components.

Setting up a new library project

A library project is a standard Android project, so you can create a new one in the same way as you would a new application project. Specifically, you can use the android tool to generate a new library project with all of the necessary files and folders.

Creating a library project

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 default.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 default.properties file.

Page 9 of 13Developing In Other IDEs | Android Developers

9/7/2010file://V:\android-sdk-windows\docs\guide\developing\other-ide.html

Page 22: Android Sdk Developing

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 from an application

If you are developing an application and want to include the shared code or resources from a library project, you can do so easily by adding a reference to the library project in the application project's build properties.

To add a reference to a library project, navigate to the <sdk>/tools/ directory and use this command:

android update lib-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 default.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 default.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

Page 10 of 13Developing In Other IDEs | Android Developers

9/7/2010file://V:\android-sdk-windows\docs\guide\developing\other-ide.html

Page 23: Android Sdk Developing

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

In the manifest file of the application project, you must add declarations of all components that the application will use that are imported from a library project. For example, you must declare any <activity>, <service>, <receiver>, <provider>, and so on, as well as <permission>, <uses-library>, and similar elements.

Declarations should reference the library components by their fully-qualified package names, where appropriate.

For example, the TicTacToeMain example application declares the library Activity GameActivity like this:

<manifest> ... <application> ... <activity android:name="com.example.android.tictactoe.library.GameActivity" /> ... </application> ... </manifest>

For more information about the manifest file, see the documentation for AndroidManifest.xml.

Building a dependent application

To build an application project that depends on one or more library projects, you can use the standard Ant build commands and compile modes, as described in Building Your Application, earlier in this document. 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.

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 highest-priority library taking precedence.

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

No export of library project to JAR

A library cannot be distributed as a binary file (such as a jar file). This is because the library project is compiled by the main project to use the correct resource IDs.

One library project cannot reference another

Page 11 of 13Developing In Other IDEs | Android Developers

9/7/2010file://V:\android-sdk-windows\docs\guide\developing\other-ide.html

Page 24: Android Sdk Developing

A library cannot depend on another library.

A library project can include a JAR library

You can develop a library project that itself includes a JAR library. When you build the dependent application project, the tools automatically locate and include the library in the application .apk.

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 their manifest files, in a <uses-library> element.

Library project cannot include AIDL files

The tools do not support the use of AIDL files in a library project. Any AIDL files used by an application must be stored in the application project itself.

Library project cannot include raw assets

The tools do not support the use of raw asset files in a library project. Any asset resources used by an application must be stored in the assets/ directory of the application project itself.

Targeting different Android platform versions in library project and application 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 fail to 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 name

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

Multiple R classes in gen/ folder of application project

When you build the dependent application project, the code of any libraries is compiled and merged to the application project. Each library has its own R class, named according to the library's package name. The R class generated from the resources of the main project and of the library is created in all the packages that are needed including the main project’s package and the libraries’ packages.

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

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. You can place the library project What is important is that the main project can reference the library project through a relative link.

Page 12 of 13Developing In Other IDEs | Android Developers

9/7/2010file://V:\android-sdk-windows\docs\guide\developing\other-ide.html

Page 25: Android Sdk Developing

↑ Go to top

Attaching a Debugger to Your Application

This section describes how to display debug information on the screen (such as CPU usage), as well as how to hook up your IDE to debug running applications on the emulator.

Attaching a debugger is automated using the Eclipse plugin, but you can configure other IDEs to listen on a debugging port to receive debugging information:

Start the Dalvik Debug Monitor Server (DDMS) tool, which acts as a port forwarding service between your IDE and the emulator.

1.

Set optional debugging configurations on your emulator, such as blocking application startup for an Activity until a debugger is attached. Note that many of these debugging options can be used without DDMS, such as displaying CPU usage or screen refresh rate on the emulator.

2.

Configure your IDE to attach to port 8700 for debugging. Read about Configuring Your IDE to Attach to the Debugging Port.

3.

Except as noted, this content is licensed under Apache 2.0. For details and restrictions, see the Content License. Android 2.2 r1 - 14 May 2010 15:20 Site Terms of Service - Privacy Policy - Brand Guidelines

Page 13 of 13Developing In Other IDEs | Android Developers

9/7/2010file://V:\android-sdk-windows\docs\guide\developing\other-ide.html

Page 26: Android Sdk Developing

In this documentSetting up a Device for Development

USB Vendor IDs

See alsoUSB Driver for Windows

Developing in Eclipse, with ADT

Developing in other IDEs

Developing on a Device

When building a mobile application, it's important that you always test your application on a real device before releasing it to users. This page describes how to set up your development environment and Android-powered device for testing and debugging on the device.

You can use any Android-powered device as an environment for running, debugging, and testing your applications. The tools included in the SDK make it easy to install and run your application on the device each time you compile. You can install your application on the device directly from Eclipse or from the command line. 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 either an Android Dev Phone or the Google Nexus One. Both are SIM-unlocked so that you can use them on any GSM network using a SIM card. The Android Dev Phones also feature an unlocked bootloader so you can install custom system images (great for developing and installing custom versions of the Android platform). To purchase a Nexus One, visit google.com/phone. To purchase an Android Dev Phone, see the Android Market site (requires a developer account).

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

In Eclipse, you can do this from the Application tab when viewing the Manifest (on the right side, set Debuggable to true). Otherwise, in the AndroidManifest.xml file, add android:debuggable="true" to the <application> element.

Turn on "USB Debugging" on your device. 2.

On the device, go to the home screen, press MENU, select Applications > Development, then enable USB debugging.

Setup your system to detect your device. 3.

If you're developing on Windows, you need to install a USB driver for adb. See the Windows USB Driver documentation.

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 rules file that contains a USB configuration for each type of device you want to use for development. Each device manufacturer uses a different vendor ID. The

Page 1 of 2Developing on a Device | Android Developers

9/7/2010file://V:\android-sdk-windows\docs\guide\developing\device.html

Page 27: Android Sdk Developing

↑ Go to top

example rules files below show how to add an entry for a single vendor ID (the HTC vendor ID). In order to support more devices, you will need additional lines of the same format that provide a different value for the SYSFS{idVendor} property. For other IDs, see the table of USB Vendor IDs, below.

Log in as root and create this file: /etc/udev/rules.d/51-android.rules. 1.

For Gusty/Hardy, edit the file to read: SUBSYSTEM=="usb", SYSFS{idVendor}=="0bb4", MODE="0666"

For Dapper, edit the file to read: SUBSYSTEM=="usb_device", SYSFS{idVendor}=="0bb4", MODE="0666"

Now execute: chmod a+r /etc/udev/rules.d/51-android.rules

2.

You can verify that your device is connected by executing adb devices from your SDK tools/ directory. If connected, you'll see the device name listed as a "device."

If using Eclipse, run or debug 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 SYSFS{idVendor} property in the rules file, as described in step 3, above.

Manufacturer USB Vendor ID

Acer 0502

Dell 413c

Foxconn 0489

Garmin-Asus 091E

HTC 0bb4

Huawei 12d1

Kyocera 0482

LG 1004

Motorola 22b8

Nvidia 0955

Pantech 10A9

Samsung 04e8

Sharp 04dd

Sony Ericsson 0fce

ZTE 19D2

Except as noted, this content is licensed under Apache 2.0. For details and restrictions, see the Content License. Android 2.2 r1 - 14 May 2010 15:20 Site Terms of Service - Privacy Policy - Brand Guidelines

Page 2 of 2Developing on a Device | Android Developers

9/7/2010file://V:\android-sdk-windows\docs\guide\developing\device.html

Page 28: Android Sdk Developing

In this documentTools

Debug with Dev Tools

Debugging Web Pages

Top Debugging Tips

Configuring Your IDE to Attach to the Debugging Port

Debugging Tasks

This document offers some helpful guidance to debugging applications on Android.

Tools

The Android SDK includes a set of tools to help you debug and profile your applications. Here are some tools that you'll use most often:

Android Debug Bridge (ADB)Provides various device management capabilities, including moving and syncing files to the emulator, forwarding ports, and running a UNIX shell on the emulator.

Dalvik Debug Monitor Server (DDMS)A graphical program that supports port forwarding (so you can set up breakpoints in your code in your IDE), screen captures on the emulator, thread and stack information, and many other features. You can also run logcat to retrieve your Log messages.

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

logcatDumps a log of system messages. The messages include a stack trace when the emulator throws an error, as well as Log messages you've written from your application. To run logcat, execute adb logcat or, from DDMS, select Device > Run logcat.

Log is a logging class you can use to print out messages to the logcat. You can read messages in real time if you run logcat on DDMS (covered next). Common logging methods include: v(String, String) (verbose), d(String, String) (debug), i(String, String) (information), w(String, String) (warning) and e(String, String) (error). For example:

Log.i("MyActivity", "MyClass.getView() — get item n umber " + position);

The logcat will then output something like:

I/MyActivity( 1557): MyClass.getView() — get item n umber 1

Logcat is also the place to look when debugging a web page in the Android Browser app. See Debugging Web Pages below.

For more information about all the development tools provided with the Android SDK, see the Tools document.

In addition to the above tools, you may also find the following useful for debugging:

Eclipse ADT plugin

Page 1 of 5Debugging Tasks | Android Developers

9/7/2010file://V:\android-sdk-windows\docs\guide\developing\debug-tasks.html

Page 29: Android Sdk Developing

The ADT Plugin for Eclipse integrates a number of the Android development tools (ADB, DDMS, logcat output, and other functionality), so that you won't work with them directly but will utilize them through the Eclipse IDE.

Developer Settings in the Dev Tools appThe Dev Tools application included in the emulator system image exposes several settings that provide useful information such as CPU usage and frame rate. See Debugging and Testing with Dev Tools below.

Debugging and Testing with Dev Tools

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 is installed by default on all system images included with the SDK, so you can use it with the Android Emulator. If you'd like to install the Dev Tools application on a real development device, you can copy the application from your emulator and then install it on your device using ADB. To copy the application from a running emulator, execute:

adb - e pull / system / app / Development. apk ./ Development. apk

This copies the .apk file into the current directory. Then install it on your connected device with:

adb - d install Development. apk

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 appLets 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 debuggerBlocks 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 updatesFlashes a momentary pink rectangle on any screen sections that are being redrawn. This is very useful for discovering unnecessary screen drawing.

Immediately destroy activitiesTells 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.

Show CPU usage

Page 2 of 5Debugging Tasks | Android Developers

9/7/2010file://V:\android-sdk-windows\docs\guide\developing\debug-tasks.html

Page 30: Android Sdk Developing

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

Debugging Web Pages

If you're developing a web application for Android devices, you can debug your JavaScript in the Android Browser using the Console APIs, which will output messages to logcat. If you're familiar debugging web pages with Firefox's FireBug or WebKit's Web Inspector, then you're probably familiar with the Console APIs. The Android Browser (and the WebChromeClient ) supports most of the same APIs.

When you call a function from the Console APIs (in the DOM's window.console object), you will see the output in logcat as a warning. For example, if your web page executes the following JavaScript:

console.log("Hello World");

Then the logcat output from the Android Browser will look like this:

W/browser ( 202): Console: Hello World http://www.e xample.com/hello.html :82

All Console messages from the Android Browser are tagged with the name "browser" on Android platforms running API Level 7 or higher. On platforms running API Level 6 or lower, Browser messages are tagged with the name "WebCore". The Android Browser also formats console messages with the log message preceded by "Console:" and then followed by the address and line number where the message occurred. (The format for the address and line number will appear different from the example above on platforms running API Level 6 or lower.)

The Android Browser (and WebChromeClient ) does not implement all of the Console APIs provided by Firefox or other WebKit-based browsers. Primarily, you need to depend on the basic text logging functions:

console.log(String)•

console.info(String)•

console.warn(String)•

console.error(String)•

Although the Android Browser may not fully implement other Console functions, they will not raise run-time errors, but may not behave the same as they do on other desktop browsers.

If you've implemented a custom WebView in your application, then in order to receive messages that are sent through the Console APIs, you must provide a WebChromeClient that implements the onConsoleMessage() callback method. For example, assuming that the myWebView field references the WebView in your application, you can log debug messages like this:

myWebView. setWebChromeClient ( new WebChromeClient() { public void onConsoleMessage ( String message , int lineNumber , String sourceID ) { Log. d( "MyApplication" , message + " -- From line " + lineNumber + " of " + sourceID );

Page 3 of 5Debugging Tasks | Android Developers

9/7/2010file://V:\android-sdk-windows\docs\guide\developing\debug-tasks.html

Page 31: Android Sdk Developing

} });

The onConsoleMessage() method will be called each time one of the Console methods is called from within your WebView.

When the "Hello World" log is executed through your WebView, it will now look like this:

D/MyApplication ( 430): Hello World -- From line 82 of http://www.example.com/hello.html

Note: The onConsoleMessage() callback method was added with API Level 7. If you are using a custom WebView on a platform running API Level 6 or lower, then your Console messages will automatically be sent to logcat with the "WebCore" logging tag.

Top Debugging Tips

Dump the stack traceTo 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 screenThe 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 Setting debug and test configurations on the emulator.

Get system state information from the emulator (dumpstate)You can access dumpstate information from the Dalvik Debug Monitor Service tool. See dumpsys and dumpstate on the adb topic page.

Get application state information from the emulator (dumpsys)You can access dumpsys information from the Dalvik Debug Monitor Service tool. See dumpsys and dumpstate on the adb topic page.

Get wireless connectivity informationYou can get information about wireless connectivity using the Dalvik Debug Monitor Service tool. From the Device menu, select "Dump radio state".

Log trace dataYou can log method calls and other tracing data in an activity by calling startMethodTracing() . See Running the Traceview Debugging Program for details.

Log radio dataBy 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 screenshotsThe Dalvik Debug Monitor Server (DDMS) can capture screenshots from the emulator. Select Device > Screen capture.

Use debugging helper classes

Page 4 of 5Debugging Tasks | Android Developers

9/7/2010file://V:\android-sdk-windows\docs\guide\developing\debug-tasks.html

Page 32: Android Sdk Developing

↑ Go to top

Android provides debug helper classes such as util.Log and Debug for your convenience.

Also see the Troubleshooting document for answers to some common developing and debugging issues.

Configuring Your IDE to Attach to the Debugging Port

DDMS will assign 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.

Except as noted, this content is licensed under Apache 2.0. For details and restrictions, see the Content License. Android 2.2 r1 - 14 May 2010 15:20 Site Terms of Service - Privacy Policy - Brand Guidelines

Page 5 of 5Debugging Tasks | Android Developers

9/7/2010file://V:\android-sdk-windows\docs\guide\developing\debug-tasks.html

Page 33: Android Sdk Developing

↑ Go to top

Testing Overview

Android includes powerful tools for setting up and running test applications. Whether you are working in Eclipse with ADT or working from the command line, these tools help you set up and run your tests within an emulator or the device you are targeting. The documents listed below explain how to work with the tools in your development environment.

If you aren't yet familiar with the Android testing framework, please read the topic Testing and Instrumentation before you get started. For a step-by-step introduction to Android testing, try the Hello, Testing tutorial, which introduces basic testing concepts and procedures. For a more advanced tutorial, try Activity Testing, which guides you through a more complex testing scenario.

Testing in Eclipse, with ADTThe ADT plugin lets you quickly set up and manage test projects directly in the Eclipse UI. Once you have written your tests, you can build and run them and then see the results in the Eclipse JUnit view. You can also use the SDK command-line tools to execute your tests if needed.

Testing in Other IDEsThe SDK command-line tools provide the same capabilities as the ADT plugin. You can use them to set up and manage test projects, build your test application, run your tests, and see the results. You use the android tool to create and manage test projects, the Ant build system to compile them, and the adb tool to install and run them.

Except as noted, this content is licensed under Apache 2.0. For details and restrictions, see the Content License. Android 2.2 r1 - 14 May 2010 15:20 Site Terms of Service - Privacy Policy - Brand Guidelines

Page 1 of 1Testing Overview | Android Developers

9/7/2010file://V:\android-sdk-windows\docs\guide\developing\testing\index.html

Page 34: Android Sdk Developing

In this documentCreating a Test Project

Creating a Test Application

Running Tests

Testing In Eclipse, with ADT

This topic explains how create and run tests of Android applications in Eclipse with ADT. with the basic processes for creating and running applications with ADT, as described in Developing In Eclipse, with ADT. Before you read this topic, you should read about how to create a Android application with the basic processes for creating and running applications with ADT, as described in Developing In Eclipse, with ADT. You may also want to read Testing and Instrumentation, 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 application'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 application and include in them flags that are passed to the Android testing framework.

It lets you run your test application without leaving Eclipse. ADT builds both the application under test and the test application automatically, installs them if necessary to your device or emulator, runs the test application, 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 in Other IDEs.

Creating a Test Project

To set up a test environment for your Android application, you must first create a separate application 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 application 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. 1.

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.

2.

Enter a project name. You may use any name, but you may want to associate the name with the project name for your Application. 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 case project name.

3.

Page 1 of 4Testing In Eclipse, with ADT | Android Developers

9/7/2010file://V:\android-sdk-windows\docs\guide\developing\testing\testing_eclipse.html

Page 35: Android Sdk Developing

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.

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

4.

In the Build Target panel, select the Android SDK platform that you will use to test your application. Make this the same as the build target of the application under test.

5.

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.

6.

Creating a Test Application

Once you have created a test project, you populate it with a test Android application. This application does not require an Activity , although you can define one if you wish. Although your test application 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.

Test applications do not have an Android GUI. Instead, when you run the application in Eclipse with ADT, its results appear in the JUnit view. 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 application, start with one of Android's test classes in the Java package android.test . These extend the JUnit TestCase class. With a few exceptions, the Android test classes also provide instrumentation for testing.

For test classes that extend TestCase , you probably want to override the setUp() and tearDown() methods:

setUp() : This method is invoked before any of the test methods in the class. Use it to set up the environment for the test. You can use setUp() to instantiate a new Intent object with the action ACTION_MAIN. You can then use this intent to start the Activity under test.

Note: If you override this method, call super.setUp() as the first statement in your code.

tearDown() : This method is invoked after all the test methods in the class. Use it to do garbage collection and re-setting before moving on to the next set of tests.

Note: If you override this method, you must call super.tearDown() as the last statement in your code.

Another useful convention is to add the method testPreConditions() to your test class. Use this method to test that the application under test is initialized correctly. If this test fails, you know that that the initial conditions were in error. When this happens, further test results are suspect, regardless of whether or not the tests succeeded.

The Resources tab contains an Activity Testing tutorial with more information about creating test classes and methods.

Running Tests

When you run a test application in Eclipse with ADT, the output appears in an Eclipse view panel. You can run the entire test application, one class, or one method of a class. To do this, Eclipse runs the adb command for running a test application, 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 application, to run a test application in Eclipse with ADT you must either attach a device to your

Page 2 of 4Testing In Eclipse, with ADT | Android Developers

9/7/2010file://V:\android-sdk-windows\docs\guide\developing\testing\testing_eclipse.html

Page 36: Android Sdk Developing

To run tests created in Eclipse with ADT with command-line tools, you must first install additional files into the test project using the android tool's "create test-project" option. To see how to do this, read the section Creating a test project in the topic Testing in Other IDEs.

computer or use the Android emulator. If you use the emulator, you must have an Android Virtual Device (AVD) that uses the same target

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

Run a test just as you run an application, by selecting Run As... > Android JUnit Test from the project's context menu or from the main menu's Run item.

1.

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.

2.

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.

1.

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 your project's classes test classes in your project.

2.

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.

3.

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

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 Emulator Startup Options.

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.

5.

Optional: Add the configuration to the Run toolbar and the Favorites menu: in the Display in Favorites pane click the checkbox next to Run.

6.

Optional: To add this configuration to the Debug menu and toolbar, click the checkbox next to Debug. 7.

To save your settings, click Close. 8.

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.

9.

Select the test run configuration you just created. 10.

The progress of your test appears in the Console view. You should see the following messages, among others: 11.

Performing Android.test.InstrumentationTestRunner J Unit launch The class name that proceeds "JUnit" depends on the Android instrumentation class you have chosen.

If you are using an emulator and you have not yet started it, then you will see the message: ◦

Automatic Target Mode: launching new emulator with compatible AVD avdname (where avdname is the name of the AVD you are using.)

If you have not already installed your test application, then you will see the message: ◦

Page 3 of 4Testing In Eclipse, with ADT | Android Developers

9/7/2010file://V:\android-sdk-windows\docs\guide\developing\testing\testing_eclipse.html

Page 37: Android Sdk Developing

↑ Go to top

Uploading testclass.apk onto device ' device-id' where testclass is the name of your unit test class and device-id is the name and port for your test device or emulator, followed by the message Installing testclass.apk

Launching instrumentation Android.test.Instrumentat ionTestRunner on device device-id. This indicates that Android's Instrumentation system is now testing your code. Again, the instrumentation class name depends on the Android instrumentation class you have chosen.

Test run complete . When you see this, your unit tests have finished.

The test results appear in the JUnit view. This is divided into an upper summary pane, and a lower stack trace pane.

The upper pane contains test information. In the pane's header, you see the following information:

Total time elapsed for the test 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.

The body of the upper pane contains the details of the test run. For each test case class that was run, you see a line with the class name. To look at the results for the individual test methods in that class, you click the left arrow to expand the line. You now see a line for each test method in the class, and to its right the time it took to run. If you double-click the method name, Eclipse opens the test class source in an editor view pane and moves the focus to the first line of the test method.

The lower pane is for stack traces. If you highlight a failed test in the upper pane, the lower pane contains a stack trace for the test. If a line corresponds to a point in your test code, you can double-click it to display the code in an editor view pane, with the line highlighted. For a successful test, the lower pane is empty.

Except as noted, this content is licensed under Apache 2.0. For details and restrictions, see the Content License. Android 2.2 r1 - 14 May 2010 15:20 Site Terms of Service - Privacy Policy - Brand Guidelines

Page 4 of 4Testing In Eclipse, with ADT | Android Developers

9/7/2010file://V:\android-sdk-windows\docs\guide\developing\testing\testing_eclipse.html

Page 38: Android Sdk Developing

In this documentWorking with Test Projects

Creating a test project

Updating a test project

Creating a Test Application

Running Tests

Quick build and run with Ant

Running tests on a device or emulator

Using the Instrument Command

Instrument options

Instrument examples

See AlsoTesting and Instrumentation

Activity Testing

Android Debug Bridge

Testing In Other IDEs

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 document Testing and Instrumentation, which provides an overview of Android testing.

If you are developing in Eclipse with ADT, you can set up and run your tests directly in Eclipse. For more information, please read Testing in Eclipse, with ADT.

Working with Test Projects

You use the android tool to create test projects. You also use android to convert existing test code into an Android test project, or to add the run-tests Ant target to an existing Android test project. These operations are described in more detail in the section Updating a test project. The run-tests target is described in Quick build and run with Ant.

Creating a test project

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

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

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

Flag Value Description

-m, --main

Path to the project of the application under test, relative to the test application directory.

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.

-n, --name

Name that you want to give the test project.

-p, --path

Directory in which you want to create the new test project.

The android tool creates the test project files and directory structure in this directory. If the directory does not exist, android creates it.

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

Page 1 of 7Testing In Other IDEs | Android Developers

9/7/2010file://V:\android-sdk-windows\docs\guide\developing\testing\testing_otheride.html

Page 39: Android Sdk Developing

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 Developing In Other IDEs.

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 the Hello, World tutorial application in the directory ~/source/HelloAndroid. In the tutorial, this application uses 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: •

android:name="android.test.InstrumentationTestRunner": InstrumentationTestRunner runs test cases. It extends both JUnit test case runner classes and Android instrumentation classes.

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. This is the package name of the Hello, World tutorial application.

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.

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 application. 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, --main

The path to the project of the application under test, relative to the test project

For example, if the application under test is in source/HelloAndroid, and the test project is in source/HelloAndroidTest, then the value for --main is ../HelloAndroid.

-p, --path

The of the test project. For example, if the test project is in source/HelloAndroidTest, then the value for --path is HelloAndroidTest.

Page 2 of 7Testing In Other IDEs | Android Developers

9/7/2010file://V:\android-sdk-windows\docs\guide\developing\testing\testing_otheride.html

Page 40: Android Sdk Developing

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

Creating a Test Application

Once you have created a test project, you populate it with a test application. The application does not require an Activity, although you can define one if you wish. Although your test application 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 application, start with one of Android's test classes in the Java package android.test. These extend the JUnit TestCase class. With a few exceptions, the Android test classes also provide instrumentation for testing.

For test classes that extend TestCase, you probably want to override the setUp() and tearDown() methods:

setUp(): This method is invoked before any of the test methods in the class. Use it to set up the environment for the test. You can use setUp() to instantiate a new Intent object with the action ACTION_MAIN. You can then use this intent to start the Activity under test.

Note: If you override this method, call super.setUp() as the first statement in your code.

tearDown(): This method is invoked after all the test methods in the class. Use it to do garbage collection and re-setting before moving on to the next set of tests.

Note: If you override this method, you must call super.tearDown() as the last statement in your code.

Another useful convention is to add the method testPreConditions() to your test class. Use this method to test that the application under test is initialized correctly. If this test fails, you know that that the initial conditions were in error. When this happens, further test results are suspect, regardless of whether or not the tests succeeded.

To learn more about creating test applications, see the topic Testing and Instrumentation, 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

If you are not developing in Eclipse with ADT, you need to run tests from the command line. You can do this either with Ant or with the ActivityManager command line interface.

You can also run tests from the command line even if you are using Eclipse with ADT to develop them. To do this, you need to create the proper files and directory structure in the test project, using the android tool with the option create test-project. This is described in the section Working with Test Projects.

Quick build and run with Ant

You can use Ant to run all the tests in your test project, using the target run-tests, 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.

Page 3 of 7Testing In Other IDEs | Android Developers

9/7/2010file://V:\android-sdk-windows\docs\guide\developing\testing\testing_otheride.html

Page 41: Android Sdk Developing

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 the ActivityManager (am) command-line tool, 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.

You run the am tool on an Android device or emulator using the Android Debug Bridge (adb) shell. When you do this, you use the ActivityManager instrument option to run your test application using an Android test runner (usually InstrumentationTestRunner). You set am options with command-line flags.

To run a test with am:

If necessary, re-build your main application and test application. 1.

Install your test application and main application Android package files (.apk files) to your current Android device or emulator

2.

At the command line, enter: 3.

$ 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 application. The Android test runner class is usually InstrumentationTestRunner.

Your test results appear in STDOUT.

This operation starts an adb shell, then runs am instrument in it with the specified parameters. This particular form of the command will run all of the tests in your test application. You can control this behavior with flags that you pass to am instrument. These flags are described in the next section.

Using the 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 application.

The value of the package attribute of the manifest element in the test application'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:

Page 4 of 7Testing In Other IDEs | Android Developers

9/7/2010file://V:\android-sdk-windows\docs\guide\developing\testing\testing_otheride.html

Page 42: Android Sdk Developing

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 , in the form of 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 next table. The only instrumentation class that understands these key-value pairs is InstrumentationTestRunner (or a subclass). Using them with any other class has no effect.

Instrument options

The am instrument tool passes testing options to InstrumentationTestRunner or a subclass in the form of key-value pairs, using the -e flag, with this syntax:

-e <key> <value>

Where applicable, a <key> may have multiple values separated by a comma (,). 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.

Page 5 of 7Testing In Other IDEs | Android Developers

9/7/2010file://V:\android-sdk-windows\docs\guide\developing\testing\testing_otheride.html

Page 43: Android Sdk Developing

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

A fully-qualified test case class name, and one of its 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.

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

Instrument examples

Here are some examples of using am instrument to run tests. They are based on the following structure:

The test application has the Android package name com.android.demo.app.tests •

There are three test classes: •

UnitTests, which contains the methods testPermissions and testSaveState. ◦

Page 6 of 7Testing In Other IDEs | Android Developers

9/7/2010file://V:\android-sdk-windows\docs\guide\developing\testing\testing_otheride.html

Page 44: Android Sdk Developing

↑ Go to top

FunctionTests, which contains the methods testCamera, testXVGA, and testHardKeyboard. ◦

IntegrationTests, which contains the method testActivityProvider. ◦

The test runner is InstrumentationTestRunner. •

Running the Entire Test Application

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

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

Running All Tests in a Test Case Class

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

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

am instrument gets the value of the -e flag, detects the class keyword, and runs all the methods in the UnitTests class.

Selecting a Subset of Tests

To run all of the tests in UnitTests, and the testCamera method in FunctionTests, enter:

$ adb shell am instrument -w \ -e class com.android.demo.app.tests.UnitTests,com.android.demo.app.tests.FunctionTests#testCamera \ com.android.demo.app.tests/android.test.InstrumentationTestRunner

You can find more examples of the command in the documentation for InstrumentationTestRunner.

Except as noted, this content is licensed under Apache 2.0. For details and restrictions, see the Content License. Android 2.2 r1 - 14 May 2010 15:20 Site Terms of Service - Privacy Policy - Brand Guidelines

Page 7 of 7Testing In Other IDEs | Android Developers

9/7/2010file://V:\android-sdk-windows\docs\guide\developing\testing\testing_otheride.html

Page 45: Android Sdk Developing

Tools Overview

The Android SDK includes a variety of custom tools that help you develop mobile applications on the Android platform. The most important of these are the Android Emulator and the Android Development Tools plugin for Eclipse, but the SDK also includes a variety of other tools for debugging, packaging, and installing your applications on the emulator.

Android Development Tools Plugin (for the Eclipse IDE)The ADT plugin adds powerful extensions to the Eclipse integrated environment, making creating and debugging your Android applications easier and faster. If you use Eclipse, the ADT plugin gives you an incredible boost in developing Android applications.

Android EmulatorA QEMU-based device-emulation tool that you can use to design, debug, and test your applications in an actual Android run-time environment.

Android Virtual Devices (AVDs)Virtual device configurations that you create, to model device characteristics in the Android Emulator. In each configuration, you can specify the Android platform to run, the hardware options, and the emulator skin to use. Each AVD functions as an independent device with it's own storage for user data, SD card, and so on.

Hierarchy ViewerThe Hierarchy Viewer tool allows you to debug and optimize your user interface. It provides a visual representation of your layout's hierarchy of Views and a magnified inspector of the current display with a pixel grid, so you can get your layout just right.

layoutoptThis tool lets you quickly analyze your application's layouts for efficiency.

Draw 9-patchThe Draw 9-patch tool 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.

Dalvik Debug Monitor Service (ddms)Integrated with Dalvik, the Android platform's custom VM, this tool lets you manage processes on an emulator or device and assists in debugging. You can use it to kill processes, select a specific process to debug, generate trace data, view heap and thread information, take screenshots of the emulator or device, and more.

Android Debug Bridge (adb)The adb tool lets you install your application's .apk files on an emulator or device and access the emulator or device from a command line. You can also use it to link a standard debugger to application code running on an Android emulator or device.

Android Asset Packaging Tool (aapt)The aapt tool lets you create .apk files containing the binaries and resources of Android applications.

Android Interface Description Language (aidl)Lets you generate code for an interprocess interface, such as what a service might use.

sqlite3Included as a convenience, this tool lets you access the SQLite data files created and used by Android applications.

Page 1 of 2Tools Overview | Android Developers

9/7/2010file://V:\android-sdk-windows\docs\guide\developing\tools\index.html

Page 46: Android Sdk Developing

↑ Go to top

TraceviewThis tool produces graphical analysis views of trace log data that you can generate from your Android application.

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

dxThe dx tool rewrites .class bytecode into Android bytecode (stored in .dex files.)

UI/Application Exerciser MonkeyThe 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.

androidA script that lets you manage AVDs and generate Ant build files that you can use to compile your Android applications.

zipalignAn important .apk optimization tool. This tool ensures 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.

Except as noted, this content is licensed under Apache 2.0. For details and restrictions, see the Content License. Android 2.2 r1 - 14 May 2010 15:20 Site Terms of Service - Privacy Policy - Brand Guidelines

Page 2 of 2Tools Overview | Android Developers

9/7/2010file://V:\android-sdk-windows\docs\guide\developing\tools\index.html

Page 47: Android Sdk Developing

↑ Go to top

Using aapt

aapt stands for Android Asset Packaging Tool and is included in the tools/ directory of the SDK. This tool allows you to view, create, and update Zip-compatible archives (zip, jar, apk). It can also compile resources into binary assets.

Though you probably won't often use aapt directly, build scripts and IDE plugins can utilize this tool to package the apk file that constitutes an Android application.

For more usage details, open a terminal, go to the tools/ directory, and run the command:

Linux or Mac OS X:•

./aapt

Windows:•

aapt.exe

Except as noted, this content is licensed under Apache 2.0. For details and restrictions, see the Content License. Android 2.2 r1 - 14 May 2010 15:20 Site Terms of Service - Privacy Policy - Brand Guidelines

Page 1 of 1Using aapt | Android Developers

9/7/2010file://V:\android-sdk-windows\docs\guide\developing\tools\aapt.html

Page 48: Android Sdk Developing

ADB quickviewManage the state of an emulator or device•Run shell commands on a device•Manage port forwarding on an emulator or device

Copy files to/from an emulator or device•

In this documentIssuing ADB 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

Listing of adb Commands

Issuing Shell Commands

Enabling logcat Logging

Stopping the adb Server

See alsoEmulator

Android Debug Bridge

Android Debug Bridge (adb) is a versatile tool lets you manage the state of an emulator instance or Android-powered device. It is a client-server program that includes three components:

A client, which runs on your development machine. You can invoke a client from a shell by issuing an adb command. Other Android tools such as the ADT plugin and DDMS also create adb clients.

A server, which runs as a background process on your development machine. The server manages communication between the client and the adb daemon running on an emulator or device.

A daemon, which runs as a background process on each emulator or device instance.

When you start an adb client, the client first checks whether there is an adb server process already running. If there isn't, it starts the server process. When the server starts, it binds to local TCP port 5037 and listens for commands sent from adb clients—all adb clients use port 5037 to communicate with the adb server.

The server then sets up connections to all running emulator/device instances. It locates emulator/device instances by scanning odd-numbered ports in the range 5555 to 5585, the range used by emulators/devices. Where the server finds an adb daemon, it sets up a connection to that port. Note that each emulator/device instance acquires a pair of sequential ports — an even-numbered port for console connections and an odd-numbered port for adb connections. For example:

Emulator 1, console: 5554 Emulator 1, adb: 5555 Emulator 2, console: 5556 Emulator 2, adb: 5557 ...

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

The sections below describe the commands that you can use to access adb capabilities and manage the state of an emulator/device. Note that if you are developing Android applications in Eclipse and have installed the ADT plugin, you do not need to access adb from the command line. The ADT plugin provides a transparent integration of adb into the Eclipse IDE. However, you can still use adb directly as necessary, such as for debugging.

Page 1 of 12Android Debug Bridge | Android Developers

9/7/2010file://V:\android-sdk-windows\docs\guide\developing\tools\adb.html

Page 49: Android Sdk Developing

Issuing adb Commands

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>

When you issue a command, the program invokes an adb client. The client is not specifically associated with any emulator instance, so if multiple emulators/devices are running, you need to use the -d option to specify the target instance to which the command should be directed. For more information about using this option, see Directing Commands to a Specific Emulator/Device Instance.

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. Three states are supported: •

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

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.

The output for each instance is formatted like this:

[serialNumber] [state]

Here's an example showing the devices command and its output:

$ adb devices List of devices attached emulator-5554 device emulator-5556 device emulator-5558 device

If there is no emulator/device running, adb returns no device.

Directing Commands to a Specific Emulator/Device Instance

If multiple emulator/device instances are running, you need to specify a target instance when issuing adb commands. To so so, use the -s option in the commands. The usage for the -s option is:

Page 2 of 12Android Debug Bridge | Android Developers

9/7/2010file://V:\android-sdk-windows\docs\guide\developing\tools\adb.html

Page 50: Android Sdk Developing

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.

Here is an example:

adb -s emulator-5556 install helloWorld.apk

Note that, if you issue a command without specifying a target emulator/device instance using -s, adb generates an error.

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 Android Asset Packaging Tool (aapt).

Note that, if you are using the Eclipse IDE and have the ADT plugin installed, you do not need to use adb (or aapt) directly to install your application on the emulator/device. Instead, the ADT plugin handles the packaging and installation of the application for you.

Forwarding Ports

You can use the forward command to set up arbitrary port forwarding — forwarding of requests on a specific host port to a different port on an emulator/device instance. Here's how you would set up forwarding of host port 6100 to emulator/device port 7100:

adb forward tcp:6100 tcp:7100

You can also use adb to set up forwarding to named abstract UNIX domain sockets, as illustrated here:

adb forward tcp:6100 local:logd

Copying Files to or from an Emulator/Device Instance

You can use the adb commands pull and push to copy files to and from an emulator/device instance's data file. 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 (recursively) from the emulator or device, use

Page 3 of 12Android Debug Bridge | Android Developers

9/7/2010file://V:\android-sdk-windows\docs\guide\developing\tools\adb.html

Page 51: Android Sdk Developing

adb pull <remote> <local>

To copy a file or directory (recursively) 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).

Here's an example:

adb push foo.txt /sdcard/foo.txt

Listing of adb Commands

The table below lists all of the supported adb commands and explains their meaning and usage.

Page 4 of 12Android Debug Bridge | Android Developers

9/7/2010file://V:\android-sdk-windows\docs\guide\developing\tools\adb.html

Page 52: Android Sdk Developing

Category Command Description Comments

Options -d Direct an adb command to the only attached USB device.

Returns an error if more than one USB device is attached.

-e Direct an adb command to the only running emulator instance.

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

-s <serialNumber> Direct an adb command a specific emulator/device instance, referred to by its adb-assigned serial number (such as "emulator-5556").

If not specified, adb generates an error.

General devices Prints a list of all attached emulator/device instances.

See Querying for Emulator/Device Instances for more information.

help Prints a list of supported adb commands.

version Prints the adb version number.

Debug logcat [<option>] [<filter-specs>]

Prints log data to the screen.

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

jdwp Prints a list of available JDWP processes on a given device.

You can use the forward jdwp:<pid> port-forwarding specification to connect to a specific JDWP process. For example: adb forward tcp:8000 jdwp:472 jdb -attach localhost:8000

Data install <path-to-apk> Pushes an Android application (specified as a full path to an .apk file) to the data file of an emulator/device.

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

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

Page 5 of 12Android Debug Bridge | Android Developers

9/7/2010file://V:\android-sdk-windows\docs\guide\developing\tools\adb.html

Page 53: Android Sdk Developing

Ports and Networking

forward <local> <remote> Forwards socket connections from a specified local port to a specified remote port on the emulator/device instance.

Port specifications can use these schemes:

tcp:<portnum>•

local:<UNIX domain socket name>

dev:<character device name>

jdwp:<pid>•

ppp <tty> [parm]... Run PPP over USB. <tty> — the tty for PPP stream. For example dev:/dev/omap_csmi_ttyl.

[parm]... &mdash 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.

See Querying for Emulator/Device Instances for more information. get-state Prints the adb state of an

emulator/device instance.

Page 6 of 12Android Debug Bridge | Android Developers

9/7/2010file://V:\android-sdk-windows\docs\guide\developing\tools\adb.html

Page 54: Android Sdk Developing

wait-for-device Blocks execution until the device is online — that is, until the instance state is device.

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

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

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 start-server Checks whether the adb server process is running and starts it, if not.

kill-server Terminates the adb server process.

Shell shell Starts a remote shell in the target emulator/device instance.

See Issuing Shell Commands for more information.

shell [<shellCommand>] Issues a shell command in the target emulator/device instance and then exits the remote shell.

Page 7 of 12Android Debug Bridge | Android Developers

9/7/2010file://V:\android-sdk-windows\docs\guide\developing\tools\adb.html

Page 55: Android Sdk Developing

Issuing Shell Commands

Adb provides an ash shell that you can use to run a variety of commands on an emulator or device. The command binaries are stored in the file system of the emulator or device, in this location:

/system/bin/...

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

To drop into a remote shell on a emulator/device instance, use the shell command like this:

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

When you are ready to exit the remote shell, use CTRL+D or exit to end the shell session.

The sections below provide more information about shell commands that you can use.

Examining sqlite3 Databases from a Remote Shell

From an adb remote shell, you can use the sqlite3 command-line program to manage SQLite databases created by Android applications. The sqlite3 tool includes many useful commands, such as .dump to print out the contents of a table and .schema to print the SQL CREATE statement for an existing table. The tool also gives you the ability to execute SQLite commands on the fly.

To use sqlite3, enter a remote shell on the emulator instance, as described above, then invoke the tool using the sqlite3 command. Optionally, when invoking sqlite3 you can specify the full path to the database you want to explore. Emulator/device instances store SQLite3 databases in the folder /data/data/<package_name>/databases/.

Here's an example:

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

Once you've invoked sqlite3, you can issue sqlite3 commands in the shell. To exit and return to the adb remote shell, use exit or CTRL+D.

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.

Page 8 of 12Android Debug Bridge | Android Developers

9/7/2010file://V:\android-sdk-windows\docs\guide\developing\tools\adb.html

Page 56: Android Sdk Developing

The simplest way to use the monkey is with the following command, which will launch your application and send 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

The table below lists several of the adb shell commands available. For a complete list of commands and programs, start an emulator instance and use the adb -help command.

adb shell ls /system/bin

Help is available for most of the commands.

Shell Command Description Comments

dumpsys Dumps system data to the screen.

The Dalvik Debug Monitor Service (DDMS) tool offers integrated debug environment that you may find easier to use.dumpstate Dumps state to a file.

logcat [<option>]... [<filter-spec>]...

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

Using logcat Commands

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

The sections below explain filter specifications and the command options. See Listing of logcat Command Options for a summary of options.

Page 9 of 12Android Debug Bridge | Android Developers

9/7/2010file://V:\android-sdk-windows\docs\guide\developing\tools\adb.html

Page 57: Android Sdk Developing

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

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

V — Verbose (lowest priority)◦

D — Debug◦

I — Info◦

W — Warning◦

E — Error◦

F — Fatal◦

S — Silent (highest priority, on which nothing is ever printed)◦

You can obtain a list of tags used in the system, together with priorities, by running logcat and observing the first two columns of each message, given as <priority>/<tag>.

Here's an example of logcat output that shows that the message relates to priority level "I" and tag "ActivityManager":

I/ActivityManager( 585): Starting activity: Intent { action=android.intent.action...}

To reduce the log output to a manageable level, you can restrict log output using filter expressions. Filter expressions let you indicate to the system the tags-priority combinations that you are interested in — the system suppresses other messages for the specified tags.

A filter expression follows this format tag:priority ..., where tag indicates the tag of interest and priority indicates the minimum level of priority to report for that tag. Messages for that tag at or above the specified priority are written to the log. You can supply any number of tag:priority specifications in a single filter expression. The series of specifications is whitespace-delimited.

Here's an example of a filter expression that suppresses all log messages except those with the tag "ActivityManager", at priority "Info" or above, and all log messages with tag "MyApp", with priority "Debug" or above:

adb logcat ActivityManager:I MyApp:D *:S

The final element in the above expression, *:S, sets the priority level for all tags to "silent", thus ensuring only log messages with "View" and "MyApp" are displayed. Using *:S is an excellent way to ensure that log output is restricted to the filters that you have explicitly specified — it lets your filters serve as a "whitelist" for log output.

The following filter expression displays all log messages with priority level "warning" and higher, on all tags:

Page 10 of 12Android Debug Bridge | Android Developers

9/7/2010file://V:\android-sdk-windows\docs\guide\developing\tools\adb.html

Page 58: Android Sdk Developing

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 originating process (the default format).•

process — Display PID only.•

tag — Display the priority/tag only. •

thread — Display process:thread and 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 originating process.•

long — Display all metadata fields and separate messages with a blank lines.•

When starting logcat, you can specify the output format you want by using the -v option:

[adb] logcat [-v <format>]

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

adb logcat -v thread

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

Viewing Alternative Log Buffers

The Android logging system keeps multiple circular buffers for log messages, and not all of the log messages are sent to the default circular buffer. To see additional log messages, you can start logcat 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:

Page 11 of 12Android Debug Bridge | Android Developers

9/7/2010file://V:\android-sdk-windows\docs\guide\developing\tools\adb.html

Page 59: Android Sdk Developing

↑ Go to top

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.

Listing of logcat Command Options

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.

-f <filename>

Writes log message output to <filename>. The default is stdout.

-g Prints the size of the specified log buffer and exits.

-n <count> Sets the maximum number of rotated logs to <count>. The default value is 4. Requires the -r option.

-r <kbytes> Rotates the log file every <kbytes> of output. The default value is 16. Requires the -f option.

-s Sets the default filter spec to silent.

-v <format> Sets the output format for log messages. The default is brief format. For a list of supported formats, see Controlling Log Output Format.

Stopping the adb Server

In some cases, you might need to terminate the adb server process and then restart it. For example, if adb does not respond to a command, you can terminate the server and restart it and that may resolve the problem.

To stop the adb server, use the kill-server. You can then restart the server by issuing any adb command.

Except as noted, this content is licensed under Apache 2.0. For details and restrictions, see the Content License. Android 2.2 r1 - 14 May 2010 15:20 Site Terms of Service - Privacy Policy - Brand Guidelines

Page 12 of 12Android Debug Bridge | Android Developers

9/7/2010file://V:\android-sdk-windows\docs\guide\developing\tools\adb.html

Page 60: Android Sdk Developing

Other Tools

The sections below describe other tools that you can use when building Android applications.

All of the tools are included in the Android SDK and are accessible from the <sdk>/tools/ directory.

Contents

android mksdcarddx

android

android is an important development tool that lets you:

Create, delete, and view Android Virtual Devices (AVDs). See Android Virtual Devices.•

Create and update Android projects. See Developing in Other IDEs.•

Update your Android SDK with new platforms, add-ons, and documentation. See Adding SDK Components.•

If you develop in Eclipse with the ADT plugin, you can perform these tasks directly from the IDE. To create Android projects and AVDs from Eclipse, see Developing In Eclipse. To update your SDK from Eclipse, see Adding SDK Components.

mksdcard

The mksdcard tool lets you quickly create a FAT32 disk image that you can load in the emulator, to simulate the presence of an SD card in the device. Here is the usage for mksdcard:

mksdcard [-l label] <size>[K|M] <file>

The table below lists the available options/arguments

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

Page 1 of 2Other Tools | Android Developers

9/7/2010file://V:\android-sdk-windows\docs\guide\developing\tools\othertools.html

Page 61: Android Sdk Developing

↑ Go to top

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.

emulator -sdcard <file>

dx

The dx tool lets you generate Android bytecode from .class files. The tool converts target files and/or directories to Dalvik executable format (.dex) files, so that they can run in the Android environment. It can also dump the class files in a human-readable format and run a target unit test. You can get the usage and options for this tool by using dx --help.

Except as noted, this content is licensed under Apache 2.0. For details and restrictions, see the Content License. Android 2.2 r1 - 14 May 2010 15:20 Site Terms of Service - Privacy Policy - Brand Guidelines

Page 2 of 2Other Tools | Android Developers

9/7/2010file://V:\android-sdk-windows\docs\guide\developing\tools\othertools.html

Page 62: Android Sdk Developing

In this documentImplementing IPC Using AIDL

Create an .aidl File

Implementing the Interface

Exposing Your Interface to Clients

Pass by value Parameters using Parcelables

Calling an IPC Method

Designing a Remote Interface Using AIDL

Since each application runs in its own process, and you can write a service that runs in a different process from your Application's UI, sometimes you need to pass objects between processes. On the Android platform, one process can not normally access the memory of another process. So to talk, they need to decompose their objects into primitives that the operating system can understand, and "marshall" the object across that boundary for you.

The code to do that marshalling is tedious to write, so we provide the AIDL tool to do it for you.

AIDL (Android Interface Definition Language) is an IDL language used to generate code that enables two processes on an Android-powered device to talk using interprocess communication (IPC). If you have code in one process (for example, in an Activity) that needs to call methods on an object in another process (for example, a Service), you would use AIDL to generate code to marshall the parameters.

The AIDL IPC mechanism is interface-based, similar to COM or Corba, but lighter weight. It uses a proxy class to pass values between the client and the implementation.

Implementing IPC Using AIDL

Follow these steps to implement an IPC service using AIDL.

Create your .aidl file - This file defines an interface (YourInterface.aidl) that defines the methods and fields available to a client.

1.

Add the .aidl file to your makefile - (the ADT Plugin for Eclipse manages this for you). Android includes the compiler, called AIDL, in the tools/ directory.

2.

Implement your interface methods - The AIDL compiler creates an interface in the Java programming language from your AIDL interface. This interface has an inner abstract class named Stub that inherits the interface (and implements a few additional methods necessary for the IPC call). You must create a class that extends YourInterface.Stub and implements the methods you declared in your .aidl file.

3.

Expose your interface to clients - If you're writing a service, you should extend Service and override Service.onBind(Intent) to return an instance of your class that implements your interface.

4.

Create an .aidl File

AIDL is a simple syntax that lets you declare an interface with one or more methods, that can take parameters and return values. These parameters and return values can be of any type, even other AIDL-generated interfaces. However, it is important to note that you must import all non-built-in types, even if they are defined in the same package as your interface. Here are the data types that AIDL can support:

Primitive Java programming language types (int, boolean, etc) — No import statement is needed. •

One of the following classes (no import statements needed): •

String◦

Page 1 of 9Designing a Remote Interface Using AIDL | Android Developers

9/7/2010file://V:\android-sdk-windows\docs\guide\developing\tools\aidl.html

Page 63: Android Sdk Developing

List - All elements in the List must be one of the types in this list, including other AIDL-generated interfaces and parcelables. List may optionally be used as a "generic" class (e.g. List<String>). The actual concrete class that the other side will receive will always be an ArrayList, although the method will be generated to use the List interface.

Map - All elements in the Map must be of one of the types in this list, including other AIDL-generated interfaces and parcelables. Generic maps, (e.g. of the form Map<String,Integer> are not supported. The actual concrete class that the other side will receive will always be a HashMap, although the method will be generated to use the Map interface.

CharSequence - This is useful for the CharSequence types used by TextView and other widget objects. ◦

Other AIDL-generated interfaces, which are always passed by reference. An import statement is always needed for these.

Custom classes that implement the Parcelable protocol and are passed by value. An import statement is always needed for these.

Here is the basic AIDL syntax:

// My AIDL file, named SomeClass.aidl // Note that standard comment syntax is respected. // Comments before the import or package statements are not bubbled up // to the generated interface, but comments above i nterface/method/field // declarations are added to the generated interfac e. // Include your fully-qualified package statement. package com.android.sample; // See the list above for which classes need // import statements (hint--most of them) import com.android.sample.IAtmService; // Declare the interface. interface IBankAccountService { // Methods can take 0 or more parameters, and // return a value or void. int getAccountBalance(); void setOwnerNames(in List<String> names); // Methods can even take other AIDL-defined paramet ers. BankAccount createAccount(in String name, int startingDeposit, in IAtmService atmService); // All non-Java primitive parameters (e.g., int, bo ol, etc) require // a directional tag indicating which way the data will go. Available // values are in, out, inout. (Primitives are in by default, and cannot be otherwise). // Limit the direction to what is truly needed, bec ause marshalling parameters // is expensive. int getCustomerList(in String branch, out String[] customerList); }

Implementing the Interface

AIDL generates an interface file for you with the same name as your .aidl file. If you are using the Eclipse plugin, AIDL will automatically be run as part of the build process (you don't need to run AIDL first and then build your project). If you are not using the plugin, you should run AIDL first.

Page 2 of 9Designing a Remote Interface Using AIDL | Android Developers

9/7/2010file://V:\android-sdk-windows\docs\guide\developing\tools\aidl.html

Page 64: Android Sdk Developing

The generated interface includes an abstract inner class named Stub that declares all the methods that you declared in your .aidl file. Stub also defines a few helper methods, most notably asInterface(), which takes an IBinder (passed to a client's onServiceConnected() implementation when applicationContext.bindService() succeeds), and returns an instance of the interface used to call the IPC methods. See the section Calling an IPC Method for more details on how to make this cast.

To implement your interface, extend YourInterface.Stub, and implement the methods. (You can create the .aidl file and implement the stub methods without building between--the Android build process will process .aidl files before .java files.)

Here is an example of implementing an interface called IRemoteService, which exposes a single method, getPid(), using an anonymous instance:

// No need to import IRemoteService if it's in the same project. private final IRemoteService.Stub mBinder = new IRemoteService.Stub(){ public int getPid(){ return Process.myPid(); } }

A few rules about implementing your interface:

No exceptions that you throw will be sent back to the caller.•

By default, IPC calls are synchronous. If you know that an IPC service takes more than a few milliseconds to complete, you should not call it in the Activity/View thread, because it might hang the application (Android might display an "Application is Not Responding" dialog). Try to call them in a separate thread.

Only methods are supported; you cannot declare static fields in an AIDL interface.•

Exposing Your Interface to Clients

Now that you've got your interface implementation, you need to expose it to clients. This is known as "publishing your service." To publish a service, inherit Service and implement Service.onBind(Intent) to return an instance of the class that implements your interface. Here's a code snippet of a service that exposes the IRemoteService interface to clients.

public class RemoteService extends Service { ... @Override public IBinder onBind(Intent intent) { // Select the interface to return. If your service only implements // a single interface, you can just return it here without checking // the Intent. if (IRemoteService.class.getName().equals(intent.getAction())) { return mBinder; } if (ISecondary.class.getName().equals(intent.getAction())) { return mSecondaryBinder; } return null; } /** * The IRemoteInterface is defined through IDL */ private final IRemoteService.Stub mBinder = new IRemoteService.Stub() { public void registerCallback(IRemoteServiceCallback cb) { if (cb != null) mCallbacks.register(cb); } public void unregisterCallback(IRemoteServiceCallback cb) {

Page 3 of 9Designing a Remote Interface Using AIDL | Android Developers

9/7/2010file://V:\android-sdk-windows\docs\guide\developing\tools\aidl.html

Page 65: Android Sdk Developing

if (cb != null) mCallbacks.unregister(cb); } }; /** * A secondary interface to the service. */ private final ISecondary.Stub mSecondaryBinder = new ISecondary.Stub() { public int getPid() { return Process.myPid(); } public void basicTypes(int anInt, long aLong, boolean aBoolean, float aFloat, double aDouble, String aString) { } }; }

Pass by value Parameters using Parcelables

If you have a class that you would like to send from one process to another through an AIDL interface, you can do that. You must ensure that the code for your class is available to the other side of the IPC. Generally, that means that you're talking to a service that you started.

There are five parts to making a class support the Parcelable protocol:

Make your class implement the Parcelable interface.1.

Implement the method public void writeToParcel(Parcel out) that takes the current state of the object and writes it to a parcel.

2.

value in a parcel into your object. Add a static field called CREATOR to your class which is an object implementing the Parcelable.Creator interface.

3.

Last but not least, create an aidl file that declares your parcelable class (as shown below). If you are using a custom build process, do not add the aidl file to your build. Similar to a header file in C, the aidl file isn't compiled.

4.

AIDL will use these methods and fields in the code it generates to marshall and unmarshall your objects.

Here is an example of how the Rect class implements the Parcelable protocol.

import android.os.Parcel; import android.os.Parcelable; public final class Rect implements Parcelable { public int left; public int top; public int right; public int bottom; public static final Parcelable.Creator<Rect> CREATOR = new Parcelable.Creator<Rect>() { public Rect createFromParcel(Parcel in) { return new Rect(in); } public Rect[] newArray(int size) { return new Rect[size]; } };

Page 4 of 9Designing a Remote Interface Using AIDL | Android Developers

9/7/2010file://V:\android-sdk-windows\docs\guide\developing\tools\aidl.html

Page 66: Android Sdk Developing

public Rect() { } private Rect(Parcel in) { readFromParcel(in); } public void writeToParcel(Parcel out) { out.writeInt(left); out.writeInt(top); out.writeInt(right); out.writeInt(bottom); } public void readFromParcel(Parcel in) { left = in.readInt(); top = in.readInt(); right = in.readInt(); bottom = in.readInt(); } }

Here is Rect.aidl for this example

package android.graphics; // Declare Rect so AIDL can find it and knows that it implements // the parcelable protocol. parcelable Rect;

The marshalling in the Rect class is pretty simple. Take a look at the other methods on Parcel to see the other kinds of values you can write to a Parcel.

Warning: Don't forget the security implications of receiving data from other processes. In this case, the rect will read four numbers from the parcel, but it is up to you to ensure that these are within the acceptable range of values for whatever the caller is trying to do. See Security and Permissions for more on how to keep your application secure from malware.

Calling an IPC Method

Here are the steps a calling class should make to call your remote interface:

Declare a variable of the interface type that your .aidl file defined. 1.

Implement ServiceConnection. 2.

Call Context.bindService(), passing in your ServiceConnection implementation. 3.

In your implementation of ServiceConnection.onServiceConnected(), you will receive an IBinder instance (called service). Call YourInterfaceName .Stub.asInterface((IBinder)service ) to cast the returned parameter to YourInterface type.

4.

Call the methods that you defined on your interface. You should always trap DeadObjectException exceptions, which are thrown when the connection has broken; this will be the only exception thrown by remote methods.

5.

To disconnect, call Context.unbindService() with the instance of your interface. 6.

A few comments on calling an IPC service:

Page 5 of 9Designing a Remote Interface Using AIDL | Android Developers

9/7/2010file://V:\android-sdk-windows\docs\guide\developing\tools\aidl.html

Page 67: Android Sdk Developing

Objects are reference counted across processes. •

You can send anonymous objects as method arguments. •

Here is some sample code demonstrating calling an AIDL-created service, taken from the Remote Service sample in the ApiDemos project.

public static class Binding extends Activity { /** The primary interface we will be calling on the service. */ IRemoteService mService = null; /** Another interface we use on the service. */ ISecondary mSecondaryService = null; Button mKillButton; TextView mCallbackText; private boolean mIsBound; /** * Standard initialization of this activity. S et up the UI, then wait * for the user to poke it before doing anythin g. */ @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.remote_service_binding); // Watch for button clicks. Button button = (Button)findViewById(R.id.bind); button.setOnClickListener(mBindListener); button = (Button)findViewById(R.id.unbind); button.setOnClickListener(mUnbindListener); mKillButton = (Button)findViewById(R.id.kill); mKillButton.setOnClickListener(mKillListener); mKillButton.setEnabled(false); mCallbackText = (TextView)findViewById(R.id.callback); mCallbackText.setText("Not attached."); } /** * Class for interacting with the main interfac e of the service. */ private ServiceConnection mConnection = new ServiceConnection() { public void onServiceConnected(ComponentName className, IBinder service) { // This is called when the connection with the serv ice has been // established, giving us the service object we can use to // interact with the service. We are communicating with our // service through an IDL interface, so get a clien t-side // representation of that from the raw service obje ct. mService = IRemoteService.Stub.asInterface(service); mKillButton.setEnabled(true); mCallbackText.setText("Attached."); // We want to monitor the service for as long as we are // connected to it. try { mService.registerCallback(mCallback); } catch (RemoteException e) { // In this case the service has crashed before we c ould even // do anything with it; we can count on soon being

Page 6 of 9Designing a Remote Interface Using AIDL | Android Developers

9/7/2010file://V:\android-sdk-windows\docs\guide\developing\tools\aidl.html

Page 68: Android Sdk Developing

// disconnected (and then reconnected if it can be restarted) // so there is no need to do anything here. } // As part of the sample, tell the user what happen ed. Toast.makeText(Binding.this, R.string.remote_service_connected, Toast.LENGTH_SHORT).show(); } public void onServiceDisconnected(ComponentName className) { // This is called when the connection with the serv ice has been // unexpectedly disconnected -- that is, its proces s crashed. mService = null; mKillButton.setEnabled(false); mCallbackText.setText("Disconnected."); // As part of the sample, tell the user what happen ed. Toast.makeText(Binding.this, R.string.remote_service_disconnected, Toast.LENGTH_SHORT).show(); } }; /** * Class for interacting with the secondary int erface of the service. */ private ServiceConnection mSecondaryConnection = new ServiceConnection() { public void onServiceConnected(ComponentName className, IBinder service) { // Connecting to a secondary interface is the same as any // other interface. mSecondaryService = ISecondary.Stub.asInterface(service); mKillButton.setEnabled(true); } public void onServiceDisconnected(ComponentName className) { mSecondaryService = null; mKillButton.setEnabled(false); } }; private OnClickListener mBindListener = new OnClickListener() { public void onClick(View v) { // Establish a couple connections with the service, binding // by interface names. This allows other applicati ons to be // installed that replace the remote service by imp lementing // the same interface. bindService(new Intent(IRemoteService.class.getName()), mConnection, Context.BIND_AUTO_CREATE); bindService(new Intent(ISecondary.class.getName()), mSecondaryConnection, Context.BIND_AUTO_CREATE); mIsBound = true; mCallbackText.setText("Binding."); } }; private OnClickListener mUnbindListener = new OnClickListener() { public void onClick(View v) { if (mIsBound) { // If we have received the service, and hence regis tered with // it, then now is the time to unregister. if (mService != null) { try { mService.unregisterCallback(mCallback); } catch (RemoteException e) {

Page 7 of 9Designing a Remote Interface Using AIDL | Android Developers

9/7/2010file://V:\android-sdk-windows\docs\guide\developing\tools\aidl.html

Page 69: Android Sdk Developing

// There is nothing special we need to do if the se rvice // has crashed. } } // Detach our existing connection. unbindService(mConnection); unbindService(mSecondaryConnection); mKillButton.setEnabled(false); mIsBound = false; mCallbackText.setText("Unbinding."); } } }; private OnClickListener mKillListener = new OnClickListener() { public void onClick(View v) { // To kill the process hosting our service, we need to know its // PID. Conveniently our service has a call that w ill return // to us that information. if (mSecondaryService != null) { try { int pid = mSecondaryService.getPid(); // Note that, though this API allows us to request to // kill any process based on its PID, the kernel wi ll // still impose standard restrictions on which PIDs you // are actually able to kill. Typically this means only // the process running your application and any add itional // processes created by that app as shown here; pac kages // sharing a common UID will also be able to kill e ach // other's processes. Process.killProcess(pid); mCallbackText.setText("Killed service process."); } catch (RemoteException ex) { // Recover gracefully from the process hosting the // server dying. // Just for purposes of the sample, put up a notifi cation. Toast.makeText(Binding.this, R.string.remote_call_failed, Toast.LENGTH_SHORT).show(); } } } }; // ------------------------------------------------ ---------------------- // Code showing how to deal with callbacks. // ------------------------------------------------ ---------------------- /** * This implementation is used to receive callb acks from the remote * service. */ private IRemoteServiceCallback mCallback = new IRemoteServiceCallback.Stub() { /** * This is called by the remote service reg ularly to tell us about * new values. Note that IPC calls are dis patched through a thread * pool running in each process, so the cod e executing here will * NOT be running in our main thread like m ost other things -- so, * to update the UI, we need to use a Handl er to hop over there. */ public void valueChanged(int value) { mHandler.sendMessage(mHandler.obtainMessage(BUMP_MSG, value, 0)); }

Page 8 of 9Designing a Remote Interface Using AIDL | Android Developers

9/7/2010file://V:\android-sdk-windows\docs\guide\developing\tools\aidl.html

Page 70: Android Sdk Developing

↑ Go to top

}; private static final int BUMP_MSG = 1; private Handler mHandler = new Handler() { @Override public void handleMessage(Message msg) { switch (msg.what) { case BUMP_MSG: mCallbackText.setText("Received from service: " + msg.arg1); break; default: super.handleMessage(msg); } } }; }

Except as noted, this content is licensed under Apache 2.0. For details and restrictions, see the Content License. Android 2.2 r1 - 14 May 2010 15:20 Site Terms of Service - Privacy Policy - Brand Guidelines

Page 9 of 9Designing a Remote Interface Using AIDL | Android Developers

9/7/2010file://V:\android-sdk-windows\docs\guide\developing\tools\aidl.html

Page 71: Android Sdk Developing

AVD quickviewYou need to create an AVD to run any app in the Android emulator

Each AVD is a completely independent virtual device, with its own hardware options, system image, and data storage.

You create AVD configurations to model different device environments in the Android emulator.

The android tool offers a graphical Android AVD Manager and a command-line interface for creating AVDs.

In this documentCreating an AVD

Listing targets

Selecting a target

Creating the AVD

Setting hardware emulation options

Default location of the AVD files

Managing AVDs

Moving an AVD

Updating an AVD

Deleting an AVD

Command-line options

See AlsoAndroid Emulator

The Android SDK does not include any preconfigured AVDs, so you need to create an AVD before you can

Android Virtual Devices

Android Virtual Devices (AVDs) are configurations of emulator options that let you better model an actual device.

Each AVD is made up of:

A hardware profile. You can set options to define 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, in which is stored the device's user data (installed applications, settings, and so on) and emulated SD card.

You can create as many AVDs as you need, based on the types of devices you want to model and the Android platforms and external libraries you want to run your application on.

In addition to the options in an AVD configuration, you can also specify emulator command-line options at launch or by using the emulator console to change behaviors or characteristics at run time. For a complete reference of emulator options, please see the Emulator documentation.

To create and manage AVDs, you use the android tool provided in the tools/ directory of the Android SDK. The tool provides both a graphical AVD manager and a command-line interface that you can use to create AVDs. To access the graphical AVD manager, run the android tool without options. The sections below describe how to use the android command-line interface to create and manage AVDs. Note that some functionality, such as the capability to create an AVD with a custom hardware configuration, are only available through the command-line interface.

For more information about how to work with AVDs from inside your development environment, see Developing in Eclipse with ADT or Developing in Other IDEs, as appropriate for your environment.

Creating an AVD

To create an AVD, you use the android tool, a command-line utility available in the <sdk>/tools/ directory. Managing AVDs is one of the two main function of the

Page 1 of 6Android Virtual Devices | Android Developers

9/7/2010file://V:\android-sdk-windows\docs\guide\developing\tools\avd.html

Page 72: Android Sdk Developing

run any application in the emulator (even the Hello World application).

android tool (the other is creating and updating Android projects). 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 to create an emulated SD card for the new AVD, set the emulator skin to use, or set a custom location for the AVD's 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.

As shown in the usage above, you must use the -t (or --target ) argument when creating a new AVD. The argument sets up a mapping between the AVD and the system image that you want to use whenever the AVD is invoked. You can specify any Android system image that is available in your local SDK — it can be the system image of a standard Android platform version or that of any SDK add-on. Later, when applications use the AVD, they'll be running on the system that you specify in the -t argument.

To specify the system image to use, you refer to its target ID — an integer — as 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 have the android tool list the available system images and the target ID of each, as described in the next section. You should do this before you run the android create avd command.

Listing targets

To generate a list of system image targets, use this command:

android list targets

The android tool scans the <sdk>/platforms and <sdk>/add-ons directories looking for valid system images and then generates the list of targets. Here's an example of the command output:

Available Android targets : id : 1 Name: Android 1.1 Type: platform API level : 2 Skins: HVGA ( default), HVGA- L, HVGA- P, QVGA- L, QVGA- P id : 2 Name: Android 1.5 Type: platform API level : 3 Skins: HVGA ( default), HVGA- L, HVGA- P, QVGA- L, QVGA- P id : 3 Name: Google APIs Type: add - on Vendor: Google Inc. Description: Android + Google APIs Based on Android 1.5 ( API level 3) Libraries: * com . google . android . maps ( maps. jar ) API for Google Maps Skins: HVGA ( default), HVGA- L, QVGA- P, HVGA- P, QVGA- L

Page 2 of 6Android Virtual Devices | Android Developers

9/7/2010file://V:\android-sdk-windows\docs\guide\developing\tools\avd.html

Page 73: Android Sdk Developing

Selecting a target

Once you have generated the list of targets available, you can look at the characteristics of each system image — name, API Level, external libraries, and so on — and determine which target is appropriate for the new AVD.

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.

Creating at least one AVD that uses a target whose API Level is greater than that required by your application is strongly encouraged, 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 your application to run on the AVD you are creating, check the application's uses-library element and select a system image target that includes that library.

Creating the AVD

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.

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.

For a list of options you can use in the android create avd command, see the table in Command-line options for AVDs, at the bottom of this page.

Setting hardware emulation options

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

Page 3 of 6Android Virtual Devices | Android Developers

9/7/2010file://V:\android-sdk-windows\docs\guide\developing\tools\avd.html

Page 74: Android Sdk Developing

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 the device. Default value is "yes".

hw.touchScreen

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

Default value is "640". 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. Default value is "yes".

hw.battery

Accelerometer Whether there is an accelerometer in the device. Default value is "yes".

hw.accelerometer

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 device. Default value is "yes".

disk.cachePartition

Cache partition size Default value is "66MB". disk.cachePartition.size

Abstracted LCD density Sets the generalized density characteristic used by the AVD's screen. Default value is "160".

hw.lcd.density

Default location of the 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 a <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.

Page 4 of 6Android Virtual Devices | Android Developers

9/7/2010file://V:\android-sdk-windows\docs\guide\developing\tools\avd.html

Page 75: Android Sdk Developing

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

Managing AVDs

The sections below provide more information about how to manage AVDs once you've created them.

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

The options for this command are listed in Command-line options for AVDs at the bottom of this page.

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.

Command-line options for AVDs

The table below lists the command-line options you can use with the android tool.

Page 5 of 6Android Virtual Devices | Android Developers

9/7/2010file://V:\android-sdk-windows\docs\guide\developing\tools\avd.html

Page 76: Android Sdk Developing

↑ Go to top

Action Option Description Comments

list avds List all known AVDs, with name, path, target, and skin.

create avd -n <name> or The name for the AVD. Required

-t <targetID> Target ID of the system image to use with the new AVD.

Required. To obtain a list of available targets, use android list targets .

-c <path> or -c <size>[K|M]

The path to the SD card image to use with this AVD or the size of a new SD card image to create for this AVD.

Examples: -c path/to/sdcard or -c 1000M

-f Force creation of the AVD By default, if the name of the AVD being created matches that of an existing AVD, the android tool will not create the new AVD or overwrite the existing AVD. If you specify the -f option, however, the android tool will automatically overwrite any existing AVD that has the same name as the new AVD. The files and data of the existing AVD are deleted.

-p <path> Path to the location at which to create the directory for this AVD's files.

-s <name> or -s <width>-<height>

The skin to use for this 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. Example: -s HVGA-L

delete avd -n <name> Delete the specified AVD. Required

move avd -n <name> The name of the AVD to move. Required

-p <path> The path to the new location for the AVD.

-r <new-name> Rename the AVD.

update avds Recompute the paths to all system images.

Except as noted, this content is licensed under Apache 2.0. For details and restrictions, see the Content License. Android 2.2 r1 - 14 May 2010 15:20 Site Terms of Service - Privacy Policy - Brand Guidelines

Page 6 of 6Android Virtual Devices | Android Developers

9/7/2010file://V:\android-sdk-windows\docs\guide\developing\tools\avd.html

Page 77: Android Sdk Developing

bmgr quickview

bmgr lets you control the backup/restore system on an Android device.

In this documentForcing a Backup Operation

Forcing a Restore Operation

Other Commands

bmgr

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.

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:

Page 1 of 2bmgr | Android Developers

9/7/2010file://V:\android-sdk-windows\docs\guide\developing\tools\bmgr.html

Page 78: Android Sdk Developing

↑ Go to top

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 application's backup agent and invoke it for restore. This will happen even if your application is not currently running.

Other Commands

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.

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

Except as noted, this content is licensed under Apache 2.0. For details and restrictions, see the Content License. Android 2.2 r1 - 14 May 2010 15:20 Site Terms of Service - Privacy Policy - Brand Guidelines

Page 2 of 2bmgr | Android Developers

9/7/2010file://V:\android-sdk-windows\docs\guide\developing\tools\bmgr.html

Page 79: Android Sdk Developing

Using the Dalvik Debug Monitor

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.

DDMS ships in the tools/ directory of the SDK. Enter this directory from a terminal/console and type ddms (or ./ddms on Mac/Linux) to run it. DDMS will work with both the emulator and a connected device. If both are connected and running simultaneously, DDMS defaults to the emulator.

How DDMS works

DDMS acts as a middleman to connect the IDE to the applications running on the device. On Android, every application runs in its own process, each of which hosts its own virtual machine (VM). And each process listens for a debugger on a different port.

When it starts, DDMS connects to adb and starts a device monitoring service between the two, which will notify DDMS when a device is connected or disconnected. When a device is connected, a VM monitoring service is created between adb and DDMS, which will notify DDMS when a VM on the device is started or terminated. Once a VM is running, DDMS retrieves the 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.

For each VM on the device, DDMS opens a port upon which it will listen for a debugger. For the first VM, DDMS listens for a debugger on port 8600, the next on 8601, and so on. When a debugger connects to one of these ports, all traffic is forwarded between the debugger and the associated VM. Debugging can then process like any remote debugging session.

DDMS also opens another local port, the DDMS "base port" (8700, by default), upon which it also listens for a debugger. When a debugger connects to this base port, all traffic is forwarded to the VM currently selected in DDMS, so this is typically where you debugger should connect.

For more information on port-forwarding with DDMS, read Configuring your IDE to attach to port 8700 for debugging.

Tip: You can set a number of DDMS preferences in File > Preferences. Preferences are saved to "$HOME/.ddmsrc".

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.

Left Pane

The left side of the Debug Monitor shows each emulator/device currently found, with a list of all the VMs currently running within each. VMs are identified by the package name of the application it hosts.

Page 1 of 5Using the Dalvik Debug Monitor | Android Developers

9/7/2010file://V:\android-sdk-windows\docs\guide\developing\tools\ddms.html

Page 80: Android Sdk Developing

Use this list to find and attach to the VM running the activity(ies) that you want to debug. Next to each VM in the list is a "debugger pass-through" port (in the right-most column). If you connect your debugger to one of the the ports listed, you will be connected to the corresponding VM on the device. However, when using DDMS, you need only connect to port 8700, as DDMS forwards all traffic here to the currently selected VM. (Notice, as you select a VM in the list, the listed port includes 8700.) This way, there's no need to reconfigure the debugger's port each time you switch between VMs.

When an application running on the device calls waitForDebugger() (or you select this option in the developer options), a red icon will be shown next to the client name, while it waits for the debugger to attach to the VM. When a debugger is connected, the icon will turn green.

If you see a crossed-out bug icon, this means that the DDMS was unable to complete a connection between the debugger and the VM because it was unable to open the VM's local port. If you see this for all VMs on the device, it is likely because you have another instance of DDMS running (this includes the Eclipse plugin).

If you see a question mark in place of an application package, this means that, once DDMS received the application pid from adb, it somehow failed to make a successful handshake with the VM process. Try restarting DDMS.

Right pane

On the right side, the Debug Monitor provides tabs that display useful information and some pretty cool tools.

Info

This view shows some general information about the selected VM, including the process ID, package name, and VM version.

Threads

The threads view has a list of threads running in the process of the target VM. To reduce the amount of data sent over the wire, the thread updates are only sent when explicitly enabled by toggling the "threads" button in the toolbar. This toggle is maintained per VM. This tab includes the following information:

ID - a VM-assigned unique thread ID. In Dalvik, these are odd numbers starting from 3. •

Tid - the Linux thread ID. For the main thread in a process, this will match the process ID. •

Status - the VM thread status. Daemon threads are shown with an asterisk (*). This will be one of the following: •

running - executing application code ◦

sleeping - called Thread.sleep() ◦

monitor - waiting to acquire a monitor lock ◦

wait - in Object.wait() ◦

native - executing native code ◦

vmwait - waiting on a VM resource ◦

zombie - thread is in the process of dying ◦

init - thread is initializing (you shouldn't see this) ◦

starting - thread is about to start (you shouldn't see this either) ◦

utime - cumulative time spent executing user code, in "jiffies" (usually 10ms). •

stime - cumulative time spent executing system code, in "jiffies" (usually 10ms). •

Name - the name of the thread•

Page 2 of 5Using the Dalvik Debug Monitor | Android Developers

9/7/2010file://V:\android-sdk-windows\docs\guide\developing\tools\ddms.html

Page 81: Android Sdk Developing

"ID" and "Name" are set when the thread is started. The remaining fields are updated periodically (default is every 4 seconds).

VM Heap

Displays some heap stats, updated during garbage collection. If, when a VM is selected, the VM Heap view says that heap updates are not enabled, click the "Show heap updates" button, located in the top-left toolbar. Back in the VM Heap view, click Cause GC to perform garbage collection and update the heap stats.

Allocation Tracker

In this view, you can track the memory allocation of each virtual machine. With a VM selected in the left pane, click Start Tracking, then Get Allocations to view all allocations since tracking started. The table below will be filled with all the relevant data. Click it again to refresh the list.

Emulator Control

With these controls, you can simulate special device states and activities. Features include:

Telephony Status - change the state of the phone's Voice and Data plans (home, roaming, searching, etc.), and simulate different kinds of network Speed and Latency (GPRS, EDGE, UTMS, etc.).

Telephony Actions - perform simulated phone calls and SMS messages to the emulator.•

Location Controls - send mock location data to the emulator so that you can perform location-aware operations like GPS mapping.

To use the Location Controls, launch your application in the Android emulator and open DDMS. Click the Emulator Controls tab and scroll down to Location Controls. From here, you can:

Manually send individual longitude/latitude coordinates to the device. ◦

Click Manual, select the coordinate format, fill in the fields and click Send.

Use a GPX file describing a route for playback to the device. ◦

Click GPX and load the file. Once loaded, click the play button to playback the route for your location-aware application.

When performing playback from GPX, you can adjust the speed of playback from the DDMS panel and control playback with the pause and skip buttons. DDMS will parse both the waypoints (<wpt>, in the first table), and the tracks (<trk>, in the second table, with support for multiple segments, <trkseg>, although they are simply concatenated). Only the tracks can be played. Clicking a waypoint in the first list simply sends its coordinate to the device, while selecting a track lets you play it.

Use a KML file describing individual placemarks for sequenced playback to the device. ◦

Click KML and load the file. Once loaded, click the play button to send the coordinates to your location-aware application.

When using a KML file, it is parsed for a <coordinates> element. The value of which should be a single set of longitude, latitude and altitude figures. For example:

<coordinates>-122.084143,37.421972,4</coordinates>

In your file, you may include multiple <Placemark> elements, each containing a <coordinates> element. When you do so, the collection of placemarks will be added as tracks. DDMS will send one placemark per second to the device.

One way to generate a suitable KML file is to find a location in Google Earth. Right-click the location entry that appears on the left and select "Save place as..." with the save format set to Kml.

Page 3 of 5Using the Dalvik Debug Monitor | Android Developers

9/7/2010file://V:\android-sdk-windows\docs\guide\developing\tools\ddms.html

Page 82: Android Sdk Developing

Note: DDMS does not support routes created with the <MultiGeometry><LineString>lat1, long1, lat2, long2, ....</LineString></MultiGeometry> methods. There is also currently no support for the <TimeStamp> node inside the <Placemark>. Future releases may support timed placement and routes within a single coordinate element.

For additional methods of setting up mocks of location-based data, see the Location topic.

File Explorer

With the File Explorer, you can view the device file system and perform basic management, like pushing and pulling files. This circumvents using the adb push and pull commands, with a GUI experience.

With DDMS open, select Device > File Explorer... to open the File Explorer window. You can drag-and-drop into the device directories, but cannot drag out of them. To copy files from the device, select the file and click the Pull File from Device button in the toolbar. To delete files, use the Delete button in the toolbar.

If you're interested in using an SD card image on the emulator, you're still required to use the mksdcard command to create an image, and then mount it during emulator bootup. For example, from the /tools directory, execute:

$ mksdcard 1024M ./img $ emulator -sdcard ./img

Now, when the emulator is running, the DDMS File Explorer will be able to read and write to the sdcard directory. However, your files may not appear automatically. For example, if you add an MP3 file to the sdcard, the media player won't see them until you restart the emulator. (When restarting the emulator from command line, be sure to mount the sdcard again.)

For more information on creating an SD card image, see the Other Tools document.

Screen Capture

You can capture screen images on the device or emulator by selecting Device > Screen capture... in the menu bar, or press CTRL-S. Be sure to select a device first.

Exploring Processes

You can see the output of ps -x for a specific VM by selecting Device > Show process status... in the menu bar.

Cause a GC to Occur

Cause garbage collection to occur in the selected application by pressing the trash can button on the toolbar.

Page 4 of 5Using the Dalvik Debug Monitor | Android Developers

9/7/2010file://V:\android-sdk-windows\docs\guide\developing\tools\ddms.html

Page 83: Android Sdk Developing

↑ Go to top

Running Dumpsys and Dumpstate on the Device (logcat)

To run dumpsys (logcat) from Dalvik, select Device > Run logcat... in the menu bar.•

To run dumpstate from Dalvik, select Device > Dump device state... in the menu bar. •

Examine Radio State

By default, radio state is not output during a standard logcat (it is a lot of information). To see radio information, either click Device > Dump radio state... or run logcat as described in Logging Radio Information.

Stop a Virtual Machine

You can stop a virtual machine by selecting Actions > Halt VM. Pressing this button causes the VM to call Runtime.halt(1).

Known issues with DDMS

DDMS has the following known limitations:

If you connect and disconnect a debugger, ddms drops and reconnects the client so the VM realizes that the debugger has gone away. This will be fixed eventually.

Except as noted, this content is licensed under Apache 2.0. For details and restrictions, see the Content License. Android 2.2 r1 - 14 May 2010 15:20 Site Terms of Service - Privacy Policy - Brand Guidelines

Page 5 of 5Using the Dalvik Debug Monitor | Android Developers

9/7/2010file://V:\android-sdk-windows\docs\guide\developing\tools\ddms.html

Page 84: Android Sdk Developing

Other Tools

The sections below describe other tools that you can use when building Android applications.

All of the tools are included in the Android SDK and are accessible from the <sdk>/tools/ directory.

Contents

android mksdcarddx

android

android is an important development tool that lets you:

Create, delete, and view Android Virtual Devices (AVDs). See Android Virtual Devices.•

Create and update Android projects. See Developing in Other IDEs.•

Update your Android SDK with new platforms, add-ons, and documentation. See Adding SDK Components.•

If you develop in Eclipse with the ADT plugin, you can perform these tasks directly from the IDE. To create Android projects and AVDs from Eclipse, see Developing In Eclipse. To update your SDK from Eclipse, see Adding SDK Components.

mksdcard

The mksdcard tool lets you quickly create a FAT32 disk image that you can load in the emulator, to simulate the presence of an SD card in the device. Here is the usage for mksdcard:

mksdcard [-l label] <size>[K|M] <file>

The table below lists the available options/arguments

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

Page 1 of 2Other Tools | Android Developers

9/7/2010file://V:\android-sdk-windows\docs\guide\developing\tools\othertools.html

Page 85: Android Sdk Developing

↑ Go to top

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.

emulator -sdcard <file>

dx

The dx tool lets you generate Android bytecode from .class files. The tool converts target files and/or directories to Dalvik executable format (.dex) files, so that they can run in the Android environment. It can also dump the class files in a human-readable format and run a target unit test. You can get the usage and options for this tool by using dx --help.

Except as noted, this content is licensed under Apache 2.0. For details and restrictions, see the Content License. Android 2.2 r1 - 14 May 2010 15:20 Site Terms of Service - Privacy Policy - Brand Guidelines

Page 2 of 2Other Tools | Android Developers

9/7/2010file://V:\android-sdk-windows\docs\guide\developing\tools\othertools.html

Page 86: Android Sdk Developing

↑ Go to top

Draw 9-patch

The Draw 9-patch tool allows you to easily create a NinePatch graphic using a WYSIWYG editor.

For an introduction to Nine-patch graphics and how they work, please read the section on Nine-patch in the Nine-patch Images topic.

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.

1.

Drag your PNG image into the Draw 9-patch window (or File > Open 9-patch... to locate the file). Your workspace will now open.

2.

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.

3.

When done, select File > Save 9-patch... 4.

Your image will be saved with the .9.png file name.

Note: A normal PNG file (*.png) will be loaded with an empty one-pixel border added around the image, in which you can draw the stretchable patches and content area. A previously saved 9-patch file (*.9.png) will be loaded as-is, with no drawing area added, because it already exists.

Optional controls include:

Zoom: Adjust the zoom level of the graphic in the drawing area.•

Patch scale: Adjust the scale of the images in the preview area.•

Show lock: Visualize the non-drawable area of the graphic on mouse-over.•

Show patches: Preview the stretchable patches in the drawing area (pink is a stretchable patch).•

Show content: Highlight the content area in the preview images (purple is the area in which content is allowed).•

Show bad patches: Adds a red border around patch areas that may produce artifacts in the graphic when stretched. Visual coherence of your stretched image will be maintained if you eliminate all bad patches.

Except as noted, this content is licensed under Apache 2.0. For details and restrictions, see the Content License. Android 2.2 r1 - 14 May 2010 15:20 Site Terms of Service - Privacy Policy - Brand Guidelines

Page 1 of 2Draw 9-patch | Android Developers

9/7/2010file://V:\android-sdk-windows\docs\guide\developing\tools\draw9patch.html

Page 87: Android Sdk Developing

Page 2 of 2Draw 9-patch | Android Developers

9/7/2010file://V:\android-sdk-windows\docs\guide\developing\tools\draw9patch.html

Page 88: Android Sdk Developing

Image of the Android Emulator

Android Emulator

The Android SDK includes a mobile device emulator -- a virtual mobile device 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 can not receive or 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 Android applications running.

To let you model and test your application more easily, the emulator supports Android Virtual Device (AVD) configurations. AVDs let you specify the Android platform that you want to run on the emulator, as well as the hardware options and emulator skin files tht you want to use. Once your application is running on the emulator, it can use the services of the Android platform to invoke other applications, access the network, play audio and video, store and retrieve data, notify the user, and render graphical transitions and themes.

The emulator also includes a variety of debug capabilities, such as a console from which you can log kernel output, simulate application interrupts (such as arriving SMS messages or phone calls), and simulate latency effects and dropouts on the data channel.

Page 1 of 25Android Emulator | Android Developers

9/7/2010file://V:\android-sdk-windows\docs\guide\developing\tools\emulator.html

Page 89: Android Sdk Developing

In this document:

Overview

Starting and Stopping the Emulator

Android Virtual Devices and the Emulator

Controlling the Emulator

Emulator Startup Options

Working with Emulator Disk Images Default ImagesRuntime Images: User Data and SD CardTemporary Images

Emulator Networking Network Address SpaceLocal Networking LimitationsUsing Network RedirectionsConfiguring the Emulator's DNS SettingsUsing the Emulator with a ProxyInterconnecting Emulator InstancesSending a Voice Call or SMS to Another Emulator Instance

Using the Emulator Console Port RedirectionsGeo Location Provider EmulationSending EventsEmulating Device Power CharacteristicsNetwork StatusNetwork Delay EmulationNetwork Speed EmulationTelephony EmulationSMS EmulationVM StateEmulator WindowTerminating an Emulator Instance

Using Emulator Skins

Running Multiple Instances of the Emulator

Installing Applications on the Emulator

SD Card Emulation Creating an SD card image using the android toolCreating an SD card image using mksdcardCopying Files to a Disk ImageLoading the Disk Image at Emulator Startup

Troubleshooting Emulator Problems

Emulator Limitations

Overview

The Android emulator is a QEMU-based application that provides a virtual ARM 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 the its behaviors.

The Android system image distributed in the SDK contains ARM machine code for the Android Linux kernel, the native libraries, the Dalvik VM, and the various Android package files (such as for for the Android framework and preinstalled applications). The emulator's QEMU layers provide dynamic binary translation of the ARM machine code to the OS and processor architecture of your development machine.

Adding custom capabilities to the underlying QEMU services, 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•

The sections below provide more information about the emulator and how to use it for developing Android applications.

Page 2 of 25Android Emulator | Android Developers

9/7/2010file://V:\android-sdk-windows\docs\guide\developing\tools\emulator.html

Page 90: Android Sdk Developing

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 use it as part of 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 redirections that allow 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, change to the tools/ folder of the SDK. Enter emulator command like this:

emulator -avd <avd_name>

This initializes the emulator and loads an AVD configuration (see the next section for more information about AVDs). You will see the emulator window appear on your screen.

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.

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.

To specify the AVD you want to load when starting the emulator, you use the -avd argument, as shown in the previous section.

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 android tool, a command-line utility included in the SDK. For complete information about how to set up AVDs, see Android Virtual Devices.

Controlling the Emulator

You can use emulator startup options and console commands to control the behaviors and characteristics of the emulated environment itself.

Page 3 of 25Android Emulator | Android Developers

9/7/2010file://V:\android-sdk-windows\docs\guide\developing\tools\emulator.html

Page 91: Android Sdk Developing

When the emulator is running, you can interact with the emulated mobile device just as you would an actual mobile device, except that you use your mouse pointer to "touch" the touchscreen and your keyboard keys to "press" the simulated device keys.

The table below summarizes the mappings between the emulator keys and and the keys of your keyboard.

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

Audio volume down button KEYPAD_MINUS, Ctrl-F6

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

Note that, to use keypad keys, you must first disable NumLock on your development computer.

Emulator Startup Options

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 usage for launching the emulator with options:

emulator -avd <avd_name> [-<option> [<value>]] ... [-<qemu args>]

Page 4 of 25Android Emulator | Android Developers

9/7/2010file://V:\android-sdk-windows\docs\guide\developing\tools\emulator.html

Page 92: Android Sdk Developing

The table below summarizes the available options.

Page 5 of 25Android Emulator | Android Developers

9/7/2010file://V:\android-sdk-windows\docs\guide\developing\tools\emulator.html

Page 93: Android Sdk Developing

Category Option Description Comments

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

-help-debug-tags Print a list of all tags for -debug <tags>.

-help-disk-images Print help for using emulator disk images.

-help-environment Print help for emulator environment variables.

-help-keys Print the current mapping of keys.

-help-keyset-file Print help for defining a custom key mappings file.

-help-virtual-device

Print help for Android Virtual Device usage.

AVD -avd <avd_name> or @<avd_name>

Required . Specifies the AVD to load for this emulator instance.

You must create an AVD configuration before launching the emulator. For information, see Android Virtual

Disk Images

-cache <filepath> Use <filepath> as the working cache partition image.

Optionally, you can specify a path relative to the currentworking directory. If no cache file is specified, the emulator's default behavior is to use a temporary file instead. For more information on disk images, useimages.

-data <filepath> Use <filepath> as the working user-data disk image.

Optionally, you can specify a path relative to the current working directory. If -data is not used, the emulator looks for a file named "userdata-qemu.img" in the storage area of the AVD being used (see -avd).

-initdata <filepath>

When resetting the user-data image (through -wipe-data), copy the contents of this file to the new user-data disk image. By default, the emulator copies the <system>/userdata.img.

Optionally, you can specify a path relative to the current working directory. See also -wipe-dataFor more information on disk images, useimages.

-nocache Start the emulator without a cache partition.

See also -cache <file>.

-ramdisk <filepath> Use <filepath> as the ramdisk image.

Default value is <system>/ramdisk.imgOptionally, you can specify a path relative to the current working directory. For more information onuse -help-disk-images.

Page 6 of 25Android Emulator | Android Developers

9/7/2010file://V:\android-sdk-windows\docs\guide\developing\tools\emulator.html

Page 94: Android Sdk Developing

-sdcard <filepath> Use <file> as the SD card image.

Default value is <system>/sdcard.imgOptionally, you can specify a path relative to the current working directory. For more information onuse -help-disk-images.

-wipe-data Reset the current user-data disk image (that is, the file specified by -datadir and -data, or the default file). The emulator deletes all data from the user data image file, then copies the contents of the file at -inidata data to the image file before starting.

See also -initdata. For more information on disk images, useimages.

Debug -debug <tags> Enable/disable debug messages for the specified debug tags.

<tags> is a space/comma/column-separated list of debug component names. Use -help-debug-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-<tag> Disable debug 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 Ctrlstops the emulator instead of the shell.

-shell-serial <device>

Enable the root shell (as in -shell and specify the QEMU character device to use for communication with the shell.

<device> must be a QEMU device type. See the documentation for '-serial dev' at http://www.bellard.org/qemu/qemu-doc.html#SEC10list of device types.

Here are some examples:

-shell-serial stdio is identical to•

-shell-serial tcp::4444,server,nowaityou communicate with the shell over

-shell-serial fdpair:3:6 lets acommunicate with the shell using fds 3 (in) and 6

-shell-serial fdpair:0:1 uses the normaland stdout fds, except that QEMU won't ttydata.

-show-kernel <name> Display kernel messages.

-trace <name> Enable code profiling (press F9 to start), written to a specified file.

Page 7 of 25Android Emulator | Android Developers

9/7/2010file://V:\android-sdk-windows\docs\guide\developing\tools\emulator.html

Page 95: Android Sdk Developing

-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 youin a comma-delimited list, specifying only the stem of eachoption: -debug-<tags>.

Here's an example showing ANDROID_VERBOSE defined with the -debug-init and -debug-modem

ANDROID_VERBOSE=init,modem

For more information about debug tags, usedebug-tags>.

Media -audio <backend> Use the specified audio backend.

-audio-in <backend> Use the specified audio-input backend.

-audio-out <backend>

Use the specified audio-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 the current emulator instance.

Enabled by default.

Network -dns-server <servers>

Use the specified DNS server(s).

The value of <servers> must be a commaof up to 4 DNS server names or IP addresses.

-http-proxy <proxy> Make all TCP connections through a specified HTTP/HTTPS proxy

The value of <proxy> can be one of thehttp://<server>:<port> http://<username>:<password>@<server>:<port>The http:// prefix can be omitted. If the<proxy> command is not supplied, thethe http_proxy environment variable anduses any value matching the <proxy> format described above.

-netdelay <delay> Set network latency emulation to <delay>.

Default value is none. See the table in Network Delay Emulation for supported <delay> values.

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

Page 8 of 25Android Emulator | Android Developers

9/7/2010file://V:\android-sdk-windows\docs\guide\developing\tools\emulator.html

Page 96: Android Sdk Developing

-report-console <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:tcp:<port>[,server][,max=<seconds>]unix:<port>[,server][,max=<seconds>]

Use -help-report-console

to view more information about this topic.

System -cpu-delay <delay> Slow down emulated CPU speed by <delay>

Supported values for <delay> are integers between 0 and1000. Note that the <delay> does not correlate to clock speed orother 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 character device.

Use this command to emulate an NMEAunit connected to an external character device or socket. The format of <device> must be QEMUdevice specification. See the documentation for 'serial at http://www.bellard.org/qemu/qemu-doc.html#SEC10

-nojni Disable JNI checks in the Dalvik runtime.

-qemu Pass arguments to qemu.

-qemu -h Display qemu help.

-radio <device> Redirect radio mode to the specified character device.

The format of <device> must be QEMUdevice specification. See the documentation forat http://www.bellard.org/qemu/qemu-doc.html#SEC10

-timezone <timezone>

Set the timezone for the emulated device to <timezone>, instead of the host's timezone.

<timezone> must be specified in zoneinfo format. For example: "America/Los_Angeles" "Europe/Paris"

-version Display the emulator's version number.

UI -dpi-device <dpi> Scale the resolution of the emulator to match the screen size of a physical device.

The default value is 165. See also -scale

-no-boot-anim Disable the boot animation during emulator startup.

Disabling the boot animation can speed the startup time for the emulator.

-no-window Disable the emulator's graphical window display.

-scale <scale> Scale the emulator window. <scale> is a number between 0.1 and 3 thatthe 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 windowsize.

-raw-keys Disable Unicode keyboard reverse-mapping.

-noskin Don't use any emulator skin.

Page 9 of 25Android Emulator | Android Developers

9/7/2010file://V:\android-sdk-windows\docs\guide\developing\tools\emulator.html

Page 97: Android Sdk Developing

-keyset <file> Use the specified keyset file instead of the default.

The keyset file defines the list of key bindings betweenemulator and the host keyboard. For more information, use-help-keyset to print information about this topic.

-onion <image> Use overlay image over screen.

No support for JPEG. Only PNG is supported.

-onion-alpha <percent>

Specify onion skin translucency value (as percent).

Default is 50.

-onion-rotation <position>

Specify onion skin rotation. <position> must be one of the values 0, 1, 2,

-skin <skinID> This emulator option is deprecated.

Please set skin options using AVDs, rather than by using this emulator option. Using this option mayunexpected 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. Forinformation, see Android Virtual Devices

-skindir <dir> This emulator option is deprecated.

See comments for -skin, above.

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 disk image containing an emulator-specific kernel, the Android system, a ramdisk image, and writeable images for user data and simulated SD card.

To run properly, the emulator requires access to a specific set of disk image files. By default, the Emulator always looks for the disk images in the private storage area of the AVD in use. If no images exist there when the Emulator is launched, it creates the images in the AVD directory based on default versions stored in the SDK.

Note: The default storage location for AVDs is in ~/.android/avd on OS X and Linux, C:\Documents and Settings\<user>\.android\ on Windows XP, and C:\Users\<user>\.android\ on Windows Vista.

To let you use alternate or custom versions of the image files, the emulator provides startup options that override the default locations and filenames of the image files. When you use the 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 Images

When the emulator launches but does not find an existing user data image in the active AVD's storage area, it creates a new one from a default version included in the SDK. The default user data image is read-only. The image files are read-only.

The emulator provides the -system <dir> startup option to let you override the location under which 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 table below. When you use the option, the emulator looks in the default directory, or in a custom location (if you specified -system <dir>).

Page 10 of 25Android Emulator | Android Developers

9/7/2010file://V:\android-sdk-windows\docs\guide\developing\tools\emulator.html

Page 98: Android Sdk Developing

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 on two disk images: a user-data image and (optionally) an SD card image. This emulates the user-data partition and removable storage media on actual device.

The emulator provides a default user-data disk image. At startup, the emulator creates the default image as a copy of the system user-data image (user-data.img), described above. The emulator stores the new image with the files of the active AVD.

The emulator provides startup options to let you override the actual names and storage locations of the runtime images to load, as described in the table below. 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-qemu.img

An image to which the emulator 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 as described above, 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/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 now gets its own dedicated storage. There is no 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 Command-line options for AVDs.

Page 11 of 25Android Emulator | Android Developers

9/7/2010file://V:\android-sdk-windows\docs\guide\developing\tools\emulator.html

Page 99: Android Sdk Developing

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

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.

Page 12 of 25Android Emulator | Android Developers

9/7/2010file://V:\android-sdk-windows\docs\guide\developing\tools\emulator.html

Page 100: Android Sdk Developing

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

Each emulator instance runs behind a virtual router, but unlike an actual device connected to a physical router, the emulated device doesn't have access to a physical network. Instead it runs as part of a normal application on your development machine. This means that it is subject to the same networking limitations as other applications on your machine:

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 Redirections

To communicate with an emulator instance behind its virtual router, you need to set up network redirections 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 redirections, you create a mapping of host and guest ports/addresses on the the emulator instance. There are two ways to set up network redirections: using emulator console commands and using the ADB tool, as described below.

Setting up Redirections through the Emulator Consol e

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 redirections 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 redirections. To add a redirection, use:.

add <protocol>:<host-port>:<guest-port>

where <protocol> is either tcp or udp, and <host-port> and <guest-port> sets the mapping between your own machine and the emulated system, respectively.

For example, the following command sets up a redirection that will handle 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

Page 13 of 25Android Emulator | Android Developers

9/7/2010file://V:\android-sdk-windows\docs\guide\developing\tools\emulator.html

Page 101: Android Sdk Developing

To delete a redirection, you can use the redir del command. To list all redirections 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 Redirections through ADB

The Android Debug Bridge (ADB) tool provides port forwarding, an alternate way for you to set up network redirections. 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.

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 redirections as illustrated below.

Page 14 of 25Android Emulator | Android Developers

9/7/2010file://V:\android-sdk-windows\docs\guide\developing\tools\emulator.html

Page 102: Android Sdk Developing

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, running on A too•

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

On B's console, set up a redirection from A:localhost:<localPort> to B:10.0.2.15:<serverPort>2.

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

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

The emulator automatically forwards simulated voice calls and SMS messages from one instance to another. To send a voice call or SMS, you use the dialer application and SMS application (if available) installed on one emulator

To initiate a simulated voice call to another emulator instance:

Launch the dialer application on the originating emulator instance.1.

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

2.

Press "Dial". A new inbound call appears in the target emulator instance. 3.

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 includes a console facility that lets you dynamically query and control the simulated device environment. For example, you can use the console to dynamically manage port redirections and network characteristics and simulate telephony events. To access the console and enter commands, you 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

Page 15 of 25Android Emulator | Android Developers

9/7/2010file://V:\android-sdk-windows\docs\guide\developing\tools\emulator.html

Page 103: Android Sdk Developing

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 sections below describe the major functional areas of the console.

Port Redirection

You can use the console to add and remove port redirections while the emulator is running. After connecting to the console, you can manage port redirections in this way:

redir <list|add|del>

The redir command supports the subcommands listed in the table below.

Subcommand Description Comments

list List the current port redirections.

add <protocol>:<host-port>:<guest-port>

Add a new port redirection. <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

del <protocol>:<host-port>

Delete a port redirection. See above for meanings of <protocol> and <host-port>.

Geo Location Provider Emulation

The console provides commands to let you set the geo position used by an emulator emulated device. You can use the geo command to send a simple GPS fix to the emulator, without needing to use NMEA 1083 formatting. The usage for the command is:

geo <fix|nmea>

The geo command supports the subcommands listed in the table below.

Page 16 of 25Android Emulator | Android Developers

9/7/2010file://V:\android-sdk-windows\docs\guide\developing\tools\emulator.html

Page 104: Android Sdk Developing

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 to fix the GPS location as soon as an emulator instance is running. The emulator creates a mock location provider that sends it to GPS-aware applications as soon as they start and register location listeners. 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 and its methods.

Hardware Events Emulation

You can use the event command to send various events to the emulator.The usage for the command is:

event <send|types|codes|text>

The event command supports the subcommands listed in the table below.

Subcommand Description Comments

send <type>:<code>:<value> [...]

Send one or more events to the Android kernel.

You can use text names or 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 send the specified string of characters as a message,

The message must be a UTF-8 string. Unicode posts will be reverse-mapped according to the current device keyboard. Unsupported characters will be discarded silently.

Device Power Characteristics

You can use the power command to control the simulated power state of the emulator instance.The usage for the command is:

power <display|ac|status|present|health|capacity>

The event command supports the subcommands listed in the table below.

Page 17 of 25Android Emulator | Android Developers

9/7/2010file://V:\android-sdk-windows\docs\guide\developing\tools\emulator.html

Page 105: Android Sdk Developing

Subcommand Description Comments

display Display battery and charger state.

ac <on|off> Set AC charging state to on or off.

status <unknown|charging|discharging|not-charging|full>

Change battery status as specified.

present <true|false> Set battery presence state.

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

Set battery health state.

power health <percent> Set remaining battery capacity state (0-100).

Network Status

You can use the console to check the network status and current delay and speed characteristics. To do so, connect to the console and use the netstatus command. Here's an example of the command and its output.

network status

Network Delay Emulation

The emulator lets you simulate various network latency levels, so that you can test your application in an environment more typical of the actual conditions in which it will run. You can set a latency level or range at emulator startup or you can use the console to change the latency dynamically, 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 dynamic 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 is one of the following (numbers are milliseconds):

Page 18 of 25Android Emulator | Android Developers

9/7/2010file://V:\android-sdk-windows\docs\guide\developing\tools\emulator.html

Page 106: Android Sdk Developing

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 dynamically, 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 dynamic changes to network speed while the emulator is running, connect to the console and use the netspeed command with a supported <speed> value from the table below.

network speed 14.4 80

The format of network <speed> is one of the following (numbers are kilobits/sec):

Value Description Comments

gsm GSM/CSD (Up: 14.4, down: 14.4)

hscsd HSCSD (Up: 14.4, down: 43.2)

gprs GPRS (Up: 40.0, down: 80.0)

edge EDGE/EGPRS (Up: 118.4, down: 236.8)

umts UMTS/3G (Up: 128.0, down: 1920.0)

hsdpa HSDPA (Up: 348.0, down: 14400.0)

full no limit (Up: 0.0, down: 0.0)

<num> Set an exact rate used for both upload and download.

<up>:<down> Set exact rates for upload and download separately.

Page 19 of 25Android Emulator | Android Developers

9/7/2010file://V:\android-sdk-windows\docs\guide\developing\tools\emulator.html

Page 107: Android Sdk Developing

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 and establish/terminate data connections. The Android system handles simulated calls exactly as it would actual calls. The emulator does not support call audio in this release.

You can use the console to access the emulator's telephony functions. After connecting to the console, you can use

gsm <call|accept|busy|cancel|data|hold|list|voice|status>

to invoke telephony functions.

The gsm command supports the subcommands listed in the table below.

Page 20 of 25Android Emulator | Android Developers

9/7/2010file://V:\android-sdk-windows\docs\guide\developing\tools\emulator.html

Page 108: Android Sdk Developing

Subcommand Description Comments

call <phonenumber>

Simulate an inbound phone call from <phonenumber>.

accept <phonenumber>

Accept an inbound call from <phonenumber> and change the call's state "active".

You can change a call's state to "active" only if its current state is "waiting" or "held".

busy <phonenumber>

Close an outbound call to <phonenumber> and change the call's state to "busy".

You can change a call's state to "busy" only if its current state is "waiting".

cancel <phonenumber>

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

data <state> Change the state of the GPRS data connection to <state>.

Supported <state> values are: unregistered -- No network available•

home -- On local network, non-roaming•

roaming -- On roaming network•

searching -- Searching networks•

denied -- Emergency calls only•

off -- Same as 'unregistered'•

on -- same as 'home'•

hold Change the state of a call to "held".

You can change a call's state to "held" only if its current state is "active" or "waiting".

list List all inbound and outbound calls and their states.

voice <state> Change the state of the GPRS voice connection to <state>.

Supported <state> values are: unregistered -- No network available•

home -- On local network, non-roaming•

roaming -- On roaming network•

searching -- Searching networks•

denied -- Emergency calls only•

off -- Same as 'unregistered'•

on -- Same as 'home'•

status Report the current GSM voice/data state.

Values are those described for the voice and 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 this command:

sms send <senderPhoneNumber> <textmessage>

Page 21 of 25Android Emulator | Android Developers

9/7/2010file://V:\android-sdk-windows\docs\guide\developing\tools\emulator.html

Page 109: Android Sdk Developing

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 usage for the command is:

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 usage for the command is:

window <scale>

The vm command supports the subcommands listed in the table below.

Subcommand Description Comments

scale <scale> Scale the emulator window. <scale> must be a number between 0.1 and 3 that describes 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.

Terminating an Emulator Instance

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

Using Emulator Skins

The Android SDK includes several Emulator skins that you can use to control the resolution and density of the emulated device's screen. To select a specific skin for running the emulator, create an AVD that uses that skin. Please do not use deprecated emulator options such as -skin to control the skin used by an emulator instance. For more information about AVDs, see Android Virtual Devices.

Page 22 of 25Android Emulator | Android Developers

9/7/2010file://V:\android-sdk-windows\docs\guide\developing\tools\emulator.html

Page 110: Android Sdk Developing

Running Multiple Emulator Instances

Through the AVDs configurations used by the emulator, 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. You no longer need to use the -d option when launching the emulator, to point to an instance-specific storage area.

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 package it in a .apk file using the Android Asset Packaging Tool. Once the application is installed, you can start the emulator from the command line, as described in this document, 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.

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 use the android tool to create a new SD card image with a new AVD, or you can use the mksdcard utility included in the SDK.

The sections below describe how to create an SD card disk image, how to copy files to it, and how to load it in the emulator at startup.

Note that you can only load 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 using the android tool

The easiest way to create a new SD card is to use the android tool. When creating an AVD, you simply specify the -c option, like this:

android create avd -n <avd_name> -t <targetID> -c <size>[K|M]

You can also use the -c option to specify a path to an SD card image to use in the new AVD. For more information, see Android Virtual Devices.

Creating an SD card image using mksdcard

You can 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:

Page 23 of 25Android Emulator | Android Developers

9/7/2010file://V:\android-sdk-windows\docs\guide\developing\tools\emulator.html

Page 111: Android Sdk Developing

mksdcard <size> <file>

For example:

mksdcard 1024M sdcard1.iso

For more information, see Other Tools.

Copying Files to a Disk 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.

Loading the Disk Image at Emulator Startup

By default, the emulator loads the SD card image that is stored with the active AVD (see the -avd startup option).

Alternatively, you ca 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>

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

Emulator Limitations

In this release, the 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 camera/video capture (input).•

No support for device-attached headphones•

Page 24 of 25Android Emulator | Android Developers

9/7/2010file://V:\android-sdk-windows\docs\guide\developing\tools\emulator.html

Page 112: Android Sdk Developing

↑ Go to top

No support for determining 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•

Except as noted, this content is licensed under Apache 2.0. For details and restrictions, see the Content License. Android 2.2 r1 - 14 May 2010 15:20 Site Terms of Service - Privacy Policy - Brand Guidelines

Page 25 of 25Android Emulator | Android Developers

9/7/2010file://V:\android-sdk-windows\docs\guide\developing\tools\emulator.html

Page 113: Android Sdk Developing

Hierarchy Viewer

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 Layout View) and a magnified inspector of the display (the Pixel Perfect View).

To get the Hierarchy Viewer started:

Connect your device or launch an emulator.1.

From a terminal, launch hierarchyviewer from your SDK /tools directory. 2.

In the window that opens, you'll see a list of Devices. When a device is selected, a list of currently active Windows is displayed on the right. The <Focused Window> is the window currently in the foreground, and also the default window loaded if you do not select another.

3.

Select the window that you'd like to inspect and click Load View Hierarchy. The Layout View will be loaded. You can then load the Pixel Perfect View by clicking the second icon at the bottom-left of the window.

4.

If you've navigated to a different window on the device, press Refresh Windows to refresh the list of available windows on the right.

Layout View

The Layout View offers a look at the View layout and properties. It has three views:

Tree View: a hierarchy diagram of the Views, on the left.•

Properties View: a list of the selected View's properties, on the top-right.•

Wire-frame View: a wire-frame drawing of the layout, on the bottom-right.•

Page 1 of 1Hierarchy Viewer | Android Developers

9/7/2010file://V:\android-sdk-windows\docs\guide\developing\tools\hierarchy-viewer.html

Page 114: Android Sdk Developing

layoutopt

layoutopt is a command-line tool that helps you optimize the layouts and layout hierarchies of your applications. 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.

To run the tool, open a terminal and launch layoutopt <resources> from your SDK tools/ directory. In the command, supply a list of uncompiled resource xml files or directories that you want to analyze.

When run, the tool loads the specified XML files and analyzes their layout structures and hierarchies according to a set of predefined rules. If it detects issues, it outputs information about the issues, giving filename, line numbers, description of issue, and for some types of issues a suggested resolution.

Here's an example of the output:

$ layoutopt samples/ samples/compound.xml 7:23 The root-level <FrameLayout/> can be replaced with <merge/> 11:21 This LinearLayout layout or its FrameLayout parent is useless samples/simple.xml 7:7 The root-level <FrameLayout/> can be replaced with <merge/> samples/too_deep.xml -1:-1 This layout has too many nested layouts: 13 levels, it should have <= 10! 20:81 This LinearLayout layout or its LinearLayout parent is useless 24:79 This LinearLayout layout or its LinearLayout parent is useless 28:77 This LinearLayout layout or its LinearLayout parent is useless 32:75 This LinearLayout layout or its LinearLayout parent is useless 36:73 This LinearLayout layout or its LinearLayout parent is useless 40:71 This LinearLayout layout or its LinearLayout parent is useless 44:69 This LinearLayout layout or its LinearLayout parent is useless 48:67 This LinearLayout layout or its LinearLayout parent is useless 52:65 This LinearLayout layout or its LinearLayout parent is useless 56:63 This LinearLayout layout or its LinearLayout parent is useless samples/too_many.xml 7:413 The root-level <FrameLayout/> can be replaced with <merge/> -1:-1 This layout has too many views: 81 views, it should have <= 80! samples/useless.xml 7:19 The root-level <FrameLayout/> can be replaced with <merge/> 11:17 This LinearLayout layout or its FrameLayout parent is useless

The layoutopt tool is available in SDK Tools, Revision 3 or later. If you do not have SDK Tools r3 or later installed in your SDK, you can download it from the Android SDK repository site using the Android SDK and AVD Manager. For information, see Adding SDK Components.

Usage

To run layoutopt against a given list of layout resources:

layoutopt <list of xml files or directories>

For example:

Page 1 of 2layoutopt | Android Developers

9/7/2010file://V:\android-sdk-windows\docs\guide\developing\tools\layoutopt.html

Page 115: Android Sdk Developing

↑ Go to top

$ layoutopt res/layout-land

$ layoutopt res/layout/main.xml res/layout-land/main.xml

Except as noted, this content is licensed under Apache 2.0. For details and restrictions, see the Content License. Android 2.2 r1 - 14 May 2010 15:20 Site Terms of Service - Privacy Policy - Brand Guidelines

Page 2 of 2layoutopt | Android Developers

9/7/2010file://V:\android-sdk-windows\docs\guide\developing\tools\layoutopt.html

Page 116: Android Sdk Developing

UI/Application Exerciser Monkey

The Monkey is a program that runs on your emulator or device and generates pseudo-random streams of user events such as clicks, touches, or gestures, as well as a number of system-level events. You can use the Monkey to stress-test applications that you are developing, in a random yet repeatable manner.

Overview

The Monkey is a command-line tool that 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:

Page 1 of 4UI/Application Exerciser Monkey | Android Developers

9/7/2010file://V:\android-sdk-windows\docs\guide\developing\tools\monkey.html

Page 117: Android Sdk Developing

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

Page 2 of 4UI/Application Exerciser Monkey | Android Developers

9/7/2010file://V:\android-sdk-windows\docs\guide\developing\tools\monkey.html

Page 118: Android Sdk Developing

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.

Events -s <seed> Seed value for pseudo-random number generator. If you re-run 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.)

--pct-trackball <percent>

Adjust percentage of trackball events. (Trackball events 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 Home, Back, Start Call, End Call, or Volume controls.)

--pct-appswitch <percent>

Adjust percentage of activity launches. At random intervals, the Monkey will issue a startActivity() call, as a way of maximizing coverage of all activities within your package.

--pct-anyevent <percent>

Adjust percentage of other types of events. This is a catch-all for all other types of events such as keypresses, other less-used buttons on the device, and so forth.

Constraints -p <allowed-package-name>

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.

-c <main-category>

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.

Page 3 of 4UI/Application Exerciser Monkey | Android Developers

9/7/2010file://V:\android-sdk-windows\docs\guide\developing\tools\monkey.html

Page 119: Android Sdk Developing

↑ Go to top

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.

--ignore-crashes

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.

--ignore-timeouts

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.

--ignore-security-exceptions

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

Normally, when the Monkey stops due to an error, the 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.

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

Except as noted, this content is licensed under Apache 2.0. For details and restrictions, see the Content License. Android 2.2 r1 - 14 May 2010 15:20 Site Terms of Service - Privacy Policy - Brand Guidelines

Page 4 of 4UI/Application Exerciser Monkey | Android Developers

9/7/2010file://V:\android-sdk-windows\docs\guide\developing\tools\monkey.html

Page 120: Android Sdk Developing

ADB quickviewManage the state of an emulator or device•Run shell commands on a device•Manage port forwarding on an emulator or device

Copy files to/from an emulator or device•

In this documentIssuing ADB 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

Listing of adb Commands

Issuing Shell Commands

Enabling logcat Logging

Stopping the adb Server

See alsoEmulator

Android Debug Bridge

Android Debug Bridge (adb) is a versatile tool lets you manage the state of an emulator instance or Android-powered device. It is a client-server program that includes three components:

A client, which runs on your development machine. You can invoke a client from a shell by issuing an adb command. Other Android tools such as the ADT plugin and DDMS also create adb clients.

A server, which runs as a background process on your development machine. The server manages communication between the client and the adb daemon running on an emulator or device.

A daemon, which runs as a background process on each emulator or device instance.

When you start an adb client, the client first checks whether there is an adb server process already running. If there isn't, it starts the server process. When the server starts, it binds to local TCP port 5037 and listens for commands sent from adb clients—all adb clients use port 5037 to communicate with the adb server.

The server then sets up connections to all running emulator/device instances. It locates emulator/device instances by scanning odd-numbered ports in the range 5555 to 5585, the range used by emulators/devices. Where the server finds an adb daemon, it sets up a connection to that port. Note that each emulator/device instance acquires a pair of sequential ports — an even-numbered port for console connections and an odd-numbered port for adb connections. For example:

Emulator 1, console: 5554 Emulator 1, adb: 5555 Emulator 2, console: 5556 Emulator 2, adb: 5557 ...

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

The sections below describe the commands that you can use to access adb capabilities and manage the state of an emulator/device. Note that if you are developing Android applications in Eclipse and have installed the ADT plugin, you do not need to access adb from the command line. The ADT plugin provides a transparent integration of adb into the Eclipse IDE. However, you can still use adb directly as necessary, such as for debugging.

Page 1 of 12Android Debug Bridge | Android Developers

9/7/2010file://V:\android-sdk-windows\docs\guide\developing\tools\adb.html

Page 121: Android Sdk Developing

Issuing adb Commands

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>

When you issue a command, the program invokes an adb client. The client is not specifically associated with any emulator instance, so if multiple emulators/devices are running, you need to use the -d option to specify the target instance to which the command should be directed. For more information about using this option, see Directing Commands to a Specific Emulator/Device Instance.

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. Three states are supported: •

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

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.

The output for each instance is formatted like this:

[serialNumber] [state]

Here's an example showing the devices command and its output:

$ adb devices List of devices attached emulator-5554 device emulator-5556 device emulator-5558 device

If there is no emulator/device running, adb returns no device.

Directing Commands to a Specific Emulator/Device Instance

If multiple emulator/device instances are running, you need to specify a target instance when issuing adb commands. To so so, use the -s option in the commands. The usage for the -s option is:

Page 2 of 12Android Debug Bridge | Android Developers

9/7/2010file://V:\android-sdk-windows\docs\guide\developing\tools\adb.html

Page 122: Android Sdk Developing

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.

Here is an example:

adb -s emulator-5556 install helloWorld.apk

Note that, if you issue a command without specifying a target emulator/device instance using -s, adb generates an error.

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 Android Asset Packaging Tool (aapt).

Note that, if you are using the Eclipse IDE and have the ADT plugin installed, you do not need to use adb (or aapt) directly to install your application on the emulator/device. Instead, the ADT plugin handles the packaging and installation of the application for you.

Forwarding Ports

You can use the forward command to set up arbitrary port forwarding — forwarding of requests on a specific host port to a different port on an emulator/device instance. Here's how you would set up forwarding of host port 6100 to emulator/device port 7100:

adb forward tcp:6100 tcp:7100

You can also use adb to set up forwarding to named abstract UNIX domain sockets, as illustrated here:

adb forward tcp:6100 local:logd

Copying Files to or from an Emulator/Device Instance

You can use the adb commands pull and push to copy files to and from an emulator/device instance's data file. 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 (recursively) from the emulator or device, use

Page 3 of 12Android Debug Bridge | Android Developers

9/7/2010file://V:\android-sdk-windows\docs\guide\developing\tools\adb.html

Page 123: Android Sdk Developing

adb pull <remote> <local>

To copy a file or directory (recursively) 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).

Here's an example:

adb push foo.txt /sdcard/foo.txt

Listing of adb Commands

The table below lists all of the supported adb commands and explains their meaning and usage.

Page 4 of 12Android Debug Bridge | Android Developers

9/7/2010file://V:\android-sdk-windows\docs\guide\developing\tools\adb.html

Page 124: Android Sdk Developing

Category Command Description Comments

Options -d Direct an adb command to the only attached USB device.

Returns an error if more than one USB device is attached.

-e Direct an adb command to the only running emulator instance.

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

-s <serialNumber> Direct an adb command a specific emulator/device instance, referred to by its adb-assigned serial number (such as "emulator-5556").

If not specified, adb generates an error.

General devices Prints a list of all attached emulator/device instances.

See Querying for Emulator/Device Instances for more information.

help Prints a list of supported adb commands.

version Prints the adb version number.

Debug logcat [<option>] [<filter-specs>]

Prints log data to the screen.

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

jdwp Prints a list of available JDWP processes on a given device.

You can use the forward jdwp:<pid> port-forwarding specification to connect to a specific JDWP process. For example: adb forward tcp:8000 jdwp:472 jdb -attach localhost:8000

Data install <path-to-apk> Pushes an Android application (specified as a full path to an .apk file) to the data file of an emulator/device.

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

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

Page 5 of 12Android Debug Bridge | Android Developers

9/7/2010file://V:\android-sdk-windows\docs\guide\developing\tools\adb.html

Page 125: Android Sdk Developing

Ports and Networking

forward <local> <remote> Forwards socket connections from a specified local port to a specified remote port on the emulator/device instance.

Port specifications can use these schemes:

tcp:<portnum>•

local:<UNIX domain socket name>

dev:<character device name>

jdwp:<pid>•

ppp <tty> [parm]... Run PPP over USB. <tty> — the tty for PPP stream. For example dev:/dev/omap_csmi_ttyl.

[parm]... &mdash 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.

See Querying for Emulator/Device Instances for more information. get-state Prints the adb state of an

emulator/device instance.

Page 6 of 12Android Debug Bridge | Android Developers

9/7/2010file://V:\android-sdk-windows\docs\guide\developing\tools\adb.html

Page 126: Android Sdk Developing

wait-for-device Blocks execution until the device is online — that is, until the instance state is device.

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

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

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 start-server Checks whether the adb server process is running and starts it, if not.

kill-server Terminates the adb server process.

Shell shell Starts a remote shell in the target emulator/device instance.

See Issuing Shell Commands for more information.

shell [<shellCommand>] Issues a shell command in the target emulator/device instance and then exits the remote shell.

Page 7 of 12Android Debug Bridge | Android Developers

9/7/2010file://V:\android-sdk-windows\docs\guide\developing\tools\adb.html

Page 127: Android Sdk Developing

Issuing Shell Commands

Adb provides an ash shell that you can use to run a variety of commands on an emulator or device. The command binaries are stored in the file system of the emulator or device, in this location:

/system/bin/...

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

To drop into a remote shell on a emulator/device instance, use the shell command like this:

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

When you are ready to exit the remote shell, use CTRL+D or exit to end the shell session.

The sections below provide more information about shell commands that you can use.

Examining sqlite3 Databases from a Remote Shell

From an adb remote shell, you can use the sqlite3 command-line program to manage SQLite databases created by Android applications. The sqlite3 tool includes many useful commands, such as .dump to print out the contents of a table and .schema to print the SQL CREATE statement for an existing table. The tool also gives you the ability to execute SQLite commands on the fly.

To use sqlite3, enter a remote shell on the emulator instance, as described above, then invoke the tool using the sqlite3 command. Optionally, when invoking sqlite3 you can specify the full path to the database you want to explore. Emulator/device instances store SQLite3 databases in the folder /data/data/<package_name>/databases/.

Here's an example:

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

Once you've invoked sqlite3, you can issue sqlite3 commands in the shell. To exit and return to the adb remote shell, use exit or CTRL+D.

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.

Page 8 of 12Android Debug Bridge | Android Developers

9/7/2010file://V:\android-sdk-windows\docs\guide\developing\tools\adb.html

Page 128: Android Sdk Developing

The simplest way to use the monkey is with the following command, which will launch your application and send 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

The table below lists several of the adb shell commands available. For a complete list of commands and programs, start an emulator instance and use the adb -help command.

adb shell ls /system/bin

Help is available for most of the commands.

Shell Command Description Comments

dumpsys Dumps system data to the screen.

The Dalvik Debug Monitor Service (DDMS) tool offers integrated debug environment that you may find easier to use.dumpstate Dumps state to a file.

logcat [<option>]... [<filter-spec>]...

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

Using logcat Commands

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

The sections below explain filter specifications and the command options. See Listing of logcat Command Options for a summary of options.

Page 9 of 12Android Debug Bridge | Android Developers

9/7/2010file://V:\android-sdk-windows\docs\guide\developing\tools\adb.html

Page 129: Android Sdk Developing

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

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

V — Verbose (lowest priority)◦

D — Debug◦

I — Info◦

W — Warning◦

E — Error◦

F — Fatal◦

S — Silent (highest priority, on which nothing is ever printed)◦

You can obtain a list of tags used in the system, together with priorities, by running logcat and observing the first two columns of each message, given as <priority>/<tag>.

Here's an example of logcat output that shows that the message relates to priority level "I" and tag "ActivityManager":

I/ActivityManager( 585): Starting activity: Intent { action=android.intent.action...}

To reduce the log output to a manageable level, you can restrict log output using filter expressions. Filter expressions let you indicate to the system the tags-priority combinations that you are interested in — the system suppresses other messages for the specified tags.

A filter expression follows this format tag:priority ..., where tag indicates the tag of interest and priority indicates the minimum level of priority to report for that tag. Messages for that tag at or above the specified priority are written to the log. You can supply any number of tag:priority specifications in a single filter expression. The series of specifications is whitespace-delimited.

Here's an example of a filter expression that suppresses all log messages except those with the tag "ActivityManager", at priority "Info" or above, and all log messages with tag "MyApp", with priority "Debug" or above:

adb logcat ActivityManager:I MyApp:D *:S

The final element in the above expression, *:S, sets the priority level for all tags to "silent", thus ensuring only log messages with "View" and "MyApp" are displayed. Using *:S is an excellent way to ensure that log output is restricted to the filters that you have explicitly specified — it lets your filters serve as a "whitelist" for log output.

The following filter expression displays all log messages with priority level "warning" and higher, on all tags:

Page 10 of 12Android Debug Bridge | Android Developers

9/7/2010file://V:\android-sdk-windows\docs\guide\developing\tools\adb.html

Page 130: Android Sdk Developing

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 originating process (the default format).•

process — Display PID only.•

tag — Display the priority/tag only. •

thread — Display process:thread and 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 originating process.•

long — Display all metadata fields and separate messages with a blank lines.•

When starting logcat, you can specify the output format you want by using the -v option:

[adb] logcat [-v <format>]

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

adb logcat -v thread

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

Viewing Alternative Log Buffers

The Android logging system keeps multiple circular buffers for log messages, and not all of the log messages are sent to the default circular buffer. To see additional log messages, you can start logcat 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:

Page 11 of 12Android Debug Bridge | Android Developers

9/7/2010file://V:\android-sdk-windows\docs\guide\developing\tools\adb.html

Page 131: Android Sdk Developing

↑ Go to top

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.

Listing of logcat Command Options

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.

-f <filename>

Writes log message output to <filename>. The default is stdout.

-g Prints the size of the specified log buffer and exits.

-n <count> Sets the maximum number of rotated logs to <count>. The default value is 4. Requires the -r option.

-r <kbytes> Rotates the log file every <kbytes> of output. The default value is 16. Requires the -f option.

-s Sets the default filter spec to silent.

-v <format> Sets the output format for log messages. The default is brief format. For a list of supported formats, see Controlling Log Output Format.

Stopping the adb Server

In some cases, you might need to terminate the adb server process and then restart it. For example, if adb does not respond to a command, you can terminate the server and restart it and that may resolve the problem.

To stop the adb server, use the kill-server. You can then restart the server by issuing any adb command.

Except as noted, this content is licensed under Apache 2.0. For details and restrictions, see the Content License. Android 2.2 r1 - 14 May 2010 15:20 Site Terms of Service - Privacy Policy - Brand Guidelines

Page 12 of 12Android Debug Bridge | Android Developers

9/7/2010file://V:\android-sdk-windows\docs\guide\developing\tools\adb.html

Page 132: Android Sdk Developing

In this documentCreating Trace Files

Copying Trace Files to a Host Machine

Viewing Trace Files in Traceview

Timeline Panel

Profile Panel

Traceview File Format

Data File Format

Key File Format

Traceview Known Issues

Using dmtracedump

Traceview: A Graphical Log Viewer

Traceview is a graphical viewer for execution logs saved by your application. Traceview can help you debug your application and profile its performance. The sections below describe how to use the program.

Creating Trace Files

To use Traceview, you need to generate log files containing the trace information you want to analyze. To do that, you include the Debug class in your code and call its methods to start and stop logging of trace information to disk. When your application quits, you can then use Traceview to examine the log files for useful run-time information such as method calls and run times.

To create the trace files, include the Debug class and call one of the startMethodTracing() methods. In the call, you specify a base name for the trace files that the system generates. To stop tracing, call stopMethodTracing() . These methods start and stop method tracing across the entire virtual machine. For example, you could call startMethodTracing() in your activity's onCreate() method, and call stopMethodTracing() in that activity's onDestroy() method.

// start tracing to "/sdcard/calc.trace" Debug. startMethodTracing ( "calc" ); // ... // stop tracing Debug. stopMethodTracing ();

When your application calls startMethodTracing(), the system creates a file called <trace-base-name>.trace . This contains the binary method trace data and a mapping table with thread and method names.

The system then begins buffering the generated trace data, until your application calls stopMethodTracing(), at which time it writes the buffered data to the output file. If the system reaches the maximum buffer size before stopMethodTracing() is called, the system stops tracing and sends a notification to the console.

Interpreted code will run more slowly when profiling is enabled. Don't try to generate absolute timings from the profiler results (i.e. "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.

When using the Android emulator, you must create an SD card image upon which the trace files will be written. For example, from the /tools directory, you can create an SD card image named "imgcd" and mount it when launching the emulator like so:

$ mksdcard 1024M ./ imgcd $ emulator - sdcard ./ imgcd

For more information, read about the mksdcard tool.

The format of the trace files is described later in this document.

Page 1 of 7Traceview: A Graphical Log Viewer | Android Developers

9/7/2010file://V:\android-sdk-windows\docs\guide\developing\tools\traceview.html

Page 133: Android Sdk Developing

Copying Trace Files to a Host Machine

After your application has run and the system has created your trace files <trace-base-name>.trace on a device or emulator, you must copy those files to your development computer. You can use adb pull to copy the files. Here's an example that shows how to copy an example file, calc.trace, from the default location on the emulator to the /tmp directory on the emulator host machine:

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, you would use:

traceview / tmp / calc

Traceview loads the log files and displays their data in a window that has two panels:

A timeline panel -- describes when each thread and method started and stopped•

A profile panel -- provides a summary of what happened inside a method•

The sections below provide addition information about the traceview output panes.

Timeline Panel

The image below 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. The method in this case is LoadListener.nativeFinished() and it was selected in the profile view.

Traceview timeline panel

Page 2 of 7Traceview: A Graphical Log Viewer | Android Developers

9/7/2010file://V:\android-sdk-windows\docs\guide\developing\tools\traceview.html

Page 134: Android Sdk Developing

Profile Panel

The image below shows the profile pane. The profile pane shows 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.

Traceview profile panel.

Page 3 of 7Traceview: A Graphical Log Viewer | Android Developers

9/7/2010file://V:\android-sdk-windows\docs\guide\developing\tools\traceview.html

Page 135: Android Sdk Developing

Traceview File Format

Tracing creates two distinct pieces of output: a data file, which holds the trace data, and a key file, which provides a mapping from binary identifiers to thread and method names. The files are concatenated when tracing completes, into a single .trace file.

Note: The previous version of Traceview did not concatenate these files for you. If you have old key and data files that you'd still like to trace, you can concatenate them yourself with cat mytrace.key mytrace.data > mytrace.trace .

Data File Format

The data file is binary, structured as follows (all values are stored in little-endian order):

* File format : * header * record 0 * record 1 * ... * * Header format : * u4 magic 0x574f4c53 ( 'SLOW' ) * u2 version * u2 offset to data * u8 start date / time in usec * * Record format : * u1 thread ID * u4 method ID | method action * u4 time delta since start , in usec

The application is expected to parse all of the header fields, then seek to "offset to data" from the start of the file. From there it just reads 9-byte records until EOF is reached.

u8 start date/time in usec is the output from gettimeofday(). It's mainly there so that you can tell if the output was generated yesterday or three months ago.

method action sits in the two least-significant bits of the method word. The currently defined meanings are:

0 - method entry •

1 - method exit •

2 - method "exited" when unrolled by exception handling •

3 - (reserved)•

An unsigned 32-bit integer can hold about 70 minutes of time in microseconds.

Key File Format

The key file is a plain text file divided into three sections. Each section starts with a keyword that begins with '*'. If you see a '*' at the start of a line, you have found the start of a new section.

An example file might look like this:

* version 1 clock =global

Page 4 of 7Traceview: A Graphical Log Viewer | Android Developers

9/7/2010file://V:\android-sdk-windows\docs\guide\developing\tools\traceview.html

Page 136: Android Sdk Developing

* threads 1 main 6 JDWP Handler 5 Async GC 4 Reference Handler 3 Finalizer 2 Signal Handler * methods 0x080f23f8 java / io / PrintStream write ([ BII ) V 0x080f25d4 java / io / PrintStream print ( Ljava/ lang / String;) V 0x080f27f4 java / io / PrintStream println ( Ljava/ lang / String;) V 0x080da620 java / lang / RuntimeException <init > () V [...] 0x080f630c android / os / Debug startMethodTracing () V 0x080f6350 android / os / Debug startMethodTracing ( Ljava/ lang / String; Ljava/ lang / String; I ) V * end

version sectionThe first line is the file version number, currently 1. The second line, clock=global , indicates that we use a common clock across all threads. A future version may use per-thread CPU time counters that are independent for every thread.

threads sectionOne line per thread. Each line consists of two parts: the thread ID, followed by a tab, followed by the thread name. There are few restrictions on what a valid thread name is, so include everything to the end of the line.

methods section One line per method entry or exit. A line consists of four pieces, separated by tab marks: method-ID [TAB] class-name [TAB] method-name [TAB] signature . Only the methods that were actually entered or exited are included in the list. Note that all three identifiers are required to uniquely identify a method.

Neither the threads nor methods sections are sorted.

Traceview Known Issues

ThreadsTraceview logging does not handle threads well, resulting in these two problems:

If a thread exits during profiling, the thread name is not emitted; 1.

The VM reuses thread IDs. If a thread stops and another starts, they may get the same ID. 2.

Using dmtracedump

The Android SDK includes dmtracedump, 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.

Page 5 of 7Traceview: A Graphical Log Viewer | Android Developers

9/7/2010file://V:\android-sdk-windows\docs\guide\developing\tools\traceview.html

Page 137: Android Sdk Developing

For each node, dmtracedump shows <ref> callname (<inc-ms>, <exc-ms>,<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-base-name>.key. The table below lists the options for dmtracedump.

Page 6 of 7Traceview: A Graphical Log Viewer | Android Developers

9/7/2010file://V:\android-sdk-windows\docs\guide\developing\tools\traceview.html

Page 138: Android Sdk Developing

↑ Go to top

Option Description

-d <trace-base-name>

Diff with this trace name

-g <outfile> Generate output to <outfile>

-h Turn on HTML output

-o Dump the trace file instead of profiling

-d <trace-base-name>

URL base to the location of the sortable javascript file

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

Except as noted, this content is licensed under Apache 2.0. For details and restrictions, see the Content License. Android 2.2 r1 - 14 May 2010 15:20 Site Terms of Service - Privacy Policy - Brand Guidelines

Page 7 of 7Traceview: A Graphical Log Viewer | Android Developers

9/7/2010file://V:\android-sdk-windows\docs\guide\developing\tools\traceview.html

Page 139: Android Sdk Developing

↑ Go to top

zipalign

zipalign is an archive alignment tool that provides important optimization to Android application (.apk) files. The purpose is to ensure that all uncompressed data starts with a particular alignment relative to the start of the file. Specifically, it causes all uncompressed data within the .apk, such as images or raw files, to be aligned on 4-byte boundaries. This allows all portions to be accessed directly with mmap() even if they contain binary data with alignment restrictions. The benefit is a reduction in the amount of RAM consumed when running the application.

This tool should always be used to align your .apk file before distributing it to end-users. The Android build tools can handle this for you. When using Eclipse with the ADT plugin, the Export Wizard will automatically zipalign your .apk after it signs it with your private key. The build scripts used when compiling your application with Ant will also zipalign your .apk, as long as you have provided the path to your keystore and the key alias in your project build.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•

Except as noted, this content is licensed under Apache 2.0. For details and restrictions, see the Content License. Android 2.2 r1 - 14 May 2010 15:20 Site Terms of Service - Privacy Policy - Brand Guidelines

Page 1 of 1zipalign | Android Developers

9/7/2010file://V:\android-sdk-windows\docs\guide\developing\tools\zipalign.html