Documente Academic
Documente Profesional
Documente Cultură
Page 1 of 12
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
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).
file://V:\android-sdk-windows\docs\guide\developing\eclipse-adt.html
9/7/2010
Page 2 of 12
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. 4. Click Finish. 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.xml The Android Manifest for your project. See The AndroidManifest.xml File. default.properties This 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:
file://V:\android-sdk-windows\docs\guide\developing\eclipse-adt.html
9/7/2010
Page 3 of 12
1. Select Window > Android SDK and AVD Manager, or click the Android SDK and AVD Manager icon in the Eclipse toolbar. 2. In the Virtual Devices panel, you'll see a list of existing AVDs. Click New to create a new AVD. 3. Fill in the details for the AVD. 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). 4. Click Create AVD. 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.
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: 1. Compile the project (if there have been changes since the last build). 2. Create a default launch configuration (if one does not already exist for the project). 3. Install and start the application on an emulator (or device), based on the Deployment Target defined by the run configuration. By default, Android run configurations use an "automatic target" mode for selecting a device target. For information on how automatic target mode selects a deployment target, see Automatic and manual target modes 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:
file://V:\android-sdk-windows\docs\guide\developing\eclipse-adt.html
9/7/2010
Page 4 of 12
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.
file://V:\android-sdk-windows\docs\guide\developing\eclipse-adt.html
9/7/2010
Page 5 of 12
4. 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. 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.
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
file://V:\android-sdk-windows\docs\guide\developing\eclipse-adt.html
9/7/2010
Page 6 of 12
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 SDK Tools Android 2.2 platform Android 2.1 platform Android 2.0.1 platform Android 2.0 platform Android 1.6 platform Android 1.5 platform ADT Plugin Minimum Version r6 (or higher) r1 (or higher) r2 (or higher) not supported not supported r3 (or higher) r4 (or higher) 0.9.7 (or higher)
file://V:\android-sdk-windows\docs\guide\developing\eclipse-adt.html
9/7/2010
Page 7 of 12
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.
file://V:\android-sdk-windows\docs\guide\developing\eclipse-adt.html
9/7/2010
Page 8 of 12
file://V:\android-sdk-windows\docs\guide\developing\eclipse-adt.html
9/7/2010
Page 9 of 12
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.
file://V:\android-sdk-windows\docs\guide\developing\eclipse-adt.html
9/7/2010
Page 10 of 12
... </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
file://V:\android-sdk-windows\docs\guide\developing\eclipse-adt.html
9/7/2010
Page 11 of 12
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 projects 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.
file://V:\android-sdk-windows\docs\guide\developing\eclipse-adt.html
9/7/2010
Page 12 of 12
You can also execute arbitrary code when not debugging by using a scrapbook page. Search the Eclipse documentation for "scrapbook".
Go to top
file://V:\android-sdk-windows\docs\guide\developing\eclipse-adt.html
9/7/2010
Page 1 of 13
In this document
Creating 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
Essential Tools
When developing in IDEs or editors other than Eclipse, you'll require familiarity with the following Android SDK tools: android To create/update Android projects and to create/move/delete AVDs. Android Emulator To run your Android applications on an emulated Android platform.
See also
android Tool Android Emulator Android Debug Bridge
Android Debug Bridge To 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: Ant To compile and build your Android project into an installable .apk file. Keytool To 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.
file://V:\android-sdk-windows\docs\guide\developing\other-ide.html
9/7/2010
Page 2 of 13
file://V:\android-sdk-windows\docs\guide\developing\other-ide.html
9/7/2010
Page 3 of 13
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 optionalif you're not changing the project name, you don't need this. Here's an example: android update project --name MyApp --target 2 --path ./MyAppProject
file://V:\android-sdk-windows\docs\guide\developing\other-ide.html
9/7/2010
Page 4 of 13
file://V:\android-sdk-windows\docs\guide\developing\other-ide.html
9/7/2010
Page 5 of 13
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: 1. Open a command-line and navigate to the root of your project directory. 2. Use Ant to compile your project in release mode: ant release
This creates your Android application .apk file inside the project bin/ directory, named <your_project_name>unsigned.apk. Note: The .apk file is unsigned at this point and can't be installed until signed with your private key. Once you have created the unsigned .apk, your next step is to sign the .apk with your private key and then align it with zipalign. To complete this procedure, read Signing Your Applications. When your .apk has been signed and aligned, it's ready to be distributed to end-users.
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.
file://V:\android-sdk-windows\docs\guide\developing\other-ide.html
9/7/2010
Page 6 of 13
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: 1. Navigate to your SDK's tools/ directory and execute the android tool with no arguments: android This will launch the SDK and AVD Manager GUI. 2. In the Virtual Devices panel, you'll see a list of existing AVDs. Click New to create a new AVD. 3. Fill in the details for the AVD. 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). 4. Click Create AVD. Your AVD is now ready and you can either close the AVD Manager, create more AVDs, or launch an emulator with the AVD by clicking Start. For more information about AVDs, read the Android Virtual Devices documentation.
From your SDK's tools/ directory, execute the android tool with no arguments: android
file://V:\android-sdk-windows\docs\guide\developing\other-ide.html
9/7/2010
Page 7 of 13
In the Virtual Devices view, select an AVD and click Start. 2. Install your application From your SDK's tools/ directory, install the .apk on the emulator: adb install <path_to_your_bin>.apk Your APK file (signed with either a release or debug key) is in your 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)
file://V:\android-sdk-windows\docs\guide\developing\other-ide.html
9/7/2010
Page 8 of 13
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.
file://V:\android-sdk-windows\docs\guide\developing\other-ide.html
9/7/2010
Page 9 of 13
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 SDK Tools Android 2.2 platform Android 2.1 platform Android 2.0.1 platform Android 2.0 platform Android 1.6 platform Android 1.5 platform ADT Plugin Minimum Version r6 (or higher) r1 (or higher) r2 (or higher) not supported not supported r3 (or higher) r4 (or higher) 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.
file://V:\android-sdk-windows\docs\guide\developing\other-ide.html
9/7/2010
Page 10 of 13
file://V:\android-sdk-windows\docs\guide\developing\other-ide.html
9/7/2010
Page 11 of 13
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.
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
file://V:\android-sdk-windows\docs\guide\developing\other-ide.html
9/7/2010
Page 12 of 13
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 projects 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.
file://V:\android-sdk-windows\docs\guide\developing\other-ide.html
9/7/2010
Page 13 of 13
Go to top
file://V:\android-sdk-windows\docs\guide\developing\other-ide.html
9/7/2010
Page 1 of 2
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.
In this document
Setting up a Device for Development USB Vendor IDs
See also
USB Driver for Windows Developing in Eclipse, with ADT Developing in other IDEs
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.
file://V:\android-sdk-windows\docs\guide\developing\device.html
9/7/2010
Page 2 of 2
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. 1. Log in as root and create this file: /etc/udev/rules.d/51-android.rules. 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" 2. Now execute: chmod a+r /etc/udev/rules.d/51-android.rules 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.
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
file://V:\android-sdk-windows\docs\guide\developing\device.html
9/7/2010
Page 1 of 5
Debugging Tasks
This document offers some helpful guidance to debugging applications on Android.
In this document
Tools Debug with Dev Tools Debugging Web Pages Top Debugging Tips Configuring Your IDE to Attach to the Debugging Port
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. Traceview A graphical viewer that displays trace file data for method calls and times saved by your application, which can help you profile the performance of your application. logcat Dumps 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 number " + position); The logcat will then output something like: I/MyActivity( 1557): MyClass.getView() get item number 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
file://V:\android-sdk-windows\docs\guide\developing\debug-tasks.html
9/7/2010
Page 2 of 5
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 app The 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.
file://V:\android-sdk-windows\docs\guide\developing\debug-tasks.html
9/7/2010
Page 3 of 5
Displays CPU meters at the top of the screen, showing how much the CPU is being used. The top red bar shows overall CPU usage, and the green bar underneath it shows the CPU time spent in compositing the screen. Note: You cannot turn this feature off once it is on, without restarting the emulator. Show background Displays a background pattern when no activity screens are visible. This typically does not happen, but can happen during debugging. These settings will be remembered across emulator restarts.
file://V:\android-sdk-windows\docs\guide\developing\debug-tasks.html
9/7/2010
Page 4 of 5
} }); 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.
file://V:\android-sdk-windows\docs\guide\developing\debug-tasks.html
9/7/2010
Page 5 of 5
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.
Go to top
file://V:\android-sdk-windows\docs\guide\developing\debug-tasks.html
9/7/2010
Page 1 of 1
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 ADT The 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 IDEs The 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
Go to top
file://V:\android-sdk-windows\docs\guide\developing\testing\index.html
9/7/2010
Page 1 of 4
In this document
Creating a Test Project
This topic explains how create and run tests of Android Creating a Test Application applications in Eclipse with ADT. with the basic processes for Running Tests 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.
file://V:\android-sdk-windows\docs\guide\developing\testing\testing_eclipse.html
9/7/2010
Page 2 of 4
4. 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). 5. 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. 6. 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.
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
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.
file://V:\android-sdk-windows\docs\guide\developing\testing\testing_eclipse.html
9/7/2010
Page 3 of 4
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: 1. 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.
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.
2. Create an Eclipse run configuration for your test project. This is useful if you want multiple test suites, each consisting of selected tests from the project. To run a test suite, you run the test configuration. Creating and running test configurations is described in the next section. To create and run a test suite using a run configuration: 1. In the Package Explorer, select the test project, then from the main menu, select Run > Run Configurations.... The Run Configurations dialog appears. 2. In the left-hand pane, find the Android JUnit Test entry. In the right-hand pane, click the Test tab. The Name: text box shows the name of your project. The Test class: dropdown box shows one your project's classes test classes in your project. 3. To run one test class, click Run a single test, then enter your project name in the Project: text box and the class name in the Test class: text box. To run all the test classes, click Run all tests in the selected project or package, then enter the project or package name in the text box. 4. Now click the Target tab. 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. 5. Click the Common tab. In the Save As pane, click Local to save this run configuration locally, or click Shared to save it to another project. 6. Optional: Add the configuration to the Run toolbar and the Favorites menu: in the Display in Favorites pane click the checkbox next to Run. 7. Optional: To add this configuration to the Debug menu and toolbar, click the checkbox next to Debug. 8. To save your settings, click Close. Note: Although you can run the test immediately by clicking Run, you should save the test first and then run it by selecting it from the Eclipse standard toolbar. 9. On the Eclipse standard toolbar, click the down arrow next to the green Run arrow. This displays a menu of saved Run and Debug configurations. 10. Select the test run configuration you just created. 11. The progress of your test appears in the Console view. You should see the following messages, among others: Performing Android.test.InstrumentationTestRunner JUnit 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:
file://V:\android-sdk-windows\docs\guide\developing\testing\testing_eclipse.html
9/7/2010
Page 4 of 4
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.InstrumentationTestRunner on device deviceid. 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
Go to top
file://V:\android-sdk-windows\docs\guide\developing\testing\testing_eclipse.html
9/7/2010
Page 1 of 7
In this document
Working 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 Also
Testing and Instrumentation Activity Testing Android Debug Bridge
If the operation is successful, android lists to STDOUT the names of the files and directories it has created.
file://V:\android-sdk-windows\docs\guide\developing\testing\testing_otheride.html
9/7/2010
Page 2 of 7
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.
Value The path to the project of the application under test, relative to the test project The of the test project.
Description 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. For example, if the test project is in source/HelloAndroidTest, then the value for --path is HelloAndroidTest.
-p, -path
file://V:\android-sdk-windows\docs\guide\developing\testing\testing_otheride.html
9/7/2010
Page 3 of 7
If the operation is successful, android lists to STDOUT the names of the files and directories it has created.
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.
file://V:\android-sdk-windows\docs\guide\developing\testing\testing_otheride.html
9/7/2010
Page 4 of 7
You can update an existing test project to use this feature. To do this, use the android tool with the update testproject option. This is described in the section Updating a test project.
file://V:\android-sdk-windows\docs\guide\developing\testing\testing_otheride.html
9/7/2010
Page 5 of 7
Flag -w
Value (none)
Description 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. Outputs results in raw format. Use this flag when you want to collect performance measurements, so that they are not formatted as test results. This flag is designed for use with the flag -e perf true (documented in the section Instrument options). Provides testing options , 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.
-r
(none)
-e
<test_options>
Instrument options
The am instrument tool passes testing options to InstrumentationTestRunner or a subclass in the form of keyvalue 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.
file://V:\android-sdk-windows\docs\guide\developing\testing\testing_otheride.html
9/7/2010
Page 6 of 7
Key package
Value <Java_package_name>
Description The fully-qualified Java package name for one of the packages in the test application. Any test case class that uses this package name is 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. The fully-qualified Java class name for one of the test case classes. Only this test case class is executed. 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. Runs all test classes that extend InstrumentationTestCase. Runs all test classes that do not extend either InstrumentationTestCase or PerformanceTestCase. Runs a test method annotated by size. The annotations are @SmallTest, @MediumTest, and @LargeTest. Runs all test classes that implement PerformanceTestCase. When you use this option, also specify the -r flag for am instrument, so that the output is kept in raw format and not reformatted as test results. Runs tests in debug mode. 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. 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.
class
debug log
true true
emma
true
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.
file://V:\android-sdk-windows\docs\guide\developing\testing\testing_otheride.html
9/7/2010
Page 7 of 7
FunctionTests, which contains the methods testCamera, testXVGA, and testHardKeyboard. IntegrationTests, which contains the method testActivityProvider. The test runner is InstrumentationTestRunner.
Go to top
file://V:\android-sdk-windows\docs\guide\developing\testing\testing_otheride.html
9/7/2010
Page 1 of 2
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 Emulator A QEMU-based device-emulation tool that you can use to design, debug, and test your applications in an actual Android run-time environment. 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 Viewer The 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. layoutopt This tool lets you quickly analyze your application's layouts for efficiency. Draw 9-patch The 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. sqlite3 Included as a convenience, this tool lets you access the SQLite data files created and used by Android applications.
file://V:\android-sdk-windows\docs\guide\developing\tools\index.html
9/7/2010
Page 2 of 2
Traceview This tool produces graphical analysis views of trace log data that you can generate from your Android application. mksdcard Helps you create a disk image that you can use with the emulator, to simulate the presence of an external storage card (such as an SD card). dx The dx tool rewrites .class bytecode into Android bytecode (stored in .dex files.) 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. android A script that lets you manage AVDs and generate Ant build files that you can use to compile your Android applications. zipalign An 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
Go to top
file://V:\android-sdk-windows\docs\guide\developing\tools\index.html
9/7/2010
Page 1 of 1
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
Go to top
file://V:\android-sdk-windows\docs\guide\developing\tools\aapt.html
9/7/2010
Page 1 of 12
ADB quickview
Manage 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 document
Issuing 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 also
Emulator
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.
file://V:\android-sdk-windows\docs\guide\developing\tools\adb.html
9/7/2010
Page 2 of 12
file://V:\android-sdk-windows\docs\guide\developing\tools\adb.html
9/7/2010
Page 3 of 12
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
file://V:\android-sdk-windows\docs\guide\developing\tools\adb.html
9/7/2010
Page 4 of 12
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
file://V:\android-sdk-windows\docs\guide\developing\tools\adb.html
9/7/2010
Page 5 of 12
Category Options
Command -d
Description Direct an adb command to the only attached USB device. Direct an adb command to the only running emulator instance.
Comments Returns an error if more than one USB device is attached. Returns an error if more than one emulator instance is running. If not specified, adb generates an error.
-e
-s <serialNumber>
Direct an adb command a specific emulator/device instance, referred to by its adb-assigned serial number (such as "emulator-5556"). Prints a list of all attached emulator/device instances.
General
devices
Prints a list of supported adb commands. Prints the adb version number. Prints log data to the screen. Prints dumpsys, dumpstate, and logcat data to the screen, for the purposes of bug reporting. Prints a list of available JDWP processes on a given device. You can use the forward jdwp:<pid> portforwarding specification to connect to a specific JDWP process. For example: adb forward tcp:8000 jdwp:472 jdb -attach localhost:8000
jdwp
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. Copies a specified file from an emulator/device instance to your development computer. Copies a specified file from your development computer to an emulator/device instance.
file://V:\android-sdk-windows\docs\guide\developing\tools\adb.html
9/7/2010
Page 6 of 12
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>
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 get-state
Prints the adb instance serial number string. Prints the adb state of an emulator/device instance.
file://V:\android-sdk-windows\docs\guide\developing\tools\adb.html
9/7/2010
Page 7 of 12
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. Terminates the adb server process. Starts a remote shell in the target emulator/device instance. Issues a shell command in the target emulator/device instance and then exits the remote shell. See Issuing Shell Commands for more information.
file://V:\android-sdk-windows\docs\guide\developing\tools\adb.html
9/7/2010
Page 8 of 12
file://V:\android-sdk-windows\docs\guide\developing\tools\adb.html
9/7/2010
Page 9 of 12
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.
stop
file://V:\android-sdk-windows\docs\guide\developing\tools\adb.html
9/7/2010
Page 10 of 12
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
file://V:\android-sdk-windows\docs\guide\developing\tools\adb.html
9/7/2010
Page 11 of 12
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.
file://V:\android-sdk-windows\docs\guide\developing\tools\adb.html
9/7/2010
Page 12 of 12
Go to top
file://V:\android-sdk-windows\docs\guide\developing\tools\adb.html
9/7/2010
Page 1 of 2
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 mksdcard dx
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 -l size file Description A volume label for the disk image to create. 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. The path/filename of the disk image to create.
file://V:\android-sdk-windows\docs\guide\developing\tools\othertools.html
9/7/2010
Page 2 of 2
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
Go to top
file://V:\android-sdk-windows\docs\guide\developing\tools\othertools.html
9/7/2010
Page 1 of 9
In this document
Implementing 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
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.
file://V:\android-sdk-windows\docs\guide\developing\tools\aidl.html
9/7/2010
Page 2 of 9
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 interface/method/field declarations are added to the generated interface.
// 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 parameters. BankAccount createAccount(in String name, int startingDeposit, in IAtmService atmService); // All non-Java primitive parameters (e.g., int, bool, 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, because marshalling parameters // is expensive. int getCustomerList(in String branch, out String[] customerList); }
file://V:\android-sdk-windows\docs\guide\developing\tools\aidl.html
9/7/2010
Page 3 of 9
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.
file://V:\android-sdk-windows\docs\guide\developing\tools\aidl.html
9/7/2010
Page 4 of 9
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) { } }; }
file://V:\android-sdk-windows\docs\guide\developing\tools\aidl.html
9/7/2010
Page 5 of 9
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.
file://V:\android-sdk-windows\docs\guide\developing\tools\aidl.html
9/7/2010
Page 6 of 9
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. Set up the UI, then wait * for the user to poke it before doing anything. */ @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 interface of the service. */ private ServiceConnection mConnection = new ServiceConnection() { public void onServiceConnected(ComponentName className, IBinder service) { // This is called when the connection with the service 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 client-side // representation of that from the raw service object. 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 could even // do anything with it; we can count on soon being
file://V:\android-sdk-windows\docs\guide\developing\tools\aidl.html
9/7/2010
Page 7 of 9
// 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 happened. 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 service has been // unexpectedly disconnected -- that is, its process crashed. mService = null; mKillButton.setEnabled(false); mCallbackText.setText("Disconnected."); // As part of the sample, tell the user what happened. Toast.makeText(Binding.this, R.string.remote_service_disconnected, Toast.LENGTH_SHORT).show(); } }; /** * Class for interacting with the secondary interface 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 applications to be // installed that replace the remote service by implementing // 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 registered with // it, then now is the time to unregister. if (mService != null) { try { mService.unregisterCallback(mCallback); } catch (RemoteException e) {
file://V:\android-sdk-windows\docs\guide\developing\tools\aidl.html
9/7/2010
Page 8 of 9
// There is nothing special we need to do if the service // 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 will 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 will // still impose standard restrictions on which PIDs you // are actually able to kill. Typically this means only // the process running your application and any additional // processes created by that app as shown here; packages // sharing a common UID will also be able to kill each // 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 notification. 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 callbacks from the remote * service. */ private IRemoteServiceCallback mCallback = new IRemoteServiceCallback.Stub() { /** * This is called by the remote service regularly to tell us about * new values. Note that IPC calls are dispatched through a thread * pool running in each process, so the code executing here will * NOT be running in our main thread like most other things -- so, * to update the UI, we need to use a Handler to hop over there. */ public void valueChanged(int value) { mHandler.sendMessage(mHandler.obtainMessage(BUMP_MSG, value, 0)); }
file://V:\android-sdk-windows\docs\guide\developing\tools\aidl.html
9/7/2010
Page 9 of 9
}; 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); } } }; } Go to top
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
file://V:\android-sdk-windows\docs\guide\developing\tools\aidl.html
9/7/2010
Page 1 of 6
AVD quickview
You 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 document
Creating 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 Also
Android Emulator
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 commandline utility available in the <sdk>/tools/ directory. Managing AVDs is one of the two main function of the
The Android SDK does not include any preconfigured AVDs, so you need to create an AVD before you can
file://V:\android-sdk-windows\docs\guide\developing\tools\avd.html
9/7/2010
Page 2 of 6
android tool (the other is creating and updating Android projects). Open a terminal window and change to the <sdk>/tools/ directory, if needed
run any application in the emulator (even the Hello World application).
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
file://V:\android-sdk-windows\docs\guide\developing\tools\avd.html
9/7/2010
Page 3 of 6
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.
file://V:\android-sdk-windows\docs\guide\developing\tools\avd.html
9/7/2010
Page 4 of 6
Characteristic Device ram size Touch-screen support Trackball support Keyboard support DPad support GSM modem support Camera support Maximum horizontal camera pixels Maximum vertical camera pixels GPS support Battery support Accelerometer Audio recording support Audio playback support SD Card support Cache partition support Cache partition size Abstracted LCD density
Description The amount of physical RAM on the device, in megabytes. Default value is "96". Whether there is a touch screen or not on the device. Default value is "yes". Whether there is a trackball on the device. Default value is "yes". Whether the device has a QWERTY keyboard. Default value is "yes". Whether the device has DPad keys. Default value is "yes". Whether there is a GSM modem in the device. Default value is "yes". Whether the device has a camera. Default value is "no". Default value is "640". Default value is "480". Whether there is a GPS in the device. Default value is "yes". Whether the device can run on a battery. Default value is "yes". Whether there is an accelerometer in the device. Default value is "yes". Whether the device can record audio. Default value is "yes". Whether the device can play audio. Default value is "yes". Whether the device supports insertion/removal of virtual SD Cards. Default value is "yes". Whether we use a /cache partition on the device. Default value is "yes". Default value is "66MB". Sets the generalized density characteristic used by the AVD's screen. Default value is "160".
Property hw.ramSize hw.touchScreen hw.trackBall hw.keyboard hw.dPad hw.gsmModem hw.camera hw.camera.maxHorizontalPixels hw.camera.maxVerticalPixels hw.gps hw.battery hw.accelerometer hw.audioInput hw.audioOutput hw.sdCard disk.cachePartition disk.cachePartition.size hw.lcd.density
file://V:\android-sdk-windows\docs\guide\developing\tools\avd.html
9/7/2010
Page 5 of 6
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.
file://V:\android-sdk-windows\docs\guide\developing\tools\avd.html
9/7/2010
Page 6 of 6
Option
Description List all known AVDs, with name, path, target, and skin.
Comments
-n <name> or -t <targetID>
The name for the AVD. Target ID of the system image to use with the new AVD. 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. Force creation of the AVD
Required Required. To obtain a list of available targets, use android list targets. Examples: -c path/to/sdcard or -c 1000M
-c <path> or -c <size>[K|M]
-f
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. 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 Required Required
-s <name> or -s <width><height>
Delete the specified AVD. The name of the AVD to move. The path to the new location for the AVD. Rename the AVD. Recompute the paths to all system images.
update avds
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
Go to top
file://V:\android-sdk-windows\docs\guide\developing\tools\avd.html
9/7/2010
Page 1 of 2
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.
bmgr quickview
bmgr lets you control the backup/restore system on an Android device.
In this document
Forcing a Backup Operation Forcing a Restore Operation Other Commands
file://V:\android-sdk-windows\docs\guide\developing\tools\bmgr.html
9/7/2010
Page 2 of 2
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
Go to top
file://V:\android-sdk-windows\docs\guide\developing\tools\bmgr.html
9/7/2010
Page 1 of 5
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.
file://V:\android-sdk-windows\docs\guide\developing\tools\ddms.html
9/7/2010
Page 2 of 5
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
file://V:\android-sdk-windows\docs\guide\developing\tools\ddms.html
9/7/2010
Page 3 of 5
"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.
file://V:\android-sdk-windows\docs\guide\developing\tools\ddms.html
9/7/2010
Page 4 of 5
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.
file://V:\android-sdk-windows\docs\guide\developing\tools\ddms.html
9/7/2010
Page 5 of 5
Go to top
file://V:\android-sdk-windows\docs\guide\developing\tools\ddms.html
9/7/2010
Page 1 of 2
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 mksdcard dx
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 -l size file Description A volume label for the disk image to create. 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. The path/filename of the disk image to create.
file://V:\android-sdk-windows\docs\guide\developing\tools\othertools.html
9/7/2010
Page 2 of 2
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
Go to top
file://V:\android-sdk-windows\docs\guide\developing\tools\othertools.html
9/7/2010
Page 1 of 2
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. 1. From a terminal, launch the draw9patch application from your SDK /tools directory. 2. Drag your PNG image into the Draw 9-patch window (or File > Open 9-patch... to locate the file). Your workspace will now open. The left pane is your drawing area, in which you can edit the lines for the stretchable patches and content area. The right pane is the preview area, where you can preview your graphic when stretched. 3. Click within the 1-pixel perimeter to draw the lines that define the stretchable patches and (optional) content area. Right-click (or hold Shift and click, on Mac) to erase previously drawn lines. 4. When done, select File > Save 9-patch... Your image will be saved with the .9.png file name. Note: A normal PNG file (*.png) will be loaded with an empty one-pixel border added around the image, in which you can draw the stretchable patches and content area. A previously saved 9-patch file (*.9.png) will be loaded as-is, with no drawing area added, because it already exists. Optional controls include: Zoom: Adjust the zoom level of the graphic in the drawing area. Patch scale: Adjust the scale of the images in the preview area. Show lock: Visualize the non-drawable area of the graphic on mouse-over. Show patches: Preview the stretchable patches in the drawing area (pink is a stretchable patch). Show content: Highlight the content area in the preview images (purple is the area in which content is allowed). Show bad patches: Adds a red border around patch areas that may produce artifacts in the graphic when stretched. Visual coherence of your stretched image will be maintained if you eliminate all bad patches.
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
Go to top
file://V:\android-sdk-windows\docs\guide\developing\tools\draw9patch.html
9/7/2010
Page 2 of 2
file://V:\android-sdk-windows\docs\guide\developing\tools\draw9patch.html
9/7/2010
Page 1 of 25
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.
file://V:\android-sdk-windows\docs\guide\developing\tools\emulator.html
9/7/2010
Page 2 of 25
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 Images Runtime Images: User Data and SD Card Temporary Images
Emulator Networking
Network Address Space Local Networking Limitations Using Network Redirections Configuring the Emulator's DNS Settings Using the Emulator with a Proxy Interconnecting Emulator Instances Sending a Voice Call or SMS to Another Emulator Instance
Using Emulator Skins Running Multiple Instances of the Emulator Installing Applications on the Emulator SD Card Emulation
Creating an SD card image using the android tool Creating an SD card image using mksdcard Copying Files to a Disk Image Loading the Disk Image at Emulator Startup
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.
file://V:\android-sdk-windows\docs\guide\developing\tools\emulator.html
9/7/2010
Page 3 of 25
file://V:\android-sdk-windows\docs\guide\developing\tools\emulator.html
9/7/2010
Page 4 of 25
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 Home Menu (left softkey) Star (right softkey) Back Call/dial button Hangup/end call button Search Power button Audio volume up button Audio volume down button Camera button Switch to previous layout orientation (for example, portrait, landscape) Switch to next layout orientation (for example, portrait, landscape) Toggle cell networking on/off Toggle code profiling Toggle fullscreen mode Toggle trackball mode Enter trackball mode temporarily (while key is pressed) DPad left/up/right/down DPad center click Onion alpha increase/decrease Keyboard Key HOME F2 or Page-up button Shift-F2 or Page Down ESC F3 F4 F5 F7 KEYPAD_PLUS, Ctrl-5 KEYPAD_MINUS, Ctrl-F6 Ctrl-KEYPAD_5, Ctrl-F3 KEYPAD_7, Ctrl-F11 KEYPAD_9, Ctrl-F12 F8 F9 (only with -trace startup option) Alt-Enter F6 Delete KEYPAD_4/8/6/2 KEYPAD_5 KEYPAD_MULTIPLY(*) / KEYPAD_DIVIDE (/)
Note that, to use keypad keys, you must first disable NumLock on your development computer.
file://V:\android-sdk-windows\docs\guide\developing\tools\emulator.html
9/7/2010
Page 5 of 25
file://V:\android-sdk-windows\docs\guide\developing\tools\emulator.html
9/7/2010
Page 6 of 25
Category Help
Option -help -help-all -help-<option> -help-debug-tags -help-disk-images -help-environment -help-keys -help-keyset-file -help-virtualdevice
Description Print a list of all emulator options. Print help for all startup options. Print help for a specific startup option. Print a list of all tags for debug <tags>. Print help for using emulator disk images. Print help for emulator environment variables. Print the current mapping of keys. Print help for defining a custom key mappings file. Print help for Android Virtual Device usage. Required. Specifies the AVD to load for this emulator instance. Use <filepath> as the working cache partition image.
Comments
AVD
You must create an AVD configuration before launch emulator. For information, see Android Virtual
Disk Images
Optionally, you can specify a path relative to the curre working 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, use images.
-data <filepath>
Use <filepath> as the working user-data disk image. When resetting the userdata image (through -wipedata), copy the contents of this file to the new user-data disk image. By default, the emulator copies the <system>/userdata.img. Start the emulator without a cache partition. Use <filepath> as the ramdisk image.
Optionally, you can specify a path relative to the curre working directory. If -data is not used, the emulator for a file named "userdata-qemu.img" in the storage a the AVD being used (see -avd).
initdata <filepath>
Optionally, you can specify a path relative to the curre working directory. See also -wipe-data For more information on disk images, use images.
Default value is <system>/ramdisk.img Optionally, you can specify a path relative to the curre working directory. For more information on use -help-disk-images.
file://V:\android-sdk-windows\docs\guide\developing\tools\emulator.html
9/7/2010
Page 7 of 25
-sdcard <filepath>
Default value is <system>/sdcard.img Optionally, you can specify a path relative to the curre working directory. For more information on use -help-disk-images. See also -initdata. For more information on disk images, use 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. Enable/disable debug messages for the specified debug tags. Enable/disable debug messages for the specified debug tag. Disable debug messages for the specified debug tag. Enable logcat output with given tags. Create a root shell console on the current terminal. Enable the root shell (as in shell and specify the QEMU character device to use for communication with the shell.
Debug
-debug <tags>
<tags> is a space/comma/column-separated list of d component names. Use -help-debugof debug component names that you can use. Use -help-debug-tags to print a list of debug component names that you can use in <tag>
-debug-<tag>
If the environment variable ANDROID_LOG_TAGS is defined and not empty, its value will be used to enabl logcat output by default.
-shell
You can use this command even if the adb daemon i emulated system is broken. Pressing Ctrl stops the emulator instead of the shell. <device> must be a QEMU device type. See the documentation for '-serial dev' at http://www.bellard.org/qemu/qemu-doc.html#SEC10 list of device types. Here are some examples: -shell-serial stdio is identical to
-shellserial <device>
-shell-serial fdpair:3:6 lets a communicate with the shell using fds 3 (in) and 6
-shell-serial fdpair:0:1 uses the norma and stdout fds, except that QEMU won't tty data.
Display kernel messages. Enable code profiling (press F9 to start), written to a specified file.
file://V:\android-sdk-windows\docs\guide\developing\tools\emulator.html
9/7/2010
Page 8 of 25
-verbose
Equivalent to -debug-init. You can define the default verbose output options us emulator instances in the Android environment variab ANDROID_VERBOSE. Define the options you in a comma-delimited list, specifying only the stem of option: -debug-<tags>.
Here's an example showing ANDROID_VERBOSE d with the -debug-init and -debug-modem ANDROID_VERBOSE=init,modem For more information about debug tags, use debug-tags>. Media -audio <backend> -audio-in <backend> -audio-out <backend> -noaudio -radio <device> Use the specified audio backend. Use the specified audioinput backend. Use the specified audiooutput backend. Disable audio support in the current emulator instance. Redirect radio modem interface to a host character device. Enable audio support in the current emulator instance. Use the specified DNS server(s). Make all TCP connections through a specified HTTP/HTTPS proxy Enabled by default. The value of <servers> must be a comma of up to 4 DNS server names or IP addresses.
The value of <proxy> can be one of the http://<server>:<port> http://<username>:<password>@<server>:< The http:// prefix can be omitted. If the <proxy> command is not supplied, the the http_proxy environment variable and uses any value matching the <proxy> format describ above.
Set network latency emulation to <delay>. Shortcut for -netspeed full -netdelay none Set network speed emulation to <speed>. Set the console port number for this emulator instance to <port>.
Default value is none. See the table in Network Dela Emulation for supported <delay> values.
Default value is full. See the table in Network Spee Emulation for supported <speed> values.
The console port number must be an even integer be 5554 and 5584, inclusive. <port>+1 must also be fre will be reserved for ADB.
file://V:\android-sdk-windows\docs\guide\developing\tools\emulator.html
9/7/2010
Page 9 of 25
-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>
Supported values for <delay> are integers between 0 1000. Note that the <delay> does not correlate to clock spe other absolute metrics it simply represents an abs relative delay factor applied non-deterministically in th emulator. Effective performance does not always sca direct relationship with <delay> values.
-gps <device>
Use this command to emulate an NMEA unit connected to an external character device or soc The format of <device> must be QEMU device specification. See the documentation for 'seria at http://www.bellard.org/qemu/qemu-doc.html#SEC1
Disable JNI checks in the Dalvik runtime. Pass arguments to qemu. Display qemu help. Redirect radio mode to the specified character device. Set the timezone for the emulated device to <timezone>, instead of the host's timezone.
The format of <device> must be QEMU device specification. See the documentation for at http://www.bellard.org/qemu/qemu-doc.html#SEC1
-timezone <timezone>
Display the emulator's version number. Scale the resolution of the emulator to match the screen size of a physical device. Disable the boot animation during emulator startup. Disable the emulator's graphical window display. Scale the emulator window. The default value is 165. See also -scale
Disabling the boot animation can speed the startup ti the emulator.
<scale> is a number between 0.1 and 3 that the desired scaling factor. You can also specify scale DPI value if you add the suffix "dpi" to the scale value value of "auto" tells the emulator to select the best wi size.
-raw-keys -noskin
file://V:\android-sdk-windows\docs\guide\developing\tools\emulator.html
9/7/2010
Page 10 of 25
-keyset <file>
Use the specified keyset file instead of the default. Use overlay image over screen. Specify onion skin translucency value (as percent). Specify onion skin rotation. This emulator option is deprecated.
The keyset file defines the list of key bindings betwee emulator and the host keyboard. For more informatio -help-keyset to print information about this topic. No support for JPEG. Only PNG is supported. Default is 50.
Please set skin options using AVDs, rather than by u this emulator option. Using this option may unexpected and in some cases misleading results, si the density with which to render the skin may not be defined. AVDs let you associate each skin with a defa density and override the default as needed. For information, see Android Virtual Devices See comments for -skin, above.
-skindir <dir>
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 readonly. 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>).
file://V:\android-sdk-windows\docs\guide\developing\tools\emulator.html
9/7/2010
Page 11 of 25
Name userdata.img
Comments Override using -initdata <file>. Also see data <file>, below.
sdcard.img
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.
file://V:\android-sdk-windows\docs\guide\developing\tools\emulator.html
9/7/2010
Page 12 of 25
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.
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.
file://V:\android-sdk-windows\docs\guide\developing\tools\emulator.html
9/7/2010
Page 13 of 25
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)
file://V:\android-sdk-windows\docs\guide\developing\tools\emulator.html
9/7/2010
Page 14 of 25
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.
file://V:\android-sdk-windows\docs\guide\developing\tools\emulator.html
9/7/2010
Page 15 of 25
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: 1. Set up the server on B, listening to 10.0.2.15:<serverPort> 2. On B's console, set up a redirection from A:localhost:<localPort> to B:10.0.2.15:<serverPort> 3. On C, have the client connect to 10.0.2.2:<localPort> For example, if you wanted to run an HTTP server, you can select <serverPort> as 80 and <localPort> as 8080: B listens on 10.0.2.15:80 On B's console, issue redir add tcp:8080:80 C connects to 10.0.2.2:8080
file://V:\android-sdk-windows\docs\guide\developing\tools\emulator.html
9/7/2010
Page 16 of 25
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 list add <protocol>:<hostport>:<guest-port> Description List the current port redirections. 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>:<hostport> Delete a port redirection. See above for meanings of <protocol> and <host-port>. Comments
file://V:\android-sdk-windows\docs\guide\developing\tools\emulator.html
9/7/2010
Page 17 of 25
Description Send a simple GPS fix to the emulator instance. Send an NMEA 0183 sentence to the emulated device, as if it were sent from an emulated GPS modem.
Comments Specify longitude and latitude in decimal degrees. Specify altitude in meters. <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.
codes <type>
file://V:\android-sdk-windows\docs\guide\developing\tools\emulator.html
9/7/2010
Page 18 of 25
Subcommand display
Description Display battery and charger state. Set AC charging state to on or off. Change battery status as specified. Set battery presence state. Set battery health state. Set remaining battery capacity state (0-100).
Comments
ac <on|off> status <unknown|charging|discharging|notcharging|full> present <true|false> health <unknown|good|overheat|dead|overvoltage|failure> power health <percent>
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
file://V:\android-sdk-windows\docs\guide\developing\tools\emulator.html
9/7/2010
Page 19 of 25
Description GPRS EDGE/EGPRS UMTS/3G No latency Emulate an exact latency (milliseconds). Emulate an specified latency range (min, max milliseconds).
Comments (min 150, max 550) (min 80, max 400) (min 35, max 200) (min 0, max 0)
file://V:\android-sdk-windows\docs\guide\developing\tools\emulator.html
9/7/2010
Page 20 of 25
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.
file://V:\android-sdk-windows\docs\guide\developing\tools\emulator.html
9/7/2010
Page 21 of 25
Description Simulate an inbound phone call from <phonenumber>. Accept an inbound call from <phonenumber> and change the call's state "active". Close an outbound call to <phonenumber> and change the call's state to "busy". Terminate an inbound or outbound phone call to/from <phonenumber>. Change the state of the GPRS data connection to <state>.
Comments
You can change a call's state to "active" only if its current state is "waiting" or "held".
busy <phonenumber>
You can change a call's state to "busy" only if its current state is "waiting".
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 list
Change the state of a call to "held". List all inbound and outbound calls and their states. Change the state of the GPRS voice connection to <state>.
You can change a call's state to "held" only if its current state is "active" or "waiting".
voice <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
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>
file://V:\android-sdk-windows\docs\guide\developing\tools\emulator.html
9/7/2010
Page 22 of 25
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 start stop start Description Start the VM on the instance. Stop the VM on the instance. Display the current status of the VM (running or stopped). Comments
Emulator Window
You can use the window command to manage the emulator window. The usage for the command is: window <scale> The vm command supports the subcommands listed in the table below. Subcommand scale <scale> Description Scale the emulator window. Comments <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.
file://V:\android-sdk-windows\docs\guide\developing\tools\emulator.html
9/7/2010
Page 23 of 25
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.
file://V:\android-sdk-windows\docs\guide\developing\tools\emulator.html
9/7/2010
Page 24 of 25
mksdcard <size> <file> For example: mksdcard 1024M sdcard1.iso For more information, see Other Tools.
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
file://V:\android-sdk-windows\docs\guide\developing\tools\emulator.html
9/7/2010
Page 25 of 25
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
Go to top
file://V:\android-sdk-windows\docs\guide\developing\tools\emulator.html
9/7/2010
Page 1 of 1
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: 1. Connect your device or launch an emulator. 2. From a terminal, launch hierarchyviewer from your SDK /tools directory. 3. 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. 4. 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. 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.
file://V:\android-sdk-windows\docs\guide\developing\tools\hierarchy-viewer.html
9/7/2010
Page 1 of 2
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:
file://V:\android-sdk-windows\docs\guide\developing\tools\layoutopt.html
9/7/2010
Page 2 of 2
$ layoutopt res/layout-land
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
file://V:\android-sdk-windows\docs\guide\developing\tools\layoutopt.html
9/7/2010
Page 1 of 4
Overview
The Monkey is a command-line tool that that you can run on any emulator instance or on a device. It sends a pseudorandom 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.
file://V:\android-sdk-windows\docs\guide\developing\tools\monkey.html
9/7/2010
Page 2 of 4
file://V:\android-sdk-windows\docs\guide\developing\tools\monkey.html
9/7/2010
Page 3 of 4
Category General
Option --help -v
Description Prints a simple usage guide. Each -v on the command line will increment the verbosity level. Level 0 (the default) provides little information beyond startup notification, test completion, and final results. Level 1 provides more details about the test as it runs, such as individual events being sent to your activities. Level 2 provides more detailed setup information such as activities selected or not selected for testing. Seed value for pseudo-random number generator. If you re-run the Monkey with the same seed value, it will generate the same sequence of events. Inserts a fixed delay between events. You can use this option to slow down the Monkey. If not specified, there is no delay and the events are generated as rapidly as possible. Adjust percentage of touch events. (Touch events are a down-up event in a single place on the screen.) Adjust percentage of motion events. (Motion events consist of a down event somewhere on the screen, a series of pseudo-random movements, and an up event.) Adjust percentage of trackball events. (Trackball events consist of one or more random movements, sometimes followed by a click.) Adjust percentage of "basic" navigation events. (Navigation events consist of up/down/left/right, as input from a directional input device.) Adjust percentage of "major" navigation events. (These are navigation events that will typically cause actions within your UI, such as the center button in a 5-way pad, the back key, or the menu key.) Adjust percentage of "system" key events. (These are keys that are generally reserved for use by the system, such as Home, Back, Start Call, End Call, or Volume controls.) Adjust percentage of activity launches. At random intervals, the Monkey will issue a startActivity() call, as a way of maximizing coverage of all activities within your package. Adjust percentage of other types of events. This is a catch-all for all other types of events such as keypresses, other less-used buttons on the device, and so forth. If you specify one or more packages this way, the Monkey will only allow the system to visit activities within those packages. If your application requires access to activities in other packages (e.g. to select a contact) you'll need to specify those packages as well. If you don't specify any packages, the Monkey will allow the system to launch activities in all packages. To specify multiple packages, use the -p option multiple times one -p option per package. If you specify one or more categories this way, the Monkey will only allow the system to visit activities that are listed with one of the specified categories. If you don't specify any categories, the Monkey will select activities listed with the category Intent.CATEGORY_LAUNCHER or Intent.CATEGORY_MONKEY. To specify multiple categories, use the -c option multiple times one -c option per category.
Events
-s <seed>
--throttle <milliseconds> --pct-touch <percent> --pct-motion <percent> --pct-trackball <percent> --pct-nav <percent> --pct-majornav <percent> --pct-syskeys <percent> --pct-appswitch <percent> --pct-anyevent <percent> Constraints -p <allowedpackage-name>
-c <maincategory>
file://V:\android-sdk-windows\docs\guide\developing\tools\monkey.html
9/7/2010
Page 4 of 4
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. 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. 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. 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. 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. 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. Watches for and reports crashes occurring in the Android system native code. If --kill-process-after-error is set, the system will stop. Stops the Monkey from executing until a debugger is attached to it. Go to top
--hprof
--ignorecrashes
--ignoretimeouts
--ignoresecurityexceptions --kill-processafter-error
--monitornative-crashes --wait-dbg
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
file://V:\android-sdk-windows\docs\guide\developing\tools\monkey.html
9/7/2010
Page 1 of 12
ADB quickview
Manage 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 document
Issuing 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 also
Emulator
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.
file://V:\android-sdk-windows\docs\guide\developing\tools\adb.html
9/7/2010
Page 2 of 12
file://V:\android-sdk-windows\docs\guide\developing\tools\adb.html
9/7/2010
Page 3 of 12
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
file://V:\android-sdk-windows\docs\guide\developing\tools\adb.html
9/7/2010
Page 4 of 12
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
file://V:\android-sdk-windows\docs\guide\developing\tools\adb.html
9/7/2010
Page 5 of 12
Category Options
Command -d
Description Direct an adb command to the only attached USB device. Direct an adb command to the only running emulator instance.
Comments Returns an error if more than one USB device is attached. Returns an error if more than one emulator instance is running. If not specified, adb generates an error.
-e
-s <serialNumber>
Direct an adb command a specific emulator/device instance, referred to by its adb-assigned serial number (such as "emulator-5556"). Prints a list of all attached emulator/device instances.
General
devices
Prints a list of supported adb commands. Prints the adb version number. Prints log data to the screen. Prints dumpsys, dumpstate, and logcat data to the screen, for the purposes of bug reporting. Prints a list of available JDWP processes on a given device. You can use the forward jdwp:<pid> portforwarding specification to connect to a specific JDWP process. For example: adb forward tcp:8000 jdwp:472 jdb -attach localhost:8000
jdwp
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. Copies a specified file from an emulator/device instance to your development computer. Copies a specified file from your development computer to an emulator/device instance.
file://V:\android-sdk-windows\docs\guide\developing\tools\adb.html
9/7/2010
Page 6 of 12
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>
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 get-state
Prints the adb instance serial number string. Prints the adb state of an emulator/device instance.
file://V:\android-sdk-windows\docs\guide\developing\tools\adb.html
9/7/2010
Page 7 of 12
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. Terminates the adb server process. Starts a remote shell in the target emulator/device instance. Issues a shell command in the target emulator/device instance and then exits the remote shell. See Issuing Shell Commands for more information.
file://V:\android-sdk-windows\docs\guide\developing\tools\adb.html
9/7/2010
Page 8 of 12
file://V:\android-sdk-windows\docs\guide\developing\tools\adb.html
9/7/2010
Page 9 of 12
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.
stop
file://V:\android-sdk-windows\docs\guide\developing\tools\adb.html
9/7/2010
Page 10 of 12
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
file://V:\android-sdk-windows\docs\guide\developing\tools\adb.html
9/7/2010
Page 11 of 12
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.
file://V:\android-sdk-windows\docs\guide\developing\tools\adb.html
9/7/2010
Page 12 of 12
Go to top
file://V:\android-sdk-windows\docs\guide\developing\tools\adb.html
9/7/2010
Page 1 of 7
In this document
Creating 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
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.
file://V:\android-sdk-windows\docs\guide\developing\tools\traceview.html
9/7/2010
Page 2 of 7
Timeline Panel
The image below shows a close up of the timeline panel. Each threads execution is shown in its own row, with time increasing to the right. Each method is shown in another color (colors are reused in a round-robin fashion starting with the methods that have the most inclusive time). The thin lines underneath the first row show the extent (entry to exit) of all the calls to the selected method. The method in this case is LoadListener.nativeFinished() and it was selected in the profile view.
Traceview timeline panel
file://V:\android-sdk-windows\docs\guide\developing\tools\traceview.html
9/7/2010
Page 3 of 7
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.
file://V:\android-sdk-windows\docs\guide\developing\tools\traceview.html
9/7/2010
Page 4 of 7
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.
file://V:\android-sdk-windows\docs\guide\developing\tools\traceview.html
9/7/2010
Page 5 of 7
*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 section The 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 section One 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] classname [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.
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.
file://V:\android-sdk-windows\docs\guide\developing\tools\traceview.html
9/7/2010
Page 6 of 7
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.
file://V:\android-sdk-windows\docs\guide\developing\tools\traceview.html
9/7/2010
Page 7 of 7
Generate output to <outfile> Turn on HTML output Dump the trace file instead of profiling URL base to the location of the sortable javascript file
Minimum threshold for including child nodes in the graph (child's inclusive time as a percentage of parent inclusive time). If this option is not used, the default threshold is 20%. Go to top
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
file://V:\android-sdk-windows\docs\guide\developing\tools\traceview.html
9/7/2010
Page 1 of 1
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 32bit 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
Go to top
file://V:\android-sdk-windows\docs\guide\developing\tools\zipalign.html
9/7/2010