diff options
Diffstat (limited to 'docs')
142 files changed, 15322 insertions, 5843 deletions
diff --git a/docs/html/guide/appendix/api-levels.jd b/docs/html/guide/appendix/api-levels.jd index 5898fe5..6ab0fc2 100644 --- a/docs/html/guide/appendix/api-levels.jd +++ b/docs/html/guide/appendix/api-levels.jd @@ -294,12 +294,11 @@ Manager</strong>.</p> <p>To run your application against different platform versions in the emulator, create an AVD for each platform version that you want to test. For more information about AVDs, see <a -href="{@docRoot}guide/developing/tools/avd.html">Android Virtual Devices</a>. If +href="{@docRoot}guide/developing/devices/index.html">Creating and Managing Virtual Devices</a>. If you are using a physical device for testing, ensure that you know the API Level of the Android platform it runs. See the table at the top of this document for a list of platform versions and their API Levels. </p> - <h2 id="provisional">Using a Provisional API Level</h2> <p>In some cases, an "Early Look" Android SDK platform may be available. To let diff --git a/docs/html/guide/appendix/glossary.jd b/docs/html/guide/appendix/glossary.jd index 97669ba..06fdef2 100644 --- a/docs/html/guide/appendix/glossary.jd +++ b/docs/html/guide/appendix/glossary.jd @@ -91,8 +91,7 @@ page.title=Glossary with the SDK. It provides screen capture, log dump, and process examination capabilities. If you are developing in Eclipse using the ADT Plugin, DDMS is integrated into your development environment. See <a - href="{@docRoot}guide/developing/tools/ddms.html">Dalvik Debug Monitor - Server</a> to learn more about the program.</dd> + href="{@docRoot}guide/developing/debugging/ddms.html">Using DDMS</a> to learn more about the program.</dd> <dt id="dialog">Dialog</dt> <dd> A floating window that that acts as a lightweight form. A dialog can have button controls only and is intended to perform a diff --git a/docs/html/guide/developing/building/building-cmdline.jd b/docs/html/guide/developing/building/building-cmdline.jd new file mode 100644 index 0000000..f40ad04 --- /dev/null +++ b/docs/html/guide/developing/building/building-cmdline.jd @@ -0,0 +1,306 @@ +page.title=Building and Running Apps on the Command Line +@jd:body + + <div id="qv-wrapper"> + <div id="qv"> + <h2>In this document</h2> + + <ol> + <li><a href="#DebugMode">Building in debug mode</a></li> + + <li><a href="#ReleaseMode">Building in release mode</a></li> + + <li><a href="#RunningOnEmulator">Running on an emulator</a></li> + + <li><a href="#RunningOnDevice">Running on a device</a></li> + </ol> + </div> + </div> + + <p>There are two ways to build your application using the Ant build script: one for + testing/debugging your application — <em>debug mode</em> — and one for building your + final package for release — <em>release mode</em>. Regardless of which way you build your application, + it must be signed before it can install on an emulator or device—with a debug key when building + in debug mode and with your own private key when building in release mode.</p> + + <p>Whether you're building in debug mode or release mode, you need to use the Ant tool to compile + and build your project. This will create the .apk file that you can install on an emulator or device. + When you build in debug mode, the .apk file is automatically signed by the SDK tools with + a debug key, so it's instantly ready for installation onto an emulator or attached + development device. You cannot distribute an application that is signed with a debug key. + When you build in release mode, the .apk file is <em>unsigned</em>, so you + must manually sign it with your own private key, using Keytool and Jarsigner.</p> + + <p>It's important that you read and understand <a href= + "{@docRoot}guide/publishing/app-signing.html">Signing Your Applications</a>, particularly once + you're ready to release your application and share it with end-users. That document describes the + procedure for generating a private key and then using it to sign your .apk file. If you're just + getting started, however, you can quickly run your applications on an emulator or your own + development device by building in debug mode.</p> + + <p>If you don't have Ant, you can obtain it from the <a href="http://ant.apache.org/">Apache Ant + home page</a>. Install it and make sure it is in your executable PATH. Before calling Ant, you + need to declare the JAVA_HOME environment variable to specify the path to where the JDK is + installed.</p> + + <p class="note"><strong>Note:</strong> When installing JDK on Windows, the default is to install + in the "Program Files" directory. This location will cause <code>ant</code> to fail, because of + the space. To fix the problem, you can specify the JAVA_HOME variable like this: + <pre>set JAVA_HOME=c:\Progra~1\Java\<jdkdir> + </pre> + + The easiest solution, however, is to install JDK in a non-space directory, for example: + + <pre>c:\java\jdk1.6.0_02</pre> + + <h2 id="DebugMode">Building in debug mode</h2> + + <p>For immediate application testing and debugging, you can build your application in debug mode + and immediately install it on an emulator. In debug mode, the build tools automatically sign your + application with a debug key and optimize the package with {@code zipalign}.</p> + + <p>To build in debug mode:</p> + + <ol> + <li>Open a command-line and navigate to the root of your project directory.</li> + <li>Use Ant to compile your project in debug mode: + <pre> +ant debug +</pre> + + <p>This creates your debug <code>.apk</code> file inside the project <code>bin/</code> directory, named + <code><your_project_name>-debug.apk</code>. The file is already signed with + the debug key and has been aligned with + <a href="{@docRoot}/guide/developing/tools/zipalign.html"><code>zipalign</code></a>. + </p> + </li> + </ol> + + <p>Each time you change a source file or resource, you must run Ant again in order to package up + the latest version of the application.</p> + + <p>To install and run your application on an emulator, see the following section about <a href= + "#RunningOnEmulator">Running on the Emulator</a>.</p> + + <h2 id="ReleaseMode">Building in release mode</h2> + + <p>When you're ready to release and distribute your application to end-users, you must build your + application in release mode. Once you have built in release mode, it's a good idea to perform + additional testing and debugging with the final .apk.</p> + + <p>Before you start building your application in release mode, be aware that you must sign the + resulting application package with your private key, and should then align it using the {@code + zipalign} tool. There are two approaches to building in release mode: build an unsigned package + in release mode and then manually sign and align the package, or allow the build script to sign + and align the package for you.</p> + + <h3 id="ManualReleaseMode">Build unsigned</h3> + + <p>If you build your application <em>unsigned</em>, then you will need to manually sign and align + the package.</p> + + <p>To build an <em>unsigned</em> .apk in release mode:</p> + + <ol> + <li>Open a command-line and navigate to the root of your project directory.</li> + + <li>Use Ant to compile your project in release mode: + <pre> +ant release +</pre> + </li> + </ol> + + <p>This creates your Android application .apk file inside the project <code>bin/</code> + directory, named <code><em><your_project_name></em>-unsigned.apk</code>.</p> + + <p class="note"><strong>Note:</strong> The .apk file is <em>unsigned</em> at this point and can't + be installed until signed with your private key.</p> + + <p>Once you have created the unsigned .apk, your next step is to sign the .apk with your private + key and then align it with {@code zipalign}. To complete this procedure, read <a href= + "{@docRoot}guide/publishing/app-signing.html">Signing Your Applications</a>.</p> + + <p>When your <code>.apk</code> has been signed and aligned, it's ready to be distributed to end-users. + You should test the final build on different devices or AVDs to ensure that it + runs properly on different platforms.</p> + + <h3 id="AutoReleaseMode">Build signed and aligned</h3> + + <p>If you would like, you can configure the Android build script to automatically sign and align + your application package. To do so, you must provide the path to your keystore and the name of + your key alias in your project's {@code build.properties} file. With this information provided, + the build script will prompt you for your keystore and alias password when you build in release + mode and produce your final application package, which will be ready for distribution.</p> + + <p class="caution"><strong>Caution:</strong> Due to the way Ant handles input, the password that + you enter during the build process <strong>will be visible</strong>. If you are concerned about + your keystore and alias password being visible on screen, then you may prefer to perform the + application signing manually, via Jarsigner (or a similar tool). To instead perform the signing + procedure manually, <a href="#ManualReleaseMode">build unsigned</a> and then continue with + <a href="{@docRoot}guide/publishing/app-signing.html">Signing Your Applications</a>.</p> + + <p>To specify your keystore and alias, open the project {@code build.properties} file (found in + the root of the project directory) and add entries for {@code key.store} and {@code key.alias}. + For example:</p> + <pre> +key.store=path/to/my.keystore +key.alias=mykeystore +</pre> + + <p>Save your changes. Now you can build a <em>signed</em> .apk in release mode:</p> + + <ol> + <li>Open a command-line and navigate to the root of your project directory.</li> + + <li>Use Ant to compile your project in release mode: + <pre> +ant release +</pre> + </li> + + <li>When prompted, enter you keystore and alias passwords. + + <p class="caution"><strong>Caution:</strong> As described above, your password will be + visible on the screen.</p> + </li> + </ol> + + <p>This creates your Android application .apk file inside the project <code>bin/</code> + directory, named <code><em><your_project_name></em>-release.apk</code>. This .apk file has + been signed with the private key specified in {@code build.properties} and aligned with {@code + zipalign}. It's ready for installation and distribution.</p> + + <h3>Once built and signed in release mode</h3> + + <p>Once you have signed your application with a private key, you can install and run it on an + <a href="#RunningOnEmulator">emulator</a> or <a href="#RunningOnDevice">device</a>. You can + also try installing it onto a device from a web server. Simply upload the signed .apk to a web + site, then load the .apk URL in your Android web browser to download the application and begin + installation. (On your device, be sure you have enabled + <em>Settings > Applications > Unknown sources</em>.)</p> + + <h2 id="RunningOnEmulator">Running on the emulator</h2> + + <p>Before you can run your application on the Android Emulator, you must <a href= + "{@docRoot}guide/developing/devices/managing-avds.html">create an AVD</a>.</p> + + <p>To run your application:</p> + + <ol> + <li> + <strong>Open the SDK and AVD Manager and launch a virtual device</strong> + + <p>From your SDK's <code>platform-tools/</code> directory, execute the {@code android} tool with no + arguments:</p> + <pre> +android +</pre> + + <p>In the <em>Virtual Devices</em> view, select an AVD and click <strong>Start</strong>.</p> + </li> + + <li> + <strong>Install your application</strong> + + <p>From your SDK's <code>tools/</code> directory, install the {@code .apk} on the + emulator:</p> + <pre> +adb install <em><path_to_your_bin></em>.apk +</pre> + + <p>Your .apk file (signed with either a release or debug key) is in your project {@code bin/} + directory after you build your application.</p> + + <p>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 <code>-s</code> option. For + example:</p> + <pre> +adb -s emulator-5554 install <em>path/to/your/app</em>.apk +</pre> + + <p>To see a list of available device serial numbers, execute {@code adb devices}.</p> + </li> + </ol> + + <p>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 application for the + first time, it won't show up in the application launcher or be accessible by other applications. + This is because the package manager usually examines manifests completely only on emulator + startup.</p> + + <p>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 <a href= + "{@docRoot}guide/practices/screens_support.html">screen type</a> you support, then test your + application on each one.</p> + + <p class="note"><strong>Tip:</strong> If you have <em>only one</em> 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 <em>install mode</em>: <code>ant + install</code>. This will build your application, sign it with the debug key, and install it on + the currently running emulator.</p> + + <h2 id="RunningOnDevice">Running on a device</h2> + + <p>Before you can run your application on a device, you must perform some basic setup for your + device:</p> + + <ul> + <li>Ensure that your application is debuggable by setting the + <code>android:debuggable</code> attribute of the <code><application></code> + element to <code>true</code>. As of ADT 8.0, this is done by default when you build in debug mode.</li> + + <li>Enable USB Debugging on your device. You can find the setting on most Android devices by + going to <strong>Settings > Applications > Development > USB debugging</strong>.</li> + + <li>Ensure that your development computer can detect your device when connected via USB</li> + </ul> + + <p>Read <a href="{@docRoot}guide/developing/device.html#setting-up">Setting up a Device for + Development</a> for more information.</p> + + <p>Once your device is set up and connected via USB, navigate to your SDK's <code>platform-tools/</code> + directory and install the <code>.apk</code> on the device:</p> + <pre> +adb -d install <em>path/to/your/app</em>.apk +</pre> + + <p>The {@code -d} flag specifies that you want to use the attached device (in case you also have + an emulator running).</p> + + <p>For more information on the tools used above, please see the following documents:</p> + + <ul> + <li><a href="{@docRoot}guide/developing/tools/android.html">android Tool</a></li> + + <li><a href="{@docRoot}guide/developing/devices/emulator.html">Android Emulator</a></li> + + <li><a href="{@docRoot}guide/developing/tools/adb.html">Android Debug Bridge</a> (ADB)</li> + </ul> + + <h2 id="Signing">Application Signing</h2> + + <p>As you begin developing Android applications, understand that all Android applications must be + digitally signed before the system will install them on an emulator or device. There are two ways + to do this: with a <em>debug key</em> (for immediate testing on an emulator or development + device) or with a <em>private key</em> (for application distribution).</p> + + <p>The Android build tools help you get started by automatically signing your .apk files with a + debug key at build time. This means that you can compile your application and install it on the + emulator without having to generate your own private key. However, please note that if you intend + to publish your application, you <strong>must</strong> sign the application with your own private + key, rather than the debug key generated by the SDK tools.</p> + + <p>The ADT plugin helps you get started quickly by signing your .apk files with a debug key, + prior to installing them on an emulator or development device. This means that you can quickly + run your application from Eclipse without having to generate your own private key. No specific + action on your part is needed, provided ADT has access to Keytool.However, please note that if + you intend to publish your application, you <strong>must</strong> sign the application with your + own private key, rather than the debug key generated by the SDK tools.</p> + + <p>Please read <a href="{@docRoot}guide/publishing/app-signing.html">Signing Your + Applications</a>, which provides a thorough guide to application signing on Android and what it + means to you as an Android application developer. The document also includes a guide to exporting + and signing your application with the ADT's Export Wizard.</p>
\ No newline at end of file diff --git a/docs/html/guide/developing/building/building-eclipse.jd b/docs/html/guide/developing/building/building-eclipse.jd new file mode 100644 index 0000000..2c610c1 --- /dev/null +++ b/docs/html/guide/developing/building/building-eclipse.jd @@ -0,0 +1,163 @@ +page.title=Building and Running Apps in Eclipse +@jd:body + +<div id="qv-wrapper"> + <div id="qv"> + <h2>In this document</h2> + + <ol> + <li><a href="#RunningOnEmulatorEclipse">Running on an Emulator</a></li> + + <li><a href="#RunningOnDeviceEclipse">Running on a Device</a></li> + + <li><a href="#RunConfig">Creating a Run Configuration</a></li> + </ol> + </div> + </div> + + <p>Eclipse and ADT provide an environment where most of the details of the build process are + hidden from you. By default, the build process constantly runs in the background as you make + changes to your project.</p> + + <p>When Eclipse automatically builds your application, it enables debugging and signs the + <code>.apk</code> with a debug key, by default. When you run the application, + Eclipse invokes ADB and installs your application to a device or emulator, so you do not have to + manually perform these tasks. Since most of the build process is taken care of by Eclipse, the + following topics show you how to run an application, which will automatically build your + application as well.</p> + + <p>To distribute your application, however, you must build your application in release mode and sign the + <code>.apk</code> file with your own private key.</p> + + <p>This document shows you how to run your application on an emulator or a real device + from Eclipse—all of which is done using the debug version of your application. + For more information about how to sign your application with a private key for release, see <a href= + "{@docRoot}guide/publishing/app-signing.html#ExportWizard">Signing Your Applications</a></p> + + <h2 id="RunningOnEmulatorEclipse">Running on the emulator</h2> + + <p>Before you can run your application on the Android Emulator, you must <a href= + "{@docRoot}guide/developing/devices/managing-avds.html">create an AVD</a>.</p> + + <p>To run (or debug) your application, select <strong>Run</strong> > <strong>Run</strong> (or + <strong>Run</strong> > <strong>Debug</strong>) from the Eclipse menu bar. The ADT plugin will + automatically create a default run configuration for the project. Eclipse will then perform the + following:</p> + + <ol> + <li>Compile the project (if there have been changes since the last build).</li> + + <li>Create a default run configuration (if one does not already exist for the project).</li> + + <li>Install and start the application on an emulator (or device), based on the Deployment + Target defined by the run configuration. + + <p>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 + <a href="#AutoAndManualTargetModes">Automatic and manual target modes</a> below.</p> + </li> + </ol> + + <p>If you run the application with the Debug option, the application will start in the "Waiting For Debugger" mode. Once the debugger + is attached, Eclipse opens the Debug perspective and starts the application's main activity. Otherwise, if you run the + application with the normal Run option, Eclipse installs the application on the device and launches the main activity.</p> + + <p>To set or change the run configuration used for your project, use the run configuration + manager. See the section below about <a href="#RunConfig">Creating a Run Configuration</a> for more information.</p> + + <p>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 <a href= + "{@docRoot}guide/practices/screens_support.html">screen type</a> you support, then test your + application on each one.</p> + + <h2 id="RunningOnDeviceEclipse">Running on a device</h2> + + <p>Before you can run your application on a device, you must perform some basic setup for your + device:</p> + + <ul> + <li>Ensure that your application is debuggable by setting the + <code>android:debuggable</code> attribute of the <code><application></code> + element to <code>true</code>. As of ADT 8.0, this is done by default when you build in debug mode.</li> + + <li>Enable USB Debugging on your device. You can find the setting on most Android devices by + going to <strong>Settings > Applications > Development > USB debugging</strong>.</li> + + <li>Ensure that your development computer can detect your device when connected via USB</li> + </ul> + + <p>Read <a href="{@docRoot}guide/developing/device.html">Connecting Hardware Devices</a> + for more information.</p> + + <p>Once set up and your device is connected via USB, install your application on the device by + selecting <strong>Run</strong> > <strong>Run</strong> (or <strong>Run</strong> > + <strong>Debug</strong>) from the Eclipse menu bar.</p> + + <h2 id="RunConfig">Creating a Run Configuration</h2> + + <p>The run configuration specifies the project to run, the Activity to start, the emulator or + connected device to use, and so on. When you first run a project as an <em>Android + Application</em>, ADT will automatically create a run configuration. The default run + configuration will launch the default project Activity and use automatic target mode for device + selection (with no preferred AVD). If the default settings don't suit your project, you can + customize the run configuration or even create a new one.</p> + + <p>To create or modify a run configuration, refer to the Eclipse documentation on how to create Run configurations. + The following steps highlight the important things you need to do for an Android project:</p> + + <ol> + <li>Open the run configuration manager from the Run Menu.</li> + + <li>Expand the <strong>Android Application</strong> item and create a new configuration or open + an existing one. + </li> + + <li>With the Run Configuration selected, adjust your desired run configuration settings: + <ul> + <li>In the Android tab, specify the Project and Activity to launch. + </li> + <li><p>In the Target tab, consider whether you'd like to use Manual or Automatic mode when + selecting an AVD to run your application. See the following section on <a href= + "#AutoAndManualTargetModes">Automatic and manual target modes</a>).</p> + + <p>You can specify any emulator options to the Additional Emulator Command Line Options + field. For example, you could add <code>-scale 96dpi</code> to scale the AVD's screen to an + accurate size, based on the dpi of your computer monitor. For a full list of emulator + options, see the <a href="{@docRoot}guide/developing/tools/emulator.html">Android + Emulator</a> document.</p> + </li> + </ul> + </li> + </ol> + + <h4 id="AutoAndManualTargetModes">Automatic and manual target modes</h4> + + <p>By default, a run configuration uses the <strong>automatic</strong> target mode in order to + select an AVD. In this mode, ADT will select an AVD for the application in the following + manner:</p> + + <ol> + <li>If there's a device or emulator already running and its AVD configuration meets the + requirements of the application's build target, the application is installed and run upon + it.</li> + + <li>If there's more than one device or emulator running, each of which meets the requirements + of the build target, a "device chooser" is shown to let you select which device to use.</li> + + <li>If there are no devices or emulators running that meet the requirements of the build + target, ADT looks at the available AVDs. If there is an AVD that matches the build target of the project, + ADT chooses that AVD. If the AVD versions are newer than the build target of the project, ADT chooses + the oldest possible version of an AVD that meets the project's build target requirement.</li> + + <li>If there are no suitable AVDs, the application is not installed a console error warning tells + you that there is no existing AVD that meets the build target requirements.</li> + </ol> + + <p>However, if a "preferred AVD" is selected in the run configuration, then the application will + <em>always</em> be deployed to that AVD. If it's not already running, then a new emulator will be + launched.</p> + + <p>If your run configuration uses <strong>manual</strong> mode, then the "device chooser" is + presented every time that your application is run, so that you can select which AVD to use.</p>
\ No newline at end of file diff --git a/docs/html/guide/developing/building/index.jd b/docs/html/guide/developing/building/index.jd new file mode 100644 index 0000000..25a6e23 --- /dev/null +++ b/docs/html/guide/developing/building/index.jd @@ -0,0 +1,81 @@ +page.title=Building and Running Apps +@jd:body + +<div id="qv-wrapper"> + <div id="qv"> + <h2>In this document</h2> + <ol> + <li><a href="#detailed-build">A Detailed Look at the Build Process</a></li> + </ol> + </div> + </div> + + <p>During the build process, your Android projects are compiled and packaged into an .apk file, + the container for your application binary. It contains all of the information necessary to run + your application on a device or emulator, such as compiled <code>.dex</code> files (<code>.class</code> files + converted to Dalvik byte code), a binary version of the <code>AndroidManifest.xml</code> file, compiled + resources (<code>resources.arsc</code>) and uncompiled resource files for your application.</p> + + <p>If you are developing in Eclipse, the ADT plugin incrementally builds your project as you + make changes to the source code. Eclipse outputs an <code>.apk</code> file automatically to the bin folder of + the project, so you do not have to do anything extra to generate the <code>.apk</code>.</p> + + <p>If you are developing in a non-Eclipse environment, you can build your project with the + generated <code>build.xml</code> Ant file that is in the project directory. The Ant file calls targets that + automatically call the build tools for you.</p> + + <p>To run an application on an emulator or device, the application must be signed using debug or + release mode. You typically want to sign your application in debug mode when you develop and test + your application, because the build tools use a debug key with a known password so you do not have + to enter it every time you build. When you are ready to release the application to Android + Market, you must sign the application in release mode, using your own private key.</p> + + <p>Fortunately, Eclipse or your Ant build script signs the application for you in debug mode + when you build your application. You can also easily setup Eclipse or your Ant build to sign your + application in release mode as well. For more information on signing applications, see <a href= + "{@docRoot}guide/publishing/app-signing.html">Signing Your Applications</a>.</p> + + <p>The following diagram depicts the components involved in building and running an application:</p> + + <img src="{@docRoot}images/build-simplified.png" /> + + <h2 id="detailed-build">A Detailed Look at the Build Process</h2> + + <p>The build process involves many tools and processes that generate intermediate files on the + way to producing an <code>.apk</code>. If you are developing in Eclipse, the complete build process is + automatically done periodically as you develop and save your code changes. If you are using other + IDEs, this build process is done every time you run the generated Ant build script for your + project. It is useful, however, to understand what is happening under the hood since much of the + tools and processes are masked from you. The following diagram depicts the different tools and + processes that are involved in a build:</p> + + <p><img src="{@docRoot}images/build.png" /></p> + + <p>The general process for a typical build is outlined below:</p> + + <ul> + + <li>The Android Asset Packaging Tool (aapt) takes your application resource files, such as the + <code>AndroidManifest.xml</code> file and the XML files for your Activities, and compiles them. An <code>R.java</code> is + also produced so you can reference your resources from your Java code.</li> + + <li>The aidl tool converts any <code>.aidl</code> interfaces that you have into Java interfaces.</li> + + <li>All of your Java code, including the <code>R.java</code> and <code>.aidl</code> files, are compiled by the Java + compiler and .class files are output.</li> + + <li>The dex tool converts the .class files to Dalvik byte code. Any 3rd party libraries and + .class files that you have included in your project are also converted into <code>.dex</code> files so that + they can be packaged into the final <code>.apk</code> file.</li> + + <li>All non-compiled resources (such as images), compiled resources, and the .dex files are + sent to the apkbuilder tool to be packaged into an <code>.apk</code> file.</li> + + <li>Once the <code>.apk</code> is built, it must be signed with either a debug or release key before it can + be installed to a device.</li> + + <li>Finally, if the application is being signed in release mode, you must align the <code>.apk</code> with + the zipalign tool. Aligning the final <code>.apk</code> decreases memory usage when the application is + running on a device.</li> + </ul> + diff --git a/docs/html/guide/developing/debug-tasks.html b/docs/html/guide/developing/debug-tasks.html new file mode 100644 index 0000000..4e73804 --- /dev/null +++ b/docs/html/guide/developing/debug-tasks.html @@ -0,0 +1,10 @@ +<html> +<head> +<meta http-equiv="refresh" content="0;url=http://developer.android.com/guide/developing/debugging/index.html"> +<title>Redirecting...</title> +</head> +<body> +<p>You should be redirected. Please <a +href="http://developer.android.com/guide/developing/debugging/index.html">click here</a>.</p> +</body> +</html>
\ No newline at end of file diff --git a/docs/html/guide/developing/debug-tasks.jd b/docs/html/guide/developing/debug-tasks.jd deleted file mode 100644 index 8f40b48..0000000 --- a/docs/html/guide/developing/debug-tasks.jd +++ /dev/null @@ -1,232 +0,0 @@ -page.title=Debugging Tasks -@jd:body - -<div id="qv-wrapper"> -<div id="qv"> - <h2>In this document</h2> - <ol> - <li><a href="#tools">Tools</a></li> - <li><a href="#additionaldebugging">Debug with Dev Tools</a></li> - <li><a href="#DebuggingWebPages">Debugging Web Pages</a></li> - <li><a href="#toptips">Top Debugging Tips</a></li> - <li><a href="#ide-debug-port">Configuring Your IDE to Attach to the Debugging Port</a></li> - </ol> -</div> -</div> - -<p>This document offers some helpful guidance to debugging applications on Android. - - -<h2 id="tools">Tools</h2> - -<p>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:</p> - -<dl> - <dt><strong><a href="{@docRoot}guide/developing/tools/adb.html">Android Debug Bridge -(ADB)</a></strong></dt> - <dd>Provides various device management capabilities, including - moving and syncing files to the emulator, forwarding ports, and running a UNIX - shell on the emulator.</dd> - <dt><strong><a href="{@docRoot}guide/developing/tools/ddms.html">Dalvik Debug Monitor Server -(DDMS)</a></strong></dt> - <dd>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.</dd> - </dd> - <dt><strong><a href="{@docRoot}guide/developing/tools/traceview.html">Traceview</a></strong></dt> - <dd>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.</dd> - <dt><strong><a href="{@docRoot}guide/developing/tools/ddms.html#logcat">logcat</a></strong></dt> - <dd>Dumps a log of system - messages. The messages include a stack trace when the device throws an error, - as well as {@link android.util.Log} messages you've written from your application. To run - logcat, execute <code>adb logcat</code> from your Android SDK {@code platform-tools/} -directory or, from DDMS, select <strong>Device > Run - logcat</strong>. When using the <a href="{@docRoot}sdk/eclipse-adt.html">ADT plugin for -Eclipse</a>, you can also view logcat messages by opening the Logcat view, available from -<strong>Window > Show View > Other > Android > Logcat</strong>. - <p>{@link android.util.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: - {@link android.util.Log#v(String,String)} (verbose), {@link - android.util.Log#d(String,String)} (debug), {@link android.util.Log#i(String,String)} - (information), {@link android.util.Log#w(String,String)} (warning) and {@link - android.util.Log#e(String,String)} (error). For example:</p> -<pre class="no-pretty-print"> -Log.i("MyActivity", "MyClass.getView() — get item number " + position); -</pre> - <p>The logcat will then output something like:</p> -<pre class="no-pretty-print"> -I/MyActivity( 1557): MyClass.getView() — get item number 1 -</pre> - <p>Logcat is also the place to look when debugging a web page in the Android Browser app. See -<a href="#DebuggingWebPages">Debugging Web Pages</a> below.</p> -</dl> - -<p>For more information about all the development tools provided with the Android SDK, see the <a -href="{@docRoot}guide/developing/tools/index.html">Tools</a> document.</p> - -<p>In addition to the above tools, you may also find the following useful for debugging: -<dl> - <dt><a href="{@docRoot}guide/developing/eclipse-adt.html"><strong>Eclipse ADT -plugin</strong></a></dt> - <dd>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.</dd> - <dt><strong>Developer Settings in the Dev Tools app</strong></dt> - <dd>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 <a -href="#additionaldebugging">Debugging and Testing with Dev Tools</a> below.</dd> -</dl> - -<h2 id="additionaldebugging">Debugging and Testing with Dev Tools</h2> - -<p>With the Dev Tools application, you can enable a number of settings on your device that will -make it easier to test and debug your applications.</p> - -<p>The Dev Tools application is installed by default -on all system images included with the SDK, so you can use it with the Android Emulator. If you'd -like to install the Dev Tools application on a real development device, you can copy the -application from your emulator and then install it on your device using ADB. To copy the -application from a running emulator, execute: -</p> -<pre> -adb -e pull /system/app/Development.apk ./Development.apk -</pre> -<p>This copies the .apk file into the current directory. Then install it on your connected device -with:</p> -<pre> -adb -d install Development.apk -</pre> - -<p>To get started, launch the Dev Tools application and -select Development Settings. This will open the Development Settings page with the -following options (among others):</p> - -<dl> - <dt><strong>Debug app</strong></dt> - <dd>Lets you select the application to debug. You do not need to set this to attach a debugger, - but setting this value has two effects: - <ul> - <li>It will prevent Android from throwing an error if you pause on - a breakpoint for a long time while debugging.</li> - <li>It will enable you to select the <em>Wait for Debugger</em> option - to pause application startup until your debugger attaches (described - next). </li> - </ul> - </dd> - <dt><strong>Wait for debugger</strong></dt> - <dd>Blocks the selected application from loading until a debugger attaches. This - way you can set a breakpoint in onCreate(), which is important to debug - the startup process of an Activity. When you change this option, any - currently running instances of the selected application will be killed. - In order to check this box, you must have selected a debug application - as described in the previous option. You can do the same thing by adding - {@link android.os.Debug#waitForDebugger()} to your code.</dd> - <dt><strong>Show screen updates</strong></dt> - <dd>Flashes a momentary pink rectangle on any screen sections that are being - redrawn. This is very useful for discovering unnecessary screen drawing.</dd> - <dt><strong>Immediately destroy activities</strong></dt> - <dd>Tells the - system to destroy an activity as soon as it is stopped (as if Android had to - reclaim memory). This is very useful for testing the {@link android.app.Activity#onSaveInstanceState} - / {@link android.app.Activity#onCreate(android.os.Bundle)} code path, which would - otherwise be difficult to force. Choosing this option will probably reveal - a number of problems in your application due to not saving state.</dd> - <dt><strong>Show CPU usage</strong></dt> - <dd>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. <em>Note: You cannot turn this feature off - once it is on, without restarting the emulator.</em> </dd> - <dt><strong>Show background</strong></dt> - <dd>Displays a background pattern - when no activity screens are visible. This typically does not happen, but - can happen during debugging.</dd> -</dl> - -<p>These settings will be remembered across emulator restarts.</p> - -<h2 id="DebuggingWebPages">Debugging Web Pages</h2> - -<p>See the <a href="{@docRoot}guide/webapps/debugging.html">Debugging Web Apps</a> document.</p> - - -<h2 id="toptips">Top Debugging Tips</h2> - -<dl> -<dt><strong>Dump the stack trace</strong></dt> -<dd>To obtain a stack dump from emulator, you can log -in with <code>adb shell</code>, use "ps" to find the process you -want, and then "kill -3 ". The stack trace appears in the log file. -</dd> - -<dt><strong>Display useful info on the emulator screen</strong></dt> -<dd>The device can display useful information such as CPU usage or highlights -around redrawn areas. Turn these features on and off in the developer settings -window as described in <a href="#additionaldebugging">Setting debug and test -configurations on the emulator</a>. -</dd> - -<dt><strong>Get system state information from the emulator (dumpstate)</strong></dt> -<dd>You can access dumpstate information from the Dalvik Debug Monitor Service -tool. See <a href="{@docRoot}guide/developing/tools/adb.html#dumpsys">dumpsys and -dumpstate</a> on the adb topic page.</dd> - -<dt><strong>Get application state information from the emulator (dumpsys)</strong></dt> -<dd>You can access dumpsys information from the Dalvik Debug Monitor Service -tool. See <a href="{@docRoot}guide/developing/tools/adb.html#dumpsys">dumpsys and -dumpstate</a> on the adb topic page.</dd> - -<dt><strong>Get wireless connectivity information</strong></dt> -<dd>You can get information about wireless connectivity using the Dalvik Debug -Monitor Service tool. From the <strong>Device</strong> menu, select "Dump -radio state".</dd> - -<dt><strong>Log trace data</strong></dt> -<dd>You can log method calls and other tracing data in an activity by calling -{@link android.os.Debug#startMethodTracing(String) startMethodTracing()}. See <a -href="{@docRoot}guide/developing/tools/traceview.html">Running the Traceview Debugging -Program</a> for details. </dd> - -<dt><strong>Log radio data</strong></dt> -<dd>By default, radio information is not logged to the system (it is a lot of -data). However, you can enable radio logging using the following commands: - -<pre class="no-pretty-print"> -adb shell -logcat -b radio -</pre> -</dd> - -<dt><strong>Capture screenshots</strong></dt> -<dd>The Dalvik Debug Monitor Server (DDMS) can capture screenshots from the emulator. Select -<strong>Device > Screen capture</strong>.</dd> - -<dt><strong>Use debugging helper classes</strong></dt> -<dd>Android provides debug helper classes such as {@link android.util.Log - util.Log} and {@link android.os.Debug} for your convenience. </dd> -</dl> - -<p>Also see the <a href="{@docRoot}resources/faq/troubleshooting.html">Troubleshooting</a> document -for answers to some common developing and debugging issues.</p> - - -<h2 id="ide-debug-port">Configuring Your IDE to Attach to the Debugging Port</h2> - -<p>DDMS will assign a specific debugging port to every virtual machine that it - finds on the emulator. You must either attach your IDE to that - port (listed on the Info tab for that VM), or you can use a default port 8700 - to connect to whatever application is currently selected on the list of discovered - virtual machines.</p> -<p>Your IDE should attach to your application running on the emulator, showing you - its threads and allowing you to suspend them, inspect their state, and set breakpoints. - If you selected "Wait for debugger" in the Development settings panel - the application will run when Eclipse connects, so you will need to set any breakpoints - you want before connecting.</p> -<p>Changing either the application being debugged or the "Wait for debugger" - option causes the system to kill the selected application if it is currently - running. You can use this to kill your application if it is in a bad state - by simply going to the settings and toggling the checkbox.</p> diff --git a/docs/html/guide/developing/debugging/ddms.jd b/docs/html/guide/developing/debugging/ddms.jd new file mode 100644 index 0000000..8f5e706 --- /dev/null +++ b/docs/html/guide/developing/debugging/ddms.jd @@ -0,0 +1,284 @@ +page.title=Using DDMS +@jd:body + + <div id="qv-wrapper"> + <div id="qv"> + <h2>In this document</h2> + + <ol> + <li><a href="#running">Running DDMS</a></li> + <li><a href="#how-ddms-works">How DDMS Interacts with a Debugger</a></li> + + <li><a href="#using-ddms">Using DDMS</a></li> + </ol> + </div> + </div> + + <p>Android ships with a debugging tool called the Dalvik Debug Monitor Server (DDMS), which + provides port-forwarding services, screen capture on the device, thread and heap information on + the device, logcat, process, and radio state information, incoming call and SMS spoofing, + location data spoofing, and more. This page provides a modest discussion of DDMS features; it is + not an exhaustive exploration of all the features and capabilities.</p> + + <h2 id="running">Running DDMS</h2> + <p>DDMS is integrated into Eclipse and is also shipped in the <code>tools/</code> directory of the + SDK. DDMS works with both the emulator and a connected device. If both are connected and running simultaneously, + DDMS defaults to the emulator.</p> + + <ul> + <li>From Eclipse: Click <strong>Window > Open Perspective > Other... > DDMS</strong>.</li> + <li>From the command line: Type <code>ddms</code> (or <code>./ddms</code> on Mac/Linux) from the <code>tools/</code> + directory. </li> + </ul> + + + <h2 id="how-ddms-works">How DDMS Interacts with a Debugger</h2> + + <p>On Android, every application runs in its own process, each of which runs in its own virtual machine + (VM). Each VM exposes a unique port that a debugger can attach to.</p> + + <p>When DDMS starts, it connects to <a href="{@docRoot}guide/developing/tools/adb.html">adb</a>. + When a device is connected, a VM monitoring service is created between + <code>adb</code> and DDMS, which notifies DDMS when a VM on the device is started or terminated. Once a VM + is running, DDMS retrieves the the VM's process ID (pid), via <code>adb</code>, and opens a connection to the + VM's debugger, through the adb daemon (adbd) on the device. DDMS can now talk to the VM using a + custom wire protocol.</p> + + <p>DDMS assigns a debugging port to each VM on the device. Typically, + DDMS assigns port 8600 for the first debuggable VM, the next on 8601, and so on. When a debugger + connects to one of these ports, all traffic is forwarded to the debugger from the associated + VM. You can only attach a single debugger to a single port, but DDMS can handle multiple, attached + debuggers.</p> + + <p>By default, DDMS also listens on another debugging port, the DDMS "base port" (8700, by default). + The base port is a port forwarder, which can accept VM traffic from any debugging port and forward + it to the debugger on port 8700. This allows you to attach one debugger to port 8700, and debug + all the VMs on a device. The traffic that is forwarded is determined by the currently selected process + in the DDMS Devices view.</p> + + <p>The following screenshot shows a typical DDMS screen in Eclipse. If you are starting DDMS from + the command line, the screen is slightly different, but much of the functionality is identical. + Notice that the highlighted process, <code>com.example.android.notepad</code>, that is running in the emulator + has the debugging port 8700 assigned to it as well as 8609. This signifies that DDMS is currently + forwarding port 8609 to the static debugging port of 8700.</p> + + <img src="{@docRoot}images/debug-ddms.png" + width="1024" /> + <p class="img-caption"><strong>Figure 1.</strong> + Screenshot of DDMS</p> + + <p>If you are not using Eclipse and ADT, read <a href= + "{@docRoot}guide/developing/debugging/debugging-projects-cmdline.html#debuggingPort">Configuring + your IDE to attach to the debugging port</a>, for more information on attaching your + debugger.</p> + + <p class="note"><strong>Tip:</strong> You can set a number of DDMS preferences in + <strong>File</strong> > <strong>Preferences</strong>. Preferences are saved to + <code>$HOME/.ddmsrc</code>.</p> + + <p class="warning"><strong>Known debugging issues with Dalvik</strong><br /> + Debugging an application in the Dalvik VM should work the same as it does in other VMs. However, + when single-stepping out of synchronized code, the "current line" cursor may jump to the last + line in the method for one step.</p> + + <h2 id="using-ddms">Using DDMS</h2> + The following sections describe how to use DDMS and the various tabs and panes that are part of the + DDMS GUI. The Eclipse version and the command line version have minor UI differences, but the + same functionality. For information on running DDMS, see the previous section in this document, + <a href="#running">Running DDMS</a>. + + + <h3>Viewing heap usage for a process</h3> + + <p>DDMS allows you to view how much heap memory a process is using. This information is useful in + tracking heap usage at a certain point of time during the execution of your application.</p> + <p>To view heap usage for a process:</p> + <ol> + <li>In the Devices tab, select the process that you want to see the heap information for.</li> + + <li>Click the <strong>Update Heap</strong> button to enable heap information for the + process.</li> + + <li>In the Heap tab, click <strong>Cause GC</strong> to invoke garbage collection, which + enables the collection of heap data. When the operation completes, you will see a group of + object types and the memory that has been allocated for each type. You can click <strong>Cause + GC</strong> again to refresh the data.</li> + + <li>Click on an object type in the list to see a bar graph that shows the number of objects + allocated for a particular memory size in bytes.</li> + </ol> + + <h3>Tracking memory allocation of objects</h3> + + <p>DDMS provides a feature to track objects that are being allocated to memory and to see which + classes and threads are allocating the objects. This allows you to track, in real time, where + objects are being allocated when you perform certain actions in your application. This + information is valuable for assessing memory usage that can affect application performance. + If you want more granular control over where allocation data is collected, use the + {@link android.os.Debug#startAllocCounting()} and {@link android.os.Debug#stopAllocCounting()} + methods.</p> + + <p>To track memory allocation of objects:</p> + <ol> + <li>In the Devices tab, select the process that you want to enable allocation tracking + for.</li> + + <li>In the Allocation Tracker tab, click the <strong>Start Tracking</strong> button to begin + allocation tracking. At this point, anything you do in your application will be tracked.</li> + + <li>Click <strong>Get Allocations</strong> to see a list of objects that have been allocated + since you clicked on the <strong>Start Tracking</strong> button. You can click on <strong>Get + Allocations</strong> again to append to the list new objects that that have been + allocated.</li> + + <li>To stop tracking or to clear the data and start over, click the <strong>Stop Tracking + button</strong>.</li> + + <li>Click on a specific row in the list to see more detailed information such as the method and + line number of the code that allocated the object.</li> + </ol> + + <h3>Working with an emulator or device's file system</h3> + + <p>DDMS provides a File Explorer tab that allows you to view, copy, and delete files on the + device. This feature is useful in examining files that are created by your application or if you + want to transfer files to and from the device.</p> + + <p>To work with an emulator or device's file system:</p> + <ol> + <li>In the Devices tab, select the emulator that you want to view the file system for.</li> + + <li>To copy a file from the device, locate the file in the File Explorer and click the + <strong>Pull file</strong> button.</li> + + <li>To copy a file to the device, click the <strong>Push file</strong> button on the File + Explorer tab.</li> + </ol> + + <!-- Need to elaborate more on where things are stored in the file system, + databases, apks, user info, files that are important to look at --> + + <h3>Examining thread information</h3> + + <p>The Threads tab in DDMS shows you the currently running threads for a selected process.</p> + + <ol> + <li>In the Devices tab, select the process that you want to examine the threads for.</li> + + <li>Click the <strong>Update Threads</strong> button.</li> + + <li>In the Threads tab, you can view the thread information for the selected process.</li> + </ol> + + <h3 id="profiling">Starting method profiling</h3> + + <p>Method profiling is a means to track certain metrics about a method, such as number of calls, + execution time, and time spent executing the method. If you want more granular control over + where profiling data is collected, use the {@link android.os.Debug#startMethodTracing()} and + {@link android.os.Debug#stopMethodTracing()} methods. For more information about generating trace logs, see + <a href="debugging-tracing.html">Profiling and Debugging UIs</a>.</p> + + <p>Before you start method profiling in DDMS, be aware of the following restrictions:</p> + <ul> + <li>Android 1.5 devices are not supported.</li> + <li>Android 2.1 and earlier devices must + have an SD card present and your application must have permission to write to the SD card. + <li>Android 2.2 and later devices do not need an SD card. The trace log files are + streamed directly to your development machine.</li> + </ul> + + <p>To start method profiling:</p> + <ol> + <li>On the Devices tab, select the process that you want to enable method profiling for.</li> + + <li>Click the <strong>Start Method Profiling</strong> button.</li> + + <li>Interact with your application to start the methods that you want to profile.</li> + + <li>Click the <strong>Stop Method Profiling</strong> button. DDMS stops profiling your + application and opens <a href="{@docRoot}guide/developing/debugging/debugging-ui.html">Traceview</a> + with the method profiling information that was collected + between the time you clicked on <strong>Start Method Profiling</strong> and <strong>Stop Method + Profiling</strong>.</li> + </ol> + + <h3 id="logcat">Using LogCat</h3> + + <p>LogCat is integrated into DDMS, and outputs the messages that you print out using the {@link android.util.Log} + class along with other system messages such as stack traces when exceptions are thrown. View the + <a href="{@docRoot}guide/developing/debugging/debugging-log.html">Reading and + Writing Log Messages.</a> topic for more information on how to log messages to the LogCat.</p> + + <p>When you have set up your logging, you can use the LogCat feature of DDMS to filter certain + messages with the following buttons:</p> + + <ul> + <li>Verbose</li> + + <li>Debug</li> + + <li>Info</li> + + <li>Warn</li> + + <li>Error</li> + </ul> + + <p>You can also setup your own custom filter to specify more details such as filtering messages + with the log tags or with the process id that generated the log message. The add filter, + edit filter, and delete filter buttons let you manage your custom filters.</p> + + <h3>Emulating phone operations and location</h3> + <p>The Emulator control tab lets you simulate a + phone's voice and data network status. This is useful when you want to test your application's + robustness in differing network environments.</p> + + <h4>Changing network state, speed, and latency</h4> + <p>The Telephony Status section of the Emulator + controls tab lets you change different aspects of the phone's networks status, speed and latency. + The following options are available to you and are effective immediately after you set them:</p> + + <ul> + <li>Voice - unregistered, home, roaming, searching, denied</li> + + <li>Data - unregistered, home, roaming, searching, denied</li> + + <li>Speed - Full, GSM, HSCSD, GPRS, EDGE, UMTS, HSDPA</li> + + <li>Latency - GPRS, EDGE, UMTS</li> + </ul> + + <h4>Spoofing calls or SMS text messages</h4> + <p>The Telephony Actions section of the Emulator + controls tab lets you spoof calls and messages. This is useful when you want to to test your + application's robustness in responding to incoming calls and messages that are sent to the phone. + The following actions are available to you:</p> + + <ul> + <li>Voice - Enter a number in the <strong>Incoming number</strong> field and click + <strong>Call</strong> to send a simulated call to the emulator or phone. Click the + <strong>Hang up</strong> button to terminate the call.</li> + + <li>SMS - Enter a number in the <strong>Incoming number</strong> field and a message in the + <strong>Message:</strong> field and click the <strong>Send</strong> button to send the + message.</li> + </ul> + + <h4>Setting the location of the phone</h4> + <p>If your application depends on the location of the phone, you can have DDMS send your + device or AVD a mock location. This is useful if you + want to test different aspects of your application's location specific features without + physically moving. The following geolocation data types are available to you:</p> + + <ul> + <li>Manual - set the location by manually specifying decimal or sexagesimal longitude and + latitude values.</li> + + <li>GPX - GPS eXchange file</li> + + <li>KML - Keyhole Markup Language file</li> + </ul> + + For more information about providing mock location data, see + <a href="{@docRoot}guide/topics/location/obtaining-user-location.html#MockData">Obtaining User Location</a>. + diff --git a/docs/html/guide/developing/debugging/debugging-devtools.jd b/docs/html/guide/developing/debugging/debugging-devtools.jd new file mode 100644 index 0000000..88e6005 --- /dev/null +++ b/docs/html/guide/developing/debugging/debugging-devtools.jd @@ -0,0 +1,82 @@ +page.title=Using the Dev Tools App +@jd:body + +<p>The Dev Tools application is installed by default on all system images included with the SDK, + so you can use it with the Android Emulator. With the Dev Tools application, you can enable a + number of settings on your device that will make it easier to test and debug your applications.</p> + + <p> If you'd like to install the Dev Tools application + on a real development device, you can copy the application from your emulator and then install it + on your device using ADB. To copy the application from a running emulator, execute:</p> + <pre> +adb -e pull /system/app/Development.apk ./Development.apk +</pre> + + <p>This copies the .apk file into the current directory. Then install it on your connected device + with:</p> + <pre> +adb -d install Development.apk +</pre> + + <p>To get started, launch the Dev Tools application and select <strong>Development Settings</strong>. This will + open the Development Settings page with the following options (among others):</p> + + <dl> + <dt><strong>Debug app</strong></dt> + + <dd> + Lets you select the application to debug. You do not need to set this to attach a debugger, + but setting this value has two effects: + + <ul> + <li>It will prevent Android from throwing an error if you pause on a breakpoint for a long + time while debugging.</li> + + <li>It will enable you to select the <em>Wait for Debugger</em> option to pause application + startup until your debugger attaches (described next).</li> + </ul> + </dd> + + <dt><strong>Wait for debugger</strong></dt> + + <dd>Blocks the selected application from loading until a debugger attaches. This way you can + set a breakpoint in {@link android.app.Activity#onCreate onCreate()}, + which is important to debug the startup process of an Activity. + When you change this option, any currently running instances of the selected application will + be killed. In order to check this box, you must have selected a debug application as described + in the previous option. You can do the same thing by adding {@link + android.os.Debug#waitForDebugger()} to your code.</dd> + + <dt><strong>Show screen updates</strong></dt> + + <dd>Flashes a momentary pink rectangle on any screen sections that are being redrawn. This is + very useful for discovering unnecessary screen drawing.</dd> + + <dt><strong>Immediately destroy activities</strong></dt> + + <dd>Tells the system to destroy an activity as soon as it is stopped (as if Android had to + reclaim memory). This is very useful for testing the {@link + android.app.Activity#onSaveInstanceState} / {@link + android.app.Activity#onCreate(android.os.Bundle)} code path, which would otherwise be difficult + to force. Choosing this option will probably reveal a number of problems in your application + due to not saving state. For more information about saving an application's state, see + <a href="{@docRoot}guide/topics/resources/runtime-changes.html">Handling Runtime Changes</a>.</dd> + + <dt><strong>Show CPU usage</strong></dt> + + <dd>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. + <p class="note">Note: You cannot turn this feature off once it is on, without + restarting the emulator.</p></dd> + + <dt><strong>Show background</strong></dt> + + <dd>Displays a background pattern when no activity screens are visible. This typically does not + happen, but can happen during debugging.</dd> + </dl> + + <p>These settings will be remembered across emulator restarts.</p> + + + diff --git a/docs/html/guide/developing/debugging/debugging-log.jd b/docs/html/guide/developing/debugging/debugging-log.jd new file mode 100644 index 0000000..6ee69c7 --- /dev/null +++ b/docs/html/guide/developing/debugging/debugging-log.jd @@ -0,0 +1,305 @@ +page.title=Reading and Writing Log Messages +@jd:body + +<div id="qv-wrapper"> + <div id="qv"> + <h2>In this document</h2> + + <ol> + <li><a href="#logClass">The Log class</a></li> + + <li><a href="#startingLogcat">Starting LogCat</a></li> + + <li><a href="#filteringOutput">Filtering Log Output</a></li> + + <li><a href="#outputFormat">Controlling Log Output Format</a></li> + + <li><a href="#alternativeBuffers">Viewing Alternative Log Output Buffers</a></li> + + <li><a href="#viewingStd">Viewing stdout and stderr</a></li> + + <li><a href="#DebuggingWebPages">Debugging Web Pages</a></li> + </ol> + </div> + </div> + + <p>The Android logging system provides a mechanism for collecting and viewing system debug + output. Logcat dumps a log of system messages, which include things such as stack traces when the + emulator throws an error and messages that you have written from your application by using the + {@link android.util.Log} class. You can run LogCat through ADB or from DDMS, which allows you to + read the messages in real time.</p> + + <h2 id="logClass">The <code>Log</code> class</h2> + + <p>{@link android.util.Log} is a logging class that you can utilize in your code to print out + messages to the LogCat. Common logging methods include:</p> + + <ul> + <li>{@link android.util.Log#v(String,String)} (verbose)</li> + + <li>{@link android.util.Log#d(String,String)} (debug)</li> + + <li>{@link android.util.Log#i(String,String)} (information)</li> + + <li>{@link android.util.Log#w(String,String)} (warning)</li> + + <li>{@link android.util.Log#e(String,String)} (error)</li> + </ul>For example: + <pre class="no-pretty-print"> +Log.i("MyActivity", "MyClass.getView() — get item number " + position); +</pre> + + <p>The LogCat will then output something like:</p> + <pre class="no-pretty-print"> +I/MyActivity( 1557): MyClass.getView() — get item number 1 +</pre> + + <h2 id="startingLogcat">Using LogCat</h2> + + <p>You can use LogCat from within DDMS or call it on an ADB shell. For more information on how to + use LogCat within DDMS, see <a href="{@docRoot}guide/developing/debugging/ddms.html#logcat">Using + DDMS</a>. To run LogCat, through the ADB shell, the general usage is:</p> + <pre> +[adb] logcat [<option>] ... [<filter-spec>] ... +</pre> + + <p>You can use the <code>logcat</code> 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</p> + <pre> +$ adb logcat +</pre> + + <p>and from a remote adb shell you use</p> + <pre> +# logcat +</pre> + + <p>The following table describes the <code>logcat</code> command line options:</p> + + <table> + <tr> + <td><code>-c</code></td> + + <td>Clears (flushes) the entire log and exits.</td> + </tr> + + <tr> + <td><code>-d</code></td> + + <td>Dumps the log to the screen and exits.</td> + </tr> + + <tr> + <td><code>-f <filename></code></td> + + <td>Writes log message output to <code><filename></code>. The default is + <code>stdout</code>.</td> + </tr> + + <tr> + <td><code>-g</code></td> + <td>Prints the size of the specified log buffer and exits.</td> + </tr> + + <tr> + <td><code>-n <count></code></td> + + <td>Sets the maximum number of rotated logs to <code><count></code>. The default value + is 4. Requires the <code>-r</code> option.</td> + </tr> + + <tr> + <td><code>-r <kbytes></code></td> + + <td>Rotates the log file every <code><kbytes></code> of output. The default value is + 16. Requires the <code>-f</code> option.</td> + </tr> + + <tr> + <td><code>-s</code></td> + + <td>Sets the default filter spec to silent.</td> + </tr> + + <tr> + <td><code>-v <format></code></td> + + <td>Sets the output format for log messages. The default is <code>brief</code> format. For a + list of supported formats, see <a href="#outputFormat">Controlling Log Output + Format</a>.</td> + </tr> + </table> + + <h3 id="filteringOutput">Filtering Log Output</h3> + + <p>Every Android log message has a <em>tag</em> and a <em>priority</em> associated with it.</p> + + <ul> + <li>The tag of a log message is a short string indicating the system component from which the + message originates (for example, "View" for the view system).</li> + + <li>The priority is one of the following character values, ordered from lowest to highest + priority:</li> + + <li style="list-style: none; display: inline"> + <ul> + <li><code>V</code> — Verbose (lowest priority)</li> + + <li><code>D</code> — Debug</li> + + <li><code>I</code> — Info</li> + + <li><code>W</code> — Warning</li> + + <li><code>E</code> — Error</li> + + <li><code>F</code> — Fatal</li> + + <li><code>S</code> — Silent (highest priority, on which nothing is ever printed)</li> + </ul> + </li> + </ul> + + <p>You can obtain a list of tags used in the system, together with priorities, by running + LogCat and observing the first two columns of each message, given as + <code><priority>/<tag></code>.</p> + + <p>Here's an example of logcat output that shows that the message relates to priority level "I" + and tag "ActivityManager":</p> + <pre> +I/ActivityManager( 585): Starting activity: Intent { action=android.intent.action...} +</pre> + + <p>To reduce the log output to a manageable level, you can restrict log output using <em>filter + expressions</em>. Filter expressions let you indicate to the system the tags-priority + combinations that you are interested in — the system suppresses other messages for the + specified tags.</p> + + <p>A filter expression follows this format <code>tag:priority ...</code>, where <code>tag</code> + indicates the tag of interest and <code>priority</code> indicates the <em>minimum</em> level of + priority to report for that tag. Messages for that tag at or above the specified priority are + written to the log. You can supply any number of <code>tag:priority</code> specifications in a + single filter expression. The series of specifications is whitespace-delimited.</p> + + <p>Here's an example of a filter expression that suppresses all log messages except those with + the tag "ActivityManager", at priority "Info" or above, and all log messages with tag "MyApp", + with priority "Debug" or above:</p> + <pre> +adb logcat ActivityManager:I MyApp:D *:S +</pre> + + <p>The final element in the above expression, <code>*:S</code>, sets the priority level for all + tags to "silent", thus ensuring only log messages with "View" and "MyApp" are displayed. Using + <code>*:S</code> is an excellent way to ensure that log output is restricted to the filters that + you have explicitly specified — it lets your filters serve as a "whitelist" for log + output.</p> + + <p>The following filter expression displays all log messages with priority level "warning" and higher, on all tags:</p> + <pre> +adb logcat *:W +</pre> + + <p>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 <code>ANDROID_LOG_TAGS</code>:</p> + <pre> +export ANDROID_LOG_TAGS="ActivityManager:I MyApp:D *:S" +</pre> + + <p>Note that <code>ANDROID_LOG_TAGS</code> filter is not exported to the emulator/device + instance, if you are running LogCat from a remote shell or using <code>adb shell + logcat</code>.</p> + + <h3 id="outputFormat">Controlling Log Output Format</h3> + + <p>Log messages contain a number of metadata fields, in addition to the tag and priority. You can + modify the output format for messages so that they display a specific metadata field. To do so, + you use the <code>-v</code> option and specify one of the supported output formats listed + below.</p> + + <ul> + <li><code>brief</code> — Display priority/tag and PID of originating process (the default + format).</li> + + <li><code>process</code> — Display PID only.</li> + + <li><code>tag</code> — Display the priority/tag only.</li> + + <li><code>thread</code> — Display process:thread and priority/tag only.</li> + + <li><code>raw</code> — Display the raw log message, with no other metadata fields.</li> + + <li><code>time</code> — Display the date, invocation time, priority/tag, and PID of the + originating process.</li> + + <li><code>long</code> — Display all metadata fields and separate messages with blank + lines.</li> + </ul> + + <p>When starting LogCat, you can specify the output format you want by using the + <code>-v</code> option:</p> + <pre> +[adb] logcat [-v <format>] +</pre> + + <p>Here's an example that shows how to generate messages in <code>thread</code> output + format:</p> + <pre> +adb logcat -v thread +</pre> + + <p>Note that you can only specify one output format with the <code>-v</code> option.</p> + + <h3 id="alternativeBuffers">Viewing Alternative Log Buffers</h3> + + <p>The Android logging system keeps multiple circular buffers for log messages, and not all of + the log messages are sent to the default circular buffer. To see additional log messages, you can + run the <code>logcat</code> command with the <code>-b</code> option, to request viewing of an alternate + circular buffer. You can view any of these alternate buffers:</p> + + <ul> + <li><code>radio</code> — View the buffer that contains radio/telephony related + messages.</li> + + <li><code>events</code> — View the buffer containing events-related messages.</li> + + <li><code>main</code> — View the main log buffer (default)</li> + </ul> + + <p>The usage of the <code>-b</code> option is:</p> + <pre> +[adb] logcat [-b <buffer>] +</pre> + + <p>Here's an example of how to view a log buffer containing radio and telephony messages:</p> + <pre> +adb logcat -b radio +</pre><a name="stdout" + id="stdout"></a> + + <h2 id="viewingStd">Viewing stdout and stderr</h2> + + <p>By default, the Android system sends <code>stdout</code> and <code>stderr</code> + (<code>System.out</code> and <code>System.err</code>) output to <code>/dev/null</code>. In + processes that run the Dalvik VM, you can have the system write a copy of the output to the log + file. In this case, the system writes the messages to the log using the log tags + <code>stdout</code> and <code>stderr</code>, both with priority <code>I</code>.</p> + + <p>To route the output in this way, you stop a running emulator/device instance and then use the + shell command <code>setprop</code> to enable the redirection of output. Here's how you do it:</p> + <pre> +$ adb shell stop +$ adb shell setprop log.redirect-stdio true +$ adb shell start +</pre> + + <p>The system retains this setting until you terminate the emulator/device instance. To use the + setting as a default on the emulator/device instance, you can add an entry to + <code>/data/local.prop</code> on the device.</p> + + <h2 id="DebuggingWebPages">Debugging Web Apps</h2> + <p> + If you're developing a web application for Android, you can debug your JavaScript using the console JavaScript APIs, + which output messages to LogCat. For more information, see + <a href="{@docRoot}guide/webapps/debugging.html">Debugging Web Apps</a>.</p>
\ No newline at end of file diff --git a/docs/html/guide/developing/debugging/debugging-projects-cmdline.jd b/docs/html/guide/developing/debugging/debugging-projects-cmdline.jd new file mode 100644 index 0000000..72bb16d --- /dev/null +++ b/docs/html/guide/developing/debugging/debugging-projects-cmdline.jd @@ -0,0 +1,76 @@ +page.title=Debugging in other IDEs +@jd:body + + + <div id="qv-wrapper"> + <div id="qv"> + <h2>In this document</h2> + + <ol> + <li><a href="#start-debugging">Starting a Debugging Environment</a> + <ul> + <li><a href="#debuggingPort">Configuring Your IDE to Attach to the Debugging Port</a></li> + </ul> + </li> + </ol> + </div> + </div> + + <p>If you are not using Eclipse to develop, you can still take advantage of all the tools that + the Android SDK provides for debugging. A basic debugging environment consists of:</p> + + <ul> + <li><a href="{@docRoot}guide/developing/tools/adb.html">ADB</a></li> + + <li><a href="{@docRoot}guide/developing/debugging/ddms.html">DDMS</a></li> + + <li>Java Debugger</li> + </ul> + + <p>You need to obtain a JDWP-compliant Java debugger to properly debug your application. + Most Java IDEs will already have one included, or you can use a command line debugger, + such as JDB, if you are using a simple text editor to develop applications.</p> + + <h2 id="start-debugging">Starting a debugging environment</h2> + <p>A Java Debugger assists you in finding problems with + your code by letting you set breakpoints, step through execution of your application, and examine + variable values. Since you are not using Eclipse, you have to manually start up the debugging + environment yourself by running a few tools that are provided in the Android SDK. To begin + debugging your application, follow these general steps:</p> + + <ol> + <li>Load an AVD with the Android emulator or connect a device to your computer.</li> + + <li>Start DDMS from the sdk <code>/tools</code> directory. This also starts ADB if it is + not already started. You should see your device appear in DDMS.</li> + + <li>Install and run your <code>.apk</code> file on the device or emulator. In DDMS, you should see your + application running under the device that you installed it to.</li> + + <li>Attach your debugger to the debugging port 8700, or to the specific port shown for the + application in DDMS.</li> + </ol> + + <h3 id="debuggingPort">Configuring Your IDE to Attach to the Debugging Port</h3> + + <p>DDMS assigns a specific debugging port to every virtual machine that it finds on the + emulator. You must either attach your IDE to that port (listed on the Info tab for that VM), or + you can use a default port 8700 to connect to whatever application is currently selected on the + list of discovered virtual machines.</p> + + <p>Your IDE should attach to your application running on the emulator, showing you its threads + and allowing you to suspend them, inspect their state, and set breakpoints. If you selected "Wait + for debugger" in the Development settings panel the application will run when Eclipse connects, + so you will need to set any breakpoints you want before connecting.</p> + + <p>Changing either the application being debugged or the "Wait for debugger" option causes the + system to kill the selected application if it is currently running. You can use this to kill your + application if it is in a bad state by simply going to the settings and toggling the + checkbox.</p> + + + + + + + diff --git a/docs/html/guide/developing/debugging/debugging-projects.jd b/docs/html/guide/developing/debugging/debugging-projects.jd new file mode 100644 index 0000000..0e14999 --- /dev/null +++ b/docs/html/guide/developing/debugging/debugging-projects.jd @@ -0,0 +1,65 @@ +page.title=Debugging in Eclipse +@jd:body + + <div id="qv-wrapper"> + <div id="qv"> + <h2>In this document</h2> + + <ol> + <li><a href="#tools">The Debug Perspective</a></li> + + <li><a href="#toptips">The DDMS Perspective</a></li> + </ol> + </div> + </div> + + <p>If you are developing in Eclipse with the ADT plugin, you can use the built-in Java Debugger, + along with DDMS, to debug your applications. To access the debugger and + DDMS, Eclipse displays the debugger and DDMS features as perspectives, which are customized + Eclipse views that display certain tabs and windows depending on the perspective that you are in. + Eclipse also takes care of starting the ADB host daemon for you, so you do not have to run this + manually.</p> + + <h2>The Debug Perspective in Eclipse</h2> + + <p>The Debug Perspective in Eclipse gives you access to the following tabs:</p> + + <ul> + <li>Debug - Displays previously and currently debugged Android applications and its currently + running threads</li> + + <li>Variables - When breakpoints are set, displays variable values during code execution</li> + + <li>Breakpoints - Displays a list of the set breakpoints in your application code</li> + + <li>LogCat - Allows you to view system log messages in real time. The LogCat tab is also + available in the DDMS perspective.</li> + </ul> + <p>You can access the Debug Perspective by clicking <strong>Window > Open Perspective > + Debug</strong>. Refer to the appropriate documentation for the Eclipse debugger for more + information.</p> + + <h2>The DDMS Perspective</h2> + <p>The DDMS Perspective in Eclipse lets you access all of the features + of DDMS from within the Eclipse IDE. The following sections of DDMS are available to you:</p> + + <ul> + <li>Devices - Shows the list of devices and AVDs that are connected to ADB.</li> + + <li>Emulator Control - Lets you carry out device functions.</li> + + <li>LogCat - Lets you view system log messages in real time.</li> + + <li>Threads - Shows currently running threads within a VM.</li> + + <li>Heap - Shows heap usage for a VM.</li> + + <li>Allocation Tracker - Shows the memory allocation of objects.</li> + + <li>File Explorer - Lets you explore the device's file system.</li> + </ul> + <p>To access the DDMS perspective, go to <strong>Window > Open Perspective > + DDMS</strong>. If DDMS does not appear, go to <strong>Window > Open Perspective > Other + ...</strong> and select <strong>DDMS</strong> from the Open Perspective window that appears. For + more information on using DDMS, see <a href="ddms.html">Using the Dalvik Debug Monitor Server</a>. + </p>
\ No newline at end of file diff --git a/docs/html/guide/developing/debugging/debugging-tracing.jd b/docs/html/guide/developing/debugging/debugging-tracing.jd new file mode 100644 index 0000000..0401966 --- /dev/null +++ b/docs/html/guide/developing/debugging/debugging-tracing.jd @@ -0,0 +1,400 @@ +page.title=Profiling with Traceview and dmtracedump +@jd:body + + <div id="qv-wrapper"> + <div id="qv"> + <h2>In this document</h2> + + <ol> + <li> + <a href="#traceviewLayout">Traceview Layout</a> + + <ol> + <li><a href="#timelinepanel">Timeline Panel</a></li> + + <li><a href="#profilepanel">Profile Panel</a></li> + </ol> + </li> + + <li> + <a href="#format">Traceview File Format</a> + <ol> + <li><a href="#datafileformat">Data File Format</a></li> + + <li><a href="#keyfileformat">Key File Format</a></li> + </ol> + </li> + + <li><a href="#creatingtracefiles">Creating Trace Files</a></li> + + <li><a href="#copyingfiles">Copying Trace Files to a Host Machine</a></li> + + <li><a href="#runningtraceview">Viewing Trace Files in Traceview</a></li> + + <li><a href="#dmtracedump">Using dmtracedump</a></li> + + <li><a href="#knownissues">Traceview Known Issues</a></li> + </ol> + </div> + </div> + + <p>Traceview is a graphical viewer for execution logs that you create by using the {@link + android.os.Debug} class to log tracing information in your code. Traceview can help you debug + your application and profile its performance.</p> + + <h2 id="traceviewLayout">Traceview Layout</h2> + + <p>When you have a trace log file (generated by adding tracing code to your application or by DDMS), + you can have Traceview load the log files and display their data in a window visualizes your application + in two panels:</p> + + <ul> + <li>A <a href="#timelinepanel">timeline panel</a> -- describes when each thread and method + started and stopped</li> + + <li>A <a href="#timelinepanel">profile panel</a> -- provides a summary of what happened inside + a method</li> + </ul> + + <p>The sections below provide addition information about the traceview output panes.</p> + + <h3 id="timelinepanel">Timeline Panel</h3> + + <p>The image below shows a close up of the timeline panel. Each thread’s execution is shown + in its own row, with time increasing to the right. Each method is shown in another color (colors + are reused in a round-robin fashion starting with the methods that have the most inclusive time). + The thin lines underneath the first row show the extent (entry to exit) of all the calls to the + selected method. The method in this case is <code>LoadListener.nativeFinished()</code> and it was selected in + the profile view.</p> + + <img src="{@docRoot}images/traceview_timeline.png" + alt="Traceview timeline panel" + width="893" + height="284" /> + <p class="img-caption"><strong>Figure 1.</strong> The Traceview Timeline Panel</p> + + <h3 id="profilepanel">Profile Panel</h3> + + <p>Figure 2 shows the profile pane, a summary of all the time spent + in a method. The table shows both the inclusive and exclusive times (as well as the percentage of + the total time). Exclusive time is the time spent in the method. Inclusive time is the time spent + in the method plus the time spent in any called functions. We refer to calling methods as + "parents" and called methods as "children." When a method is selected (by clicking on it), it + expands to show the parents and children. Parents are shown with a purple background and children + with a yellow background. The last column in the table shows the number of calls to this method + plus the number of recursive calls. The last column shows the number of calls out of the total + number of calls made to that method. In this view, we can see that there were 14 calls to + <code>LoadListener.nativeFinished();</code> looking at the timeline panel shows that one of those calls took + an unusually long time.</p> + + <img src="{@docRoot}images/traceview_profile.png" + alt="Traceview profile panel." + width="892" + height="630" /> + <p class="img-caption"><strong>Figure 2.</strong> The Traceview Profile Panel</p> + + <h2 id="format">Traceview File Format</h2> + + <p>Tracing creates two distinct pieces of output: a <em>data</em> file, which holds the trace + data, and a <em>key</em> file, which provides a mapping from binary identifiers to thread and + method names. The files are concatenated when tracing completes, into a single <em>.trace</em> + file.</p> + + <p class="note"><strong>Note:</strong> The previous version of Traceview did not concatenate + these files for you. If you have old key and data files that you'd still like to trace, you can + concatenate them yourself with <code>cat mytrace.key mytrace.data > + mytrace.trace</code>.</p> + + <h3 id="datafileformat">Data File Format</h3> + + <p>The data file is binary, structured as follows (all values are stored in little-endian + order):</p> + <pre> +* File format: +* header +* record 0 +* record 1 +* ... +* +* Header format: +* u4 magic 0x574f4c53 ('SLOW') +* u2 version +* u2 offset to data +* u8 start date/time in usec +* +* Record format: +* u1 thread ID +* u4 method ID | method action +* u4 time delta since start, in usec +</pre> + + <p>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.</p> + + <p><em>u8 start date/time in usec</em> is the output from <code>gettimeofday()</code>. It's mainly there so + that you can tell if the output was generated yesterday or three months ago.</p> + + <p><em>method action</em> sits in the two least-significant bits of the <em>method</em> word. The + currently defined meanings are:</p> + + <ul> + <li>0 - method entry</li> + + <li>1 - method exit</li> + + <li>2 - method "exited" when unrolled by exception handling</li> + + <li>3 - (reserved)</li> + </ul> + + <p>An unsigned 32-bit integer can hold about 70 minutes of time in microseconds.</p> + + <h3 id="keyfileformat">Key File Format</h3> + + <p>The key file is a plain text file divided into three sections. Each section starts with a + keyword that begins with '*'. If you see a '*' at the start of a line, you have found the start + of a new section.</p> + + <p>An example file might look like this:</p> + <pre> +*version +1 +clock=global +*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 +</pre> +<p>The following list describes the major sections of a key file:</p> + <dl> + <dt><em>version section</em></dt> + + <dd>The first line is the file version number, currently 1. The second line, + <code>clock=global</code>, 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.</dd> + + <dt><em>threads section</em></dt> + + <dd>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.</dd> + + <dt><em>methods section</em></dt> + + <dd>One line per method entry or exit. A line consists of four pieces, separated by tab marks: + <em>method-ID</em> [TAB] <em>class-name</em> [TAB] <em>method-name</em> [TAB] + <em>signature</em> . 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.</dd> + </dl> + + <p>Neither the threads nor methods sections are sorted.</p> + + <h2 id="creatingtracefiles">Creating Trace Files</h2> + + <p>To use Traceview, you need to generate log files containing the trace information you want to + analyze.</p> + + <p>There are two ways to generate trace logs:</p> + <ul> + <li>Include the {@link android.os.Debug} class in your code and call its + methods to start and stop logging of trace information to disk. This method is very precise because + you can specify in your code exactly where to start and stop logging trace data.</li> + <li>Use the method profiling feature of DDMS to generate trace logs. This method is less + precise since you do not modify code, but rather specify when to start and stop logging with + a DDMS. Although you have less control on exactly where the data is logged, this method is useful + if you don't have access to the application's code, or if you do not need the precision of the first method. + </li> + </ul> + + <p>Before you start generating trace logs, be aware of the following restrictions:</p> + <ul> + <li>If you are using the {@link android.os.Debug} class, your device or emulator must have an SD card + and your application must have permission to write to the SD card. </li> + <li>If you are using DDMS, Android 1.5 devices are not supported.</li> + <li>If you are using DDMS, Android 2.1 and earlier devices must + have an SD card present and your application must have permission to write to the SD card. + <li>If you are using DDMS, Android 2.2 and later devices do not need an SD card. The trace log files are + streamed directly to your development machine.</li> + </ul> + + <p>This document focuses on using the {@link android.os.Debug} class to generate trace data. For more information on using DDMS + to generate trace data, see <a href="ddms.html#profiling">Using the Dalvik Debug Monitor Server.</a> + </p> + + <p>To create the trace files, include the {@link android.os.Debug} class and call one of the + {@link android.os.Debug#startMethodTracing() startMethodTracing()} methods. In the call, you + specify a base name for the trace files that the system generates. To stop tracing, call {@link + android.os.Debug#stopMethodTracing() stopMethodTracing()}. These methods start and stop method + tracing across the entire virtual machine. For example, you could call + {@link android.os.Debug#startMethodTracing() startMethodTracing()} in + your activity's {@link android.app.Activity#onCreate onCreate()} method, and call + {@link android.os.Debug#stopMethodTracing() stopMethodTracing()} in that activity's + {@link android.app.Activity#onDestroy()} method.</p> + <pre> + // start tracing to "/sdcard/calc.trace" + Debug.startMethodTracing("calc"); + // ... + // stop tracing + Debug.stopMethodTracing(); +</pre> + + <p>When your application calls startMethodTracing(), the system creates a file called + <code><trace-base-name>.trace</code>. This contains the binary method trace data and a + mapping table with thread and method names.</p> + + <p>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.</p> + + <p>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.</p> + + <p>When using the Android emulator, you must specify an SD card when you create your AVD because the trace files + are written to the SD card. Your application must have permission to write to the SD card as well. + + <p>The format of the trace files is previously described <a href="#format">in this + document</a>.</p> + + <h2 id="copyingfiles">Copying Trace Files to a Host Machine</h2> + + <p>After your application has run and the system has created your trace files + <code><trace-base-name>.trace</code> on a device or emulator, you must copy those files to + your development computer. You can use <code>adb pull</code> to copy the files. Here's an example + that shows how to copy an example file, calc.trace, from the default location on the emulator to + the /tmp directory on the emulator host machine:</p> + <pre> +adb pull /sdcard/calc.trace /tmp +</pre> + + <h2 id="runningtraceview">Viewing Trace Files in Traceview</h2> + + <p>To run Traceview and view the trace files, enter <code>traceview + <trace-base-name></code>. For example, to run Traceview on the example files copied in the + previous section, use:</p> + <pre> +traceview /tmp/calc +</pre> + + <p class="note"><strong>Note:</strong> If you are trying to view the trace logs of an application + that is built with ProGuard enabled (release mode build), some method and member names might be obfuscated. + You can use the Proguard <code>mapping.txt</code> file to figure out the original unobfuscated names. For more information + on this file, see the <a href="{@docRoot}guide/developing/tools/proguard.html">Proguard</a> documentation.</p> + + <h2 id="dmtracedump">Using dmtracdedump</h2> + + <p><code>dmtracedump</code> is a tool that gives you an alternate way of generating + graphical call-stack diagrams from trace log files. The tool uses the Graphviz Dot utility to + create the graphical output, so you need to install Graphviz before running dmtracedump.</p> + + <p>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.</p> + <img src= + "{@docRoot}images/tracedump.png" + width="485" + height="401" /> + <p class="image-caption"><strong>Figure 3.</strong> Screenshot of dmtracedump</p> + + <p>For each node, dmtracedump shows <code><ref> + <em>callname</em> (<inc-ms>, <exc-ms>,<numcalls>)</code>, where</p> + + <ul> + <li><code><ref></code> -- Call reference number, as used in trace logs</li> + + <li><code><inc-ms></code> -- Inclusive elapsed time (milliseconds spent in method, + including all child methods)</li> + + <li><code><exc-ms></code> -- Exclusive elapsed time (milliseconds spent in method, + not including any child methods)</li> + + <li><code><numcalls></code> -- Number of calls</li> + </ul> + + <p>The usage for dmtracedump is:</p> + <pre> +dmtracedump [-ho] [-s sortable] [-d trace-base-name] [-g outfile] <trace-base-name> +</pre> + + <p>The tool then loads trace log data from <code><trace-base-name>.data</code> and + <code><trace-base-name>.key</code>. The table below lists the options for dmtracedump.</p> + + <table> + <tr> + <th>Option</th> + + <th>Description</th> + </tr> + + <tr> + <td><code>-d <trace-base-name></code></td> + + <td>Diff with this trace name</td> + </tr> + + <tr> + <td><code>-g <outfile></code></td> + + <td>Generate output to <outfile></td> + </tr> + + <tr> + <td><code>-h</code></td> + + <td>Turn on HTML output</td> + </tr> + + <tr> + <td><code>-o</code></td> + + <td>Dump the trace file instead of profiling</td> + </tr> + + <tr> + <td><code>-d <trace-base-name></code></td> + + <td>URL base to the location of the sortable javascript file</td> + </tr> + + <tr> + <td><code>-t <percent></code></td> + + <td>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%.</td> + </tr> + </table> + + + + <h2 id="knownissues">Traceview Known Issues</h2> + + <dl> + <dt>Threads</dt> + + <dd> + Traceview logging does not handle threads well, resulting in these two problems: + + <ol> + <li>If a thread exits during profiling, the thread name is not emitted;</li> + + <li>The VM reuses thread IDs. If a thread stops and another starts, they may get the same + ID.</li> + </ol> + </dd> + + </dl>
\ No newline at end of file diff --git a/docs/html/guide/developing/debugging/debugging-ui.jd b/docs/html/guide/developing/debugging/debugging-ui.jd new file mode 100644 index 0000000..9b02d34 --- /dev/null +++ b/docs/html/guide/developing/debugging/debugging-ui.jd @@ -0,0 +1,202 @@ +page.title=Debugging and Profiling User Interfaces +@jd:body + + <div id="qv-wrapper"> + <div id="qv"> + <h2>In this document</h2> + + <ol> + <li> + <a href="#hierarchyViewer">Debugging and Optimizing User Interfaces with Hierarchy + Viewer</a> + <ol> + <li><a href="#layoutview">Layout View</a></li> + <li><a href="#pixelperfect">Pixel Perfect View</a></li> + </ol> + </li> + + <li><a href="#layoutopt">Optimizing Layouts with <code>layoutopt</code></a></li> + </ol> + </div> + </div> + + <p>Sometimes your application's layout can slow down your application. + To help debug issues in your layout, the Android SDK provides the Hierarchy Viewer and + <code>layoutopt</code> tools. + </p> + + <p>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).</p> + + <p><code>layoutopt</code> 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.</p> + + <h2 id="hierarchyViewer">Debugging and Optimizing User Interfaces with Hierarchy Viewer</h2> + + <p>To get the Hierarchy Viewer started:</p> + + <ol> + <li>Connect your device or launch an emulator.</li> + + <li>From a terminal, launch <code>hierarchyviewer</code> from the <code><sdk>/tools/</code> + directory.</li> + + <li>In the window that opens, you'll see a list of <strong>Devices</strong>. When a device is + selected, a list of currently active <strong>Windows</strong> is displayed on the right. The + <em><Focused Window></em> is the window currently in the foreground, and also the default + window loaded if you do not select another.</li> + + <li>Select the window that you'd like to inspect and click <strong>Load View + Hierarchy</strong>. 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.</li> + </ol> + + <p>If you've navigated to a different window on the device, press <strong>Refresh + Windows</strong> to refresh the list of available windows on the right.</p> + + + <h3 id="layoutview">Layout View</h3> + + <p>The Layout View offers a look at the View layout and properties. It has three views:</p> + + <ul> + <li>Tree View: a hierarchy diagram of the Views, on the left.</li> + + <li>Properties View: a list of the selected View's properties, on the top-right.</li> + + <li>Wire-frame View: a wire-frame drawing of the layout, on the bottom-right.</li> + </ul><br /> + <img src="{@docRoot}images/hierarchyviewer-layout.png" + alt="" + height="509" + width="700" /> + <p class="img-caption"><strong>Figure 1.</strong> Screenshot of Hierarchy Viewer</p> + + <p>Select a node in the Tree View to display the properties of that element in the Properties + View. When a node is selected, the Wire-frame View also indicates the bounds of the element with + a red rectangle. Double click a node in the tree (or select it, and click <strong>Display + View</strong>) to open a new window with a rendering of that element.</p> + + <p>The Layout View includes a couple other helpful features for debugging your layout: + <strong>Invalidate</strong> and <strong>Request Layout</strong>. These buttons execute the + respective View calls, {@link android.view.View#invalidate()} and {@link + android.view.View#requestLayout()}, on the View element currently selected in the tree. Calling + these methods on any View can be very useful when simultaneously running a debugger on your + application.</p> + + <p>The Tree View can be resized by adjusting the zoom slider, below the diagram. The number of + View elements in the window is also given here. You should look for ways to minimize the number + of Views. The fewer View elements there are in a window, the faster it will perform.</p> + + <p>If you interact with the device and change the focused View, the diagram will not + automatically refresh. You must reload the Layout View by clicking <strong>Load View + Hierarchy</strong>.</p> + + <h3 id="pixelperfect">Pixel Perfect View</h3> + + <p>The Pixel Perfect View provides a magnified look at the current device window. It helps you + design your UI better by giving you a closer look at your UI's image quality, alignment, and other + aesthetic qualities. It has three views:</p> + + <ul> + <li>Explorer View: shows the View hierarchy as a list, on the left.</li> + + <li>Normal View: a normal view of the device window, in the middle.</li> + + <li>Loupe View: a magnified, pixel-grid view of the device window, on the right.</li> + </ul><br /> + <img src="{@docRoot}images/hierarchyviewer-pixelperfect.png" + alt="" + height="509" + width="700" /> + + <p>Click on an element in the Explorer View and a "layout box" will be drawn in the Normal View + to indicate the layout position of that element. The layout box uses multiple rectangles, to + indicate the normal bounds, the padding and the margin (as needed). The purple or green rectangle + indicates the normal bounds of the element (the height and width). The inner white or black + rectangle indicates the content bounds, when padding is present. A black or white rectangle + outside the normal purple/green rectangle indicates any present margins. (There are two colors + for each rectangle, in order to provide the best contrast based on the colors currently in the + background.)</p> + + <p>A very handy feature for designing your UI is the ability to overlay an image in the Normal + and Loupe Views. For example, you might have a mock-up image of how you'd like to layout your + interface. By selecting <strong>Load...</strong> from the controls in the Normal View, you can + choose the image from your computer and it will be placed atop the preview. Your chosen image + will anchor at the bottom left corner of the screen. You can then adjust the opacity of the + overlay and begin fine-tuning your layout to match the mock-up.</p> + + <p>The Normal View and Loupe View refresh at regular intervals (5 seconds by default), but the + Explorer View does not. If you navigate away and focus on a different View, then you should + refresh the Explorer's hierarchy by clicking <strong>Load View Hierarchy</strong>. This is even + true when you're working in a window that holds multiple Views that are not always visible. If + you do not, although the previews will refresh, clicking a View in the Explorer will not provide + the proper layout box in the Normal View, because the hierarchy believes you are still focused on + the prior View.</p> + + <p>Optional controls include:</p> + + <ul> + <li><strong>Overlay</strong>: Load an overlay image onto the view and adjust its opacity.</li> + + <li><strong>Refresh Rate</strong>: Adjust how often the Normal and Loupe View refresh their + display.</li> + + <li><strong>Zoom</strong>: Adjust the zoom level of the Loupe View.</li> + </ul> + + <h2 id="layoutopt">Optimizing layouts with layoutopt</h2> + <p>The <code>layoutopt</code> tool lets you analyze the XML files that represent your application's layout + and finds ineffiencies in the view hierarchy.</p> + + <p>To run the tool, open a terminal and launch <code>layoutopt <resources></code> from your + SDK <code>tools/</code> directory. In the command, supply a list of uncompiled resource xml files + or directories that you want to analyze.</p> + + <p>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.</p> + + <p>Here's an example of the output:</p> + <pre> +$ 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 +</pre> + +<p> +For more information on running the tool, see the +<a href="${@docRoot}guide/developing/debugging/debugging-ui.html#layoutopt">layoutopt</a> reference.</p> + + + + + + + + diff --git a/docs/html/guide/developing/debugging/index.jd b/docs/html/guide/developing/debugging/index.jd new file mode 100644 index 0000000..1f1a4ca --- /dev/null +++ b/docs/html/guide/developing/debugging/index.jd @@ -0,0 +1,185 @@ +page.title=Debugging +@jd:body + + + <div id="qv-wrapper"> + <div id="qv"> + <h2>In this document</h2> + + <ol> + <li><a href="#stack">Debugging Environment</a></li> + + <li><a href="#addltools">Additional Debugging Tools</a></li> + + <li><a href="#tips">Debugging Tips</a></li> + </ol> + </div> + </div> + + <p>The Android SDK provides most of the tools that you need to debug your applications. You need + a JDWP-compliant debugger if you want to be able to do things such as step through code, + view variable values, and pause execution of an application. If you are using Eclipse, a + JDWP-compliant debugger is already included and there is no setup required. If you are using + another IDE, you can use the debugger that comes with it and attach the debugger to a special + port so it can communicate with the application VMs on your devices. The main components that + comprise a typical Android debugging environment are:</p> + + <dl> + <dt><a href="{@docRoot}guide/developing/tools/adb.html"><strong>adb</strong></a></dt> + + <dd><code>adb</code> acts as a middleman between a device and your development system. It provides various + device management capabilities, including moving and syncing files to the emulator, running a + UNIX shell on the device or emulator, and providing a general means to communicate with + connected emulators and devices.</dd> + + <dt><a href="{@docRoot}guide/developing/debugging/ddms.html"><strong>Dalvik Debug Monitor + Server</strong></a></dt> + + <dd>DDMS is a graphical program that communicates with your devices through <code>adb</code>. DDMS can + capture screenshots, gather thread and stack information, spoof incoming calls and SMS + messages, and has many other features.</dd> + + <dt><strong><a href="{@docRoot}guide/developing/device.html">Device</a> or + <a href="{@docRoot}guide/developing/devices/index.html">Android Virtual Device</a></strong></dt> + + <dd>Your application must run in a device or in an AVD so that it can be debugged. An <code>adb</code> device + daemon runs on the device or emulator and provides a means for the <code>adb</code> host daemon to + communicate with the device or emulator.</dd> + + <dt><strong>JDWP debugger</strong></dt> + + <dd>The Dalvik VM (Virtual Machine) supports the JDWP protocol to allow debuggers to attach to + a VM. Each application runs in a VM and exposes a unique port that you can attach a debugger to + via DDMS. If you want to debug multiple applications, attaching to each port might become + tedious, so DDMS provides a port forwarding feature that can forward a specific VM's debugging + port to port 8700. You can switch freely from application to application by highlighting it in the + Devices tab of DDMS. DDMS forwards the appropriate port to port 8700. Most modern Java IDEs include a JDWP debugger, + or you can use a command line debugger such as <a href="http://download.oracle.com/javase/6/docs/technotes/tools/"> + <code>jdb</code></a>.</dd> + </dl> + + <h2>Debugging Environment</h2> + + <p>Figure 1 shows how the various debugging tools work together in a typical + debugging environment.</p> + <img src="{@docRoot}images/debugging.png" + alt="Debugging workflow" /> + <p class="img-caption><strong>Figure 1. </strong> Debugging Workflow</p> + + <p>On your emulator or device, each application runs in its own instance of a Dalvik VM. The <code>adb</code> + device daemon allows communication with the VMs from an outside party.</p> + + <p>On your development machine, the <code>adb</code> host daemon communicates with the <code>adb</code> device daemon and + allows tools such as DDMS to communicate with the device or emulator. The <code>adb</code> host daemon also + allows you to access shell commands on the device as well as providing capabilities such as + application installation and file transferring.</p> + + <p>Each application VM on the device or emulator exposes a debugging port that you can attach to + via DDMS. DDMS can forward any of these ports to a static debugging port (typically port 8700) by + selecting the application that you want to debug in the DDMS user interface. A JDWP debugger can + attach to this static debugging port and debug all the applications that are running on the + device or emulator without having to attach to multiple ports.</p> + + <p>If you are using Eclipse, much of these interconnections are hidden from you. DDMS, <code>adb</code>, and a + JDWP debugger are all setup for you and you can access them through the Debug and DDMS + perspectives in Eclipse. If you are developing in a non-Eclipse environment, you have to invoke + these tools manually.</p> + + <h2 id="addltools">Additional Debugging Tools</h2> + + <p>In addition to the main debugging tools, the Android SDK provides additional tools to help you + debug and profile your applications:</p> + + <dl> + <dt><strong><a href="{@docRoot}guide/developing/debugging/debugging-ui.html">Heirarchy Viewer + and layoutopt</a></strong></dt> + + <dd>Graphical programs that let you debug and profile user interfaces.</dd> + + <dt><strong><a href= + "{@docRoot}guide/developing/debugging/debugging-tracing.html">Traceview</a></strong></dt> + + <dd>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.</dd> + + <dt><strong><a href="{@docRoot}guide/developing/debugging/debugging-devtools.html">Dev Tools + Android application</a></strong></dt> + + <dd>The Dev Tools application included in the emulator system image exposes several settings + that provide useful information such as CPU usage and frame rate. You can also transfer the + application to a hardware device.</dd> + </dl> + + + <h2 id="tips">Debugging Tips</h2> + +<p>While debugging, keep these helpful tips in mind to help you figure out common problems with your +applications:</p> + +<dl> +<dt><strong>Dump the stack trace</strong></dt> +<dd>To obtain a stack dump from emulator, you can log +in with <code>adb shell</code>, use <code>ps</code> to find the process you +want, and then <code>kill -3</code>. The stack trace appears in the log file. +</dd> + +<dt><strong>Display useful info on the emulator screen</strong></dt> +<dd>The device can display useful information such as CPU usage or highlights +around redrawn areas. Turn these features on and off in the developer settings +window as described in <a href="{@docRoot}guide/developing/debugging/debugging-devtools.html"> +Debugging with the Dev Tools App</a>. +</dd> + +<dt><strong>Get application and system state information from the emulator</strong></dt> +<dd>You can access dumpstate information from the <code>adb shell</code> commands. See +<a href="{@docRoot}guide/developing/tools/adb.html#dumpsys">dumpsys and +dumpstate</a> on the adb topic page.</dd> + + + +<dt><strong>Get wireless connectivity information</strong></dt> +<dd>You can get information about wireless connectivity using DDMS. +From the <strong>Device</strong> menu, select <strong>Dump +radio state</strong>.</dd> + +<dt><strong>Log trace data</strong></dt> +<dd>You can log method calls and other tracing data in an activity by calling +{@link android.os.Debug#startMethodTracing(String) startMethodTracing()}. See <a +href="{@docRoot}guide/developing/debugging/debugging-tracing.html">Profiling with Traceview and +dmtracedump</a> for details. </dd> + +<dt><strong>Log radio data</strong></dt> +<dd>By default, radio information is not logged to the system (it is a lot of +data). However, you can enable radio logging using the following commands: + +<pre class="no-pretty-print"> +adb shell +logcat -b radio +</pre> +</dd> + +<dt><strong>Capture screenshots</strong></dt> +<dd>The Dalvik Debug Monitor Server (DDMS) can capture screenshots from the emulator. Select +<strong>Device > Screen capture</strong>.</dd> + +<dt><strong>Use debugging helper classes</strong></dt> +<dd>Android provides debug helper classes such as {@link android.util.Log + util.Log} and {@link android.os.Debug} for your convenience. </dd> +</dl> + +<p>See the <a href="{@docRoot}resources/faq/troubleshooting.html">Troubleshooting</a> document +for answers to some common developing and debugging issues.</p> + + + + + + + + + + + + + + diff --git a/docs/html/guide/developing/device.jd b/docs/html/guide/developing/device.jd index f12c7d4..657f549 100644 --- a/docs/html/guide/developing/device.jd +++ b/docs/html/guide/developing/device.jd @@ -1,4 +1,4 @@ -page.title=Developing on a Device +page.title=Connecting Hardware Devices @jd:body <div id="qv-wrapper"> @@ -30,10 +30,7 @@ environment and Android-powered device for testing and debugging on the device.< <p>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 <a -href="{@docRoot}guide/developing/eclipse-adt.html#RunningOnDevice">directly from -Eclipse</a> or <a href="{@docRoot}guide/developing/other-ide.html#RunningOnDevice">from the -command line</a>. If +device directly from Eclipse or from the command line with ADB. If you don't yet have a device, check with the service providers in your area to determine which Android-powered devices are available.</p> @@ -48,7 +45,7 @@ Dev Phone, see the <a href="http://market.android.com/publish">Android Market</a <p class="note"><strong>Note:</strong> When developing on a device, keep in mind that you should still use the <a -href="{@docRoot}guide/developing/tools/emulator.html">Android emulator</a> to test your application +href="{@docRoot}guide/developing/devices/emulator.html">Android emulator</a> 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 diff --git a/docs/html/guide/developing/devices/emulator.jd b/docs/html/guide/developing/devices/emulator.jd new file mode 100644 index 0000000..53c1407 --- /dev/null +++ b/docs/html/guide/developing/devices/emulator.jd @@ -0,0 +1,1765 @@ +page.title=Using the Android Emulator +@jd:body + +<div id="qv-wrapper"> +<div id="qv"> + + <h2>In this document</h2> + <ol> + <li><a href="#overview">Overview</a></li> + <li><a href="#starting">Starting and Stopping the Emulator</a></li> + <li><a href="#starting">Android Virtual Devices and the Emulator</a></li> + <li><a href="#controlling">Controlling the Emulator</a></li> + <li><a href="#startup-options">Emulator Startup Options</a></li> + <li><a href="#diskimages">Working with Emulator Disk Images</a> + <ol> + <li><a href="#defaultimages">Default Images</a></li> + <li><a href="#runtimeimages">Runtime Images: User Data and SD Card</a></li> + <li><a href="#temporaryimages">Temporary Images</a></li> + </ol> + </li> + <li><a href="#emulatornetworking">Emulator Networking</a> + <ol> + <li><a href="#networkaddresses">Network Address Space</a></li> + <li><a href="#networkinglimitations">Local Networking Limitations</a></li> + <li><a href="#redirections">Using Network Redirections</a></li> + <li><a href="#dns">Configuring the Emulator's DNS Settings</a></li> + <li><a href="#proxy">Using the Emulator with a Proxy</a></li> + <li><a href="#connecting">Interconnecting Emulator Instances</a></li> + <li><a href="#calling">Sending a Voice Call or SMS to Another Emulator Instance</a></li> + </ol> + </li> + </ol> +</div> +</div> + +<img src="{@docRoot}images/emulator-wvga800l.png" alt="Image of the Android Emulator" +width="367" height="349" style="margin-left:2em;float:right;"/> +<p>The Android SDK includes a virtual mobile device emulator +that runs on your computer. The emulator lets you prototype, develop, and test +Android applications without using a physical device. </p> + +<p>The Android emulator mimics all of the hardware and software features +of a typical mobile device, except that it cannot place actual phone +calls. It provides a variety of navigation and control keys, which you can "press" +using your mouse or keyboard to generate events for your application. It also +provides a screen in which your application is displayed, together with any other +Android applications running. </p> + +<p>To let you model and test your application more easily, the emulator utilizes +Android Virtual Device (AVD) configurations. AVDs let you define certain hardware +aspects of your emulated phone and allow you to create many configurations to test +many Android platforms and hardware permutations. Once your application is running on +the emulator, it can use the services of the Android platform to invoke other +applications, access the network, play audio and video, store and retrieve data, +notify the user, and render graphical transitions and themes. </p> + +<p>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.</p> + + + + + +<h2 id="overview">Overview</h2> + +<p>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. +</p> + +<p>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. </p> + +<p>Adding custom capabilities to the underlying QEMU services, the Android +emulator supports many hardware features likely to be found on mobile devices, +including: </p> + +<ul> + <li>An ARMv5 CPU and the corresponding memory-management unit (MMU)</li> + <li>A 16-bit LCD display</li> + <li>One or more keyboards (a Qwerty-based keyboard and associated Dpad/Phone +buttons)</li> + <li>A sound chip with output and input capabilities</li> + <li>Flash memory partitions (emulated through disk image files on the +development machine)</li> + <li>A GSM modem, including a simulated SIM Card</li> +</ul> + +<p>The sections below provide more information about the emulator and how to use +it for developing Android applications.</p> + + +<a name="avds"></a> + +<h2>Android Virtual Devices and the Emulator</h2> + +<p>To use the emulator, you first must create one or more AVD configurations. In each +configuration, you specify an Android platform to run in the emulator and the set of hardware +options and emulator skin you want to use. Then, when you launch the emulator, you specify +the AVD configuration that you want to load. </p> + +<p>To specify the AVD you want to load when starting the emulator, you use the +<code>-avd</code> argument, as shown in the previous section. </p> + +<p>Each AVD functions as an independent device, with its own private storage for +user data, SD card, and so on. When you launch the emulator with an AVD configuration, +it automatically loads the user data and SD card data from the AVD directory. By default, +the emulator stores the user data, SD card data, and cache in the AVD directory.</p> + +<p>To create and manage AVDs you use the AVD Manager UI or the <code>android</code> tool +that is included in the SDK. +For complete information about how to set up AVDs, see <a +href="{@docRoot}guide/developing/devices/index.html">Creating and Managing Virtual Devices</a>.</p> + +<a name="starting"></a> + +<h2>Starting and Stopping the Emulator</h2> + +<p>During development and testing of your application, you install and run your +application in the Android emulator. You can launch the emulator as a standalone +application, from a command line, or you can use it as part of your Eclipse +development environment. In either case, you specify the AVD configuration to +load and any startup options you want to use, as described in this document. +</p> + +<p>You can run your application on a single instance of the emulator or, +depending on your needs, you can start multiple emulator instances and run your +application in more than one emulated device. You can use the emulator's +built-in commands to simulate GSM phone calling or SMS between emulator +instances, and you can set up network redirections that allow emulators to send +data to one another. For more information, see <a href="#telephony">Telephony +Emulation</a>, <a href="#sms">SMS Emulation</a>, and +<a href="#emulatornetworking">Emulator Networking</a></p> + +<p>To start an instance of the emulator from the command line, change to the +<code>tools/</code> folder of the SDK. Enter <code>emulator</code> command +like this: </p> + +<pre>emulator -avd <avd_name></pre> + +<p>This initializes the emulator and loads an AVD configuration (see the next +section for more information about AVDs). You will see the emulator window +appear on your screen. </p> + +<p>If you are working in Eclipse, the ADT plugin for Eclipse installs your +application and starts the emulator automatically, when you run or debug +the application. You can specify emulator startup options in the Run/Debug +dialog, in the Target tab. When the emulator is running, you can issue +console commands as described later in this document.</p> + +<p>If you are not working in Eclipse, see <a href="#apps">Installing Applications +on the Emulator</a> for information about how to install your application.</p> + +<p>To stop an emulator instance, just close the emulator's window.</p> + + + + + + + +<a name="controlling"></a> + + +<h2>Controlling the Emulator</h2> + +<p>You can use emulator <a href="#startup-options">startup options</a> and <a +href="#console">console commands</a> to control the behaviors and +characteristics of the emulated environment itself. +</p> + +<p>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. </p> + +<p>The table below summarizes the mappings between the emulator keys and and +the keys of your keyboard. </p> + +<table border="0" style="clear:left;"> + <tr> + <th>Emulated Device Key </th> + <th>Keyboard Key </th> + </tr> + <tr> + <td>Home</td> + <td>HOME</td> + </tr> + <tr> + <td>Menu (left softkey)</td> + <td>F2 <em>or</em> Page-up button</td> + </tr> + <tr> + <td>Star (right softkey)</td> + <td>Shift-F2 <em>or </em>Page Down</td> + </tr> + <tr> + <td>Back</td> + <td>ESC</td> + </tr> + <tr> + <td>Call/dial button </td> + <td>F3</td> + </tr> + <tr> + <td>Hangup/end call button</td> + <td>F4</td> + </tr> + <tr> + <td>Search</td> + <td>F5 </td> + </tr> + <tr> + <td>Power button</td> + <td>F7 </td> + </tr> + <tr> + <td>Audio volume up button</td> + <td>KEYPAD_PLUS, Ctrl-5</td> + </tr> + + <tr> + <td>Audio volume down button</td> + <td>KEYPAD_MINUS, Ctrl-F6</td> + </tr> + <tr> + <td>Camera button</td> + <td>Ctrl-KEYPAD_5, Ctrl-F3</td> + </tr> + <tr> + <td>Switch to previous layout orientation (for example, portrait, landscape)</td> + <td>KEYPAD_7, Ctrl-F11</td> + </tr> + <tr> + <td>Switch to next layout orientation (for example, portrait, landscape)</td> + <td>KEYPAD_9, Ctrl-F12</td> + </tr> + <tr> + <td>Toggle cell networking on/off</td> + <td>F8</td> + </tr> + <tr> + <td>Toggle code profiling</td> + <td>F9 (only with <code>-trace</code> startup option)</td> + </tr> + <tr> + <td>Toggle fullscreen mode</td> + <td>Alt-Enter</td> + </tr> + <tr> + <td>Toggle trackball mode</td> + <td>F6</td> + </tr> + <tr> + <td>Enter trackball mode temporarily (while key is pressed)</td> + <td>Delete</td> + </tr> + <tr> + <td>DPad left/up/right/down</td> + <td>KEYPAD_4/8/6/2</td> + </tr> + <tr> + <td>DPad center click</td> + <td>KEYPAD_5</td> + </tr> + <tr> + <td>Onion alpha increase/decrease</td> + <td>KEYPAD_MULTIPLY(*) / KEYPAD_DIVIDE(/)</td> + </tr> +</table> + +<p>Note that, to use keypad keys, you must first disable NumLock on your development computer. </p> + +<h2 id="emulator">Emulator Startup Options</h2> + +<p>The emulator supports a variety of options that you can specify +when launching the emulator, to control its appearance or behavior. +Here's the command-line usage for launching the emulator with options: </p> + +<pre>emulator -avd <avd_name> [-<option> [<value>]] ... [-<qemu args>]</pre> + +<p>The table below summarizes the available options.</p> + +<table> +<tr> + <th width="10%" >Category</th> + <th width="20%" >Option</th> + <th width="30%" >Description</th> + <th width="40%" >Comments</th> +</tr> + +<tr> + <td rowspan="9">Help</td> + <td><code>-help</code></td> + <td>Print a list of all emulator options.</td> + <td> </td> +</tr> +<tr> + <td><code>-help-all</code></td> + <td>Print help for all startup options.</td> + <td> </td> +</tr> +<tr> + <td><code>-help-<option></code></td> + <td>Print help for a specific startup option.</td> + <td> </td> +</tr> +<tr> + <td><code>-help-debug-tags</code></td> + <td>Print a list of all tags for <code>-debug <tags></code>.</td> + <td> </td> +</tr> +<tr> + <td><code>-help-disk-images</code></td> + <td>Print help for using emulator disk images.</td> + <td> </td> +</tr> +<tr> + <td><code>-help-environment</code></td> + <td>Print help for emulator environment variables.</td> + <td> </td> +</tr><tr> + <td><code>-help-keys</code></td> + <td>Print the current mapping of keys.</td> + <td> </td> +</tr> +<tr> + <td><code>-help-keyset-file</code></td> + <td>Print help for defining a custom key mappings file.</td> + <td> </td> +</tr> +<tr> + <td><code>-help-virtual-device</code></td> + <td>Print help for Android Virtual Device usage.</td> + <td> </td> +</tr> +<tr> + <td>AVD</td> + <td><code>-avd <avd_name></code> or <br> + <code>@<avd_name></code></td> + <td><strong>Required</strong>. Specifies the AVD to load for this emulator + instance.</td> + <td>You must create an AVD configuration before launching the emulator. For + information, see <a href="{@docRoot}guide/developing/devices/managing-avds.html">Creating and Managing + Virtual Devices with AVD Manager</a>.</td> +<tr> + <td rowspan="7">Disk Images</td> + <td><code>-cache <filepath></code></td> + <td>Use <filepath> as the working cache partition image. </td> + <td>Optionally, you can specify a path relative to the current working directory. + If no cache file is specified, the emulator's default behavior is to use a temporary file instead. + <p>For more information on disk images, use <code>-help-disk-images</code>.</p> +</td></tr> +<tr> + <td><code>-data <filepath></code></td> + <td>Use <filepath> as the working user-data disk image. </td> + <td>Optionally, you can specify a path relative to the current working directory. + If <code>-data</code> is not used, the emulator looks for a file named "userdata-qemu.img" + in the storage area of the AVD being used (see <code>-avd</code>). +</td></tr> +<!-- +<tr> + <td><code>-datadir <dir></code></td> + <td>Search for the user-data disk image specified in <code>-data</code> in <dir></td> + <td><code><dir></code> is a path relative to the current working directory. + +<p>If you do not specify <code>-datadir</code>, the emulator looks for the user-data image +in the storage area of the AVD being used (see <code>-avd</code>)</p><p>For more information +on disk images, use <code>-help-disk-images</code>.</p> +</td></tr> +--> +<!-- +<tr> + <td><code>-image <filepath></code></td> + <td>Use <filepath> as the system image.</td> + <td>Optionally, you can specify a path relative to the current working directory. + Default is <system>/system.img.</td> +</tr> +--> +<tr> + <td><code>-initdata <filepath></code></td> + <td>When resetting the user-data image (through <code>-wipe-data</code>), copy the contents + of this file to the new user-data disk image. By default, the emulator copies the <code><system>/userdata.img</code>.</td> + <td>Optionally, you can specify a path relative to the current working directory. See also <code>-wipe-data</code>. + <p>For more information on disk images, use <code>-help-disk-images</code>.</p></td> +</tr> +<!-- +<tr> + <td><code>-kernel <filepath></code></td> + <td>Use <filepath> as the emulated kernel.</td> + <td>Optionally, you can specify a path relative to the current working directory. </td> +</tr> +--> +<tr> + <td><code>-nocache</code></td> + <td>Start the emulator without a cache partition.</td> + <td>See also <code>-cache <file></code>.</td> +</tr> +<tr> + <td><code>-ramdisk <filepath></code></td> + <td>Use <filepath> as the ramdisk image.</td> + <td>Default value is <code><system>/ramdisk.img</code>. + <p>Optionally, you can specify a path relative to the current working directory. + For more information on disk images, use <code>-help-disk-images</code>.</p> +</td> +</tr> +<tr> + <td><code>-sdcard <filepath></code></td> + <td>Use <file> as the SD card image.</td> + <td>Default value is <code><system>/sdcard.img</code>. + <p>Optionally, you can specify a path relative to the current working directory. For more information on disk images, use <code>-help-disk-images</code>.</p> +</td> +</tr> +<!-- +<tr> + <td><code>-system <dirpath></code></td> + <td>Search for system, ramdisk and user data images in <dir>.</td> + <td><code><dir></code> is a directory path relative to the current + working directory.</td> +</tr> +--> +<tr> + <td><code>-wipe-data</code></td> + <td>Reset the current user-data disk image (that is, the file specified by <code>-datadir</code> and + <code>-data</code>, or the default file). The emulator deletes all data from the user data image file, + then copies the contents of the file at <code>-inidata</code> data to the image file before starting. + </td> + <td>See also <code>-initdata</code>. + <p>For more information on disk images, use <code>-help-disk-images</code>.</p> +</td> +</tr> +<tr> + <td rowspan="9">Debug</td> + <td><code>-debug <tags></code></td> + <td>Enable/disable debug messages for the specified debug tags.</td> + <td><code><tags></code> is a space/comma/column-separated list of debug component names. + Use <code>-help-debug-tags</code> to print a list of debug component names that you can use. </td> +</tr> +<tr> + <td><code>-debug-<tag></code></td> + <td>Enable/disable debug messages for the specified debug tag.</td> + <td rowspan="2">Use <code>-help-debug-tags</code> to print a list of debug component names that you can use in <code><tag></code>. </td> +</tr> +<tr> + <td><code>-debug-no-<tag></code></td> + <td>Disable debug messages for the specified debug tag.</td> +</tr> +<tr> + <td><code>-logcat <logtags></code></td> + <td>Enable logcat output with given tags.</td> + <td>If the environment variable ANDROID_LOG_TAGS is defined and not + empty, its value will be used to enable logcat output by default.</td> +</tr> +<tr> + <td><code>-shell</code></td> + <td>Create a root shell console on the current terminal.</td> + <td>You can use this command even if the adb daemon in the emulated system is broken. + Pressing Ctrl-c from the shell stops the emulator instead of the shell.</td> +</tr> +<tr> + <td><code>-shell-serial <device></code></td> + <td>Enable the root shell (as in <code>-shell</code> and specify the QEMU character + device to use for communication with the shell.</td> + <td><device> must be a QEMU device type. See the documentation for '-serial <em>dev</em>' at + <a href="http://www.nongnu.org/qemu/qemu-doc.html#SEC10">http://www.bellard.org/qemu/qemu-doc.html#SEC10</a> + for a list of device types. + +<p>Here are some examples: </p> +<ul> + <li><code>-shell-serial stdio</code> is identical to <code>-shell</code></li> + <li><code>-shell-serial tcp::4444,server,nowait</code> lets you communicate with the shell over TCP port 4444</li> + <li><code>-shell-serial fdpair:3:6</code> lets a parent process communicate with the shell using fds 3 (in) and 6 (out)</li> + <li><code>-shell-serial fdpair:0:1</code> uses the normal stdin and stdout fds, except that QEMU won't tty-cook the data.</li> + </ul> +</td> +</tr> +<tr> + <td><code>-show-kernel <name></code></td> + <td>Display kernel messages.</td> + <td> </td> +</tr> +<tr> + <td><code>-trace <name></code></td> + <td>Enable code profiling (press F9 to start), written to a specified file.</td> + <td> </td> +</tr> +<tr> + <td><code>-verbose</code></td> + <td>Enable verbose output.</td> + <td>Equivalent to <code>-debug-init</code>. +<p>You can define the default verbose output options used by emulator instances in the Android environment variable +ANDROID_VERBOSE. Define the options you want to use in a comma-delimited list, specifying only the stem of each option: +<code>-debug-<tags>.</code> </p> +<p>Here's an example showing ANDROID_VERBOSE defined with the <code>-debug-init</code> and <code>-debug-modem</code> options: +<p><code>ANDROID_VERBOSE=init,modem</code></p> +<p>For more information about debug tags, use <code><-help-debug-tags></code>.</p> +</td> +</tr> +<tr> + <td rowspan="6">Media</td> + <td><code>-audio <backend></code></td> + <td>Use the specified audio backend.</td> + <td> </td> +</tr> +<tr> + <td><code>-audio-in <backend></code></td> + <td>Use the specified audio-input backend.</td> + <td> </td> +</tr> +<tr> + <td><code>-audio-out <backend></code></td> + <td>Use the specified audio-output backend.</td> + <td> </td> +</tr> +<!--<tr> + <td><code>-mic <device or file></code></td> + <td>Use device or WAV file for audio input.</td> + <td> </td> +</tr> +--> +<tr> + <td><code>-noaudio</code></td> + <td>Disable audio support in the current emulator instance.</td> + <td> </td> +</tr> +<tr> + <td><code>-radio <device></code></td> + <td>Redirect radio modem interface to a host character device.</td> + <td> </td></tr> +<tr> + <td><code>-useaudio</code></td> + <td>Enable audio support in the current emulator instance.</td> + <td>Enabled by default. </td> +</tr> + +<tr> + <td rowspan="7">Network</td> + <td><code>-dns-server <servers></code></td> + <td>Use the specified DNS server(s). </td> + <td>The value of <code><servers></code> must be a comma-separated list of up to 4 DNS server names or + IP addresses.</td> +</tr> +<tr> + <td><code>-http-proxy <proxy></code></td> + <td>Make all TCP connections through a specified HTTP/HTTPS proxy</td> + <td>The value of <code><proxy></code> can be one of the following:<br> + <code>http://<server>:<port></code><br> + <code>http://<username>:<password>@<server>:<port></code> + <p>The <code>http://</code> prefix can be omitted. If the <code>-http-proxy <proxy></code> command is not supplied, + the emulator looks up the <code>http_proxy</code> environment variable and automatically uses any value matching + the <code><proxy></code> format described above.</p></td> +</tr> +<tr> + <td><code>-netdelay <delay></code></td> + <td>Set network latency emulation to <delay>.</td> + <td>Default value is <code>none</code>. See the table in <a href="#netdelay">Network Delay Emulation</a> for + supported <code><delay></code> values. </td> +</tr> +<tr> + <td><code>-netfast</code></td> + <td>Shortcut for <code>-netspeed full -netdelay none</code></td> + <td> </td></tr> +<tr> + <td><code>-netspeed <speed></code></td> + <td>Set network speed emulation to <speed>.</td> + <td>Default value is <code>full</code>. See the table in <a href="#netspeed">Network Speed Emulation</a> for + supported <code><speed></code> values. </td> +</tr> +<tr> + <td><code>-port <port></code></td> + <td>Set the console port number for this emulator instance to <code><port></code>.</td> + <td>The console port number must be an even integer between 5554 and 5584, inclusive. <code><port></code>+1 + must also be free and will be reserved for ADB.</td> +</tr> +<tr> + <td><code>-report-console <socket></code></td> + <td>Report the assigned console port for this emulator instance to a remote third party + before starting the emulation. </td> + <td><code><socket></code> must use one of these formats: + +<p><code>tcp:<port>[,server][,max=<seconds>]</code></br> +<code>unix:<port>[,server][,max=<seconds>]</code></p> + +<p>Use <code>-help-report-console</code></p> to view more information about this topic. </td> +</tr> +<tr> + <td rowspan="8">System</td> + <td><code>-cpu-delay <delay></code></td> + <td>Slow down emulated CPU speed by <delay> </td> + <td>Supported values for <delay> are integers between 0 and 1000. + +<p>Note that the <delay> does not correlate to clock speed or other absolute metrics +— it simply represents an abstract, relative delay factor applied non-deterministically +in the emulator. Effective performance does not always +scale in direct relationship with <delay> values.</p> +</td> +</tr> +<tr> + <td><code>-gps <device></code></td> + <td>Redirect NMEA GPS to character device.</td> + <td>Use this command to emulate an NMEA-compatible GPS unit connected to + an external character device or socket. The format of <code><device></code> must be QEMU-specific + serial device specification. See the documentation for 'serial -dev' at + <a href="http://www.bellard.org/qemu/qemu-doc.html#SEC10">http://www.bellard.org/qemu/qemu-doc.html#SEC10</a>. +</td> +</tr> +<tr> + <td><code>-nojni</code></td> + <td>Disable JNI checks in the Dalvik runtime.</td><td> </td></tr> +<tr> + <td><code>-qemu</code></td> + <td>Pass arguments to qemu.</td> + <td> </td></tr> +<tr> + <td><code>-qemu -h</code></td> + <td>Display qemu help.</td> + <td></td></tr> +<tr> + <td><code>-radio <device></code></td> + <td>Redirect radio mode to the specified character device.</td> + <td>The format of <code><device></code> must be QEMU-specific + serial device specification. See the documentation for 'serial -dev' at +<a href="http://www.bellard.org/qemu/qemu-doc.html#SEC10">http://www.bellard.org/qemu/qemu-doc.html#SEC10</a>. +</td> +</tr> +<tr> + <td><code>-timezone <timezone></code></td> + <td>Set the timezone for the emulated device to <timezone>, instead of the host's timezone.</td> + <td><code><timezone></code> must be specified in zoneinfo format. For example: +<p>"America/Los_Angeles"<br> +"Europe/Paris"</p> +</td> +</tr> +<tr> + <td><code>-version</code></td> + <td>Display the emulator's version number.</td> + <td> </td> +</tr> +<tr> + <td rowspan="12">UI</td> + <td><code>-dpi-device <dpi></code></td> + <td>Scale the resolution of the emulator to match the screen size + of a physical device.</td> + <td>The default value is 165. See also <code>-scale</code>.</td> +</tr> +<tr> + <td><code>-no-boot-anim</code></td> + <td>Disable the boot animation during emulator startup.</td> + <td>Disabling the boot animation can speed the startup time for the emulator.</td> +</tr> +<tr> + <td><code>-no-window</code></td> + <td>Disable the emulator's graphical window display.</td> + <td> </td> +</tr> +<tr> + <td><code>-scale <scale></code></td> + <td>Scale the emulator window. </td> + <td><code><scale></code> is a number between 0.1 and 3 that represents the desired scaling factor. You can + also specify scale as a DPI value if you add the suffix "dpi" to the scale value. A value of "auto" + tells the emulator to select the best window size.</td> +</tr> +<tr> + <td><code>-raw-keys</code></td> + <td>Disable Unicode keyboard reverse-mapping.</td> + <td> </td></tr> +<tr> + <td><code>-noskin</code></td> + <td>Don't use any emulator skin.</td> + <td> </td></tr> +<tr> + <td><code>-keyset <file></code></td> + <td>Use the specified keyset file instead of the default.</td> + <td>The keyset file defines the list of key bindings between the emulator and the host keyboard. + For more information, use <code>-help-keyset</code> to print information about this topic. +</td> +</tr> +<tr> + <td><code>-onion <image></code></td> + <td>Use overlay image over screen.</td> + <td>No support for JPEG. Only PNG is supported.</td></tr> +<tr> + <td><code>-onion-alpha <percent></code></td> + <td>Specify onion skin translucency value (as percent). + <td>Default is 50.</td> +</tr> +<tr> + <td><code>-onion-rotation <position></code></td> + <td>Specify onion skin rotation. + <td><code><position></code> must be one of the values 0, 1, 2, 3.</td> +</tr> +<tr> + <td><code>-skin <skinID></code></td> + <td>This emulator option is deprecated. </td> + <td>Please set skin options using AVDs, rather than by using this emulator +option. Using this option may yield unexpected and in some cases misleading +results, since the density with which to render the skin may not be defined. +AVDs let you associate each skin with a default density and override the default +as needed. For more information, see <a +href="{@docRoot}guide/developing/devices/managing-avds.html">Creating and Managing Virtual Devices +with AVD Manager</a>. +</td> +</tr> +<tr> + <td><code>-skindir <dir></code></td> + <td>This emulator option is deprecated. </td> + <td>See comments for <code>-skin</code>, above.</td></tr> +</table> + + +<a name="diskimages"></a> + +<h2>Working with Emulator Disk Images</h2> + +<p>The emulator uses mountable disk images stored on your development machine to +simulate flash (or similar) partitions on an actual device. For example, it uses +disk image containing an emulator-specific kernel, the Android system, a +ramdisk image, and writeable images for user data and simulated SD card.</p> + +<p>To run properly, the emulator requires access to a specific set of disk image +files. By default, the Emulator always looks for the disk images in the +private storage area of the AVD in use. If no images exist there when +the Emulator is launched, it creates the images in the AVD directory based on +default versions stored in the SDK. </p> + +<p class="note"><strong>Note:</strong> The default storage location for +AVDs is in <code>~/.android/avd</code> on OS X and Linux, <code>C:\Documents and +Settings\<user>\.android\</code> on Windows XP, and +<code>C:\Users\<user>\.android\</code> +on Windows Vista.</p> + +<p>To let you use alternate or custom versions of the image files, the emulator +provides startup options that override the default locations and filenames of +the image files. When you use the options, the emulator searches for the image +file under the image name or location that you specify; if it can not locate the +image, it reverts to using the default names and location.</p> + +<p>The emulator uses three types of image files: default image files, runtime +image files, and temporary image files. The sections below describe how to +override the location/name of each type of file. </p> + +<a name="defaultimages"></a> +<h3>Default Images</h3> + +<p>When the emulator launches but does not find an existing user data image in +the active AVD's storage area, it creates a new one from a default version +included in the SDK. The default user data image is read-only. The image +files are read-only.</p> + +<p>The emulator provides the <code>-system <dir></code> startup option to +let you override the location under which the emulator looks for the default +user data image. </p> + +<p>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 <code>-system <dir></code>). </p> + + +<table> +<tr> + <th width="10%" >Name</th> + <th width="30%" >Description</th> + <th width="40%" >Comments</th> +</tr> + +<!-- +<tr> + <td><code>kernel-qemu.img</code></td> + <td>The emulator-specific Linux kernel image</td> + <td>Override using <code>-kernel <file></code></td> +</tr> + +<tr> + <td><code>ramdisk.img</code></td> + <td>The ramdisk image used to boot the system.</td> + <td>Override using <code>-ramdisk <file></code></td> +</tr> + +<tr> + <td><code>system.img</code></td> + <td>The <em>initial</em> Android system image.</td> + <td>Override using <code>-image <file></code></td> +</tr> +--> +<tr> + <td><code>userdata.img</code></td> + <td>The <em>initial</em> user-data disk image</td> + <td>Override using <code>-initdata <file></code>. Also see +<code>-data <file></code>, below.</td> +</tr> + +</table> + +<a name="runtimeimages"></a> +<h3>Runtime Images: User Data and SD Card</h3> + +<p>At runtime, the emulator reads and writes data on two disk images: a +user-data image and (optionally) an SD card image. This emulates the user-data +partition and removable storage media on actual device. </p> + +<p>The emulator provides a default user-data disk image. At startup, the emulator +creates the default image as a copy of the system user-data image (user-data.img), +described above. The emulator stores the new image with the files of the active AVD.</p> + +<!-- +<p>The emulator provides a startup option, <code>-datadir <dir></code>, +that you can use to override the location under which the emulator looks for the runtime +image files. </p> +--> + +<p>The emulator provides startup options to let you override the actual names and storage +locations of the runtime images to load, as described in the table below. When you use one +of these options, the emulator looks for the specified file(s) in the current working directory, +in the AVD directory, or in a custom location (if you specified a path with the filename). </p> + +<table> +<tr> + <th width="10%" >Name</th> + <th width="30%" >Description</th> + <th width="40%" >Comments</th> +</tr> +<tr> + <td><code>userdata-qemu.img</code></td> + <td>An image to which the emulator writes runtime user-data for a unique user.</td> + <td>Override using <code>-data <filepath></code>, where <code><filepath></code> is the +path the image, relative to the current working directory. If you supply a filename only, +the emulator looks for the file in the current working directory. If the file at <code><filepath></code> does +not exist, the emulator creates an image from the default userdata.img, stores it under the name you +specified, and persists user data to it at shutdown. </td> +</tr> + +<tr> + <td><code>sdcard.img</code></td> + <td>An image representing an SD card inserted into the emulated device.</td> + <td>Override using <code>-sdcard <filepath></code>, where <code><filepath></code> is the +path the image, relative to the current working directory. If you supply a filename only, +the emulator looks for the file in the current working directory. </td> +</tr> + +</table> + +<h4>User-Data Image</h4> + +<p>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. </p> + +<p>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. </p> + +<ul> +<li>If it finds a user-data image, it mounts the image and makes it available +to the system for reading/writing of user data. </li> +<li>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 <code>-data</code> startup option.</li> +</ul> + +<p class="note"><strong>Note:</strong> 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 <code>-d</code> option to specify an instance-specific storage area.</p> + +<h4>SD Card</h4> + +<P>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 <a href="#sdcard">SD Card Emulation</a></p> + +<p>You can also use the android tool to automatically create an SD Card image +for you, when creating an AVD. For more information, see <a +href="{@docRoot}guide/developing/devices/managing-avds.html">Creating and Managing Virtual Devices with AVD Manager</a>. + +<a name="temporaryimages"></a> +<h3>Temporary Images</h3> + +<p>The emulator creates two writeable images at startup that it deletes at +device power-off. The images are: </p> + +<ul> + <li>A writable copy of the Android system image</li> + <li>The <code>/cache</code> partition image</li> +</ul> + +<p>The emulator does not permit renaming the temporary system image or +persisting it at device power-off. </p> + +<p>The <code>/cache</code> partition image is initially empty, and is used by +the browser to cache downloaded web pages and images. The emulator provides an +<code>-cache <file></code>, which specifies the name of the file at which +to persist the <code>/cache</code> image at device power-off. If <code><file> +</code> does not exist, the emulator creates it as an empty file. </p> + +<p>You can also disable the use of the cache partition by specifying the +<code>-nocache</code> option at startup. </p> + + +<a name="emulatornetworking"></a> +<h2>Emulator Networking</h2> + +<p>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. +</p> + +<a name="networkaddresses"></a> +<h3>Network Address Space</h3> + +<p>Each instance of the emulator runs behind a virtual router/firewall service +that isolates it from your development machine's network interfaces and settings +and from the internet. An emulated device can not see your development machine +or other emulator instances on the network. Instead, it sees only that it is +connected through Ethernet to a router/firewall.</p> + +<p>The virtual router for each instance manages the 10.0.2/24 network address +space — all addresses managed by the router are in the form of +10.0.2.<xx>, where <xx> is a number. Addresses within this space are +pre-allocated by the emulator/router as follows:</p> + +<table> + <tr> + <th>Network Address</th> + <th>Description</th> + </tr> + <tr> + <td>10.0.2.1</td> + <td>Router/gateway address </td> + </tr> + <tr> + <td>10.0.2.2</td> + <td>Special alias to your host loopback interface (i.e., 127.0.0.1 on your +development machine)</td> + </tr> + <tr> + <td>10.0.2.3</td> + <td>First DNS server</td> + </tr> + <tr> + <td>10.0.2.4 / 10.0.2.5 / 10.0.2.6</td> + <td>Optional second, third and fourth DNS server (if any) </td> + </tr> + <tr> + <td>10.0.2.15</td> + <td>The emulated device's own network/ethernet interface</td> + </tr> + <tr> + <td>127.0.0.1</td> + <td>The emulated device's own loopback interface </td> + </tr> +</table> + +<p>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 +<em>not</em> see each other on the same network. For information about how to +let emulator instances communicate over TCP/UDP, see <a +href="#connecting">Connecting Emulator Instances</a>.</p> + +<p>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.</p> + +<p>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)</p> + +<a name="networkinglimitations"></a> +<h3>Local Networking Limitations</h3> + +<p>Each emulator instance runs behind a virtual router, but unlike an actual +device connected to a physical router, the emulated device doesn't have access +to a physical network. Instead it runs as part of a normal application on your +development machine. This means that it is subject to the same networking +limitations as other applications on your machine:</p> + +<ul> + <li>Communication with the emulated device may be blocked by a firewall +program running on your machine.</li> + <li>Communication with the emulated device may be blocked by another +(physical) firewall/router to which your machine is connected.</li> +</ul> + +<p>The emulator's virtual router should be able to handle all outbound TCP and +UDP connections/messages on behalf of the emulated device, provided your +development machine's network environment allows it to do so. There are no +built-in limitations on port numbers or ranges except the one imposed by your +host operating system and network.</p> + +<p>Depending on the environment, the emulator may not be able to support other +protocols (such as ICMP, used for "ping") might not be supported. Currently, the +emulator does not support IGMP or multicast. </p> + +<a name="redirections"></a> +<h3>Using Network Redirections</h3> + +<p>To communicate with an emulator instance behind its virtual router, you need +to set up network redirections on the virtual router. Clients can then connect +to a specified guest port on the router, while the router directs traffic +to/from that port to the emulated device's host port. </p> + +<p>To set up the network redirections, you create a mapping of host and guest +ports/addresses on the the emulator instance. There are two ways to set up +network redirections: using emulator console commands and using the ADB tool, as +described below. </p> + +<a name="consoleredir"></a> +<h4>Setting up Redirections through the Emulator Console</h4> + +<p>Each emulator instance provides a control console the you can connect to, to +issue commands that are specific to that instance. You can use the +<code>redir</code> console command to set up redirections as needed for an +emulator instance. </p> + +<p>First, determine the console port number for the target emulator instance. +For example, the console port number for the first emulator instance launched is +5554. Next, connect to the console of the target emulator instance, specifying +its console port number, as follows: </p> + +<pre><code>telnet localhost 5554</code></pre> + +<p>Once connected, use the <code>redir</code> command to work with redirections. +To add a redirection, use:</p> + +<pre><code>add <protocol>:<host-port>:<guest-port></code> +</pre> + +<p>where <code><protocol></code> is either <code>tcp</code> or <code>udp</code>, +and <code><host-port></code> and <code><guest-port></code> sets the +mapping between your own machine and the emulated system, respectively. </p> + +<p>For example, the following command sets up a redirection that will handle all +incoming TCP connections to your host (development) machine on 127.0.0.1:5000 +and will pass them through to the emulated system's 10.0.2.15:6000.:</p> + +<pre>redir add tcp:5000:6000</pre> + +<p>To delete a redirection, you can use the <code>redir del</code> command. To +list all redirections for a specific instance, you can use <code>redir +list</code>. For more information about these and other console commands, see +<a href="#console">Using the Emulator Console</a>. </p> + +<p>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, <code>redir</code> generates an error message to that effect. </p> + +<a name="adbredir"></a> +<h4>Setting Up Redirections through ADB</h4> + +<p>The Android Debug Bridge (ADB) tool provides port forwarding, an alternate +way for you to set up network redirections. For more information, see <a +href="{@docRoot}guide/developing/tools/adb.html#forwardports">Forwarding Ports</a> in the ADB +documentation.</p> + +<p>Note that ADB does not currently offer any way to remove a redirection, +except by killing the ADB server.</p> + +<a name="dns"></a> +<h3>Configuring the Emulator's DNS Settings</h3> + +<p>At startup, the emulator reads the list of DNS servers that your system is +currently using. It then stores the IP addresses of up to four servers on this +list and sets up aliases to them on the emulated addresses 10.0.2.3, 10.0.2.4, +10.0.2.5 and 10.0.2.6 as needed. </p> + +<p>On Linux and OS X, the emulator obtains the DNS server addresses by parsing +the file <code>/etc/resolv.conf</code>. On Windows, the emulator obtains the +addresses by calling the <code>GetNetworkParams()</code> API. Note that this +usually means that the emulator ignores the content of your "hosts" file +(<code>/etc/hosts</code> on Linux/OS X, <code>%WINDOWS%/system32/HOSTS</code> + on Windows).</P> + +<p>When starting the emulator at the command line, you can also use the +<code>-dns-server <serverList></code> option to manually specify the +addresses of DNS servers to use, where <serverList> is a comma-separated +list of server names or IP addresses. You might find this option useful if you +encounter DNS resolution problems in the emulated network (for example, an +"Unknown Host error" message that appears when using the web browser).</p> + +<a name="proxy"></a> +<h3>Using the Emulator with a Proxy</h3> + +<p>If your emulator must access the Internet through a proxy server, you can use +the <code>-http-proxy <proxy></code> option when starting the emulator, to +set up the appropriate redirection. In this case, you specify proxy information +in <code><proxy></code> in one of these formats:</p> + +<pre>http://<machineName>:<port></pre> + +<p>or</p> + +<pre>http://<username>:<password>@<machineName>:<port></pre> + +<p>The <code>-http-proxy</code> option forces the emulator to use the specified +HTTP/HTTPS proxy for all outgoing TCP connections. Redirection for UDP is not +currently supported.</p> + +<p>Alternatively, you can define the environment variable +<code>http_proxy</code> to the value you want to use for +<code><proxy></code>. In this case, you do not need to specify a value for +<code><proxy></code> in the <code>-http-proxy</code> command — the +emulator checks the value of the <code>http_proxy</code> environment variable at +startup and uses its value automatically, if defined. </p> + +<p>You can use the <code>-verbose-proxy</code> option to diagnose proxy +connection problems.</p> + +<a name="connecting"></a> +<h3>Interconnecting Emulator Instances</h3> + +<p>To allow one emulator instance to communicate with another, you must set up +the necessary network redirections as illustrated below. </p> + +<p>Assume that your environment is</p> + +<ul> + <li>A is you development machine</li> + <li>B is your first emulator instance, running on A</li> + <li>C is your second emulator instance, running on A too</li> +</ul> + +<p>and you want to run a server on B, to which C will connect, here is how you +could set it up: </p> + +<ol> + <li>Set up the server on B, listening to +<code>10.0.2.15:<serverPort></code></li> + <li>On B's console, set up a redirection from +<code>A:localhost:<localPort></code> to <code> +B:10.0.2.15:<serverPort></code></li> + <li>On C, have the client connect to <code>10.0.2.2:<localPort></code></li> +</ol> + +<p>For example, if you wanted to run an HTTP server, you can select +<code><serverPort></code> as 80 and <code><localPort></code> as +8080:</p> + +<ul> + <li>B listens on 10.0.2.15:80</li> + <li>On B's console, issue <code>redir add tcp:8080:80</code></li> + <li>C connects to 10.0.2.2:8080</li> +</ul> + +<a name="calling"></a> +<h3>Sending a Voice Call or SMS to Another Emulator Instance</h3> + +<p>The emulator automatically forwards simulated voice calls and SMS messages from one instance to another. To send a voice call or SMS, you use the dialer application and SMS application (if available) installed on one emulator </p> + +<p>To initiate a simulated voice call to another emulator instance:</p> +<ol> +<li>Launch the dialer application on the originating emulator instance.</li> +<li>As the number to dial, enter the console port number of the instance you'd like to call. You can determine + the console port number of the target instance by checking its window title, where the + console port number is reported as "Android Emulator (<port>). </li> +<li>Press "Dial". A new inbound call appears in the target emulator instance. </li> +</ol> + +<p>To send an SMS message to another emulator instance, launch the SMS application (if available). Specify the console port number of the target emulator instance as as the SMS address, enter the message text, and send the message. The message is delivered to the target emulator instance. </p> + +<p>You can also connect to an emulator instance's console to simulate an incoming voice call or SMS. For more information, see <a href="#telephony">Telephony Emulation</a> and <a href="#sms">SMS Emulation</a>. + +<a name="console"></a> + +<h2>Using the Emulator Console</h2> + +<p>Each running emulator instance includes a console facility that lets you dynamically query and control the simulated device environment. For example, you can use the console to dynamically manage port redirections and network characteristics and simulate telephony events. To access the console and enter commands, you use telnet to connect to the console's port number. </p> +<p>To connect to the console of any running emulator instance at any time, use this command: </p> + +<pre>telnet localhost <console-port></pre> + +<p>An emulator instance occupies a pair of adjacent ports: a console port and an adb port. The port numbers differ by 1, with the adb port having the higher port number. The console of the first emulator instance running on a given machine uses console port 5554 and adb port 5555. Subsequent instances use port numbers increasing by two — for example, 5556/5557, 5558/5559, and so on. Up to 16 concurrent emulator instances can run a console facility. </p> + +<p>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:</p> + +<p><code>Android Emulator (5554)</code></p> + +<p>Alternatively, you can use the <code>adb devices</code> command, which prints a list of running emulator instances and their console port numbers. For more information, see <a href="{@docRoot}guide/developing/tools/adb.html#devicestatus">Querying for Emulator/Device Instances</a> in the adb documentation.</p> + +<p class="note">Note: The emulator listens for connections on ports 5554-5587 and accepts connections only from localhost.</p> + +<p>Once you are connected to the console, you can then enter <code>help [command]</code> to see a list of console commands and learn about specific commands. </p> + +<p>To exit the console session, use <code>quit</code> or <code>exit</code>.</p> + +<p>The sections below describe the major functional areas of the console.</p> + +<a name="portredirection"></a> + +<h3>Port Redirection</h3> +<p>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:</p> +<pre>redir <list|add|del> </pre> + +<p>The <code>redir</code> command supports the subcommands listed in the table below. </p> + +<table> +<tr> + <th width="25%" >Subcommand + <th width="30%" >Description</th> + <th width="35%">Comments</th> +</tr> + + <tr> + <td><code>list</code></td> + <td>List the current port redirections.</td> + <td> </td> + </tr> + + +<tr> + <td><code>add <protocol>:<host-port>:<guest-port></code></td> + <td>Add a new port redirection.</td> +<td><ul><li><protocol> must be either "tcp" or "udp"</li> +<li><host-port> is the port number to open on the host</li> +<li><guest-port> is the port number to route data to on the emulator/device</li> +</ul></td> +</tr> +<tr> + <td><code>del <protocol>:<host-port></code></td> + <td>Delete a port redirection.</td> +<td>See above for meanings of <protocol> and <host-port>.</td> +</tr> +</table> + +<a name="geo"></a> +<h3>Geo Location Provider Emulation</h3> + +<p>The console provides commands to let you set the geo position used by an emulator emulated device. +You can use the <code>geo</code> command to send a simple GPS fix to the emulator, without needing to +use NMEA 1083 formatting. The usage for the command is:</p> + +<pre>geo <fix|nmea></pre> + +<p>The <code>geo</code> command supports the subcommands listed in the table below.</p> + +<table> +<tr> + <th width="25%" >Subcommand + <th width="30%" >Description</th> + <th width="35%">Comments</th> +</tr> + + <tr> + <td><code>fix <longitude> <latitude> [<altitude>]</code></td> + <td>Send a simple GPS fix to the emulator instance.</td> + <td>Specify longitude and latitude in decimal degrees. Specify altitude in meters.</td> + </tr> +<tr> + <td><code>nmea <sentence></code></td> + <td>Send an NMEA 0183 sentence to the emulated device, as if it were sent from an emulated GPS modem.</td> +<td><code><sentence></code> must begin with '$GP'. Only '$GPGGA' and '$GPRCM' sentences are currently supported.</td> +</tr> +</table> + +<p>You can issue the <code>geo</code> 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: + +<pre>LocationManager.getLastKnownLocation("gps")</pre> + +<p>For more information about the Location Manager, see {@link android.location.LocationManager} and its methods.</p> + +<a name="events"></a> +<h3>Hardware Events Emulation</h3> + +<p>You can use the <code>event</code> command to send various events to the emulator.The usage for the command is: </p> + +<pre>event <send|types|codes|text></pre> + +<p>The <code>event</code> command supports the subcommands listed in the table below. </p> + +<table> +<tr> + <th width="25%" >Subcommand + <th width="30%" >Description</th> + <th width="35%">Comments</th> +</tr> + + <tr> + <td><code>send <type>:<code>:<value> [...]</code></td> + <td>Send one or more events to the Android kernel. </td> + <td>You can use text names or integers for <code><type></code> and <code><value></code>.</td> + </tr> +<tr> + <td><code>types</code></td> + <td>List all <code><type></code> string aliases supported by the <code>event</code> subcommands.</td> +<td> </td> +</tr> +<tr> + <td><code>codes <type></code></td> + <td>List all <code><codes></code> string aliases supported by the <code>event</code> + subcommands for the specified <code><type></code>.</td> +<td> </td> +</tr> +<tr> + <td><code>event text <message></code></td> + <td>Simulate keypresses to send the specified string of characters as a message,</td> +<td>The message must be a UTF-8 string. Unicode posts will be reverse-mapped according to the current device keyboard. Unsupported characters will be discarded silently.</td> +</tr> +</table> + +<a name="power"></a> +<h3>Device Power Characteristics</h3> + +<p>You can use the <code>power</code> command to control the simulated power state of the emulator instance.The usage for the command is: </p> + +<pre>power <display|ac|status|present|health|capacity></pre> + +<p>The <code>event</code> command supports the subcommands listed in the table below. </p> + +<table> +<tr> + <th width="25%" >Subcommand </th> + <th width="30%" >Description</th> + <th width="35%">Comments</th> +</tr> + + <tr> + <td><code>display</code></td> + <td>Display battery and charger state.</td> + <td> </td> + </tr> +<tr> + <td><code>ac <on|off></code></td> + <td>Set AC charging state to on or off. </td> +<td> </td> +</tr> +<tr> + <td><code>status <unknown|charging|discharging|not-charging|full></code></td> + <td>Change battery status as specified.</td> +<td> </td> +</tr> + +<tr> + <td><code>present <true|false></code></td> + <td>Set battery presence state.</td> +<td> </td> +</tr> +<tr> + <td><code>health <unknown|good|overheat|dead|overvoltage|failure></code></td> + <td>Set battery health state.</td> +<td> </td> +</tr> +<tr> + <td><code>power health <percent></code></td> + <td>Set remaining battery capacity state (0-100).</td> +<td> </td> +</tr> +</table> + +<a name="netstatus"></a> +<h3>Network Status</h3> + +<p>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 <code>netstatus</code> command. Here's an example of the command and its output. </p> + +<pre>network status +</pre> + +<a name="netdelay"></a> +<h3>Network Delay Emulation</h3> + +<p>The emulator lets you simulate various network latency levels, so that you can test your application in an environment more typical of the actual conditions in which it will run. You can set a latency level or range at emulator startup or you can use the console to change the latency dynamically, while the application is running in the emulator. </p> +<p>To set latency at emulator startup, use the <code>-netdelay</code> emulator option with a supported <code><delay></code> value, as listed in the table below. Here are some examples:</p> +<pre>emulator -netdelay gprs +emulator -netdelay 40 100</pre> + +<p>To make dynamic changes to network delay while the emulator is running, connect to the console and use the <code>netdelay</code> command with a supported <code><delay></code> value from the table below. </p> + +<pre>network delay gprs</pre> + +<p>The format of network <delay> is one of the following (numbers are milliseconds):</p> + +<table style="clear:right;width:100%;"> +<tr> + <th width="30%" >Value</th> + <th width="35%" >Description</th><th width="35%">Comments</th></tr> + + <tr><td><code>gprs</code></td><td>GPRS</td> + <td>(min 150, max 550)</td> + </tr> + +<tr><td><code>edge</code></td><td>EDGE/EGPRS</td> +<td>(min 80, max 400)</td> +</tr> +<tr><td><code>umts</code></td><td>UMTS/3G</td> +<td>(min 35, max 200)</td> +</tr> +<tr><td><code>none</code></td><td>No latency</td><td>(min 0, max 0)</td></tr> +<tr><td><code><num></code></td> +<td>Emulate an exact latency (milliseconds).</td> +<td> </td></tr> +<tr><td><code><min>:<max></code></td> +<td>Emulate an specified latency range (min, max milliseconds).</td> +<td> </td></tr> +</table> + +<a name="netspeed"></a> +<h3>Network Speed Emulation</h3> + +<p>The emulator also lets you simulate various network transfer rates. +You can set a transfer rate or range at emulator startup or you can use the console to change the rate dynamically, +while the application is running in the emulator.</p> + +<p>To set the network speed at emulator startup, use the <code>-netspeed</code> emulator option with a supported +<code><speed></code> value, as listed in the table below. Here are some examples:</p> +<pre>emulator -netspeed gsm +emulator -netspeed 14.4 80</pre> + +<p>To make dynamic changes to network speed while the emulator is running, connect to the console and use the <code>netspeed</code> command with a supported <code><speed></code> value from the table below. </p> + +<pre>network speed 14.4 80</pre> + +<p>The format of network <code><speed></code> is one of the following (numbers are +kilobits/sec):</p> +<table style="clear:right;width:100%;"> +<tbody> +<tr> + <th width="30%">Value</th> + <th width="35%">Description</th><th width="35%">Comments</th></tr> + + <tr> + <td><code>gsm</code></td> + <td>GSM/CSD</td><td>(Up: 14.4, down: 14.4)</td></tr> +<tr> + <td><code>hscsd</code></td> + <td>HSCSD</td><td>(Up: 14.4, down: 43.2)</td></tr> +<tr> + <td><code>gprs</code></td> + <td>GPRS</td><td>(Up: 40.0, down: 80.0)</td></tr> +<tr> + <td><code>edge</code></td> + <td>EDGE/EGPRS</td> + <td>(Up: 118.4, down: 236.8)</td> +</tr> +<tr> + <td><code>umts</code></td> + <td>UMTS/3G</td><td>(Up: 128.0, down: 1920.0)</td></tr> +<tr> + <td><code>hsdpa</code></td> + <td>HSDPA</td><td>(Up: 348.0, down: 14400.0)</td></tr> +<tr> + <td><code>full</code></td> + <td>no limit</td><td>(Up: 0.0, down: 0.0)</td></tr> +<tr> + <td><code><num></code></td> + <td>Set an exact rate used for both upload and download.</td><td></td></tr> +<tr> + <td><code><up>:<down></code></td> + <td>Set exact rates for upload and download separately.</td><td></td></tr> +</table> + +<a name="telephony"></a> + +<h3>Telephony Emulation</h3> + +<p>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. </p> +<p>You can use the console to access the emulator's telephony functions. After connecting to the console, you can use</p> +<pre>gsm <call|accept|busy|cancel|data|hold|list|voice|status> </pre> +<p>to invoke telephony functions. </p> +<p>The <code>gsm</code> command supports the subcommands listed in the table below. </p> +<table> + <tr> + <th>Subcommand </th> + <th width="25%">Description</th> + <th>Comments</th> + </tr> + <tr> + <td><code>call <phonenumber></code></td> + <td>Simulate an inbound phone call from <phonenumber>.</td> + <td> </td> + </tr> + <tr> + <td><code>accept <phonenumber></code></td> + <td>Accept an inbound call from <phonenumber> and change the call's state "active".</td> + <td>You can change a call's state to "active" only if its current state is "waiting" or "held".</td> + </tr> + <tr> + <td><code>busy <phonenumber></code></td> + <td>Close an outbound call to <phonenumber> and change the call's state to "busy".</td> + <td>You can change a call's state to "busy" only if its current state is "waiting".</td> + </tr> + <tr> + <td><code>cancel <phonenumber></code></td> + <td>Terminate an inbound or outbound phone call to/from <phonenumber>.</td> + <td> </td> + </tr> + <tr> + <td><code>data <state></code></td> + <td>Change the state of the GPRS data connection to <state>.</td> + <td>Supported <state> values are:<br /> + <ul> + <li><code>unregistered</code> -- No network available</li> + <li><code>home</code> -- On local network, non-roaming</li> + <li><code>roaming</code> -- On roaming network</li> + <li><code>searching</code> -- Searching networks</li> + <li><code>denied</code> -- Emergency calls only</li> + <li><code>off</code> -- Same as 'unregistered'</li> + <li><code>on</code> -- same as 'home'</li> + </ul> + </td> + </tr> + <tr> + <td><code>hold</code></td> + <td>Change the state of a call to "held". </td> + <td>You can change a call's state to "held" only if its current state is "active" or "waiting". </td> + </tr> + <tr> + <td><code>list</code></td> + <td>List all inbound and outbound calls and their states.</td> + <td> </td> + </tr> + <tr> + <td><code>voice <state></code></td> + <td>Change the state of the GPRS voice connection to <state>.</td> + <td>Supported <state> values are:<br /> + <ul> + <li><code>unregistered</code> -- No network available</li> + <li><code>home</code> -- On local network, non-roaming</li> + <li><code>roaming</code> -- On roaming network</li> + <li><code>searching</code> -- Searching networks</li> + <li><code>denied</code> -- Emergency calls only</li> + <li><code>off</code> -- Same as 'unregistered'</li> + <li><code>on</code> -- Same as 'home'</li> + </ul> + </td> + </tr> + + <tr> + <td><code>status</code></td> + <td>Report the current GSM voice/data state.</td> + <td>Values are those described for the <code>voice</code> and <code>data</code> commands.</td> + </tr> +</table> + +<a name="sms"></a> + +<h3>SMS Emulation</h3> + +<p>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:</p> + +<pre>sms send <senderPhoneNumber> <textmessage></pre> + +<p>where <code><senderPhoneNumber></code> contains an arbitrary numeric string. </p> + +<p>The console forwards the SMS message to the Android framework, which passes it through to an application that handles that message type. </p> + +<a name="vm"></a> + +<h3>VM State</h3> + +<p>You can use the <code>vm</code> command to control the VM on an emulator instance.The usage for the command is: </p> + +<pre>vm <start|stop|status></pre> + +<p>The <code>vm</code> command supports the subcommands listed in the table below. </p> + +<table> +<tr> + <th width="25%" >Subcommand </th> + <th width="30%" >Description</th> + <th width="35%">Comments</th> +</tr> +<tr> + <td><code>start</code></td> + <td>Start the VM on the instance. </td> + <td> </td> +</tr> +<tr> + <td><code>stop</code></td> + <td>Stop the VM on the instance. </td> + <td> </td> +</tr> +<tr> + <td><code>start</code></td> + <td>Display the current status of the VM (running or stopped). </td> + <td> </td> +</tr> +</table> + + +<a name="window"></a> + +<h3>Emulator Window</h3> + +<p>You can use the <code>window</code> command to manage the emulator window. The usage for the command is: </p> + +<pre>window <scale></pre> + +<p>The <code>vm</code> command supports the subcommands listed in the table below. </p> + +<table> +<tr> + <th width="25%" >Subcommand + <th width="30%" >Description</th> + <th width="35%">Comments</th> +</tr> +<tr> + <td><code>scale <scale></code></td> + <td>Scale the emulator window.</td> + <td><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.</td> +</tr> +</table> + + +<a name="terminating"></a> + +<h3>Terminating an Emulator Instance</h3> + +<p>You can terminate an emulator instance through the console, using the <code>kill</code> command.</p> + + +<a name="skins"></a> + +<h2>Using Emulator Skins</h2> + +<p>The Android SDK includes several Emulator skins that you can use to control the resolution and density of the emulated device's screen. To select a specific skin for running the emulator, create an AVD that uses that skin. Please do not use deprecated emulator options such as <code>-skin</code> to control the skin used by an emulator instance. For more information about AVDs, see <a +href="{@docRoot}guide/developing/devices/index.html">Creating and Managing Virtual Devices</a>.</p> + + +<a name="multipleinstances"></a> + +<h2>Running Multiple Emulator Instances</h2> + +<p>Through the AVDs configurations used by the emulator, you can run multiple +instances of the emulator concurrently, each with its own AVD configuration and +storage area for user data, SD card, and so on. You no longer need to use the +<code>-d</code> option when launching the emulator, to point to an +instance-specific storage area. </p> + +<a name="apps"></a> + +<h2>Installing Applications on the Emulator</h2> + +<p>If you don't have access to Eclipse or the ADT Plugin, you can install +your application on the emulator <a href="{@docRoot}guide/developing/tools/adb.html#move">using +the adb utility</a>. Before installing the application, you need to build and package it +into an <code>.apk</code> as described in <a href="{@docRoot}guide/developing/building/index.html">Building and +Running Apps</a>. Once the application is installed, you can start the emulator from the command +line, as described in this document, using any startup options necessary. +When the emulator is running, you can also connect to the emulator instance's +console to issue commands as needed.</p> + +<p>As you update your code, you periodically package and install it on the emulator. +The emulator preserves the application and its state data across restarts, +in a user-data disk partition. To ensure that the application runs properly +as you update it, you may need to delete the emulator's user-data partition. +To do so, start the emulator with the <code>-wipe-data</code> option. +For more information about the user-data partition and other emulator storage, +see <a href="#diskimages">Working with Emulator Disk Images</a>.</p> + +<a name="sdcard"></a> +<a name="creating"></a> + +<h2>SD Card Emulation</h2> + +<p>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. </p> + +<p>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. </p> + +<p>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. </p> + +<p>The emulator supports emulated SDHC cards, so you can create an SD card image +of any size up to 128 gigabytes.</p> + +<h3 id="creatinga">Creating an SD card image using the android tool</h3> + +<p>The easiest way to create a new SD card is to use the android tool. When +creating an AVD, you simply specify the <code>-c</code> option, like this: </p> + +<pre>android create avd -n <avd_name> -t <targetID> -c <size>[K|M]</pre> + +<p>You can also use the <code>-c</code> option to specify a path to an SD card +image to use in the new AVD. For more information, see <a +href="{@docRoot}guide/developing/devices/managing-avds-cmdline.html">Creating and Managing Virtual Devices on the Command Line</a>. +</p> + +<h3 id="creatingm">Creating an SD card image using mksdcard</h3> + +<p>You can use the mksdcard tool, included in the SDK, to create a FAT32 disk +image that you can load in the emulator at startup. You can access mksdcard in +the tools/ directory of the SDK and create a disk image like this: </p> + +<pre>mksdcard <size> <file></pre> + +<p>For example:</p> + +<pre>mksdcard 1024M sdcard1.iso</pre> + +<p>For more information, see <a href="{@docRoot}guide/developing/tools/mksdcard.html"><code>mksdcard</code></a>.</p> + +<a name="copying"></a> +<h3>Copying Files to a Disk Image</h3> + +<p>Once you have created the disk image, you can copy files to it prior to +loading it in the emulator. To copy files, you can mount the image as a loop +device and then copy the files to it, or you can use a utility such as mtools to +copy the files directly to the image. The mtools package is available for Linux, +Mac, and Windows.</p> + +<a name="loading"></a> +<a name="step3" id="step3"></a> + +<h3>Loading the Disk Image at Emulator Startup</h3> + +<p>By default, the emulator loads the SD card image that is stored with the active +AVD (see the <code>-avd</code> startup option).</p> + +<p>Alternatively, you ca start the emulator with the +<code>-sdcard</code> flag and specify the name and path of your image (relative +to the current working directory): </p> + +<pre>emulator -sdcard <filepath></pre> + +<a name="troubleshooting"></a> + +<h2>Troubleshooting Emulator Problems</h2> + +<p>The adb utility sees the emulator as an actual physical device. For this reason, you might have to use the -d flag with some common adb commands, such as <code>install</code>. The -d flag lets you specify which of several connected devices to use as the target of a command. If you don't specify -d, the emulator will target the first device in its list. For more information about adb, see <a href="{@docRoot}guide/developing/tools/adb.html">Android Debug Bridge</a>.</p> + +<p>For emulators running on Mac OS X, if you see an error "Warning: No DNS servers found" when starting the emulator, check to see whether you have an <code>/etc/resolv.conf</code> file. If not, please run the following line in a command window:</p> + <pre>ln -s /private/var/run/resolv.conf /etc/resolv.conf</pre> + +<p>See <a href="{@docRoot}resources/faq/index.html">Frequently Asked Questions</a> for more troubleshooting information. </p> + +<a name="limitations"></a> + <h2>Emulator Limitations</h2> + <p>In this release, the limitations of the emulator include: </p> + <ul> + <li>No support for placing or receiving actual phone calls. You can simulate phone calls (placed and received) through the emulator console, however. </li> + <li>No support for USB connections</li> + <li>No support for camera/video capture (input).</li> + <li>No support for device-attached headphones</li> + <li>No support for determining connected state</li> + <li>No support for determining battery charge level and AC charging state</li> + <li>No support for determining SD card insert/eject</li> + <li>No support for Bluetooth</li> + </ul> diff --git a/docs/html/guide/developing/devices/index.jd b/docs/html/guide/developing/devices/index.jd new file mode 100644 index 0000000..3e73eb0 --- /dev/null +++ b/docs/html/guide/developing/devices/index.jd @@ -0,0 +1,78 @@ +page.title=Creating and Managing Virtual Devices +@jd:body + + + <p>An Android Virtual Device (AVD) is an emulator configuration that lets you model an actual + device by defining hardware and software options to be emulated by the Android Emulator.</p> + + <p>The easiest way to create an AVD is to use the graphical <a href= + "{@docRoot}guide/developing/devices/managing-avds.html">AVD Manager</a>, which you launch + from Eclipse by clicking <strong>Window > Android SDK and AVD Manager</strong>. You can also start + the AVD Manager from the command line by calling the <code>android</code> tool in the <strong>tools</strong> + directory of the Android SDK.</p> + + <p>You can also create AVDs on the command line by passing the <code>android</code> tool options. + For more information on how to create AVDs in this manner, see <a href= + "{@docRoot}guide/developing/devices/managing-avds-cmdline.html">Creating and Managing Virtual + Devices on the Command Line</a>.</p> + + <p>An AVD consists of:</p> + + <ul> + <li>A hardware profile: Defines the hardware features of the virtual + device. For example, you can define whether the device has a camera, whether it uses a physical + QWERTY keyboard or a dialing pad, how much memory it has, and so on.</li> + + <li>A mapping to a system image: You can define what version of the Android platform will run + on the virtual device. You can choose a version of the standard Android platform or the system + image packaged with an SDK add-on.</li> + + <li>Other options: You can specify the emulator skin you want to use with the AVD, which lets + you control the screen dimensions, appearance, and so on. You can also specify the emulated SD + card to use with the AVD.</li> + + <li>A dedicated storage area on your development machine: the device's user data (installed + applications, settings, and so on) and emulated SD card are stored in this area.</li> + </ul> + + <p>You can create as many AVDs as you need, based on the types of device you want to model. + To thoroughly test your application, you should create an AVD for each general device configuration + (for example, different screen sizes and platform versions) with which your application is compatible + and test your application on each one.</p> + + <p>Keep these points in mind when you are selecting a system image target for your AVD:</p> + + <ul> + <li>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 <a href="{@docRoot}guide/topics/manifest/uses-sdk-element.html"> + <code>minSdkVersion</code></a> attribute of the application's manifest file. For more + information about the relationship between system API Level and application + <code>minSdkVersion</code>, see <a href= + "{@docRoot}guide/publishing/versioning.html">Specifying Minimum System API Version</a>.</li> + + <li>You should create at least one AVD that uses a target whose API Level is greater than that required + by your application, because it allows you to test the + forward-compatibility of your application. Forward-compatibility testing ensures that, when + users who have downloaded your application receive a system update, your application will + continue to function normally.</li> + + <li>If your application declares a + <a href="{@docRoot}guide/topics/manifest/uses-library-element.html"><code>uses-library</code></a> + element in its manifest file, the application can only run on a system image in which that external + library is present. If you want to run your application on an emulator, create an AVD that + includes the required library. Usually, you must create such an AVD using an Add-on component for the + AVD's platform (for example, the Google APIs Add-on contains the Google Maps library).</li> + </ul> + + <p>To learn how to manage AVDs using a graphical tool, read <a href= + "{@docRoot}guide/developing/devices/managing-avds.html"> + Creating and Managing AVDs with AVD Manager</a>. To learn how to manage AVDs on the command line, read + <a href="{@docRoot}guide/developing/devices/managing-avds-cmdline.html">Creating and Managing AVDs + on the Command Line</a>.</p> + + + + + + diff --git a/docs/html/guide/developing/devices/managing-avds-cmdline.jd b/docs/html/guide/developing/devices/managing-avds-cmdline.jd new file mode 100644 index 0000000..878ccc9 --- /dev/null +++ b/docs/html/guide/developing/devices/managing-avds-cmdline.jd @@ -0,0 +1,312 @@ +page.title=Creating and Managing AVDs on the Command Line +@jd:body + +<div id="qv-wrapper"> + <div id="qv"> + <h2>In this document</h2> + <ol> + <li><a href="#listingtargets">Listing targets</a></li> + <li><a href="#AVDCmdLine">Creating AVDs</a></li> + <li><a href="#moving">Moving an AVD</a></li> + <li><a href="#updating">Updating an AVD</a></li> + <li><a href="#deleting">Deleting an AVD</a></li> + </ol> + </div> +</div> + + +<p>The <code>android</code> tool lets you manage AVDs on the command line. For a complete reference +of the command line options that you can use, see the reference for the +<a href="{@docRoot}guide/developing/tools/android.html"><code>android</code></a> tool.</p> + + + +<h2 id="listingtargets">Listing targets</h2> + +<p>To generate a list of system image targets, use this command: </p> + +<pre>android list targets</pre> + +<p>The <code>android</code> tool scans the <code><sdk>/platforms/</code> and +<code><sdk>/add-ons/</code> directories looking for valid system images and +then generates the list of targets. Here's an example of the command output: +</p> + +<pre>Available Android targets: +id: 1 or "android-3" + Name: Android 1.5 + Type: Platform + API level: 3 + Revision: 4 + Skins: QVGA-L, HVGA-L, HVGA (default), HVGA-P, QVGA-P +id: 2 or "android-4" + Name: Android 1.6 + Type: Platform + API level: 4 + Revision: 3 + Skins: QVGA, HVGA (default), WVGA800, WVGA854 +id: 3 or "android-7" + Name: Android 2.1-update1 + Type: Platform + API level: 7 + Revision: 2 + Skins: QVGA, WQVGA400, HVGA (default), WVGA854, WQVGA432, WVGA800 +id: 4 or "android-8" + Name: Android 2.2 + Type: Platform + API level: 8 + Revision: 2 + Skins: WQVGA400, QVGA, WVGA854, HVGA (default), WVGA800, WQVGA432 +id: 5 or "android-9" + Name: Android 2.3 + Type: Platform + API level: 9 + Revision: 1 + Skins: HVGA (default), WVGA800, WQVGA432, QVGA, WVGA854, WQVGA400 +</pre> + +<h2 id="AVDCmdLine">Creating AVDs</h2> +<p>In addition to creating AVDs with the +<a href="{@docRoot}guide/developing/devices/managing-avds-cmdline.html">AVD Manager user interface</a>, +you can also create them by passing in command line arguments to the <code>android</code> tool. +</p> + +<p>Open a terminal window and change to +the <code><sdk>/tools/</code> directory, if needed.</p> + +<p>To create each AVD, you issue the command <code>android create avd</code>, +with options that specify a name for the new AVD and the system image you want +to run on the emulator when the AVD is invoked. You can specify other options on +the command line also, such as the emulated SD card size, the emulator skin, or a custom +location for the user data files.</p> + +<p>Here's the command-line usage for creating an AVD: </p> + +<pre>android create avd -n <name> -t <targetID> [-<option> <value>] ... </pre> + +<p>You can use any name you want for the AVD, but since you are likely to be +creating multiple AVDs, you should choose a name that lets you recognize the +general characteristics offered by the AVD. The target ID is an integer assigned by the +<code>android</code> tool. The target ID is not derived from the system image name, +version, or API Level, or other attribute, so you need to run the <code>android list targets</code> +command to list the target ID of each system image. You should do this <em>before</em> you run +the <code>android create avd</code> command. See the <a href="{@docRoot}guide/developing/tools/android.html">android</a></p> +tool documentation for more information on the command line options. + + +<p>When you've selected the target you want to use and made a note of its ID, +use the <code>android create avd</code> command to create the AVD, supplying the +target ID as the <code>-t</code> argument. Here's an example that creates an +AVD with name "my_android1.5" and target ID "2" (the standard Android 1.5 +system image in the list above): </p> + +<pre>android create avd -n my_android1.5 -t 2</pre> + +<p>If the target you selected was a standard Android system image ("Type: +platform"), the <code>android</code> tool next asks you whether you want to +create a custom hardware profile. </p> +<pre>Android 1.5 is a basic Android platform. +Do you wish to create a custom hardware profile [no]</pre> + +<p>If you want to set custom hardware emulation options for the AVD, enter +"yes" and set values as needed. If you want to use the default hardware +emulation options for the AVD, just press the return key (the default is "no"). +The <code>android</code> tool creates the AVD with name and system image mapping you +requested, with the options you specified. For more information, see <a href="#hardwareopts"> +Setting Hardware Emulation Options</a>. + +<p class="note"><strong>Note:</strong> If you are creating an AVD whose target is an SDK add-on, the +<code>android</code> tool does not allow you to set hardware emulation options. +It assumes that the provider of the add-on has set emulation options +appropriately for the device that the add-on is modeling, and so prevents you +from resetting the options. </p> + + +<h3>Default location of AVD files</h3> +<p>When you create an AVD, the <code>android</code> tool creates a dedicated directory for it +on your development computer. The directory contains the AVD configuration file, +the user data image and SD card image (if available), and any other files +associated with the device. Note that the directory does not contain a system +image — instead, the AVD configuration file contains a mapping to the +system image, which it loads when the AVD is launched. </p> + +<p>The <code>android</code> tool also creates an <code><AVD_name>.ini</code> file for the AVD at the +root of the <code>.android/avd/</code> directory on your computer. The file specifies the +location of the AVD directory and always remains at the root the .android +directory.</p> + +<p>By default, the <code>android</code> tool creates the AVD directory inside +<code>~/.android/avd/</code> (on Linux/Mac), <code>C:\Documents and +Settings\<user>\.android\</code> on Windows XP, and +<code>C:\Users\<user>\.android\</code> on Windows 7 and Vista. +If you want to use a custom location for the AVD directory, you +can do so by using the <code>-p <path></code> option when +you create the AVD: </p> + +<pre>android create avd -n my_android1.5 -t 2 -p path/to/my/avd</pre> + +<p>If the .android directory is hosted on a network drive, we recommend using +the <code>-p</code> 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. + + +<h3 id="hardwareopts">Setting Hardware Emulation Options</h3> + +<p>When you are creating a new AVD that uses a standard Android system image ("Type: +platform"), the <code>android</code> tool lets you set hardware emulation +options for virtual device. The table below lists the options available and the +default values, as well as the names of properties that store the emulated +hardware options in the AVD's configuration file (the config.ini file in the +AVD's local directory). </p> + +<p class="table-caption"><strong>Table 1.</strong> Available hardware profile options for AVDs and +the default values </p> + +<table> +<tr> +<th>Characteristic</th> +<th>Description</th> +<th>Property</th> +</tr> + +<tr> +<td>Device ram size</td> +<td>The amount of physical RAM on the device, in megabytes. Default value is "96". +<td>hw.ramSize</td> +</tr> + +<tr> +<td>Touch-screen support</td> +<td>Whether there is a touch screen or not on the device. Default value is "yes".</td> +<td>hw.touchScreen + +<tr> +<td>Trackball support </td> +<td>Whether there is a trackball on the device. Default value is "yes".</td> +<td>hw.trackBall</td> +</tr> + +<tr> +<td>Keyboard support</td> +<td>Whether the device has a QWERTY keyboard. Default value is "yes".</td> +<td>hw.keyboard</td> +</tr> + +<tr> +<td>DPad support</td> +<td>Whether the device has DPad keys. Default value is "yes".</td> +<td>hw.dPad</td> +</tr> + +<tr> +<td>GSM modem support</td> +<td>Whether there is a GSM modem in the device. Default value is "yes".</td> +<td>hw.gsmModem</td> +</tr> + +<tr> +<td>Camera support</td> +<td>Whether the device has a camera. Default value is "no".</td> +<td>hw.camera</td> +</tr> + +<tr> +<td>Maximum horizontal camera pixels</td> +<td>Default value is "640".</td> +<td>hw.camera.maxHorizontalPixels</td> +</tr> + +<tr> +<td>Maximum vertical camera pixels</td> +<td>Default value is "480".</td> +<td>hw.camera.maxVerticalPixels</td> +</tr> + +<tr> +<td>GPS support</td> +<td>Whether there is a GPS in the device. Default value is "yes".</td> +<td>hw.gps</td> +</tr> + +<tr> +<td>Battery support</td> +<td>Whether the device can run on a battery. Default value is "yes".</td> +<td>hw.battery</td> +</tr> + +<tr> +<td>Accelerometer</td> +<td>Whether there is an accelerometer in the device. Default value is "yes".</td> +<td>hw.accelerometer</td> +</tr> + +<tr> +<td>Audio recording support</td> +<td>Whether the device can record audio. Default value is "yes".</td> +<td>hw.audioInput</td> +</tr> + +<tr> +<td>Audio playback support</td> +<td>Whether the device can play audio. Default value is "yes".</td> +<td>hw.audioOutput</td> +</tr> + +<tr> +<td>SD Card support</td> +<td>Whether the device supports insertion/removal of virtual SD Cards. Default value is "yes".</td> +<td>hw.sdCard</td> +</tr> + +<tr> +<td>Cache partition support</td> +<td>Whether we use a /cache partition on the device. Default value is "yes".</td> +<td>disk.cachePartition</td> +</tr> + +<tr> +<td>Cache partition size</td> +<td>Default value is "66MB".</td> +<td>disk.cachePartition.size </td> +</tr> + +<tr> +<td>Abstracted LCD density</td> +<td>Sets the generalized density characteristic used by the AVD's screen. Default value is "160".</td> +<td>hw.lcd.density </td> +</tr> + +<tr> +<td>Trackball support</td> +<td>Whether there is a trackball present.</td> +<td>hw.trackBall </td> +</tr> +</table> + + +<h2 id="moving">Moving an AVD</h2> + +<p>If you want to move or rename an AVD, you can do so using this command:</p> + +<pre>android move avd -n <name> [-<option> <value>] ...</pre> + +<h2 id="updating">Updating an AVD</h2> + +<p>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 <code>android list targets</code> command will produce this output: + +<pre>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' </pre> + +<p>To fix this error, use the <code>android update avd</code> command to recompute the path to the system images.</p> + +<h2 id="deleting">Deleting an AVD</h2> + +<p>You can use the <code>android</code> tool to delete an AVD. Here is the command usage:</p> + +<pre>android delete avd -n <name> </pre> + +<p>When you issue the command, the <code>android</code> tool looks for an AVD matching the +specified name deletes the AVD's directory and files. </p> diff --git a/docs/html/guide/developing/devices/managing-avds.jd b/docs/html/guide/developing/devices/managing-avds.jd new file mode 100644 index 0000000..27d2b55 --- /dev/null +++ b/docs/html/guide/developing/devices/managing-avds.jd @@ -0,0 +1,243 @@ +page.title=Creating and Managing AVDs with AVD Manager +@jd:body + + <div id="qv-wrapper"> + <div id="qv"> + <h2>In this document</h2> + + <ol> + <li><a href="#createavd">Creating an AVD</a> + <ol> + <li><a href="#hardwareopts">Hardware options</a></li> + </ol> + </li> + </ol> + </div> + </div> + + <p>The AVD Manager is an easy to use user interface to manage your AVD (Android Virtual Device) + configurations. An AVD is a device configuration for the Android emulator that allows you to + model different configurations of Android-powered devices. When you start the AVD Manager in Eclipse + or run the <code>android</code> tool on the command line, you will see the AVD Manager as shown in + figure 1:</p> + + <img src="{@docRoot}images/avd-manager.png"> + + <p class="img-caption"><strong>Figure 1. </strong>Screenshot of the AVD Manager. </p> + + <p>From the main screen, you can create, delete, repair and start AVDs as well as see the details + of each AVD. </p> + + + <h2 id="createavd">Creating an AVD</h2> + + <p>You can create as many AVDs as you would like to test on. It is recommended that you test your + applications on all API levels higher than the target API level for your application.</p> + + <p>To create an AVD:</p> + + <ol> + <li>Start the AVD Manager: + + <ul> + <li>In Eclipse: select <strong>Window > Android SDK and AVD Manager</strong>, or click + the Android SDK and AVD Manager icon in the Eclipse toolbar.</li> + + <li>In other IDEs: Navigate to your SDK's <code>tools/</code> directory and execute the + <code>android</code> tool with no arguments.</li> + </ul> + </li> + + <li><p>In the <em>Virtual Devices</em> panel, you'll see a list of existing AVDs. Click + <strong>New</strong> to create a new AVD. The <strong>Create New AVD</strong> dialog appears.</p> + + <img src="{@docRoot}images/developing/avd-dialog.png" alt="AVD Dialog"> + <p class="img-caption"><strong>Figure 2.</strong> Screenshot of the Create AVD window</p> + </li> + + <li>Fill in the details for the AVD. + + <p>Give it a name, a platform target, an SD card size, and a skin (HVGA is default). You can + also add specific hardware features of the emulated device by clicking the + <strong>New...</strong> button and selecting the feature. For a list of hardware features, + see <a href="#hardwareopts">Hardware options</a>.</p> + + <p class="note"><strong>Note:</strong> 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).</p> + </li> + + <li>Click <strong>Create AVD</strong>.</li> + </ol> + + <p>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 <strong>Start</strong>.</p> + +<h3 id="hardwareopts">Hardware options</h3> +<p>If you are creating a new AVD, you can specify the following hardware options for the AVD +to emulate:</p> + + <table> + <tr> + <th>Characteristic</th> + + <th>Description</th> + + <th>Property</th> + </tr> + + <tr> + <td>Device ram size</td> + + <td>The amount of physical RAM on the device, in megabytes. Default value is "96".</td> + + <td>hw.ramSize</td> + </tr> + + <tr> + <td>Touch-screen support</td> + + <td>Whether there is a touch screen or not on the device. Default value is "yes".</td> + + <td>hw.touchScreen</td> + </tr> + + <tr> + <td>Trackball support</td> + + <td>Whether there is a trackball on the device. Default value is "yes".</td> + + <td>hw.trackBall</td> + </tr> + + <tr> + <td>Keyboard support</td> + + <td>Whether the device has a QWERTY keyboard. Default value is "yes".</td> + + <td>hw.keyboard</td> + </tr> + + <tr> + <td>DPad support</td> + + <td>Whether the device has DPad keys. Default value is "yes".</td> + + <td>hw.dPad</td> + </tr> + + <tr> + <td>GSM modem support</td> + + <td>Whether there is a GSM modem in the device. Default value is "yes".</td> + + <td>hw.gsmModem</td> + </tr> + + <tr> + <td>Camera support</td> + + <td>Whether the device has a camera. Default value is "no".</td> + + <td>hw.camera</td> + </tr> + + <tr> + <td>Maximum horizontal camera pixels</td> + + <td>Default value is "640".</td> + + <td>hw.camera.maxHorizontalPixels</td> + </tr> + + <tr> + <td>Maximum vertical camera pixels</td> + + <td>Default value is "480".</td> + + <td>hw.camera.maxVerticalPixels</td> + </tr> + + <tr> + <td>GPS support</td> + + <td>Whether there is a GPS in the device. Default value is "yes".</td> + + <td>hw.gps</td> + </tr> + + <tr> + <td>Battery support</td> + + <td>Whether the device can run on a battery. Default value is "yes".</td> + + <td>hw.battery</td> + </tr> + + <tr> + <td>Accelerometer</td> + + <td>Whether there is an accelerometer in the device. Default value is "yes".</td> + + <td>hw.accelerometer</td> + </tr> + + <tr> + <td>Audio recording support</td> + + <td>Whether the device can record audio. Default value is "yes".</td> + + <td>hw.audioInput</td> + </tr> + + <tr> + <td>Audio playback support</td> + + <td>Whether the device can play audio. Default value is "yes".</td> + + <td>hw.audioOutput</td> + </tr> + + <tr> + <td>SD Card support</td> + + <td>Whether the device supports insertion/removal of virtual SD Cards. Default value is + "yes".</td> + + <td>hw.sdCard</td> + </tr> + + <tr> + <td>Cache partition support</td> + + <td>Whether we use a /cache partition on the device. Default value is "yes".</td> + + <td>disk.cachePartition</td> + </tr> + + <tr> + <td>Cache partition size</td> + + <td>Default value is "66MB".</td> + + <td>disk.cachePartition.size</td> + </tr> + + <tr> + <td>Abstracted LCD density</td> + + <td>Sets the generalized density characteristic used by the AVD's screen. Default value is + "160".</td> + + <td>hw.lcd.density</td> + </tr> + + <tr> + <td>Trackball support</td> + + <td>Whether there is a trackball present.</td> + + <td>hw.trackBall</td> + </tr> + </table> + diff --git a/docs/html/guide/developing/eclipse-adt.html b/docs/html/guide/developing/eclipse-adt.html new file mode 100644 index 0000000..879a356 --- /dev/null +++ b/docs/html/guide/developing/eclipse-adt.html @@ -0,0 +1,10 @@ +<html> +<head> +<meta http-equiv="refresh" content="0;url=http://developer.android.com/guide/developing/projects/projects-eclipse.html"> +<title>Redirecting...</title> +</head> +<body> +<p>You should be redirected. Please <a +href="http://developer.android.com/guide/developing/projects/projects-eclipse.html">click here</a>.</p> +</body> +</html>
\ No newline at end of file diff --git a/docs/html/guide/developing/eclipse-adt.jd b/docs/html/guide/developing/eclipse-adt.jd deleted file mode 100644 index f8d32e7..0000000 --- a/docs/html/guide/developing/eclipse-adt.jd +++ /dev/null @@ -1,860 +0,0 @@ -page.title=Developing In Eclipse, with ADT -@jd:body - -<div id="qv-wrapper"> - <div id="qv"> - <h2>In this document</h2> - <ol> - <li><a href="#CreatingAProject">Creating an Android Project</a></li> - <li><a href="#AVD">Creating an AVD</a></li> - <li><a href="#Running">Running Your Application</a> - <ol> - <li><a href="#RunningOnEmulator">Running on the emulator</a></li> - <li><a href="#RunningOnDevice">Running on a device</a></li> - </ol> - </li> - <li><a href="#RunConfig">Creating a Run Configuration</a></li> - <li><a href="#Signing">Setting Up Application Signing</a></li> - <li><a href="#libraryProject">Working with Library Projects</a> - <ol> - <li><a href="#libraryReqts">Development requirements</a></li> - <li><a href="#librarySetup">Setting up a library project</a></li> - <li><a href="#libraryReference">Referencing a library project</a></li> - <li><a href="#considerations">Development considerations</a></li> - <li><a href="#libraryMigrating">Migrating library projects to ADT 0.9.8</a></li> - </ol> - </li> - <li><a href="#Tips">Eclipse Tips</a></li> - </div> -</div> - - -<p>The Android Development Tools (ADT) plugin for Eclipse adds powerful extensions to the Eclipse -integrated development environment. It allows you to create and debug Android applications easier -and faster. If you use Eclipse, the ADT plugin gives you an incredible boost in developing Android -applications:</p> - -<ul> - <li>It gives you access to other Android development tools from inside the Eclipse IDE. For -example, ADT lets you access the many capabilities of the DDMS tool: take screenshots, manage -port-forwarding, set breakpoints, and view thread and process information directly from -Eclipse.</li> - <li>It provides a New Project Wizard, which helps you quickly create and set up all of the -basic files you'll need for a new Android application.</li> - <li>It automates and simplifies the process of building your Android application.</li> - <li>It provides an Android code editor that helps you write valid XML for your Android -manifest and resource files.</li> - <li>It will even export your project into a signed APK, which can be distributed to users.</li> -</ul> - -<p>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 <a href="{@docRoot}sdk/eclipse-adt.html#installing">Installing -the ADT Plugin</a>.</p> - -<p>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 -<a href="{@docRoot}sdk/eclipse-adt.html#updating">Updating Your ADT Plugin</a>.</p> - -<p class="note"><strong>Note:</strong> 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).</p> - - -<h2 id="CreatingAProject">Creating an Android Project</h2> - -<p>The ADT plugin provides a New Project Wizard that you can use to quickly create a new -Android project (or a project from existing code). To create a new project:</p> - -<ol> - <li>Select <strong>File</strong> > <strong>New</strong> > <strong>Project</strong>.</li> - <li>Select <strong>Android</strong> > <strong>Android Project</strong>, and click - <strong>Next</strong>.</li> - <li>Select the contents for the project: - <ul> - <li>Enter a <em>Project Name</em>. This will be the name of the folder where your - project is created.</li> - <li>Under Contents, select <strong>Create new project in workspace</strong>. - Select your project workspace location.</li> - <li>Under Target, select an Android target to be used as the project's Build Target. - The Build Target - specifies which Android platform you'd like your application built against. - <p>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.</p> - <p class="note"><strong>Note:</strong> You can change your the Build Target for your - project at any time: Right-click the project in the Package Explorer, select - <strong>Properties</strong>, select <strong>Android</strong> and then check - the desired Project Target.</p> - </li> - <li>Under Properties, fill in all necessary fields. - <ul> - <li>Enter an <em>Application name</em>. This is the human-readable title for your - application — the name that will appear on the Android device.</li> - <li>Enter a <em>Package name</em>. This is the package namespace (following the same rules - as for packages in the Java programming language) where all your source code - will reside.</li> - <li>Select <em>Create Activity</em> (optional, of course, but common) and enter a name - for your main Activity class.</li> - <li>Enter a <em>Min SDK Version</em>. This is an integer that indicates - the minimum API Level required to properly run your application. - Entering this here automatically sets the <code>minSdkVersion</code> attribute in the - <a href="{@docRoot}guide/topics/manifest/uses-sdk-element.html"><uses-sdk></a> - of your Android Manifest file. If you're unsure of the appropriate <a -href="{@docRoot}guide/appendix/api-levels.html">API Level</a> to use, - copy the API Level listed for the Build Target you selected in the Target tab.</li> - </ul> - </li> - </ul> - </li> - <li>Click <strong>Finish</strong>.</li> -</ol> - -<p class="note"><strong>Tip:</strong> -You can also start the New Project Wizard from the <em>New</em> icon in the toolbar.</p> - -<p>Once you complete the New Project Wizard, ADT creates the following -folders and files in your new project:</p> - <dl> - <dt><code>src/</code></dt> - <dd>Includes your stub Activity Java file. All other Java files for your application - go here.</dd> - <dt><code><em><Android Version></em>/</code> (e.g., <code>Android 1.1/</code>)</dt> - <dd>Includes the <code>android.jar</code> file that your application will build against. - This is determined by the build target that you have chosen in the <em>New Project - Wizard</em>.</dd> - <dt><code>gen/</code></dt> - <dd>This contains the Java files generated by ADT, such as your <code>R.java</code> file - and interfaces created from AIDL files.</dd> - <dt><code>assets/</code></dt> - <dd>This is empty. You can use it to store raw asset files. </dd> - <dt><code>res/</code></dt> - <dd>A folder for your application resources, such as drawable files, layout files, string - values, etc. See - <a href="{@docRoot}guide/topics/resources/index.html">Application Resources</a>.</dd> - <dt><code>AndroidManifest.xml</code></dt> - <dd>The Android Manifest for your project. See - <a href="{@docRoot}guide/topics/manifest/manifest-intro.html">The AndroidManifest.xml - File</a>.</dd> - <dt><code>default.properties</code></dt> - <dd>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".</dd> - </dl> - - -<h2 id="AVD">Creating an AVD</h2> - -<p>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.</p> - -<p>To create an AVD from Eclipse:</p> - -<ol> - <li>Select <strong>Window > Android SDK and AVD Manager</strong>, or click the Android SDK and -AVD Manager icon in the Eclipse toolbar.</p> - </li> - <li>In the <em>Virtual Devices</em> panel, you'll see a list of existing AVDs. Click -<strong>New</strong> to create a new AVD.</li> - <li>Fill in the details for the AVD. - <p>Give it a name, a platform target, an SD card size, and - a skin (HVGA is default).</p> - <p class="note"><strong>Note:</strong> 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).</p> - </li> - <li>Click <strong>Create AVD</strong>.</li> -</ol> - -<p>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 <strong>Start</strong>.</p> - -<p>For more information about AVDs, read the -<a href="{@docRoot}guide/developing/tools/avd.html">Android Virtual Devices</a> -documentation.</p> - - -<h2 id="Running">Running Your Application</h2> - -<div class="sidebox-wrapper"> -<div class="sidebox"> -<h2>Use the Emulator to Test Different Configurations</h2> -<p>Create multiple AVDs that each define a different device configuration with which your -application is compatible, then launch each AVD into a new emulator from the SDK and AVD Manager. -Set the target mode in your app's run configuration to manual, so that when you run your -application, you can select from the available virtual devices.</p> -</div> -</div> - -<p>Running your application from Eclipse will usually require just a couple clicks, whether you're -running it on the emulator or on an attached device. The information below describes how to get -set up and run your application from Eclipse.</p> - -<h3 id="RunningOnEmulator">Running on the emulator</h3> - -<p>Before you can run your application on the Android Emulator, -you <strong>must</strong> <a href="#AVD">create an AVD</a>.</p> - -<p>To run (or debug) your application, select <strong>Run</strong> > <strong>Run</strong> (or -<strong>Run</strong> > <strong>Debug</strong>) from the Eclipse menu bar. The ADT plugin -will automatically create a default launch configuration for the project. Eclipse will then perform -the following:</p> - -<ol> - <li>Compile the project (if there have been changes since the last build).</li> - <li>Create a default launch configuration (if one does not already exist for the -project).</li> - <li>Install and start the application on an emulator (or device), based on the Deployment -Target - defined by the run configuration. - <p>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 <a href="#AutoAndManualTargetModes">Automatic and manual - target modes</a> below.</p> - </li> -</ol> - -<p>If debugging, the application will start in the "Waiting For Debugger" mode. Once the -debugger is attached, Eclipse will open the Debug perspective.</p> - -<p>To set or change the launch configuration used for your project, use the launch configuration -manager. -See <a href="#RunConfig">Creating a Run Configuration</a> for information.</p> - -<p>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 <a -href="{@docRoot}guide/practices/screens_support.html">screen type</a> you support, then test -your application on each one.</p> - - -<h3 id="RunningOnDevice">Running on a device</h3> - -<p>Before you can run your application on a device, you must perform some basic setup for your -device:</p> - -<ul> - <li>Declare your application as debuggable in your manifest</li> - <li>Enable USB Debugging on your device</li> - <li>Ensure that your development computer can detect your device when connected via USB</li> -</ul> -<p>Read <a href="{@docRoot}guide/developing/device.html#setting-up">Setting up a Device for -Development</a> for more information.</p> - -<p>Once set up and your device is connected via USB, install your application on the device by -selecting <strong>Run</strong> > <strong>Run</strong> (or -<strong>Run</strong> > <strong>Debug</strong>) from the Eclipse menu bar.</p> - - - -<h2 id="RunConfig">Creating a Run Configuration</h2> - -<p>The run configuration specifies the project to run, the Activity -to start, the emulator or connected device to use, and so on. When you first run a project -as an <em>Android Application</em>, ADT will automatically create a run configuration. -The default run configuration will -launch the default project Activity and use automatic target mode for device selection -(with no preferred AVD). If the default settings don't suit your project, you can -customize the launch configuration or even create a new.</p> - -<p>To create or modify a launch configuration, follow these steps as appropriate -for your Eclipse version:</p> - -<ol> - <li>Open the run configuration manager. - <ul> - <li>In Eclipse 3.3 (Europa), select <strong>Run</strong> > - <strong>Open Run Dialog</strong> (or <strong>Open Debug Dialog</strong>) - </li> - <li>In Eclipse 3.4 (Ganymede), select <strong>Run </strong>> - <strong>Run Configurations</strong> (or - <strong>Debug Configurations</strong>) - </li> - </ul> - </li> - <li>Expand the <strong>Android Application</strong> item and create a new - configuration or open an existing one. - <ul> - <li>To create a new configuration: - <ol> - <li>Select <strong>Android Application</strong> and click the <em>New launch -configuration</em> - icon above the list (or, right-click <strong>Android Application</strong> and click - <strong>New</strong>).</li> - <li>Enter a Name for your configuration.</li> - <li>In the Android tab, browse and select the project you'd like to run with the - configuration.</li> - </ol> - <li>To open an existing configuration, select the configuration name from the list - nested below <strong>Android Application</strong>.</li> - </ul> - </li> - <li>Adjust your desired launch configuration settings. - <p>In the Target tab, consider whether you'd like to use Manual or Automatic mode - when selecting an AVD to run your application. - See the following section on <a href="#AutoAndManualTargetModes">Automatic and manual target - modes</a>).</p> - <p>You can specify any emulator options to the Additional Emulator Command - Line Options field. For example, you could add <code>-scale 96dpi</code> to - scale the AVD's screen to an accurate size, based on the dpi of your - computer monitor. For a full list of emulator options, see the <a - href="{@docRoot}guide/developing/tools/emulator.html">Android Emulator</a> -document.</p> - </li> -</ol> - - -<h3 id="AutoAndManualTargetModes">Automatic and manual target modes</h3> - -<p>By default, a run configuration uses the <strong>automatic</strong> target mode in order to -select an AVD. In this mode, ADT will select an AVD for the application in the following manner:</p> - -<ol> - <li>If there's a device or emulator already running and its AVD configuration - meets the requirements of the application's build target, the application is installed - and run upon it.</li> - <li>If there's more than one device or emulator running, each of which meets the requirements - of the build target, a "device chooser" is shown to let you select which device to use.</li> - <li>If there are no devices or emulators running that meet the requirements of the build target, - ADT looks at the available AVDs. If one meets the requirements of the build target, - the AVD is used to launch a new emulator, upon which the application is installed and run.</li> - <li>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.</li> -</ol> - -<p>However, if a "preferred AVD" is selected in the run configuration, then the application -will <em>always</em> be deployed to that AVD. If it's not already running, then a new emulator -will be launched.</p> - -<p>If your run configuration uses <strong>manual</strong> mode, then the "device chooser" -is presented every time that your application is run, so that you can select which AVD to use.</p> - - -<h2 id="Signing">Signing your Applications</h2> - -<p>As you begin developing Android applications, understand that all -Android applications must be digitally signed before the system will install -them on an emulator or an actual device. There are two ways to do this: -with a debug key (for immediate testing on an emulator or development device) -or with a private key (for application distribution).</p> - -<p>The ADT plugin helps you get started quickly by signing your .apk files with -a debug key, prior to installing them on an emulator or development device. This means that you can -quickly run your application from Eclipse without having to -generate your own private key. No specific action on your part is needed, -provided ADT has access to Keytool.However, please note that if you intend -to publish your application, you <strong>must</strong> sign the application with your -own private key, rather than the debug key generated by the SDK tools.</p> - -<p>Please read <a href="{@docRoot}guide/publishing/app-signing.html">Signing Your -Applications</a>, which provides a thorough guide to application signing on Android -and what it means to you as an Android application developer. The document also includes -a guide to exporting and signing your application with the ADT's Export Wizard.</p> - - -<h2 id="libraryProject">Working with Library Projects</h2> - -<div class="sidebox-wrapper"> -<div class="sidebox"> -<h2>Library project example code</h2> - -<p>The SDK includes an example application called TicTacToeMain that shows how a -dependent application can use code and resources from an Android Library -project. The TicTacToeMain application uses code and resources from an example -library project called TicTacToeLib. - -<p style="margin-top:1em;">To download the sample applications and run them as -projects in your environment, use the <em>Android SDK and AVD Manager</em> to -download the "Samples for SDK API 8" component into your SDK. </p> - -<p style="margin-top:1em;">For more information and to browse the code of the -samples, see the <a -href="{@docRoot}resources/samples/TicTacToeMain/index.html">TicTacToeMain -application</a>.</p> -</div> -</div> - -<p>An Android <em>library project</em> is a development project that holds -shared Android source code and resources. Other Android application projects can -reference the library project and, at build time, include its compiled sources -in their <code>.apk</code> files. Multiple application projects can reference -the same library project and any single application project can reference -multiple library projects. </p> - -<p>If you have source code and resources that are common to multiple application -projects, you can move them to a library project so that it is easier to -maintain across applications and versions. Here are some common scenarios in -which you could make use of library projects: </p> - -<ul> -<li>If you are developing multiple related applications that use some of the -same components, you could move the redundant components out of their respective -application projects and create a single, reuseable set of the same components -in a library project. </li> -<li>If you are creating an application that exists in both free and paid -versions, you could 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.</li> -</ul> - -<p>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 <code>src/</code>, <code>res/</code> 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 <code>R</code> class. </p> - -<p>However, a library project differs from an standard Android application -project in that you cannot compile it directly to its own <code>.apk</code> 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. </p> - -<p>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 <code>.apk</code>. 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 <code>.apk</code>. This -gives your application the flexibility to either use or redefine any resource -behaviors or values that are defined in any library.</p> - -<p>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. </p> - -<p>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 -<strong>Up</strong> and <strong>Down</strong> 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. </p> - -<p>Note that a library project cannot itself reference another library project -and that, at build time, library projects are <em>not</em> 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.</p> - -<p>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. -</p> - - -<h3 id="libraryReqts">Development requirements</h3> - -<p>Android library projects are a build-time construct, so you can use them to -build a final application <code>.apk</code> that targets any API level and is -compiled against any version of the Android library. </p> - -<p>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:</p> - -<p class="table-caption"><strong>Table 1.</strong> Minimum versions of SDK tools -and plaforms on which you can develop library projects.</p> - -<table> -<tr> -<th>Component</th> -<th>Minimum Version</th> -</tr> -<tr> -<td>SDK Tools</td> -<td>r6 (or higher)</td> -</tr> -<tr><td>Android 2.2 platform</td><td>r1 (or higher)</td></tr> -<tr><td>Android 2.1 platform</td><td>r2 (or higher)</td></tr> -<tr><td style="color:gray">Android 2.0.1 platform</td><td style="color:gray"><em>not supported</em></td></tr> -<tr><td style="color:gray">Android 2.0 platform</td><td style="color:gray"><em>not supported</em></td></tr> -<tr><td>Android 1.6 platform</td><td>r3 (or higher)</td></tr> -<tr><td>Android 1.5 platform</td><td>r4 (or higher)</td></tr> -<tr><td>ADT Plugin</td><td>0.9.7 (or higher)</td></tr> -</table> - -<p>You can download the tools and platforms using the <em>Android SDK and AVD -Manager</em>, as described in <a href="{@docRoot}sdk/adding-components.html">Adding SDK -Components</a>. To install or update ADT, use the Eclipse Updater as described -in <a href="{@docRoot}sdk/eclipse-adt.html">ADT Plugin for Eclipse</a>.</p> - - -<h3 id="librarySetup">Setting up a library project</h3> - -<p>A library project is a standard Android project, so you can create a new one in the -same way as you would a new application project. Specifically, you can use -the New Project Wizard, as described in <a href="#CreatingAProject">Creating an -Android Project</a>, above. </p> - -<p>When you are creating the library project, you can select any application -name, package, and set other fields as needed, as shown in the diagram below. -Click Finish to create the project in the workspace.</p> - -<p>Next, set the project's Properties to indicate that it is a library project:</p> - -<ol> -<li>In the <strong>Package Explorer</strong>, right-click the library project -and select <strong>Properties</strong>.</li> -<li>In the <strong>Properties</strong> window, select the "Android" properties -group at left and locate the <strong>Library</strong> properties at right. </li> -<li>Select the "is Library" checkbox and click <strong>Apply</strong>.</li> -<li>Click <strong>OK</strong> to close the <strong>Properties</strong> window.</li> -</ol> - -<p>The new project is now marked as a library project. You can begin moving -source code and resources into it, as described in the sections below. </p> - -<p>You can also convert an existing application project into a library. To do -so, simply open the Properties for the project and select the "is Library" -checkbox. Other application projects can now reference the existing project as a -library project.</p> - -<img src="{@docRoot}images/developing/adt-props-isLib.png" style="margin:0;padding:0;" /> -<p class="img-caption" style="margin-left:3em;margin-bottom:2em;"><strong>Figure 1.</strong> -Marking a project as an Android library project. </p> - -<h4>Creating the manifest file</h4> - -<p>A library project's manifest file must declare all of the shared components -that it includes, just as would a standard Android application. For more -information, see the documentation for <a -href="{@docRoot}guide/topics/manifest/manifest-intro.html">AndroidManifest.xml</a>.</p> - -<p>For example, the <a -href="{@docRoot}resources/samples/TicTacToeLib/AndroidManifest.html">TicTacToeLib</a> -example library project declares the Activity <code>GameActivity</code>: </p> - -<pre><manifest> - ... - <application> - ... - <activity android:name="GameActivity" /> - ... - </application> -</manifest></pre> - - -<h3 id="libraryReference">Referencing a library project from an application</h3> - -<p>If you are developing an application and want to include the shared code or -resources from a library project, you can do so easily by adding a reference to -the library project in the application project's Properties.</p> - -<p>To add a reference to a library project, follow these steps: </p> - -<ol> -<li>In the <strong>Package Explorer</strong>, right-click the dependent project -and select <strong>Properties</strong>.</li> -<li>In the <strong>Properties</strong> window, select the "Android" properties group -at left and locate the <strong>Library</strong> properties at right.</li> -<li>Click <strong>Add</strong> to open the <strong>Project Selection</strong> -dialog. </li> -<li>From the list of available library projects, select a project and click -<strong>OK</strong>.</li> -<li>When the dialog closes, click <strong>Apply</strong> in the -<strong>Properties</strong> window.</li> -<li>Click <strong>OK</strong> to close the <strong>Properties</strong> window.</li> -</ol> - -<p>As soon as the Properties dialog closes, Eclipse rebuilds the project, -including the contents of the library project. </p> - -<p>The figure below shows the Properties dialog that lets you add library -references and move them up and down in priority. </p> - -<img src="{@docRoot}images/developing/adt-props-libRef.png" style="margin:0;padding:0;" /> -<p class="img-caption" style="margin-left:3em;margin-bottom:2em;"><strong>Figure 2.</strong> -Adding a reference to a library project in the properties of an application project. </p> - -<p>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 -<strong>Up</strong> and <strong>Down</strong> 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.</p> - -<h4>Declaring library components in the the manifest file</h4> - -<p>In the manifest file of the application project, you must add declarations -of all components that the application will use that are imported from a library -project. For example, you must declare any <code><activity></code>, -<code><service></code>, <code><receiver></code>, -<code><provider></code>, and so on, as well as -<code><permission></code>, <code><uses-library></code>, and similar -elements.</p> - -<p>Declarations should reference the library components by their fully-qualified -package names, where appropriate. </p> - -<p>For example, the <a -href="{@docRoot}resources/samples/TicTacToeMain/AndroidManifest.html">TicTacToeMain</a> -example application declares the library Activity <code>GameActivity</code> -like this: </p> - -<pre><manifest> - ... - <application> - ... - <activity android:name="com.example.android.tictactoe.library.GameActivity" /> - ... - </application> -</manifest></pre> - -<p>For more information about the manifest file, see the documentation for <a -href="{@docRoot}guide/topics/manifest/manifest-intro.html">AndroidManifest.xml</a>.</p> - - -<h3 id="considerations">Development considerations</h3> - -<p>As you develop your library project and dependent applications, keep the -points listed below in mind.</p> - -<p><strong>Resource conflicts</strong></p> - -<p>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.</p> - -<p><strong>Using prefixes to avoid resource conflicts</strong></p> - -<p>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). </p> - -<p><strong>No export of library project to JAR</strong></p> - -<p>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.</p> - -<p><strong>A library project can include a JAR library</strong></p> - -<p>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. </p> - -<p><strong>A library project can depend on an external JAR library</strong></p> - -<p>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 <a -href="{@docRoot}guide/topics/manifest/uses-library-element.html"><code><uses-library></code></a> -element. </p> - -<p><strong>Library project can not include raw assets</strong></p> - -<p>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 -<code>assets/</code> directory of the application project -itself.</p> - -<p><strong>Targeting different Android platform versions in library project and -application project</strong></p> - -<p>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 <a href="{@docRoot}guide/appendix/api-levels.html">API level</a> -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.</p> - -<p><strong>No restriction on library package name</strong></p> - -<p>There is no requirement for the package name of a library to be the same as -that of applications that use it.</p> - -<p><strong>Multiple R classes in gen/ folder of application project</strong></p> - -<p>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 -<code>R</code> class, named according to the library's package name. The -<code>R</code> class generated from the resources of the main project and of the -library is created in all the packages that are needed including the main -project’s package and the libraries’ packages.</p> - -<p><strong>Testing a library project</strong></p> - -<p>There are two recommended ways of setting up testing on code and resources in -a library project: </p> - -<ul> -<li>You can set up a <a -href="{@docRoot}guide/developing/testing/testing_otheride.html">test project</a> -that instruments an application project that depends on the library project. You -can then add tests to the project for library-specific features.</li> -<li>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.</li> -</ul> - -<p><strong>Library project storage location</strong></p> - -<p>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.</p> - -<h3 id="libraryMigrating">Migrating library projects to ADT 0.9.8</h3> - -<p>This section provides information about how to migrate a library project -created with ADT 0.9.7 to ADT 0.9.8 (or higher). The migration is needed only if -you are developing in Eclipse with ADT and assumes that you have also upgraded -to SDK Tools r7 (or higher). </p> - -<p>The way that ADT handles library projects has changed between -ADT 0.9.7 and ADT 0.9.8. Specifically, in ADT 0.9.7, the <code>src/</code> -source folder of the library was linked into the dependent application project -as a folder that had the same name as the library project. This worked because -of two restrictions on the library projects:</p> - -<ul> -<li>The library was only able to contain a single source folder (excluding the -special <code>gen/</code> source folder), and</li> -<li>The source folder was required to have the name <code>src/</code> and be -stored at the root of the project.</li> -</ul> - -<p>In ADT 0.9.8, both of those restrictions were removed. A library project can -have as many source folders as needed and each can have any name. Additionally, -a library project can store source folders in any location of the project. For -example, you could store sources in a <code>src/java/</code> directory. In order -to support this, the name of the linked source folders in the main project are -now called <<em>library-name</em>>_<<em>folder-name</em>> For -example: <code>MyLibrary_src/</code> or <code>MyLibrary_src_java/</code>.</p> - -<p>Additionally, the linking process now flags those folders in order for ADT to -recognize that it created them. This will allow ADT to automatically migrate the -project to new versions of ADT, should they contain changes to the handling of -library projects. ADT 0.9.7 did not flag the linked source folders, so ADT 0.9.8 -cannot be sure whether the old linked folders can be removed safely. After -upgrading ADT to 0.9.8, you will need to remove the old linked folders manually -in a simple two-step process, as described below.</p> - -<p>Before you begin, make sure to create a backup copy of your application or -save the latest version to your code version control system. This ensures that -you will be able to easily revert the migration changes in case there is a -problem in your environment.</p> - -<p>When you first upgrade to ADT 0.9.8, your main project will look as shown -below, with two linked folders (in this example, <code>MyLibrary</code> and -<code>MyLibrary_src</code> — both of which link to -<code>MyLibrary/src</code>. Eclipse shows an error on one of them because they -are duplicate links to a single class.</p> - -<img src="{@docRoot}images/developing/lib-migration-0.png" alt=""> - -<p>To fix the error, remove the linked folder that <em>does not</em> contain the -<code>_src</code> suffix. </p> - -<ol> -<li>Right click the folder that you want to remove (in this case, the -<code>MyLibrary</code> folder) and choose <strong>Build Path</strong> > -<strong>Remove from Build Path</strong>, as shown below.</li> - -<img src="{@docRoot}images/developing/lib-migration-1.png" style="height:600px" -alt=""> - -<li>Next, When asked about unlinking the folder from the project, select -<strong>Yes</strong>, as shown below.</li> - -<img src="{@docRoot}images/developing/lib-migration-2.png" alt=""> -</ol> - -<p>This should resolve the error and migrate your library project to the new -ADT environment. </p> - -<h2 id="Tips">Eclipse Tips</h2> - -<h3 id="arbitraryexpressions">Executing arbitrary Java expressions in Eclipse</h3> - -<p>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 <code>android.os.Debug.startMethodTracing()</code> will - start dmTrace. </p> -<p>Open a code execution window, select <strong>Window</strong> > <strong>Show - View</strong> > <strong>Display</strong> 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().)</p> -<p>If you are currently paused on a breakpoint, you can simply highlight and execute - a piece of source code by pressing CTRL + SHIFT + D. </p> -<p>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. </p> -<p>Here are a few sample inputs and responses in Eclipse using the Display window.</p> - -<table width="100%" border="1"> - <tr> - <th scope="col">Input</th> - <th scope="col">Response</th> - </tr> - <tr> - <td><code>zip</code></td> - <td><code>(java.lang.String) - /work/device/out/linux-x86-debug/android/app/android_sdk.zip</code></td> - </tr> - <tr> - <td><code>zip.endsWith(".zip")</code></td> - <td><code>(boolean) true</code></td> - </tr> - <tr> - <td><code>zip.endsWith(".jar")</code></td> - <td><code>(boolean) false</code></td> - </tr> -</table> -<p>You can also execute arbitrary code when not debugging by using a scrapbook page. - Search the Eclipse documentation for "scrapbook".</p> - - -<h3>Running DDMS Manually</h3> - -<p>Although the recommended way to debug is to use the ADT plugin, you can manually run -DDMS and configure Eclipse to debug on port 8700. (<strong>Note: </strong>Be sure that you -have first started <a href="{@docRoot}guide/developing/tools/ddms.html">DDMS</a>). </p> - - - - -<!-- TODO: clean this up and expand it to cover more wizards and features -<h3>ADT Wizards</h3> - -<p>Notice that the "New Android Project" wizard has been expanded to use the multi-platform -capabilities of the new SDK.</p> - -<p>There is now a "New XML File" wizard that lets you create skeleton XML resource -files for your Android projects. This makes it easier to create a new layout, a new menu, a -new strings file, etc.</p> - -<p>Both wizards are available via <strong>File > New</strong> and new icons in the main -Eclipse toolbar (located to the left of the Debug and Run icons). -If you do not see the new icons, you may need to select <strong>Window > Reset -Perspective</strong> from the Java perspective.</p> ---> diff --git a/docs/html/guide/developing/index.html b/docs/html/guide/developing/index.html deleted file mode 100644 index 4881acf..0000000 --- a/docs/html/guide/developing/index.html +++ /dev/null @@ -1,8 +0,0 @@ -<html> -<head> -<meta http-equiv="refresh" content="0;url=../index.html"> -</head> -<body> -<a href="../index.html">click here</a> if you are not redirected. -</body> -</html>
\ No newline at end of file diff --git a/docs/html/guide/developing/index.jd b/docs/html/guide/developing/index.jd new file mode 100644 index 0000000..f19f97e --- /dev/null +++ b/docs/html/guide/developing/index.jd @@ -0,0 +1,116 @@ +page.title=Overview +@jd:body + +<p>Developing applications for Android devices is facilitated by a group of tools that are + provided with the SDK. You can access these tools through an Eclipse plugin called ADT (Android + Development Tools) or from the command line. Developing with Eclipse is the preferred method because + it can directly invoke the tools that you need while developing applications.</p> + + <p>However, you may choose to develop with another IDE or a simple text editor and invoke the + tools on the command line or with scripts. This is a less streamlined way to develop because you + will sometimes have to call command line tools manually, but you will have access to the same + amount of features that you would have in Eclipse.</p> + + <p>The basic steps for developing applications with or without Eclipse are the same:</p> + + <ol> + <li>Install Eclipse or your own IDE. + + <p>Install Eclipse along with <a href="{@docRoot}sdk/eclipse-adt.html#installing">the ADT + Plugin</a>, or install an editor of your choice if you want to use the command line SDK tools. + If you are already developing applications, be sure to <a href= + "{@docRoot}sdk/eclipse-adt.html#updating">update Your ADT Plugin</a> to the latest version + before continuing.</p> + </li> + + <li>Set up Android Virtual Devices or hardware devices</a>. + + <p>You need to create Android Virtual Devices (AVD) or connect hardware devices on which + you will install your applications.</p> + + <p>See <a href="{@docRoot}guide/developing/devices/index.html">Creating and Managing Virtual Devices</a> + and <a href="{@docRoot}guide/developing/device.html">Connecting Hardware Devices</a> for more information. + </li> + + <li> + <a href="{@docRoot}guide/developing/projects/index.html">Create an Android project</a>. + + <p>An Android project contains all source code and resource files for your application. It is + built into an <code>.apk</code> package that you can install on Android devices.</p> + </li> + + <li> + <a href="{@docRoot}guide/developing/building/index.html">Build and run your + application</a>. + + <p>If you are using Eclipse, builds are generated each time you save changes and you can install + your application on a device by clicking <strong>Run</strong>. If you're using another IDE, you can build your + project using Ant and install it on a device using <code>adb</code>.</p> + </li> + + <li> + <a href="{@docRoot}guide/developing/debugging/index.html">Debug your application with the + SDK debugging and logging tools</a>. + + <p>Debugging your application involves using a JDWP-compliant debugger along with the + debugging and logging tools that are provided with the Android SDK. Eclipse already + comes packaged with a compatible debugger.</p> + </li> + + <li> + <a href="{@docRoot}guide/developing/testing/index.html">Test your application with the + Testing and Instrumentation framework</a>. + + <p>The Android SDK provides a testing and instrumnetation framework to help you set up and + run tests within an emulator or device.</p> + </li> + </ol> + + <h2 id="EssentialTools">Essential command line tools</h2> + + <p>When developing in IDEs or editors other than Eclipse, be familiar with + all of the tools below, because you will have to run them from the command line.</p> + + <dl> + <dt><a href="{@docRoot}guide/developing/tools/android.html">android</a></dt> + + <dd>Create and update Android projects and create, move, and delete AVDs.</dd> + + <dt><a href="{@docRoot}guide/developing/devices/emulator.html">Android Emulator</a></dt> + + <dd>Run your Android applications on an emulated Android platform.</dd> + + <dt><a href="{@docRoot}guide/developing/tools/adb.html">Android Debug Bridge</a></dt> + + <dd>Interface with your emulator or connected device (install apps, shell the device, issue + commands, etc.).</dd> + </dl> + + <p>In addition to the above tools that are included with the SDK, you need the following open + source and third-party tools:</p> + + <dl> + <dt>Ant</dt> + + <dd>To compile and build your Android project into an installable .apk file.</dd> + + <dt>Keytool</dt> + + <dd>To generate a keystore and private key, used to sign your .apk file. Keytool is part of the + JDK.</dd> + + <dt>Jarsigner (or similar signing tool)</dt> + + <dd>To sign your .apk file with a private key generated by keytool. Jarsigner is part of the + JDK.</dd> + </dl> + + <p>If you are using Eclipse and ADT, tools such as <code>adb</code> and the <code>android</code> + are called by Eclipse and ADT under the hood or similar functionality is provided within Eclipse. + You need to be familiar with <code>adb</code>, however, because certain functions are not accessible from + Eclipse, such as the <code>adb</code> shell commands. You might also need to call Keytool and Jarsigner to + sign your applications, but you can set up Eclipse to do this automatically as well.</p> + + <p>For more information on the tools provided with the Android SDK, see the + <a href="{@docRoot}guide/developing/tools/index.html">Tools</a> section of the documentation.</p> + diff --git a/docs/html/guide/developing/other-ide.html b/docs/html/guide/developing/other-ide.html new file mode 100644 index 0000000..41dba05 --- /dev/null +++ b/docs/html/guide/developing/other-ide.html @@ -0,0 +1,10 @@ +<html> +<head> +<meta http-equiv="refresh" content="0;url=http://developer.android.com/guide/developing/projects/projects-cmdline.html"> +<title>Redirecting...</title> +</head> +<body> +<p>You should be redirected. Please <a +href="http://developer.android.com/guide/developing/projects/projects-cmdline.html">click here</a>.</p> +</body> +</html>
\ No newline at end of file diff --git a/docs/html/guide/developing/other-ide.jd b/docs/html/guide/developing/other-ide.jd deleted file mode 100644 index d309f47..0000000 --- a/docs/html/guide/developing/other-ide.jd +++ /dev/null @@ -1,937 +0,0 @@ -page.title=Developing In Other IDEs -@jd:body - -<div id="qv-wrapper"> -<div id="qv"> - <h2>In this document</h2> - <ol> - <li><a href="#CreatingAProject">Creating an Android Project</a></li> - <li><a href="#Signing">Preparing to Sign Your Application</a></li> - <li><a href="#Building">Building Your Application</a> - <ol> - <li><a href="#DebugMode">Building in debug mode</a></li> - <li><a href="#ReleaseMode">Building in release mode</a></li> - </ol> - </li> - <li><a href="#AVD">Creating an AVD</a></li> - <li><a href="#Running">Running Your Application</a> - <ol> - <li><a href="#RunningOnEmulator">Running on the emulator</a></li> - <li><a href="#RunningOnDevice">Running on a device</a></li> - </ol> - </li> - <li><a href="#libraryProject">Working with Library Projects</a> - <ol> - <li><a href="#libraryReqts">Development requirements</a></li> - <li><a href="#librarySetup">Setting up a library project</a></li> - <li><a href="#libraryReference">Referencing a library project</a></li> - <li><a href="#depAppBuild">Building a dependent application project</a></li> - <li><a href="#considerations">Development considerations</a></li> - </ol> - </li> - <li><a href="#AttachingADebugger">Attaching a Debugger to Your Application</a></li> - </ol> - - <h2>See also</h2> - <ol> - <li><a href="{@docRoot}guide/developing/tools/othertools.html#android">android Tool</a></li> - <li><a href="{@docRoot}guide/developing/tools/emulator.html">Android Emulator</a></li> - <li><a href="{@docRoot}guide/developing/tools/adb.html">Android Debug Bridge</a></li> - </ol> -</div> -</div> - -<p>The recommended way to develop an Android application is to use -<a href="{@docRoot}guide/developing/eclipse-adt.html">Eclipse with the ADT plugin</a>. -The ADT plugin provides editing, building, debugging, and .apk packaging and signing functionality -integrated right into the IDE.</p> - -<p>However, if you'd rather develop your application in another IDE, such as IntelliJ, -or in a basic editor, such as Emacs, you can do that instead. The SDK -includes all the tools you need to set up an Android project, build it, debug it and then -package it for distribution. This document is your guide to using these tools.</p> - - -<h2 id="EssentialTools">Essential Tools</h2> - -<p>When developing in IDEs or editors other than Eclipse, you'll require -familiarity with the following Android SDK tools:</p> - -<dl> - <dt><a href="{@docRoot}guide/developing/tools/othertools.html#android">android</a></dt> - <dd>To create/update Android projects and to create/move/delete AVDs.</dd> - <dt><a href="{@docRoot}guide/developing/tools/emulator.html">Android Emulator</a></dt> - <dd>To run your Android applications on an emulated Android platform.</dd> - <dt><a href="{@docRoot}guide/developing/tools/adb.html">Android Debug Bridge</a></dt> - <dd>To interface with your emulator or connected device (install apps, - shell the device, issue commands, etc.). - </dd> -</dl> - -<p>In addition to the above tools, included with the SDK, you'll use the following -open source and third-party tools:</p> - -<dl> - <dt>Ant</dt> - <dd>To compile and build your Android project into an installable .apk file.</dd> - <dt>Keytool</dt> - <dd>To generate a keystore and private key, used to sign your .apk file.</dd> - <dt>Jarsigner (or similar signing tool)</dt> - <dd>To sign your .apk file with a private key generated by keytool.</dd> -</dl> - -<p>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.</p> - - -<h2 id="CreatingAProject">Creating an Android Project</h2> - -<p>To create an Android project, you must use the <code>android</code> tool. When you create -a new project with <code>android</code>, it will generate a project directory -with some default application files, stub files, configuration files and a build file.</p> - - -<h3 id="CreatingANewProject">Creating a new Project</h3> - -<p>If you're starting a new project, use the <code>android create project</code> -command to generate all the necessary files and folders.</p> - -<p>To create a new Android project, open a command-line, -navigate to the <code>tools/</code> directory of your SDK and run:</p> -<pre> -android create project \ ---target <em><target_ID></em> \ ---name <em><your_project_name></em> \ ---path <em>path/to/your/project</em> \ ---activity <em><your_activity_name></em> \ ---package <em><your_package_namespace></em> -</pre> - -<ul> - <li><code>target</code> 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: <code>android list targets</code>.</li> - <li><code>name</code> is the name for your project. This is optional. If provided, this name will -be used - for your .apk filename when you build your application.</li> - <li><code>path</code> is the location of your project directory. If the directory does not exist, - it will be created for you.</li> - <li><code>activity</code> is the name for your default {@link android.app.Activity} class. This -class file - will be created for you inside - -<code><em><path_to_your_project></em>/src/<em><your_package_namespace_path></em>/</code> -. - This will also be used for your .apk filename unless you provide a the <code>name</code>.</li> - <li><code>package</code> is the package namespace for your project, following the same rules as -for - packages in the Java programming language.</li> -</ul> - -<p>Here's an example:</p> -<pre> -android create project \ ---target 1 \ ---name MyAndroidApp \ ---path ./MyAndroidAppProject \ ---activity MyAndroidAppActivity \ ---package com.example.myandroid -</pre> - -<p>The tool generates the following files and directories:</p> - -<ul> - <li><code>AndroidManifest.xml</code> - The application manifest file, - synced to the specified Activity class for the project.</li> - <li><code>build.xml</code> - Build file for Ant.</li> - <li><code>default.properties</code> - Properties for the build system. <em>Do not modify - this file</em>.</li> - <li><code>build.properties</code> - Customizable properties for the build system. You can edit -this - file to override default build settings used by Ant and provide a pointer to your keystore and key -alias - so that the build tools can sign your application when built in release mode.</li> - <li><code>src<em>/your/package/namespace/ActivityName</em>.java</code> - The Activity class - you specified during project creation.</li> - <li><code>bin/</code> - Output directory for the build script.</li> - <li><code>gen/</code> - Holds <code>Ant</code>-generated files, such as <code>R.java</code>. -</li> - <li><code>libs/</code> - Holds private libraries.</li> - <li><code>res/</code> - Holds project resources.</li> - <li><code>src/</code> - Holds source code.</li> - <li><code>tests/</code> - Holds a duplicate of all-of-the-above, for testing purposes.</li> -</ul> - -<p>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 <a href="{@docRoot}guide/developing/tools/adb.html">Android Debug Bridge</a> -(adb) — located in the SDK <code>platform-tools/</code> directory — to send your -application -to the emulator (discussed later). So you need access between your project solution and -the <code>platform-tools/</code> folder.</p> - -<p class="caution"><strong>Caution:</strong> 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.)</p> - - -<h3 id="UpdatingAProject">Updating a project</h3> - -<p>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 -<code>android update project</code> 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 <code>--target</code> option) and the project name (with the <code>--name</code> -option). The <code>android</code> 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.</p> - -<p>To update an existing Android project, open a command-line -and navigate to the <code>tools/</code> directory of your SDK. Now run:</p> -<pre> -android update project --name <em><project_name></em> --target <em><target_ID></em> ---path <em><path_to_your_project></em> -</pre> - -<ul> - <li><code>target</code> 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: <code>android list targets</code>.</li> - <li><code>path</code> is the location of your project directory.</li> - <li><code>name</code> is the name for the project. This is optional—if you're not - changing the project name, you don't need this.</li> -</ul> - -<p>Here's an example:</p> -<pre> -android update project --name MyApp --target 2 --path ./MyAppProject -</pre> - - -<h2 id="Signing">Preparing to Sign Your Application</h2> - -<p>As you begin developing Android applications, understand that all -Android applications must be digitally signed before the system will install -them on an emulator or device. There are two ways to do this: -with a <em>debug key</em> (for immediate testing on an emulator or development device) -or with a <em>private key</em> (for application distribution).</p> - -<p>The Android build tools help you get started by automatically signing your .apk -files with a debug key at build time. This means -that you can compile your application and install it on the emulator without -having to generate your own private key. However, please note that if you intend -to publish your application, you <strong>must</strong> sign the application with your -own private key, rather than the debug key generated by the SDK tools. </p> - -<p>Please read <a href="{@docRoot}guide/publishing/app-signing.html">Signing Your -Applications</a>, which provides a thorough guide to application signing on Android -and what it means to you as an Android application developer.</p> - - - -<h2 id="Building">Building Your Application</h2> - -<p>There are two ways to build your application: one for testing/debugging your application -— <em>debug mode</em> — and one for building your final package for release — -<em>release mode</em>. As described in the previous -section, your application must be signed before it can be installed on an emulator -or device.</p> - -<p>Whether you're building in debug mode or release mode, you -need to use the Ant tool to compile and build your project. This will create the .apk file -that is installed onto the emulator or device. When you build in debug mode, the .apk -file is automatically signed by the SDK tools with a debug key, so it's instantly ready for -installation -(but only onto an emulator or attached development device). -When you build in release mode, the .apk file is <em>unsigned</em>, so you must manually -sign it with your own private key, using Keytool and Jarsigner.</p> - -<p>It's important that you read and understand -<a href="{@docRoot}guide/publishing/app-signing.html">Signing Your Applications</a>, particularly -once you're ready to release your application and share it with end-users. That document describes -the procedure for generating a private key and then using it to sign your .apk file. -If you're just getting started, however, -you can quickly run your applications on an emulator or your own development device by building in -debug mode.</p> - -<p>If you don't have Ant, you can obtain it from the -<a href="http://ant.apache.org/">Apache Ant home page</a>. Install it and make -sure it is in your executable PATH. Before calling Ant, you need to declare the JAVA_HOME -environment variable to specify the path to where the JDK is installed.</p> - -<p class="note"><strong>Note:</strong> When installing JDK on Windows, the default is to install -in the "Program Files" directory. This location will cause <code>ant</code> to fail, because of -the space. To fix the problem, you can specify the JAVA_HOME variable like this: -<code>set JAVA_HOME=c:\Progra~1\Java\<jdkdir></code>. The easiest solution, however, is to -install JDK in a non-space directory, for example: <code>c:\java\jdk1.6.0_02</code>.</p> - - -<h3 id="DebugMode">Building in debug mode</h3> - -<p>For immediate application testing and debugging, you can build your application -in debug mode and immediately install it on an emulator. In debug mode, the build tools -automatically sign your application with a debug key and optimize the package with -{@code zipalign}. However, you can (and should) also test your -application in release mode. Debug mode simply allows you to run your application without -manually signing the application.</p> - -<p>To build in debug mode:</p> - -<ol> - <li>Open a command-line and navigate to the root of your project directory.</li> - <li>Use Ant to compile your project in debug mode: - <pre>ant debug</pre> - <p>This creates your debug .apk file inside the project <code>bin/</code> - directory, named <code><em><your_project_name></em>-debug.apk</code>. The file - is already signed with the debug key and has been aligned with {@code zipalign}.</p> - </li> -</ol> - -<p>Each time you change a source file or resource, you must run Ant -again in order to package up the latest version of the application.</p> - -<p>To install and run your application on an emulator, see the following section -about <a href="#Running">Running Your Application</a>.</p> - - -<h3 id="ReleaseMode">Building in release mode</h3> - -<p>When you're ready to release and distribute your application to end-users, you must build -your application in release mode. Once you have built in release mode, it's a good idea to perform -additional testing and debugging with the final .apk.</p> - -<p>Before you start building your application in release mode, be aware that you must sign -the resulting application package with your private key, and should then align it using the -{@code zipalign} tool. There are two approaches to building in release mode: -build an unsigned package in release mode and then manually sign and align -the package, or allow the build script -to sign and align the package for you.</p> - -<h4 id="ManualReleaseMode">Build unsigned</h4> - -<p>If you build your application <em>unsigned</em>, then you will need to -manually sign and align the package.</p> - -<p>To build an <em>unsigned</em> .apk in release mode:</p> - -<ol> - <li>Open a command-line and navigate to the root of your project directory.</li> - <li>Use Ant to compile your project in release mode: - <pre>ant release</pre> - </li> -</ol> - -<p>This creates your Android application .apk file inside the project <code>bin/</code> -directory, named <code><em><your_project_name></em>-unsigned.apk</code>.</p> - -<p class="note"><strong>Note:</strong> The .apk file is <em>unsigned</em> at this point -and can't be installed until signed with your private key.</p> - -<p>Once you have created the unsigned .apk, your next step is to sign the .apk -with your private key and then align it with {@code zipalign}. To complete this procedure, -read <a href="{@docRoot}guide/publishing/app-signing.html">Signing Your Applications</a>.</p> - -<p>When your .apk has been signed and aligned, it's ready to be distributed to end-users.</p> - -<h4 id="AutoReleaseMode">Build signed and aligned</h4> - -<p>If you would like, you can configure the Android build script to automatically -sign and align your application package. To do so, you must provide the path to your keystore -and the name of your key alias in your project's {@code build.properties} file. With this -information provided, the build script will prompt you for your keystore and alias password -when you build in release mode and produce your final application package, which will be ready -for distribution.</p> - -<p class="caution"><strong>Caution:</strong> Due to the way Ant handles input, the password that -you enter during the build process <strong>will be visible</strong>. If you are -concerned about your keystore and alias password being visible on screen, then you -may prefer to perform the application signing manually, via Jarsigner (or a similar tool). To -instead -perform the signing procedure manually, <a href="#ManualReleaseMode">build unsigned</a> and then -continue -with <a href="{@docRoot}guide/publishing/app-signing.html">Signing Your Applications</a>.</p> - -<p>To specify your keystore and alias, open the project {@code build.properties} file (found in the -root of the project directory) and add entries for {@code key.store} and {@code key.alias}. -For example:</p> - -<pre> -key.store=path/to/my.keystore -key.alias=mykeystore -</pre> - -<p>Save your changes. Now you can build a <em>signed</em> .apk in release mode:</p> - -<ol> - <li>Open a command-line and navigate to the root of your project directory.</li> - <li>Use Ant to compile your project in release mode: - <pre>ant release</pre> - </li> - <li>When prompted, enter you keystore and alias passwords. - <p class="caution"><strong>Caution:</strong> As described above, - your password will be visible on the screen.</p> - </li> -</ol> - -<p>This creates your Android application .apk file inside the project <code>bin/</code> -directory, named <code><em><your_project_name></em>-release.apk</code>. -This .apk file has been signed with the private key specified in -{@code build.properties} and aligned with {@code zipalign}. It's ready for -installation and distribution.</p> - - -<h4>Once built and signed in release mode</h4> - -<p>Once you have signed your application with a private key, you can install it on an -emulator or device as discussed in the following section about -<a href="#Running">Running Your Application</a>. -You can also try installing it onto a device from a web server. -Simply upload the signed APK to a web site, then load the .apk URL in your Android web browser to -download the application and begin installation. -(On your device, be sure you have enabled <em>Settings > Applications > Unknown sources</em>.)</p> - - -<h2 id="AVD">Creating an AVD</h2> - -<p>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.</p> - -<p>To create an AVD using the SDK tools:</p> - -<ol> - <li>Navigate to your SDK's <code>tools/</code> directory and execute the {@code android} -tool with no arguments: - <pre>android</pre> - <p>This will launch the SDK and AVD Manager GUI.</p> - </li> - <li>In the <em>Virtual Devices</em> panel, you'll see a list of existing AVDs. Click -<strong>New</strong> - to create a new AVD.</li> - <li>Fill in the details for the AVD. - <p>Give it a name, a platform target, an SD card size, and - a skin (HVGA is default).</p> - <p class="note"><strong>Note:</strong> 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).</p> - </li> - <li>Click <strong>Create AVD</strong>.</li> -</ol> - -<p>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 <strong>Start</strong>.</p> - -<p>For more information about AVDs, read the -<a href="{@docRoot}guide/developing/tools/avd.html">Android Virtual Devices</a> -documentation.</p> - - -<h2 id="Running">Running Your Application</h2> - -<div class="sidebox-wrapper"> -<div class="sidebox"> -<h2>Use the Emulator to Test Different Configurations</h2> -<p>Create multiple AVDs that each define a different device configuration with which your -application is compatible, then launch each AVD into a new emulator from the SDK and AVD Manager. -Set the target mode in your app's run configuration to manual, so that when you run your -application, you can select from the available virtual devices.</p> -</div> -</div> - -<p>Running your application on a virtual or real device takes just a couple steps. Remember to -first <a href="#Building">build your application</a>.</p> - -<h3 id="RunningOnEmulator">Running on the emulator</h3> - -<p>Before you can run your application on the Android Emulator, -you must <a href="#AVD">create an AVD</a>.</p> - -<p>To run your application:</p> -<ol> - <li><strong>Open the SDK and AVD Manager and launch a virtual device</strong></li> - <p>From your SDK's <code>tools/</code> directory, execute the {@code android} tool with no -arguments: - <pre>android</pre> - <p>In the <em>Virtual Devices</em> view, select an AVD and click <strong>Start</strong>.</p> - </li> - - <li><strong>Install your application</strong> - <p>From your SDK's <code>platform-tools/</code> directory, install the {@code .apk} on the -emulator: - <pre>adb install <em><path_to_your_bin></em>.apk</pre> - <p>Your APK file (signed with either a release or debug key) is in your project {@code bin/} -directory after you <a href="#Building">build your application</a>.</p> - <p>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 <code>-s</code> option. For example:</p> - <pre>adb -s emulator-5554 install <em>path/to/your/app</em>.apk</pre> - <p>To see a list of available device serial numbers, execute {@code adb devices}.</p> - </li> -</ol> - -<p>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.</p> - -<p>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 <a -href="{@docRoot}guide/practices/screens_support.html">screen type</a> you support, then test -your application on each one.</p> - -<p class="note"><strong>Tip:</strong> If you have <em>only one</em> 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 <em>install mode</em>: -<code>ant install</code>. This will build your application, sign it with the debug key, -and install it on the currently running emulator.</p> - - -<h3 id="RunningOnDevice">Running on a device</h3> - -<p>Before you can run your application on a device, you must perform some basic setup for your -device:</p> - -<ul> - <li>Declare your application as debuggable in your manifest</li> - <li>Enable USB Debugging on your device</li> - <li>Ensure that your development computer can detect your device when connected via USB</li> -</ul> -<p>Read <a href="{@docRoot}guide/developing/device.html#setting-up">Setting up a Device for -Development</a> for more information.</p> - -<p>Once your device is set up and connected via USB, navigate to your -SDK's <code>platform-tools/</code> directory and install the <code>.apk</code> on the device: - <pre>adb -d install <em>path/to/your/app</em>.apk</pre> - <p>The {@code -d} flag specifies that you want to use the attached device (in case you also -have an emulator running).</p> - -<p>For more information on the tools used above, please see the following documents:</p> -<ul> - <li><a href="{@docRoot}guide/developing/tools/othertools.html#android">android Tool</a></li> - <li><a href="{@docRoot}guide/developing/tools/emulator.html">Android Emulator</a></li> - <li><a href="{@docRoot}guide/developing/tools/adb.html">Android Debug Bridge</a> (ADB)</li> -</ul> - -<h2 id="libraryProject">Working with Library Projects</h2> - -<div class="sidebox-wrapper"> -<div class="sidebox"> -<h2>Library project example code</h2> - -<p>The SDK includes an example application called TicTacToeMain that shows how a -dependent application can use code and resources from an Android Library -project. The TicTacToeMain application uses code and resources from an example -library project called TicTacToeLib. - -<p style="margin-top:1em;">To download the sample applications and run them as -projects in your environment, use the <em>Android SDK and AVD Manager</em> to -download the "Samples for SDK API 8" component into your SDK. </p> - -<p style="margin-top:1em;">For more information and to browse the code of the -samples, see the <a -href="{@docRoot}resources/samples/TicTacToeMain/index.html">TicTacToeMain -application</a>.</p> -</div> -</div> - -<p>An Android <em>library project</em> is a development project that holds -shared Android source code and resources. Other Android application projects can -reference the library project and, at build time, include its compiled sources -in their <code>.apk</code> files. Multiple application projects can reference -the same library project and any single application project can reference -multiple library projects. </p> - -<p>If you have source code and resources that are common to multiple application -projects, you can move them to a library project so that it is easier to -maintain across applications and versions. Here are some common scenarios in -which you could make use of library projects: </p> - -<ul> -<li>If you are developing multiple related applications that use some of the -same components, you could move the redundant components out of their respective -application projects and create a single, reuseable set of the same components -in a library project. </li> -<li>If you are creating an application that exists in both free and paid -versions, you could 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.</li> -</ul> - -<p>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 <code>src/</code>, <code>res/</code> 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 <code>R</code> class. </p> - -<p>However, a library project differs from an standard Android application -project in that you cannot compile it directly to its own <code>.apk</code> 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. </p> - -<p>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 <code>.apk</code>. 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 <code>.apk</code>. This -gives your application the flexibility to either use or redefine any resource -behaviors or values that are defined in any library.</p> - -<p>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. - -<p>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. </p> - -<p>Note that a library project cannot itself reference another library project -and that, at build time, library projects are <em>not</em> 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.</p> - -<p>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. -</p> - - -<h3 id="libraryReqts">Development requirements</h3> - -<p>Android library projects are a build-time construct, so you can use them to -build a final application <code>.apk</code> that targets any API level and is -compiled against any version of the Android library. </p> - -<p>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:</p> - -<p class="table-caption"><strong>Table 1.</strong> Minimum versions of SDK tools -and plaforms on which you can develop library projects.</p> - -<table> -<tr> -<th>Component</th> -<th>Minimum Version</th> -</tr> -<tr> -<td>SDK Tools</td> -<td>r6 (or higher)</td> -</tr> -<tr><td>Android 2.2 platform</td><td>r1 (or higher)</td></tr> -<tr><td>Android 2.1 platform</td><td>r2 (or higher)</td></tr> -<tr><td style="color:gray">Android 2.0.1 platform</td><td style="color:gray"><em>not supported</em></td></tr> -<tr><td style="color:gray">Android 2.0 platform</td><td style="color:gray"><em>not supported</em></td></tr> -<tr><td>Android 1.6 platform</td><td>r3 (or higher)</td></tr> -<tr><td>Android 1.5 platform</td><td>r4 (or higher)</td></tr> -<tr><td>ADT Plugin</td><td>0.9.7 (or higher)</td></tr> -</table> - -<p>You can download the tools and platforms using the <em>Android SDK and AVD -Manager</em>, as described in <a href="{@docRoot}sdk/adding-components.html">Adding SDK -Components</a>.</p> - - -<h3 id="librarySetup">Setting up a new library project</h3> - -<p>A library project is a standard Android project, so you can create a new one in the -same way as you would a new application project. Specifically, you can use -the <code>android</code> tool to generate a new library project with all of the -necessary files and folders. </p> - -<h4>Creating a library project</h4> - -<p>To create a new library project, navigate to the <code><sdk>/tools/</code> directory -and use this command:</p> - -<pre class="no-pretty-print" style="color:black"> -android create lib-project --name <em><your_project_name></em> \ ---target <em><target_ID></em> \ ---path <em>path/to/your/project</em> \ ---package <em><your_library_package_namespace></em> -</pre> - -<p>The <code>create lib-project</code> command creates a standard project -structure that includes preset property that indicates to the build system that -the project is a library. It does this by adding this line to the project's -<code>default.properties</code> file: </p> - -<pre class="no-pretty-print" style="color:black">android.library=true</pre> - -<p>Once the command completes, the library project is created and you can begin moving -source code and resources into it, as described in the sections below.</p> - -<p>If you want to convert an existing application project to a library project, -so that other applications can use it, you can do so by adding a the -<code>android.library=true</code> property to the application's -<code>default.properties</code> file. </p> - -<h4>Creating the manifest file</h4> - -<p>A library project's manifest file must declare all of the shared components -that it includes, just as would a standard Android application. For more -information, see the documentation for <a -href="{@docRoot}guide/topics/manifest/manifest-intro.html">AndroidManifest.xml</a>.</p> - -<p>For example, the <a -href="{@docRoot}resources/samples/TicTacToeLib/AndroidManifest.html">TicTacToeLib</a> -example library project declares the Activity <code>GameActivity</code>: </p> - -<pre><manifest> - ... - <application> - ... - <activity android:name="GameActivity" /> - ... - </application> -</manifest></pre> - -<h4>Updating a library project</h4> - -<p>If you want to update the build properties (build target, location) of the -library project, use this command: </p> - -<pre> -android update lib-project \ ---target <em><target_ID></em> \ ---path <em>path/to/your/project</em> -</pre> - - -<h3 id="libraryReference">Referencing a library project from an application</h3> - -<p>If you are developing an application and want to include the shared code or -resources from a library project, you can do so easily by adding a reference to -the library project in the application project's build properties.</p> - -<p>To add a reference to a library project, navigate to the <code><sdk>/tools/</code> directory -and use this command:</p> - -<pre> -android update lib-project \ ---target <em><target_ID></em> \ ---path <em>path/to/your/project</em> ---library <em>path/to/library_projectA</em> -</pre> - -<p>This command updates the application project's build properties to include a -reference to the library project. Specifically, it adds an -<code>android.library.reference.<em>n</em></code> property to the project's -<code>default.properties</code> file. For example: </p> - -<pre class="no-pretty-print" style="color:black"> -android.library.reference.1=path/to/library_projectA -</pre> - -<p>If you are adding references to multiple libraries, note that you can set -their relative priority (and merge order) by manually editing the -<code>default.properties</code> file and adjusting the each reference's -<code>.<em>n</em></code> index as appropriate. For example, assume these -references: </p> - -<pre class="no-pretty-print" style="color:black"> -android.library.reference.1=path/to/library_projectA -android.library.reference.2=path/to/library_projectB -android.library.reference.3=path/to/library_projectC -</pre> - -<p>You can reorder the references to give highest priority to -<code>library_projectC</code> in this way:</p> - -<pre class="no-pretty-print" style="color:black"> -android.library.reference.2=path/to/library_projectA -android.library.reference.3=path/to/library_projectB -android.library.reference.1=path/to/library_projectC -</pre> - -<p>Note that the <code>.<em>n</em></code> index in the references -must begin at "1" and increase uniformly without "holes". References -appearing in the index after a hole are ignored. </p> - -<p>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.</p> - - -<h4>Declaring library components in the the manifest file</h4> - -<p>In the manifest file of the application project, you must add declarations -of all components that the application will use that are imported from a library -project. For example, you must declare any <code><activity></code>, -<code><service></code>, <code><receiver></code>, -<code><provider></code>, and so on, as well as -<code><permission></code>, <code><uses-library></code>, and similar -elements.</p> - -<p>Declarations should reference the library components by their fully-qualified -package names, where appropriate. </p> - -<p>For example, the -<a href="{@docRoot}resources/samples/TicTacToeMain/AndroidManifest.html">TicTacToeMain</a> -example application declares the library Activity <code>GameActivity</code> -like this: </p> - -<pre><manifest> - ... - <application> - ... - <activity android:name="com.example.android.tictactoe.library.GameActivity" /> - ... - </application> -</manifest></pre> - -<p>For more information about the manifest file, see the documentation for <a -href="{@docRoot}guide/topics/manifest/manifest-intro.html">AndroidManifest.xml</a>.</p> - -<h3 id="depAppBuild">Building a dependent application</h3> - -<p>To build an application project that depends on one or more library projects, -you can use the standard Ant build commands and compile modes, as described in -<a href="#Building">Building Your Application</a>, earlier in this document. The -tools compile and merge all libraries referenced by the application as part -of compiling the dependent application project. No additional commands or steps -are necessary. </p> - -<h3 id="considerations">Development considerations</h3> - -<p>As you develop your library project and dependent applications, keep the -points listed below in mind.</p> - -<p><strong>Resource conflicts</strong></p> - -<p>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.</p> - -<p><strong>Using prefixes to avoid resource conflicts</strong></p> - -<p>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). </p> - -<p><strong>No export of library project to JAR</strong></p> - -<p>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.</p> - -<p><strong>A library project can include a JAR library</strong></p> - -<p>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 <code>.apk</code>. </p> - -<p><strong>A library project can depend on an external JAR library</strong></p> - -<p>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 <a -href="{@docRoot}guide/topics/manifest/uses-library-element.html"><code><uses-library></code></a> -element. </p> - -<p><strong>Library project cannot include raw assets</strong></p> - -<p>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 -<code>assets/</code> directory of the application project -itself.</p> - -<p><strong>Targeting different Android platform versions in library project and -application project</strong></p> - -<p>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 <a href="{@docRoot}guide/appendix/api-levels.html">API level</a> -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.</p> - -<p><strong>No restriction on library package name</strong></p> - -<p>There is no requirement for the package name of a library to be the same as -that of applications that use it.</p> - -<p><strong>Multiple R classes in gen/ folder of application project</strong></p> - -<p>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 -<code>R</code> class, named according to the library's package name. The -<code>R</code> class generated from the resources of the main project and of the -library is created in all the packages that are needed including the main -project’s package and the libraries’ packages.</p> - -<p><strong>Testing a library project</strong></p> - -<p>There are two recommended ways of setting up testing on code and resources in -a library project: </p> - -<ul> -<li>You can set up a <a -href="{@docRoot}guide/developing/testing/testing_otheride.html">test project</a> -that instruments an application project that depends on the library project. You -can then add tests to the project for library-specific features.</li> -<li>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.</li> -</ul> - -<p><strong>Library project storage location</strong></p> - -<p>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.</p> - -<h2 id="AttachingADebugger">Attaching a Debugger to Your Application</h2> - -<p>This section describes how to display debug information on the screen (such - as CPU usage), as well as how to hook up your IDE to debug running applications - on the emulator. </p> - -<p>Attaching a debugger is automated using the Eclipse plugin, - but you can configure other IDEs to listen on a debugging port to receive debugging - information:</p> -<ol> - <li><strong>Start the <a href="{@docRoot}guide/developing/tools/ddms.html">Dalvik Debug Monitor - Server (DDMS)</a> tool, </strong> which - acts as a port forwarding service between your IDE and the emulator.</li> - <li><strong>Set - optional debugging configurations on - your emulator</strong>, such as blocking application startup for an Activity - until a debugger is attached. Note that many of these debugging options - can be used without DDMS, such as displaying CPU usage or screen refresh - rate on the emulator.</li> - <li><strong>Configure your IDE to attach to port 8700 for debugging.</strong> Read - about <a href="{@docRoot}guide/developing/debug-tasks.html#ide-debug-port"> - Configuring Your IDE to Attach to the Debugging Port</a>. </li> -</ol> diff --git a/docs/html/guide/developing/projects/index.jd b/docs/html/guide/developing/projects/index.jd new file mode 100644 index 0000000..609a71a --- /dev/null +++ b/docs/html/guide/developing/projects/index.jd @@ -0,0 +1,572 @@ +page.title=Creating and Managing Projects +@jd:body + + <div id="qv-wrapper"> + <div id="qv"> + <h2>In this document</h2> + + <ol> + <li><a href="#ApplicationProjects">Android Projects</a></li> + + <li><a href="#LibraryProjects">Library Projects</a> + <ol> + <li><a href="#libraryMigrating">Migrating library projects to ADT 0.9.8 or higher</a></li> + </ol> + </li> + + <li><a href="#TestProjects">Test Projects</a></li> + </ol> + </div> + </div> + + <p>Projects act as containers for storing things such as code and resource files. The SDK tools + expect your projects to follow a specific structure so it can compile and package your + application correctly, so it is highly recommended that you create them with Eclipse and ADT or + with the <code>android</code> tool on the command line. There are three types of projects, and + they all share the same general structure but differ in function:</p> + + <dl> + <dt><strong>Android Projects</strong></dt> + + <dd>An Android project is the container for your application's source code, resource files, and + files such as the Ant build and Android Manifest file. An application project is the main type + of project and the contents are eventually built into an <code>.apk</code> file that you install on a + device.</dd> + + <dt><strong>Test Projects</strong></dt> + + <dd>These projects contain code to test your application projects and are built into + applications that run on a device.</dd> + + <dt><strong>Library Projects</strong></dt> + + <dd>These projects contain shareable Android source code and resources that you can reference + in Android projects. This is useful when you have common code that you want to reuse. + Library projects cannot be installed onto a device, however, they are + pulled into the <code>.apk</code> file at build time.</dd> + </dl> + + <p>When you use the Android development tools to create a new project, the essential files and + folders will be created for you. There are only a handful of files and folders generated for you, + and some of them depend on whether you use the Eclipse plugin or the {@code android} tool to + generate your project. As your application grows in complexity, you might require new kinds of + resources, directories, and files.</p> + + <h2 id="ApplicationProjects">Android Projects</h2> + + <p>Android projects are the projects that eventually get built into an <code>.apk</code> file that you install + onto a device. They contain things such as application source code and resource files. + Some are generated for you by default, while others should be created if + required. The following directories and files comprise an Android project:</p> + + <dl> + <dt><code>src/</code></dt> + + <dd>Contains your stub Activity file, which is stored at + <code>src<em>/your/package/namespace/ActivityName</em>.java</code>. All other source code + files (such as <code>.java</code> or <code>.aidl</code> files) go here as well.</dd> + + <dt><code>bin</code></dt> + + <dd>Output directory of the build. This is where you can find the final <code>.apk</code> file and other + compiled resources.</dd> + + <dt><code>jni</code></dt> + + <dd>Contains native code sources developed using the Android NDK. For more information, see the + <a href="{@docRoot}sdk/ndk/index.html">Android NDK documentation</a>.</dd> + + <dt><code>gen/</code></dt> + + <dd>Contains the Java files generated by ADT, such as your <code>R.java</code> file and + interfaces created from AIDL files.</dd> + + <dt><code>assets/</code></dt> + + <dd>This is empty. You can use it to store raw asset files. Files that you save here are + compiled into an <code>.apk</code> file as-is, and the original filename is preserved. You can navigate this + directory in the same way as a typical file system using URIs and read files as a stream of + bytes using the the {@link android.content.res.AssetManager}. For example, this is a good + location for textures and game data.</dd> + + <dt><code>res/</code></dt> + + <dd> + Contains application resources, such as drawable files, layout files, and string values. See + <a href="{@docRoot}guide/topics/resources/index.html">Application Resources</a> for more + information. + + <dl> + <dt><code>anim/</code></dt> + + <dd>For XML files that are compiled into animation objects. See the <a href= + "{@docRoot}guide/topics/resources/animation-resource.html">Animation</a> resource + type.</dd> + + <dt><code>color/</code></dt> + + <dd>For XML files that describe colors. See the <a href= + "{@docRoot}guide/topics/resources/color-list-resource.html">Color Values</a> resource + type.</dd> + + <dt><code>drawable/</code></dt> + + <dd>For bitmap files (PNG, JPEG, or GIF), 9-Patch image files, and XML files that describe + Drawable shapes or a Drawable objects that contain multiple states (normal, pressed, or + focused). See the <a href= + "{@docRoot}guide/topics/resources/drawable-resource.html">Drawable</a> resource type.</dd> + + <dt><code>layout/</code></dt> + + <dd>XML files that are compiled into screen layouts (or part of a screen). See the <a href= + "{@docRoot}guide/topics/resources/layout-resource.html">Layout</a> resource type.</dd> + + <dt><code>menu/</code></dt> + + <dd>For XML files that define application menus. + See the <a href="{@docRoot}guide/topics/resources/menu-resource.html">Menus</a> + resource type.</dd> + + <dt><code>raw/</code></dt> + + <dd>For arbitrary raw asset files. Saving asset files here instead of in the + <code>assets/</code> directory only differs in the way that you access them. These files + are processed by aapt and must be referenced from the application using a resource + identifier in the {@code R} class. For example, this is a good place for media, such as MP3 + or Ogg files.</dd> + + <dt><code>values/</code></dt> + + <dd>For XML files that are compiled into many kinds of resource. Unlike other resources in + the <code>res/</code> directory, resources written to XML files in this folder are not + referenced by the file name. Instead, the XML element type controls how the resources is + defined within them are placed into the {@code R} class.</dd> + + <dt><code>xml/</code></dt> + + <dd>For miscellaneous XML files that configure application components. For example, an XML + file that defines a {@link android.preference.PreferenceScreen}, {@link + android.appwidget.AppWidgetProviderInfo}, or <a href= + "{@docRoot}reference/android/app/SearchManager.html#SearchabilityMetadata">Searchability + Metadata</a>. See <a href="{@docRoot}guide/topics/resources/index.html">Application Resources</a> + for more information about configuring these application components.</dd> + </dl> + </dd> + + <dt><code>libs/</code></dt> + + <dd>Contains private libraries.</dd> + + <dt><code>AndroidManifest.xml</code></dt> + + <dd>The control file that describes the nature of the application and each of its components. + For instance, it describes: certain qualities about the activities, services, intent receivers, + and content providers; what permissions are requested; what external libraries are needed; what + device features are required, what API Levels are supported or required; and others. See the + <a href="{@docRoot}guide/topics/manifest/manifest-intro.html">AndroidManifest.xml</a> + documentation for more information</dd> + + <dt><code>build.properties</code></dt> + + <dd>Customizable properties for the build system. You can edit this file to override default + build settings used by Ant and provide a pointer to your keystore and key alias so that the + build tools can sign your application when built in release mode. If you use Eclipse, this file + is not used.</dd> + + <dt><code>build.xml</code></dt> + + <dd>The Ant build file for your project. This is only applicable for projects that + you create on the command line.</dd> + + <dt><code>default.properties</code></dt> + + <dd>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. Do not edit + the file manually.</dd> + </dl> + + <h2 id="LibraryProjects">Library Projects</h2> + + <div class="sidebox-wrapper"> + <div class="sidebox"> + <h2>Library project example code</h2> + + <p>The SDK includes an example application called <code>TicTacToeMain</code> that shows how a dependent + application can use code and resources from an Android Library project. The TicTacToeMain + application uses code and resources from an example library project called TicTacToeLib.</p> + + <p>To download the sample applications and run them as projects in + your environment, use the <em>Android SDK and AVD Manager</em> to download the "Samples for + SDK API 8" component into your SDK.</p> + + <p>For more information and to browse the code of the samples, see + the <a href="{@docRoot}resources/samples/TicTacToeMain/index.html">TicTacToeMain + application</a>.</p> + </div> + </div> + + <p>An Android <em>library project</em> is a development project that holds shared Android + source code and resources. Other Android application projects can reference the library project + and, at build time, include its compiled sources in their <code>.apk</code> files. Multiple + application projects can reference the same library project and any single application project + can reference multiple library projects.</p> + + <p>If you have source code and resources that are common to multiple Android projects, you + can move them to a library project so that it is easier to maintain across applications and + versions. Here are some common scenarios in which you could make use of library projects:</p> + + <ul> + <li>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.</li> + + <li>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.</li> + </ul> + + <p>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 <code>src/</code>, + <code>res/</code> 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 <code>R</code> class.</p> + + <p>However, a library project differs from an standard Android application project in that you + cannot compile it directly to its own <code>.apk</code> and run it on an Android device. + Similarly, you cannot export the library project to a self-contained JAR file, as you would do + for a true library. Instead, you must compile the library indirectly, by referencing the + library in the dependent application and building that application.</p> + + <p>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 <code>.apk</code>. 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 <code>.apk</code>. + This gives your application the flexibility to either use or redefine any resource behaviors or + values that are defined in any library.</p> + + <p>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.</p> + + <p>Once you have added references to library projects to your Android project, + you can set their relative priority. At build time, the + libraries are merged with the application one at a time, starting from the lowest priority to + the highest.</p> + + <p>Note that a library project cannot itself reference another library project and that, at + build time, library projects are <em>not</em> 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.</p> + + <h3 id="libraryReqts">Development requirements</h3> + + <p>Android library projects are a build-time construct, so you can use them to build a final + application <code>.apk</code> that targets any API level and is compiled against any version of + the Android library.</p> + + <p>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:</p> + + <p class="table-caption"><strong>Table 1.</strong> Minimum versions of SDK tools and platforms on + which you can develop library projects.</p> + + <table> + <tr> + <th>Component</th> + + <th>Minimum Version</th> + </tr> + + <tr> + <td>SDK Tools</td> + + <td>r6 (or higher)</td> + </tr> + + <tr> + <td>Android 2.2 platform</td> + + <td>r1 (or higher)</td> + </tr> + + <tr> + <td>Android 2.1 platform</td> + + <td>r2 (or higher)</td> + </tr> + + <tr> + <td style="color:gray">Android 2.0.1 platform</td> + + <td style="color:gray"><em>not supported</em></td> + </tr> + + <tr> + <td style="color:gray">Android 2.0 platform</td> + + <td style="color:gray"><em>not supported</em></td> + </tr> + + <tr> + <td>Android 1.6 platform</td> + + <td>r3 (or higher)</td> + </tr> + + <tr> + <td>Android 1.5 platform</td> + + <td>r4 (or higher)</td> + </tr> + + <tr> + <td>ADT Plugin</td> + + <td>0.9.7 (or higher)</td> + </tr> + </table> + + <p>You can download the tools and platforms using the <em>Android SDK and AVD Manager</em>, as + described in <a href="{@docRoot}sdk/adding-components.html">Adding SDK Components</a>.</p> + + <h3 id="considerations">Development considerations</h3> + + <p>As you develop your library project and dependent applications, keep the points listed below + in mind:</p> + + <ul> + <li><p><strong>Resource conflicts</strong></p> + <p>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.</p> + </li> + + <li><p><strong>Use prefixes to avoid resource conflicts</strong></p> + + <p>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).</p></li> + + <li><p><strong>You cannot export a library project to a JAR file</strong></p> + + <p>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.</p></li> + <li><p><strong>One library project cannot reference another</strong></p> + + <p>A library cannot depend on another library</p></li> + + <li><p><strong>A library project can include a JAR library</strong></p> + + <p>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.</p></li> + + <li><p><strong>A library project can depend on an external JAR library</strong></p> + + <p>You can develop a library project that depends on an external library (for example, the Maps + external library). In this case, the dependent application must build against a target that + includes the external library (for example, the Google APIs Add-On). Note also that both the + library project and the dependent application must declare the external library in their manifest + files, in a <a href= + "{@docRoot}guide/topics/manifest/uses-library-element.html"><code><uses-library></code></a> + element.</p></li> + <li><p><strong>Library project cannot include AIDL files</strong></p> + + <p>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.</p></li> + + <li> <p><strong>Library projects cannot include raw assets</strong></p> + + <p>The tools do not support the use of raw asset files (saved in the <code>assets/</code> directory) + in a library project. Any asset resources + used by an application must be stored in the <code>assets/</code> directory of the application + project itself. However, resource files saved in the + <code>res/</code> directory are supported.</p></li> + + <li><p><strong>Platform version must be lower than or equal to the Android project</strong></p> + + <p>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 <a href= + "{@docRoot}guide/appendix/api-levels.html">API level</a> that is the same as — or lower + than — that used by the application. If the library project uses an API level that is + higher than that of the application, the application project will not compile. It is + perfectly acceptable to have a library that uses the Android 1.5 API (API level 3) and that is + used in an Android 1.6 (API level 4) or Android 2.1 (API level 7) project, for instance.</p></li> + + <li> <p><strong>No restriction on library package names</strong></p> + + <p>There is no requirement for the package name of a library to be the same as that of + applications that use it.</p></li> + + <li><p><strong>Each library project creates its own R class </strong></p> + + <p>When you build the dependent application project, library projects are compiled and + merged with the application project. Each library has its own <code>R</code> class, named according + to the library's package name. The <code>R</code> class generated from main + project and the library project is created in all the packages that are needed including the main + project's package and the libraries' packages.</p></li> + + <li><p><strong>Library project storage location</strong></p> + + <p>There are no specific requirements on where you should store a library project, relative to a + dependent application project, as long as the application project can reference the library + project by a relative link. What is important is that the main + project can reference the library project through a relative link.</p></li> + </ul> + + + + <h3 id="libraryMigrating">Migrating library projects to ADT 0.9.8 or higher</h3> + +<p>This section provides information about how to migrate a library project +created with ADT 0.9.7 to ADT 0.9.8 or higher. The migration is needed only if +you are developing in Eclipse with ADT and assumes that you have also upgraded +to SDK Tools r7 (or higher). </p> + +<p>The way that ADT handles library projects has changed between +ADT 0.9.7 and ADT 0.9.8. Specifically, in ADT 0.9.7, the <code>src/</code> +source folder of the library was linked into the dependent application project +as a folder that had the same name as the library project. This worked because +of two restrictions on the library projects:</p> + +<ul> +<li>The library was only able to contain a single source folder (excluding the +special <code>gen/</code> source folder), and</li> +<li>The source folder was required to have the name <code>src/</code> and be +stored at the root of the project.</li> +</ul> + +<p>In ADT 0.9.8, both of those restrictions were removed. A library project can +have as many source folders as needed and each can have any name. Additionally, +a library project can store source folders in any location of the project. For +example, you could store sources in a <code>src/java/</code> directory. In order +to support this, the name of the linked source folders in the main project are +now called <library-name>_<folder-name> For +example: <code>MyLibrary_src/</code> or <code>MyLibrary_src_java/</code>.</p> + +<p>Additionally, the linking process now flags those folders in order for ADT to +recognize that it created them. This will allow ADT to automatically migrate the +project to new versions of ADT, should they contain changes to the handling of +library projects. ADT 0.9.7 did not flag the linked source folders, so ADT 0.9.8 +cannot be sure whether the old linked folders can be removed safely. After +upgrading ADT to 0.9.8, you will need to remove the old linked folders manually +in a simple two-step process, as described below.</p> + +<p>Before you begin, make sure to create a backup copy of your application or +save the latest version to your code version control system. This ensures that +you will be able to easily revert the migration changes in case there is a +problem in your environment.</p> + +<p>When you first upgrade to ADT 0.9.8, your main project will look as shown +in figure 1, with two linked folders (in this example, <code>MyLibrary</code> and +<code>MyLibrary_src</code> — both of which link to +<code>MyLibrary/src</code>. Eclipse shows an error on one of them because they +are duplicate links to a single class.</p> + +<img src="{@docRoot}images/developing/lib-migration-0.png" alt=""> +<p class="img-caption"><strong>Figure 1.</strong> Library project migration error</p> +<p>To fix the error, remove the linked folder that <em>does not</em> contain the +<code>_src</code> suffix. </p> + +<ol> +<li>Right click the folder that you want to remove (in this case, the +<code>MyLibrary</code> folder) and choose <strong>Build Path</strong> > +<strong>Remove from Build Path</strong>, as shown in figure 2.</li> + +<img src="{@docRoot}images/developing/lib-migration-1.png" style="height:600px" +alt=""> +<p class="img-caption"><strong>Figure 2.</strong> Remove from Build Path menu item</p> + +<li>Next, when asked about unlinking the folder from the project, select +<strong>Yes</strong>, as shown in figure 3.</li> + +<img src="{@docRoot}images/developing/lib-migration-2.png" alt=""> + +<p class="img-caption"><strong>Figure 3.</strong> Unlink folder confirmation window</p> +</ol> + +<p>This should resolve the error and migrate your library project to the new +ADT environment. </p> + + + + <h2 id="TestProjects">Test Projects</h2> + + <p>Test projects contain Android applications that you write using the + <a href="{@docRoot}guide/topics/testing/index.html">Testing and + Instrumentation framework</a>. The framework is an extension of the JUnit test framework and adds + access to Android system objects. The file structure of a test project is the same as an + Android project.</p> + + <dl> + <dt><code>src/</code></dt> + + <dd>Includes your test source files. Test projects do not require an Activity <code>.java</code> + file, but can include one.</dd> + + <dt><code>gen/</code></dt> + + <dd>This contains the Java files generated by ADT, such as your <code>R.java</code> file and + interfaces created from AIDL files.</dd> + + <dt><code>assets/</code></dt> + + <dd>This is empty. You can use it to store raw asset files.</dd> + + <dt><code>res/</code></dt> + + <dd>A folder for your application resources, such as drawable files, layout files, string + values, etc. See <a href="{@docRoot}guide/topics/resources/index.html">Application + Resources</a>.</dd> + + <dt><code>AndroidManifest.xml</code></dt> + + <dd>The Android Manifest for your project. See <a href= + "{@docRoot}guide/topics/manifest/manifest-intro.html">The AndroidManifest.xml File</a>. Test + Projects have a special <a href= + "{@docRoot}guide/topics/manifest/instrumentation-element.html"> + <code><instrumentation></code></a> + element that connects the test project with the application project.</dd> + + <dt><code>build.properties</code></dt> + + <dd>Customizable properties for the build system. You can edit this file to override default + build settings used by Ant and provide a pointer to your keystore and key alias so that the + build tools can sign your application when built in release mode.</dd> + + <dt><code>build.xml</code></dt> + + <dd>The Ant build file for your project.</dd> + + <dt><code>default.properties</code></dt> + + <dd>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".</dd> + </dl>For more information, see the <a href= + "{@docRoot}guide/developing/testing/index.html">Testing</a> section. + + + <h2>Testing a library project</h2> + + <p>There are two recommended ways of setting up testing on code and resources in a library + project:</p> + + <ul> + <li>You can set up a <a href="{@docRoot}guide/developing/testing/testing_otheride.html">test + project</a> that instruments an application project that depends on the library project. You + can then add tests to the project for library-specific features.</li> + + <li>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.</li> + </ul>
\ No newline at end of file diff --git a/docs/html/guide/developing/projects/projects-cmdline.jd b/docs/html/guide/developing/projects/projects-cmdline.jd new file mode 100644 index 0000000..8b889ab --- /dev/null +++ b/docs/html/guide/developing/projects/projects-cmdline.jd @@ -0,0 +1,285 @@ +page.title=Creating and Managing Projects on the Command Line +@jd:body + + <div id="qv-wrapper"> + <div id="qv"> + <h2>In this document</h2> + + <ol> + <li><a href="#CreatingAProject">Creating an Android Project</a></li> + + <li><a href="#UpdatingAProject">Updating a Project</a></li> + + <li><a href="#SettingUpLibraryProject">Setting up a Library Project</a></li> + + <li><a href="#ReferencingLibraryProject">Referencing a Library Project from an + Application</a></li> + </ol> + + <h2>See also</h2> + + <ol> + <li><a href= + "{@docRoot}guide/developing/testing/testing_otheride.html#CreateTestProjectCommand">Testing + in Other IDEs</a></li> + </ol> + </div> + </div> + + <p>The <code>android</code> tool provides you with commands to create all three types of + projects. An Android project contains all of the files and resources that are needed to build a + project into an .apk file for installation. + + <ul> + <li>An Android project contains all of the files and resources that are needed to build a project into + an .apk file for installation. You need to create an Android project for any application that you + want to eventually install on a device.</li> + + <li>You can also designate an Android project as a library project, which allows it to be shared + with other projects that depend on it. Once an Android project is designated as a library + project, it cannot be installed onto a device.</li> + + <li>Test projects extend JUnit test functionality to include Android specific functionality. For + more information on creating a test project, see <a href= + "{@docRoot}guide/developing/testing/testing_otheride.html">Testing in other IDEs</a>.</li> + </ul> + + + <h2 id="CreatingAProject">Creating an Android Project</h2> + + <p>To create an Android project, you must use the <code>android</code> tool. When you create a + new project with <code>android</code>, it will generate a project directory with some default + application files, stub files, configuration files and a build file.</p> + + <p>To create a new Android project, open a command-line, navigate to the <code>tools/</code> + directory of your SDK and run:</p> + <pre> +android create project \ +--target <target_ID> \ +--name <your_project_name> \ +--path path/to/your/project \ +--activity <your_activity_name> \ +--package <your_package_namespace> +</pre> + + <ul> + <li><code>target</code> 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: <code>android list targets</code>.</li> + + <li><code>name</code> is the name for your project. This is optional. If provided, this name + will be used for your .apk filename when you build your application.</li> + + <li><code>path</code> is the location of your project directory. If the directory does not + exist, it will be created for you.</li> + + <li><code>activity</code> is the name for your default {@link android.app.Activity} class. This + class file will be created for you inside + <code><em><path_to_your_project></em>/src/<em><your_package_namespace_path></em>/</code> + . This will also be used for your .apk filename unless you provide a <code>name</code>.</li> + + <li><code>package</code> is the package namespace for your project, following the same rules as + for packages in the Java programming language.</li> + </ul> + + <p>Here's an example:</p> + <pre> +android create project \ +--target 1 \ +--name MyAndroidApp \ +--path ./MyAndroidAppProject \ +--activity MyAndroidAppActivity \ +--package com.example.myandroid +</pre> + + <p>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 <a href= + "{@docRoot}guide/developing/tools/adb.html">Android Debug Bridge</a> (adb) — located in the + SDK <code>platform-tools/</code> directory — to send your application to the emulator (discussed + later). So you need access between your project solution and the <code>platform-tools/</code> folder.</p> + + <p class="note"><strong>Tip:</strong> Add the <code>platform-tools/</code> as well as the <code>tools/</code> directory + to your <code>PATH</code> environment variable.</p> + + <p class="caution"><strong>Caution:</strong> 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.)</p> + + <h2 id="UpdatingAProject">Updating a project</h2> + + <p>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 <code>android update project</code> 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 <code>--target</code> option) and the project name (with + the <code>--name</code> option). The <code>android</code> 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.</p> + + <p>To update an existing Android project, open a command-line and navigate to the + <code>tools/</code> directory of your SDK. Now run:</p> + <pre> +android update project --name <project_name> --target <target_ID> +--path <path_to_your_project> +</pre> + + <ul> + <li><code>target</code> 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: <code>android list targets</code>.</li> + + <li><code>path</code> is the location of your project directory.</li> + + <li><code>name</code> is the name for the project. This is optional—if you're not + changing the project name, you don't need this.</li> + </ul> + + <p>Here's an example:</p> + <pre> +android update project --name MyApp --target 2 --path ./MyAppProject +</pre> + + <h2 id="SettingUpLibraryProject">Setting up a library project</h2> + + <p>A library project is a standard Android project, so you can create a new one in the same way + as you would a new application project. Specifically, you can use the <code>android</code> tool + to generate a new library project with all of the necessary files and folders.</p> + + <p>To create a new library project, navigate to the <code><sdk>/tools/</code> directory and + use this command:</p> + <pre class="no-pretty-print"> +android create lib-project --name <your_project_name> \ +--target <target_ID> \ +--path path/to/your/project \ +--package <your_library_package_namespace> +</pre> + + <p>The <code>create lib-project</code> command creates a standard project structure that includes + preset property that indicates to the build system that the project is a library. It does this by + adding this line to the project's <code>default.properties</code> file:</p> + <pre class="no-pretty-print"> +android.library=true +</pre> + + <p>Once the command completes, the library project is created and you can begin moving source + code and resources into it, as described in the sections below.</p> + + <p>If you want to convert an existing application project to a library project, so that other + applications can use it, you can do so by adding a the <code>android.library=true</code> property + to the application's <code>default.properties</code> file.</p> + + <h4>Creating the manifest file</h4> + + <p>A library project's manifest file must declare all of the shared components that it includes, + just as would a standard Android application. For more information, see the documentation for + <a href="{@docRoot}guide/topics/manifest/manifest-intro.html">AndroidManifest.xml</a>.</p> + + <p>For example, the <a href= + "{@docRoot}resources/samples/TicTacToeLib/AndroidManifest.html">TicTacToeLib</a> example library + project declares the Activity <code>GameActivity</code>:</p> + <pre> +<manifest> + ... + <application> + ... + <activity android:name="GameActivity" /> + ... + </application> +</manifest> +</pre> + + <h4>Updating a library project</h4> + + <p>If you want to update the build properties (build target, location) of the library project, + use this command:</p> + <pre> +android update lib-project \ +--target <em><target_ID></em> \ +--path <em>path/to/your/project</em> +</pre> + + <h2 id="ReferencingLibraryProject">Referencing a Library Project</h2> + + <p>If you are developing an application and want to include the shared code or resources from a + library project, you can do so easily by adding a reference to the library project in the + application project's build properties.</p> + + <p>To add a reference to a library project, navigate to the <code><sdk>/tools/</code> + directory and use this command:</p> + <pre> +android update lib-project \ +--target <em><target_ID></em> \ +--path <em>path/to/your/project</em> +--library <em>path/to/library_projectA</em> +</pre> + + <p>This command updates the application project's build properties to include a reference to the + library project. Specifically, it adds an <code>android.library.reference.<em>n</em></code> + property to the project's <code>default.properties</code> file. For example:</p> + <pre class="no-pretty-print"> +android.library.reference.1=path/to/library_projectA +</pre> + + <p>If you are adding references to multiple libraries, note that you can set their relative + priority (and merge order) by manually editing the <code>default.properties</code> file and + adjusting the each reference's <code>.<em>n</em></code> index as appropriate. For example, assume + these references:</p> + <pre class="no-pretty-print"> +android.library.reference.1=path/to/library_projectA +android.library.reference.2=path/to/library_projectB +android.library.reference.3=path/to/library_projectC +</pre> + + <p>You can reorder the references to give highest priority to <code>library_projectC</code> in + this way:</p> + <pre class="no-pretty-print"> +android.library.reference.2=path/to/library_projectA +android.library.reference.3=path/to/library_projectB +android.library.reference.1=path/to/library_projectC +</pre> + + <p>Note that the <code>.<em>n</em></code> index in the references must begin at "1" and increase + uniformly without "holes". References appearing in the index after a hole are ignored.</p> + + <p>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.</p> + + <h3>Declaring library components in the the manifest file</h3> + + <p>In the manifest file of the application project, you must add declarations of all components + that the application will use that are imported from a library project. For example, you must + declare any <code><activity></code>, <code><service></code>, + <code><receiver></code>, <code><provider></code>, and so on, as well as + <code><permission></code>, <code><uses-library></code>, and similar elements.</p> + + <p>Declarations should reference the library components by their fully-qualified package names, + where appropriate.</p> + + <p>For example, the <a href= + "{@docRoot}resources/samples/TicTacToeMain/AndroidManifest.html">TicTacToeMain</a> example + application declares the library Activity <code>GameActivity</code> like this:</p> + <pre> +<manifest> + ... + <application> + ... + <activity android:name="com.example.android.tictactoe.library.GameActivity" /> + ... + </application> +</manifest> +</pre> + + <p>For more information about the manifest file, see the documentation for + <a href="{@docRoot}guide/topics/manifest/manifest-intro.html">AndroidManifest.xml</a>.</p> + + <h3 id="depAppBuild">Building a dependent application</h3> + + <p>To build an application project that depends on one or more library projects, you can use the + standard Ant build commands and compile modes, as described in <a href= + "{@docRoot}guide/developing/building/index.html">Building Your Application</a>, earlier in this + document. The tools compile and merge all libraries referenced by the application as part of + compiling the dependent application project. No additional commands or steps are necessary.</p> + diff --git a/docs/html/guide/developing/projects/projects-eclipse.jd b/docs/html/guide/developing/projects/projects-eclipse.jd new file mode 100644 index 0000000..949e6f7 --- /dev/null +++ b/docs/html/guide/developing/projects/projects-eclipse.jd @@ -0,0 +1,235 @@ +page.title=Creating and Managing Projects in Eclipse +@jd:body + + <div id="qv-wrapper"> + <div id="qv"> + <h2>In this document</h2> + + <ol> + <li><a href="#CreatingAProject">Creating an Android Project</a></li> + + <li><a href="#SettingUpLibraryProject">Setting up a Library Project</a></li> + + <li><a href="#ReferencingLibraryProject">Referencing a Library Project</a></li> + </ol> + + <h2>See also</h2> + + <ol> + <li><a href= + "{@docRoot}guide/developing/testing/testing_eclipse.html#CreateTestProjectEclipse">Testing + in Eclipse, with ADT</a></li> + </ol> + </div> + </div> + + <p>Eclipse and the ADT plugin provide GUIs and wizards to create all three types of projects + (Android project, Library project, and Test project): + + <ul> + <li>An Android project contains all of the files and resources that are needed to build a project into + an .apk file for installation. You need to create an Android project for any application that you + want to eventually install on a device.</li> + + <li>You can also designate an Android project as a library project, which allows it to be shared + with other projects that depend on it. Once an Android project is designated as a library + project, it cannot be installed onto a device.</li> + + <li>Test projects extend JUnit test functionality to include Android specific functionality. For + more information on creating a test project, see <a href= + "{@docRoot}guide/developing/testing/testing_eclipse.html">Testing in Eclipse</a></li> + </ul> + + <h2 id="CreatingAProject">Creating an Android Project</h2> + + <p>The ADT plugin provides a <em>New Project Wizard</em> that you can use to quickly create a new Android + project (or a project from existing code). To create a new project:</p> + + <ol> + <li>Select <strong>File</strong> > <strong>New</strong> > <strong>Project</strong>.</li> + + <li>Select <strong>Android</strong> > <strong>Android Project</strong>, and click + <strong>Next</strong>.</li> + + <li>Select the contents for the project: + + <ul> + <li>Enter a <em>Project Name</em>. This will be the name of the folder where your project + is created.</li> + + <li>Under Contents, select <strong>Create new project in workspace</strong>. Select your + project workspace location.</li> + + <li>Under Target, select an Android target to be used as the project's Build Target. The + Build Target specifies which Android platform you'd like your application built against. + + <p>Select the lowest platform with which your application is compatible.</p> + + <p class="note"><strong>Note:</strong> You can change your the Build Target for your + project at any time: Right-click the project in the Package Explorer, select + <strong>Properties</strong>, select <strong>Android</strong> and then check the desired + Project Target.</p> + </li> + + <li>Under Properties, fill in all necessary fields. + + <ul> + <li>Enter an <em>Application name</em>. This is the human-readable title for your + application — the name that will appear on the Android device.</li> + + <li>Enter a <em>Package name</em>. This is the package namespace (following the same + rules as for packages in the Java programming language) where all your source code will + reside.</li> + + <li>Select <em>Create Activity</em> (optional, of course, but common) and enter a name + for your main Activity class.</li> + + <li>Enter a <em>Min SDK Version</em>. This is an integer that indicates the minimum API + Level required to properly run your application. Entering this here automatically sets + the <code>minSdkVersion</code> attribute in the <a href= + "{@docRoot}guide/topics/manifest/uses-sdk-element.html"><uses-sdk></a> of your + Android Manifest file. If you're unsure of the appropriate <a href= + "{@docRoot}guide/appendix/api-levels.html">API Level</a> to use, copy the API Level + listed for the Build Target you selected in the Target tab.</li> + </ul> + </li> + </ul> + </li> + + <li>Click <strong>Finish</strong>.</li> + </ol> + + <p class="note"><strong>Tip:</strong> You can also start the New Project Wizard from the + <em>New</em> icon in the toolbar.</p> + + <h2 id="SettingUpLibraryProject">Setting up a Library Project</h2> + + <p>A library project is a standard Android project, so you can create a new one in the same way + as you would a new application project.</p> + + <p>When you are creating the library project, you can select any application name, package, and + set other fields as needed, as shown in figure 1.</p> + + <p>Next, set the project's properties to indicate that it is a library project:</p> + + <ol> + <li>In the <strong>Package Explorer</strong>, right-click the library project and select + <strong>Properties</strong>.</li> + + <li>In the <strong>Properties</strong> window, select the "Android" properties group at left + and locate the <strong>Library</strong> properties at right.</li> + + <li>Select the "is Library" checkbox and click <strong>Apply</strong>.</li> + + <li>Click <strong>OK</strong> to close the <em>Properties</em> window.</li> + </ol> + + <p>The new project is now marked as a library project. You can begin moving source code and + resources into it, as described in the sections below.</p> + + <p>You can also convert an existing application project into a library. To do so, simply open the + Properties for the project and select the "is Library" checkbox. Other application projects can + now reference the existing project as a library project.</p> + + <img src= "{@docRoot}images/developing/adt-props-isLib.png"> + + <p class="img-caption"><strong>Figure 1.</strong> Marking a project as an + Android library project.</p> + + <h3>Creating the manifest file</h3> + + <p>A library project's manifest file must declare all of the shared components that it includes, + just as would a standard Android application. For more information, see the documentation for + <a href="{@docRoot}guide/topics/manifest/manifest-intro.html">AndroidManifest.xml</a>.</p> + + <p>For example, the <a href= + "{@docRoot}resources/samples/TicTacToeLib/AndroidManifest.html">TicTacToeLib</a> example library + project declares the Activity <code>GameActivity</code>:</p> + <pre> +<manifest> + ... + <application> + ... + <activity android:name="GameActivity" /> + ... + </application> +</manifest> +</pre> + + <h2 id="ReferencingLibraryProject">Referencing a library project</h2> + + <p>If you are developing an application and want to include the shared code or resources from a + library project, you can do so easily by adding a reference to the library project in the + application project's Properties.</p> + + <p>To add a reference to a library project, follow these steps:</p> + + <ol> + <li>In the <strong>Package Explorer</strong>, right-click the dependent project and select + <strong>Properties</strong>.</li> + + <li>In the <strong>Properties</strong> window, select the "Android" properties group at left + and locate the <strong>Library</strong> properties at right.</li> + + <li>Click <strong>Add</strong> to open the <strong>Project Selection</strong> dialog.</li> + + <li>From the list of available library projects, select a project and click + <strong>OK</strong>.</li> + + <li>When the dialog closes, click <strong>Apply</strong> in the <strong>Properties</strong> + window.</li> + + <li>Click <strong>OK</strong> to close the <strong>Properties</strong> window.</li> + </ol> + + <p>As soon as the Properties dialog closes, Eclipse rebuilds the project, including the contents + of the library project.</p> + + <p>Figure 2 shows the Properties dialog that lets you add library references and move + them up and down in priority.</p><img src="{@docRoot}images/developing/adt-props-libRef.png"> + + <p class="img-caption"><strong>Figure 2.</strong> Adding a reference to a + library project in the properties of an application project.</p> + + <p>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 <strong>Up</strong> and + <strong>Down</strong> 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.</p> + + <h3>Declaring library components in the the manifest file</h3> + + <p>In the manifest file of the application project, you must add declarations of all components + that the application will use that are imported from a library project. For example, you must + declare any <code><activity></code>, <code><service></code>, + <code><receiver></code>, <code><provider></code>, and so on, as well as + <code><permission></code>, <code><uses-library></code>, and similar elements.</p> + + <p>Declarations should reference the library components by their fully-qualified package names, + where appropriate.</p> + + <p>For example, the <a href= + "{@docRoot}resources/samples/TicTacToeMain/AndroidManifest.html">TicTacToeMain</a> example + application declares the library Activity <code>GameActivity</code> like this:</p> + <pre> +<manifest> + ... + <application> + ... + <activity android:name="com.example.android.tictactoe.library.GameActivity" /> + ... + </application> +</manifest> +</pre> + + <p>For more information about the manifest file, see the documentation for <a href= + "{@docRoot}guide/topics/manifest/manifest-intro.html">AndroidManifest.xml</a>.</p> + + + + + + + diff --git a/docs/html/guide/developing/testing/index.jd b/docs/html/guide/developing/testing/index.jd index 2164705..8ffaf58 100644 --- a/docs/html/guide/developing/testing/index.jd +++ b/docs/html/guide/developing/testing/index.jd @@ -1,4 +1,4 @@ -page.title=Testing Overview +page.title=Testing @jd:body <p> Android includes powerful tools for setting up and running test applications. diff --git a/docs/html/guide/developing/testing/testing_eclipse.jd b/docs/html/guide/developing/testing/testing_eclipse.jd index 370c142..1b9c6b1 100644 --- a/docs/html/guide/developing/testing/testing_eclipse.jd +++ b/docs/html/guide/developing/testing/testing_eclipse.jd @@ -12,9 +12,10 @@ page.title=Testing In Eclipse, with ADT </div> <p> This topic explains how create and run tests of Android applications in Eclipse with ADT. - Before you read this topic, you should read about how to create a Android application with the + Before you read this topic, you should read about how to create an Android application with the basic processes for creating and running applications with ADT, as described in - <a href="{@docRoot}guide/developing/eclipse-adt.html">Developing In Eclipse, with ADT</a>. + <a href="{@docRoot}guide/developing/projects/projects-eclipse.html">Creating and Managing Projects in Eclipse</a> + and <a href="guide/developing/building/building-eclipse.html">Building and Running Apps in Eclipse</a>. You may also want to read <a href="{@docRoot}guide/topics/testing/testing_android.html">Testing Fundamentals</a>, which provides an overview of the Android testing framework. diff --git a/docs/html/guide/developing/testing/testing_otheride.jd b/docs/html/guide/developing/testing/testing_otheride.jd index adb0efa..48fa032 100644 --- a/docs/html/guide/developing/testing/testing_otheride.jd +++ b/docs/html/guide/developing/testing/testing_otheride.jd @@ -133,7 +133,7 @@ android create test-project -m <main_path> -n <project_name> -p < 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 - <a href="{@docRoot}guide/developing/other-ide.html">Developing In Other IDEs</a>. + <a href="{@docRoot}guide/developing/projects/index.html">Creating and Managing Projects</a>. </p> <p> The operation also creates an <code>AndroidManifest.xml</code> file with instrumentation diff --git a/docs/html/guide/developing/tools/aapt.html b/docs/html/guide/developing/tools/aapt.html new file mode 100644 index 0000000..e66a201 --- /dev/null +++ b/docs/html/guide/developing/tools/aapt.html @@ -0,0 +1,10 @@ +<html> +<head> +<meta http-equiv="refresh" content="0;url=http://developer.android.com/guide/developing/building/index.html#detailed-build"> +<title>Redirecting...</title> +</head> +<body> +<p>You should be redirected. Please <a +href="http://developer.android.com/guide/developing/building/index.html#detailed-build">click here</a>.</p> +</body> +</html>
\ No newline at end of file diff --git a/docs/html/guide/developing/tools/aapt.jd b/docs/html/guide/developing/tools/aapt.jd deleted file mode 100644 index 40a209d..0000000 --- a/docs/html/guide/developing/tools/aapt.jd +++ /dev/null @@ -1,20 +0,0 @@ -page.title=Using aapt -@jd:body - -<p><strong>aapt</strong> stands for Android Asset Packaging Tool and is included in the <code>tools/</code> 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. -</p> -<p> -Though you probably won't often use <strong>aapt</strong> directly, build scripts and IDE plugins can utilize this tool to package the apk file that constitutes an Android application. -</p> -<p> -For more usage details, open a terminal, go to the <code>tools/</code> directory, and run the command: -</p> -<ul> - <li><p>Linux or Mac OS X:</p> - <pre>./aapt</pre> - </li> - <li><p>Windows:</p> - <pre>aapt.exe</pre> - </li> -</ul> - diff --git a/docs/html/guide/developing/tools/adb.jd b/docs/html/guide/developing/tools/adb.jd index 3c6351e..bcdc2e6 100644 --- a/docs/html/guide/developing/tools/adb.jd +++ b/docs/html/guide/developing/tools/adb.jd @@ -171,7 +171,7 @@ emulator-5558 device</pre> <pre>adb install <path_to_apk></pre> -<p>For more information about how to create an .apk file that you can install on an emulator/device instance, see <a href="{@docRoot}guide/developing/tools/aapt.html">Android Asset Packaging Tool</a> (aapt). </p> +<p>For more information about how to create an .apk file that you can install on an emulator/device instance, see <a href="{@docRoot}guide/developing/building/index.html">Building and Running Apps</a></p> <p>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. </p> @@ -465,7 +465,8 @@ application and send 500 pseudo-random events to it.</p> <tr> <td><code>dumpsys</code></td> <td>Dumps system data to the screen.</td> -<td rowspan=4">The <a href="{@docRoot}guide/developing/tools/ddms.html">Dalvik Debug Monitor Service</a> (DDMS) tool offers integrated debug environment that you may find easier to use.</td> +<td rowspan=4">The <a href="{@docRoot}guide/developing/debugging/ddms.html">Dalvik Debug Monitor Server</a> +(DDMS) tool offers integrated debug environment that you may find easier to use.</td> </tr> <tr> diff --git a/docs/html/guide/developing/tools/android.jd b/docs/html/guide/developing/tools/android.jd new file mode 100644 index 0000000..ebf95ce --- /dev/null +++ b/docs/html/guide/developing/tools/android.jd @@ -0,0 +1,364 @@ +page.title=android +@jd:body + +<p>{@code android} is an important development tool that lets you:</p> + + <ul> + <li>Create, delete, and view Android Virtual Devices (AVDs). See <a href= + "{@docRoot}guide/developing/devices/managing-avds-cmdline.html"> + Creating and Managing AVDs on the Command Line</a>.</li> + + <li>Create and update Android projects. See <a href= + "{@docRoot}guide/developing/projects/projects-cmdline.html">Creating and Managing Projects on + the Command Line</a>.</li> + + <li>Update your Android SDK with new platforms, add-ons, and documentation. See <a href= + "{@docRoot}sdk/adding-components.html">Adding SDK Components</a>.</li> + </ul>If you are using Eclipse, the <code>android</code> tool's features are integrated + into ADT, so you should not need to use this tool directly. + + <h2>Syntax</h2> + <pre>android [global options] action [action options]</pre> + + <h3>Global Options</h3> + + <dl> + <dt><code>-s</code></dt> + + <dd>Silent mode: only errors are printed out</dd> + + <dt><code>-h</code></dt> + + <dd>Usage help</dd> + + <dt><code>-v</code></dt> + + <dd>Verbose mode: errors, warnings and informational messages are printed.</dd> + </dl> + + <h3>AVD actions and options</h3> + + <table> + <tr> + <th width="15%">Action</th> + + <th width="20%">Option</th> + + <th width="30%">Description</th> + + <th>Comments</th> + </tr> + + <tr> + <td rowspan="6"><code>create avd</code></td> + + <td><code>-n <name></code></td> + + <td>The name for the AVD.</td> + + <td>Required</td> + </tr> + + <tr> + <td><code>-t <targetID></code></td> + + <td>Target ID of the system image to use with the new AVD. To obtain a list of available + targets, use <code>android list targets</code></td> + + <td>Required</td> + </tr> + + <tr> + <td><code>-c <path>|<size>[K|M]</code></td> + + <td>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. For example, <code>-c path/to/sdcard</code> or <code>-c + 1000M</code>.</td> + + <td></td> + </tr> + + <tr> + <td><code>-f</code></td> + + <td>Force creation of the AVD</td> + + <td></td> + </tr> + + <tr> + <td><code>-p <path></code></td> + + <td>Path to the location at which to create the directory for this AVD's files.</td> + + <td></td> + </tr> + + <tr> + <td><code>-s <name>|<width>-<height></code></td> + + <td>The skin to use for this AVD, identified by name or dimensions. The <code>android</code> + tool scans for a matching skin by name or dimension in the <code>skins/</code> directory of + the target referenced in the <code>-t <targetID></code> argument. For example, <code>-s + HVGA-L</code></td> + + <td></td> + </tr> + + <tr> + <td><code>delete avd</code></td> + + <td><code>-n <name></code></td> + + <td>The name of the AVD to delete</td> + + <td>Required</td> + </tr> + + <tr> + <td rowspan="3"><code>move avd</code></td> + + <td><code>-n <name></code></td> + + <td>The name of the AVD to move</td> + + <td>Required</td> + </tr> + + <tr> + <td><code>-p <path></code></td> + + <td>Path to the location at which to create the directory for this AVD's files.</td> + + <td></td> + </tr> + + <tr> + <td><code>-r <new-name></code></td> + + <td>New name of the AVD if you want to rename it</td> + + <td></td> + </tr> + + <tr> + <td><code>update avd</code></td> + + <td><code>-n <name></code></td> + + <td>The name of the AVD to move</td> + + <td>Required</td> + </tr> + </table> + + <h3>Project actions and options</h3> + + <table> + <tr> + <th width="15%">Action</th> + + <th width="20%">Option</th> + + <th width="30%">Description</th> + + <th>Comments</th> + </tr> + + <tr> + <td rowspan="5"><code>create project</code></td> + + <td><code>-n <name></code></td> + + <td>The name for the project</td> + + <td>Required</td> + </tr> + + <tr> + <td><code>-t <targetID></code></td> + + <td>Target ID of the system image to use with the new AVD. To obtain a list of available + targets, use <code>android list targets</code></td> + + <td>Required</td> + </tr> + + <tr> + <td><code>-k <path>|<size>[K|M]</code></td> + + <td>Package namespace</td> + + <td>Required</td> + </tr> + + <tr> + <td><code>-a</code></td> + + <td>Name for the default Activity class</td> + + <td>Required</td> + </tr> + + <tr> + <td><code>-p <path></code></td> + + <td>Location of your project directory</td> + + <td>Required</td> + </tr> + + <tr> + <td rowspan="5"><code>update project</code></td> + + <td><code>-n <name></code></td> + + <td>The name of the project to update</td> + + <td></td> + </tr> + + <tr> + <td><code>-p <path></code></td> + + <td>Location path of the project</td> + + <td>Required</td> + </tr> + + <tr> + <td><code>-l <library path></code></td> + + <td>Location path of an Android Library to add, relative to the main project</td> + + <td></td> + </tr> + + <tr> + <td><code>-s <subprojects></code></td> + + <td>Update any projects in subfolders such as test projects</td> + + <td></td> + </tr> + + <tr> + <td><code>-t <targetID></code></td> + + <td>Target id to set for the project</td> + + <td></td> + </tr> + + <tr> + <td rowspan="3"><code>create-test-project</code></td> + + <td><code>-n <name></code></td> + + <td>The name of the project</td> + + <td></td> + </tr> + + <tr> + <td><code>-p <path></code></td> + + <td>Location path of the project</td> + + <td>Required</td> + </tr> + + <tr> + <td><code>-m <main></code></td> + + <td>The name of the project</td> + + <td>Required</td> + </tr> + + <tr> + <td rowspan="2"><code>update-test-project</code></td> + + <td><code>-p <path></code></td> + + <td>Location path of the project to test, relative to the new project</td> + + <td>Required</td> + </tr> + + <tr> + <td><code>-m <main></code></td> + + <td>The main class of the project to test</td> + + <td>Required</td> + </tr> + + <tr> + <td rowspan="4"><code>create-lib-project</code></td> + + <td><code>-k <packageName></code></td> + + <td>(Required) Package name of the library project</td> + + <td>Required</td> + </tr> + + <tr> + <td><code>-p <path></code></td> + + <td>Location path of the project</td> + + <td>Required</td> + </tr> + + <tr> + <td><code>-t <targetID></code></td> + + <td>Target ID of the library project</td> + + <td>Required</td> + </tr> + + <tr> + <td><code>-n <name></code></td> + + <td>The name of the project</td> + + <td>Required</td> + </tr> + + <tr> + <td rowspan="3"><code>update-lib-project</code></td> + + <td><code>-p <path></code></td> + + <td>Location path of the project</td> + + <td>Required</td> + </tr> + + <tr> + <td><code>-l <libraryPath></code></td> + + <td>Location path of an Android Library to add, relative to the main project</td> + + <td></td> + </tr> + + <tr> + <td><code>-t <name></code></td> + + <td>Target ID of the library project</td> + + <td></td> + </tr> + </table> + + <h3>Update actions</h3> + <dl> + <dt><code>update adb</code></dt> + <dd>Updates adb to support the USB devices declared in the SDK add-ons.</dd> + + <dt><code>update sdk</code></dt> + <dd>Updates the SDK by suggesting new platforms to install if available.</dd> diff --git a/docs/html/guide/developing/tools/avd.html b/docs/html/guide/developing/tools/avd.html new file mode 100644 index 0000000..c8455db --- /dev/null +++ b/docs/html/guide/developing/tools/avd.html @@ -0,0 +1,10 @@ +<html> +<head> +<meta http-equiv="refresh" content="0;url=http://developer.android.com/guide/developing/devices/index.html"> +<title>Redirecting...</title> +</head> +<body> +<p>You should be redirected. Please <a +href="http://developer.android.com/guide/developing/devices/index.html">click here</a>.</p> +</body> +</html>
\ No newline at end of file diff --git a/docs/html/guide/developing/tools/avd.jd b/docs/html/guide/developing/tools/avd.jd deleted file mode 100644 index ca197cf..0000000 --- a/docs/html/guide/developing/tools/avd.jd +++ /dev/null @@ -1,447 +0,0 @@ -page.title=Android Virtual Devices -@jd:body - -<div id="qv-wrapper"> -<div id="qv"> - - <h2>AVD quickview</h2> - <ul> - <li>You need to create an AVD to run any app in the Android emulator</li> - <li>Each AVD is a completely independent virtual device, with its own - hardware options, system image, and data storage. - <li>You create AVD configurations to model different device environments - in the Android emulator.</li> - <li>You can launch a graphical Android AVD Manager either through Eclipse or -through the <code>android</code> tool. The <code>android</code> tool also offers -a command-line interface for creating and managing AVDs.</li> </ul> - <h2>In this document</h2> - <ol> - <li><a href="#creating">Creating an AVD</a> - <ol> - <li><a href="#hardwareopts">Setting hardware emulation options</a></li> - <li><a href="#location">Default location of the AVD files</a></li> - </ol> - </li> - <li><a href="#managing">Managing AVDs</a> - <ol> - <li><a href="#moving">Moving an AVD</a></li> - <li><a href="#updating">Updating an AVD</a></li> - <li><a href="#deleting">Deleting an AVD</a></li> - </ol> - </li> - <li><a href="#options">Command-line options</a></li> - </ol> - <h2>See Also</h2> - <ol> - <li><a href="{@docRoot}guide/developing/tools/emulator.html">Android - Emulator</a></li> - </ol> -</div> -</div> - -<p>Android Virtual Devices (AVDs) are configurations of emulator options that let -you better model an actual device.</p> - -<p>Each AVD is made up of: </p> - -<ul> -<li>A hardware profile. You can set options to define the hardware -features of the virtual device. For example, you can define whether the device -has a camera, whether it uses a physical QWERTY keyboard or a dialing pad, how -much memory it has, and so on. </li> -<li>A mapping to a system image. You can define what version of the -Android platform will run on the virtual device. You can choose a version of the -standard Android platform or the system image packaged with an SDK add-on.</li> -<li>Other options. You can specify the emulator skin you want to use -with the AVD, which lets you control the screen dimensions, appearance, and so -on. You can also specify the emulated SD card to use with the AVD.</li> -<li>A dedicated storage area on your development machine, in which is stored the -device's user data (installed applications, settings, and so on) and emulated SD -card.</li> -</ul> - -<p>You can create as many AVDs as you need, based on the types of devices you -want to model and the Android platforms and external libraries you want to run -your application on. </p> - -<p>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 <a -href="{@docRoot}guide/developing/tools/emulator.html">Emulator</a> -documentation. </p> - -<p>The easiest way to create an AVD is to use the graphical AVD Manager, which -you can launch from Eclipse or from the command line using the -<code>android</code> tool. The <code>android</code> tool is provided in the -<code>tools/</code> directory of the Android SDK. When you run the -<code>android</code> tool without options, it launches the graphical AVD -Manager.</p> - -<p>For more information about how to work with AVDs from inside your development -environment, see <a -href="{@docRoot}guide/developing/eclipse-adt.html">Developing in Eclipse with -ADT</a> or <a href="{@docRoot}guide/developing/other-ide.html">Developing in -Other IDEs</a>, as appropriate for your environment.</p> - -<h2 id="creating">Creating an AVD</h2> - -<div class="sidebox-wrapper"> -<div class="sidebox"> -<p>The Android SDK does not include any preconfigured AVDs, so -you need to create an AVD before you can run any application in the emulator -(even the Hello World application).</p> -</div> -</div> -<p>The easiest way to create an AVD is to use the graphical AVD Manager, but the -<code>android</code> tool also offers a <a href="#options">command line option</a>.</p> -<p>To create an AVD:</p> -<ol> - <li>In Eclipse, choose <strong>Window > Android SDK and AVD Manager</strong>. </li> - <p>Alternatively, you can launch the graphical AVD Manager by running the -<code>android</code> tool with no options.</p> - <li>Select <strong>Virtual Devices</strong> in the left panel.</li> - - <li>Click <strong>New</strong>. </li> - -<p>The <strong>Create New AVD</strong> dialog appears.</p> <a -href="{@docRoot}images/developing/avd-dialog.png"><img -src="{@docRoot}images/developing/avd-dialog.png" alt="AVD -Dialog" /></a> - - <li>Type the name of the AVD, such as "my_avd".</li> - <li>Choose a target. </li> -<p>The target is the system image that you want to run on the emulator, -from the set of platforms that are installed in your SDK environment. You can -choose a version of the standard Android platform or an SDK add-on. For more -information about how to add platforms to your SDK, see <a -href="{@docRoot}sdk/adding-components.html">Adding SDK Components</a>. </p> - <li>Optionally specify any additional settings: </li> - <dl> - <dt><em>SD Card</em></dt> <dd>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.</dd> </dl> -<dt><em>Skin</em></dt> - <dd>The skin to use for this AVD, identified by name or dimensions.</dd> -<dt><em>Hardware</em></dt> - <dd>The hardware emulation options for the device. For a list of the options, see -<a href="#hardwareopts">Setting hardware emulation options</a>.</dd> - </dl> - <li>Click <strong>Create AVD</strong>.</li> -</ol> - -<h3 id="hardwareopts">Setting hardware emulation options</h3> - -<p>When you create a new AVD that uses a standard Android system image ("Type: -platform"), the AVD Manager - lets you set hardware emulation -options for your virtual device. -The table below lists the options available and the -default values, as well as the names of properties that store the emulated -hardware options in the AVD's configuration file (the <code>config.ini</code> file in the -AVD's local directory). </p> - -<table> -<tr> -<th>Characteristic</th> -<th>Description</th> -<th>Property</th> -</tr> - -<tr> -<td>Device ram size</td> -<td>The amount of physical RAM on the device, in megabytes. Default value is "96". -<td>hw.ramSize</td> -</tr> - -<tr> -<td>Touch-screen support</td> -<td>Whether there is a touch screen or not on the device. Default value is "yes".</td> -<td>hw.touchScreen - -<tr> -<td>Trackball support </td> -<td>Whether there is a trackball on the device. Default value is "yes".</td> -<td>hw.trackBall</td> -</tr> - -<tr> - -<td>Keyboard support</td> -<td>Whether the device has a QWERTY keyboard. Default value is "yes".</td> -<td>hw.keyboard</td> -</tr> - -<tr> -<td>DPad support</td> -<td>Whether the device has DPad keys. Default value is "yes".</td> -<td>hw.dPad</td> -</tr> - -<tr> -<td>GSM modem support</td> -<td>Whether there is a GSM modem in the device. Default value is "yes".</td> -<td>hw.gsmModem</td> -</tr> - -<tr> -<td>Camera support</td> -<td>Whether the device has a camera. Default value is "no".</td> -<td>hw.camera</td> -</tr> - -<tr> -<td>Maximum horizontal camera pixels</td> -<td>Default value is "640".</td> -<td>hw.camera.maxHorizontalPixels</td> -</tr> - -<tr> -<td>Maximum vertical camera pixels</td> -<td>Default value is "480".</td> -<td>hw.camera.maxVerticalPixels</td> - -</tr> - -<tr> -<td>GPS support</td> -<td>Whether there is a GPS in the device. Default value is "yes".</td> -<td>hw.gps</td> -</tr> - -<tr> -<td>Battery support</td> -<td>Whether the device can run on a battery. Default value is "yes".</td> -<td>hw.battery</td> - -</tr> - -<tr> -<td>Accelerometer</td> -<td>Whether there is an accelerometer in the device. Default value is "yes".</td> -<td>hw.accelerometer</td> -</tr> - -<tr> -<td>Audio recording support</td> -<td>Whether the device can record audio. Default value is "yes".</td> -<td>hw.audioInput</td> - -</tr> - -<tr> -<td>Audio playback support</td> -<td>Whether the device can play audio. Default value is "yes".</td> -<td>hw.audioOutput</td> -</tr> - -<tr> -<td>SD Card support</td> -<td>Whether the device supports insertion/removal of virtual SD Cards. Default value is "yes".</td> -<td>hw.sdCard</td> - -</tr> - -<tr> -<td>Cache partition support</td> -<td>Whether we use a /cache partition on the device. Default value is "yes".</td> -<td>disk.cachePartition</td> -</tr> - -<tr> -<td>Cache partition size</td> -<td>Default value is "66MB".</td> -<td>disk.cachePartition.size </td> - -</tr> - -<tr> -<td>Abstracted LCD density</td> -<td>Sets the generalized density characteristic used by the AVD's screen. Most -skins come with a value (which you can modify), but if a skin doesn't provide -its own value, the default is 160. </td> -<td>hw.lcd.density </td> -</tr> - -<tr> -<td>Max VM application heap size</td> -<td>The maximum heap size a Dalvik application might allocate before being -killed by the system. Value is in megabytes. Most skins come with a value (which -you can modify), but if a skin doesn't provide its own value, the default is -16.</td> -<td>vm.heapSize</td> -</tr> - -</table> - -<h3 id="location">Default location of the AVD files</h3> - -<p>When you create an AVD, the AVD Manager creates a dedicated directory for it -on your development computer. The directory contains the AVD configuration file, -the user data image and SD card image (if available), and any other files -associated with the device. Note that the directory does not contain a system -image — instead, the AVD configuration file contains a mapping to the -system image, which it loads when the AVD is launched. </p> - -<p>The AVD Manager also creates a <code><AVD name>.ini</code> file for the -AVD at the root of the <code>.android/avd</code> directory on your computer. The file -specifies the location of the AVD directory and always remains at the root the -.android directory.</p> - -<p>By default, the AVD Manager creates the AVD directory inside -<code>~/.android/avd/</code> (on Linux/Mac), <code>C:\Documents and -Settings\<user>\.android\</code> on Windows XP, and -<code>C:\Users\<user>\.android\</code> on Windows Vista. -If you want to use a custom location for the AVD directory, you -can do so by using the <code>-p <path></code> option when -you create the AVD (command line tool only): </p> - -<pre>android create avd -n my_android1.5 -t 2 -p path/to/my/avd</pre> - -<p>If the <code>.android</code> directory is hosted on a network drive, we recommend using -the <code>-p</code> option to place the AVD directory in another location. -The AVD's <code>.ini</code> file remains in the <code>.android</code> directory on the network -drive, regardless of the location of the AVD directory. </p> - -<h2 id="managing">Managing AVDs</h2> - -<p>The sections below provide more information about how to manage AVDs once you've created them. </p> - -<h3 id="moving">Moving an AVD</h3> - -<p>If you want to move or rename an AVD, you can do so using this command:</p> - -<pre>android move avd -n <name> [-<option> <value>] ...</pre> - -<p>The options for this command are listed in <a href="#options">Command-line -options for AVDs</a> at the bottom of this page. </p> - -<h3 id="updating">Updating an AVD</h3> - -<p> -If you rename or move the root directory of a platform (or add-on), an AVD configured to use that platform will no longer be able to load the system image properly. To fix the AVD, use the <strong>Repair...</strong> button in the AVD Manager. From the command line, you can also use the <code>android update avd</code> command to recompute the path to the system images.</p> - -<h3 id="deleting">Deleting an AVD</h3> - -<p>You can delete an AVD in the AVD Manager by selecting the -AVD and clicking <strong>Delete</strong>.</p> - -<p>Alternatively, you can use the <code>android</code> tool to delete an AVD. Here is the command usage:</p> - -<pre>android delete avd -n <name> </pre> - -<p>When you issue the command, the <code>android</code> tool looks for an AVD matching the -specified name deletes the AVD's directory and files. </p> - - -<h2 id="options">Command-line options</h2> - -<p>You can use the <code>android</code> tool to create and manage AVDs.</p> - -<p>The command line for creating an AVD has the following syntax:</p> - -<pre> -android create avd -n <name> -t <targetID> [-<option> <value>] ... -</pre> - -<p>Here's an example that creates an AVD with the name "my_android2.2" and target ID "3":</p> - -<pre> -android create avd -n my_android2.2 -t 3 -</pre> - -<p>The table below lists the command-line options you can use with the -<code>android</code> tool. </p> - - -<table> -<tr> - <th width="15%">Action</th> - <th width="20%">Option</th> - <th width="30%">Description</th> - <th>Comments</th> -</tr> - - -<tr> - <td><code>list avds</code></td> - <td> </td> - <td>List all known AVDs, with name, path, target, and skin. </td> - <td> </td> -</tr> -<tr> - <td rowspan="6"><code>create avd</code></td> - <td><code>-n <name> or <br></code></td> - <td>The name for the AVD.</td> - <td>Required</td> -</tr> -<tr> - <td><code>-t <targetID></code></td> - <td>Target ID of the system image to use with the new AVD.</td> - <td>Required. To obtain a list of available targets, use <code>android list - targets</code>.</td> -</tr> -<tr> - <td><code>-c <path></code> or <br> - <code>-c <size>[K|M]</code></td> - <td>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.</td> - <td>Examples: <code>-c path/to/sdcard</code> or <code>-c 1000M</code></td> -</tr> -<tr> - <td><code>-f</code></td> - <td>Force creation of the AVD</td> - <td>By default, if the name of the AVD being created matches that of an - existing AVD, the <code>android</code> tool will not create the new AVD or overwrite - the existing AVD. If you specify the <code>-f</code> option, however, the - <code>android</code> 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. </td> -</tr> - -<tr> - <td><code>-p <path></code></td> - <td>Path to the location at which to create the directory for this AVD's -files.</td> - <td> </td> -</tr> -<tr> - <td><code>-s <name></code> or <br> - <code>-s <width>-<height></code> </td> - <td>The skin to use for this AVD, identified by name or dimensions.</td> - <td>The <code>android</code> tool scans for a matching skin by name or dimension in the -<code>skins/</code> directory of the target referenced in the <code>-t -<targetID></code> argument. Example: <code>-s HVGA-L</code></td> -</tr> -<tr> - <td><code>delete avd</code></td> - <td><code>-n <name></code></td> - <td>Delete the specified AVD.</td> - <td>Required</td> -</tr> -<tr> - <td rowspan="3"><code>move avd</code></td> - <td><code>-n <name></code></td> - <td>The name of the AVD to move.</td> - <td>Required</td> -</tr> -<tr> - <td><code>-p <path></code></td> - <td>The path to the new location for the AVD.</td> - <td> </td> -</tr> -<tr> - <td><code>-r <new-name></code></td> - <td>Rename the AVD.</td> - <td> </td> -</tr> -<tr> - <td><code>update avds</code></td> - <td> </td> - <td>Recompute the paths to all system images.</td> - <td> </td> -</tr> - - - -</table> - diff --git a/docs/html/guide/developing/tools/ddms.html b/docs/html/guide/developing/tools/ddms.html new file mode 100644 index 0000000..052ccc9 --- /dev/null +++ b/docs/html/guide/developing/tools/ddms.html @@ -0,0 +1,10 @@ +<html> +<head> +<meta http-equiv="refresh" content="0;url=http://developer.android.com/guide/developing/debugging/ddms.html"> +<title>Redirecting...</title> +</head> +<body> +<p>You should be redirected. Please <a +href="http://developer.android.com/guide/developing/debugging/ddms.html">click here</a>.</p> +</body> +</html>
\ No newline at end of file diff --git a/docs/html/guide/developing/tools/ddms.jd b/docs/html/guide/developing/tools/ddms.jd deleted file mode 100644 index f55940d..0000000 --- a/docs/html/guide/developing/tools/ddms.jd +++ /dev/null @@ -1,251 +0,0 @@ -page.title=Using the Dalvik Debug Monitor -@jd:body - -<p>Android ships with a debugging tool called the Dalvik Debug Monitor Server (DDMS), - which provides port-forwarding services, screen capture on the device, thread - and heap information on the device, logcat, process, and radio state information, - incoming call and SMS spoofing, location data spoofing, and more. This page - provides a modest discussion of DDMS features; it is not an exhaustive exploration of - all the features and capabilities.</p> - -<p>DDMS ships in the <code>tools/</code> directory of the SDK. - Enter this directory from a terminal/console and type <code>ddms</code> (or <code>./ddms</code> - on Mac/Linux) to run it. DDMS will work with both the emulator and a connected device. If both are - connected and running simultaneously, DDMS defaults to the emulator.</p> - -<h2 id="how-ddms-works">How DDMS works</h2> -<p>DDMS acts as a middleman to connect the IDE to the applications running on -the device. On Android, every application runs in its own process, -each of which hosts its own virtual machine (VM). And each process -listens for a debugger on a different port.</p> - -<p>When it starts, DDMS connects to <a href="{@docRoot}guide/developing/tools/adb.html">adb</a> and -starts a device monitoring service between the two, which will notify DDMS when a device is -connected or disconnected. When a device is connected, a VM monitoring service is created -between adb and DDMS, which will notify DDMS when a VM on the device is started -or terminated. Once a VM is running, DDMS retrieves the the VM's process ID (pid), via adb, -and opens a connection to the VM's debugger, through the adb daemon (adbd) on the device. -DDMS can now talk to the VM using a custom wire protocol.</p> - -<p>For each VM on the device, DDMS opens a port upon which it will listen for a debugger. For the first VM, DDMS listens for a debugger on port 8600, the next on 8601, and so on. When a debugger connects to one of these ports, all traffic is forwarded between the debugger and the associated VM. Debugging can then process like any remote debugging session.</p> - -<p>DDMS also opens another local port, the DDMS "base port" (8700, by default), upon which it also listens for a debugger. When a debugger connects to this base port, all traffic is forwarded to the VM currently selected in DDMS, so this is typically where you debugger should connect.</p> - -<p>For more information on port-forwarding with DDMS, -read <a href="{@docRoot}guide/developing/debug-tasks.html#ide-debug-port">Configuring your IDE to attach -to port 8700 for debugging</a>.</p> - -<p class="note"><strong>Tip:</strong> -You can set a number of DDMS preferences in <strong>File</strong> > <strong>Preferences</strong>. -Preferences are saved to "$HOME/.ddmsrc". </p> - -<p class="warning"><strong>Known debugging issues with Dalvik</strong><br/> -Debugging an application in the Dalvik VM should work the same as it does -in other VMs. However, when single-stepping out of synchronized code, the "current line" -cursor may jump to the last line in the method for one step.</p> - - -<h2 id="left-pane">Left Pane</h2> -<p>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.</p> -<p>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.</p> -<p>When an application running on the device calls {@link android.os.Debug#waitForDebugger()} - (or you select this option in the <a href="{@docRoot}guide/developing/debug-tasks.html#additionaldebugging">developer - options</a>), 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. </p> -<p>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).</p> -<p>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.</p> - - -<h2 id="right-pane">Right pane</h2> -<p>On the right side, the Debug Monitor provides tabs that display useful information -and some pretty cool tools.</p> - -<h3 id="info">Info</h3> -<p>This view shows some general information about the selected VM, including the process - ID, package name, and VM version.</p> - -<h3 id="threads">Threads</h3> -<p> 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: </p> -<ul> - <li> <strong>ID</strong> - a VM-assigned unique thread ID. In Dalvik, these are - odd numbers starting from 3. </li> - <li> <strong>Tid</strong> - the Linux thread ID. For the main thread in a process, - this will match the process ID. </li> - <li> <strong>Status</strong> - the VM thread status. Daemon threads are - shown with an asterisk (*). This will be one of the following: - <ul> - <li> <em>running</em> - executing application code </li> - <li> <em>sleeping</em> - called Thread.sleep() </li> - <li> <em>monitor</em> - waiting to acquire a monitor lock </li> - <li> <em>wait</em> - in Object.wait() </li> - <li> <em>native</em> - executing native code </li> - <li> <em>vmwait</em> - waiting on a VM resource </li> - <li> <em>zombie</em> - thread is in the process of dying </li> - <li> <em>init</em> - thread is initializing (you shouldn't see this) </li> - <li> <em>starting</em> - thread is about to start (you shouldn't see - this either) </li> - </ul> - </li> - <li> <strong>utime</strong> - cumulative time spent executing user code, in "jiffies" (usually - 10ms). </li> - <li> <strong>stime</strong> - cumulative time spent executing system code, in "jiffies" (usually - 10ms). </li> - <li> <strong>Name</strong> - the name of the thread</li> -</ul> -<p> "ID" and "Name" are set when the thread is started. The remaining - fields are updated periodically (default is every 4 seconds). </p> - -<h3 id="vm-heap">VM Heap</h3> -<p> 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 <strong>Cause GC</strong> -to perform garbage collection and update the heap stats.</p> - - -<h3 id="allocation-tracker">Allocation Tracker</h3> -<p>In this view, you can track the memory allocation of each virtual machine. -With a VM selected in the left pane, click <strong>Start Tracking</strong>, then -<strong>Get Allocations</strong> 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.</p> - - -<h3 id="emulator-control">Emulator Control</h3> -<p>With these controls, you can simulate special device states and activities. -Features include:</p> -<ul> -<li><strong>Telephony Status</strong> - 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.).</li> -<li><strong>Telephony Actions</strong> - perform simulated phone calls and SMS messages to the emulator.</li> -<li><strong>Location Controls</strong> - send mock location data to the emulator so that you can perform - location-aware operations like GPS mapping. - -<p>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:</p> -<ul class="listhead"> - <li>Manually send individual longitude/latitude coordinates to the device. - <p>Click <strong>Manual</strong>, - select the coordinate format, fill in the fields and click <strong>Send</strong>. - </p> - </li> - <li>Use a GPX file describing a route for playback to the device. - <p>Click <strong>GPX</strong> and load the file. Once loaded, - click the play button to playback the route for your location-aware application.</p> - <p>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 (<code><wpt></code>, in the first table), - and the tracks (<code><trk></code>, - in the second table, with support for multiple segments, <code><trkseg></code>, - 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.</p> - </li> - <li>Use a KML file describing individual placemarks for sequenced playback to the device. - <p>Click <strong>KML</strong> and load the file. Once loaded, - click the play button to send the coordinates to your location-aware application.</p> - <p>When using a KML file, it is parsed for a <code><coordinates></code> - element. The value of which should be a single - set of longitude, latitude and altitude figures. For example:</p> - <pre><coordinates>-122.084143,37.421972,4</coordinates></pre> - <p>In your file, you may include multiple <code><Placemark></code> elements, each containing - a <code><coordinates></code> element. When you do so, the collection of placemarks will - be added as tracks. DDMS will send one placemark per second to the device.</p> - <p>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.</p> -<p class="note"><strong>Note:</strong> DDMS does not support routes created with the -<code><MultiGeometry><LineString>lat1, long1, lat2, long2, ....</LineString></MultiGeometry></code> methods. - There is also currently no support for the <code><TimeStamp></code> node inside - the <code><Placemark></code>. - Future releases may support timed placement and routes within a single coordinate element.</p> - </li> - </ul> - <p>For <em>additional</em> methods of setting up mocks of location-based data, see the - <a href="{@docRoot}guide/topics/location/index.html">Location</a> topic.</p> - </li> -</ul> - - -<!-- <h4>Event Log</h4> --> - - -<h2 id="file-explorer">File Explorer</h2> -<p>With the File Explorer, you can view the device file system and perform basic management, -like pushing and pulling files. This circumvents using the <a href="{@docRoot}guide/developing/tools/adb.html">adb</a> -<code>push</code> and <code>pull</code> commands, with a GUI experience.</p> -<p>With DDMS open, select <strong>Device</strong> > <strong>File Explorer...</strong> to open the -File Explorer window. You can drag-and-drop into the device directories, but cannot drag <em>out</em> of them. -To copy files from the device, select the file and click the <strong>Pull File from Device</strong> -button in the toolbar. To delete files, use the <strong>Delete</strong> button in the toolbar.</p> -<p>If you're interested in using an SD card image on the emulator, you're still required to use -the <code>mksdcard</code> command to create an image, and then mount it during emulator bootup. -For example, from the <code>/tools</code> directory, execute:</p> -<pre> -<b>$</b> mksdcard 1024M ./img -<b>$</b> emulator -sdcard ./img -</pre> -<p>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.)</p> -<p>For more information on creating an SD card image, see the -<a href="{@docRoot}guide/developing/tools/othertools.html#mksdcard">Other Tools</a> document.</p> - -<h2 id="screen-capture">Screen Capture</h2> -<p>You can capture screen images on the device or emulator by selecting <strong>Device</strong> - > <strong>Screen capture...</strong> in the menu bar, or press CTRL-S. - Be sure to select a device first.</p> - -<h2 id="exploring-processes">Exploring Processes</h2> -<p>You can see the output of <code>ps -x</code> for a specific VM by selecting <strong>Device</strong> - > <strong>Show process status</strong>... in the menu bar.</p> - -<h2 id="cause-a-gc-to-occur">Cause a GC to Occur</h2> -<p>Cause garbage collection to occur in the selected application by pressing the trash can button on the toolbar. </p> - -<h2 id="running-dumpsys-and-dumpstate">Running Dumpsys and Dumpstate on the Device (logcat)<a name="logcat" id="logcat"></a> </h2> -<ul> - <li>To run <strong>dumpsys</strong> (logcat) from Dalvik, select <strong>Device</strong> > - <strong>Run logcat...</strong> in the menu bar.</li> - <li>To run <strong>dumpstate</strong> from Dalvik, select <strong>Device</strong> > <strong>Dump device - state...</strong> in the menu bar. </li> -</ul> - -<h2 id="examine-radio-state">Examine Radio State</h2> -<p>By default, radio state is not output during a standard logcat (it is a lot of - information). To see radio information, either click <strong>Device</strong> > <strong>Dump radio - state...</strong> or run logcat as described in <a href="{@docRoot}guide/developing/debug-tasks.html#logradio">Logging - Radio Information</a>. </p> - -<h2 id="stop-a-vitrual-machine">Stop a Virtual Machine </h2> -<p>You can stop a virtual machine by selecting <strong>Actions</strong> > <strong>Halt -VM</strong>. Pressing this button causes the VM to call <code>Runtime.halt(1)</code>.</p> - -<h2 id="known-issues" style="color:#FF0000">Known issues with DDMS </h2> -<p>DDMS has the following known limitations:</p> -<ul> - <li>If you connect and disconnect a debugger, ddms drops and reconnects the - client so the VM realizes that the debugger has gone away. This will be fixed - eventually. </li> -</ul> diff --git a/docs/html/guide/developing/tools/dmtracedump.jd b/docs/html/guide/developing/tools/dmtracedump.jd new file mode 100644 index 0000000..492a049 --- /dev/null +++ b/docs/html/guide/developing/tools/dmtracedump.jd @@ -0,0 +1,64 @@ +page.title=dmtracedump +@jd:body + + + <p><code>dmtracedump</code> is a tool that gives you an alternate way of generating + graphical call-stack diagrams from trace log files (instead of using Traceview).</p> + + <p>This document is a reference to the available command line options. For more information on generating trace + logs, see <a href="{@docRoot}guide/developing/debugging/debugging-tracing.html">Profiling with + Traceview and dmtracedump</a>.</p> + + <p>The usage for <code>dmtracedump</code> is:</p> + <pre> +dmtracedump [-ho] [-s sortable] [-d trace-base-name] [-g outfile] <trace-base-name> +</pre> + + <p>The tool then loads trace log data from <code><trace-base-name>.data</code> and + <trace-base-name>.key. The table below lists the options for dmtracedump.</p> + + <table> + <tr> + <th>Option</th> + + <th>Description</th> + </tr> + + <tr> + <td><nobr><code>-d <em><trace-base-name></em></code></nobr></td> + + <td>Diff with this trace name</td> + </tr> + + <tr> + <td><code>-g <em><outfile></em></code></td> + + <td>Generate output to <outfile></td> + </tr> + + <tr> + <td><code>-h</code></td> + + <td>Turn on HTML output</td> + </tr> + + <tr> + <td><code>-o</code></td> + + <td>Dump the trace file instead of profiling</td> + </tr> + + <tr> + <td><code>-d <em><trace-base-name></em></code></td> + + <td>URL base to the location of the sortable javascript file</td> + </tr> + + <tr> + <td><code>-t <percent></code></td> + + <td>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%.</td> + </tr> + </table>
\ No newline at end of file diff --git a/docs/html/guide/developing/tools/emulator.jd b/docs/html/guide/developing/tools/emulator.jd index 2250979..9baf1a1 100644 --- a/docs/html/guide/developing/tools/emulator.jd +++ b/docs/html/guide/developing/tools/emulator.jd @@ -1,321 +1,29 @@ page.title=Android Emulator @jd:body - -<div style="padding:1em;"><img src="/images/emulator-wvga800l.png" alt="Image of the Android Emulator" width="367" height="349" style="margin-left:2em;margin-top:-4em;float:right;"/></div> - -<p>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. </p> - -<p>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. </p> - -<p>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. </p> - -<p>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.</p> - -<table> -<tr> -<td colspan="2" style="border:0;"><strong>In this document:</strong></td> -</tr> -<tr> -<td style="border:0;"> - -<ol class="toc"> -<li><a href="#overview">Overview</a></li> -<li><a href="#starting">Starting and Stopping the Emulator</a></li> -<li><a href="#starting">Android Virtual Devices and the Emulator</a></li> -<li><a href="#controlling">Controlling the Emulator</a></li> -<li><a href="#startup-options">Emulator Startup Options</a></li> -<li><a href="#diskimages">Working with Emulator Disk Images</a> - <ol class="toc"> - <li><a href="#defaultimages">Default Images</a></li> - <li><a href="#runtimeimages">Runtime Images: User Data and SD Card</a></li> - <li><a href="#temporaryimages">Temporary Images</a></li> - </ol></li> -<li><a href="#emulatornetworking">Emulator Networking</a> - <ol class="toc"> - <li><a href="#networkaddresses">Network Address Space</a></li> - <li><a href="#networkinglimitations">Local Networking Limitations</a></li> - <li><a href="#redirections">Using Network Redirections</a></li> - <li><a href="#dns">Configuring the Emulator's DNS Settings</a></li> - <li><a href="#proxy">Using the Emulator with a Proxy</a></li> - <li><a href="#connecting">Interconnecting Emulator Instances</a></li> - <li><a href="#calling">Sending a Voice Call or SMS to Another Emulator Instance</a></li> - </ol></li> -</ol> -</td> - -<td style="border:0;"> -<ol class="toc"> -<li><a href="#console">Using the Emulator Console</a> - <ol class="toc"> - <li><a href="#portredirection">Port Redirections</a></li> - <li><a href="#geo">Geo Location Provider Emulation</a></li> - <li><a href="#events">Sending Events</a></li> - <li><a href="#power">Emulating Device Power Characteristics</a></li> - <li><a href="#netstatus">Network Status</a></li> - <li><a href="#netdelay">Network Delay Emulation</a></li> - <li><a href="#netspeed">Network Speed Emulation</a></li> - <li><a href="#telephony">Telephony Emulation</a></li> - <li><a href="#sms">SMS Emulation</a></li> - <li><a href="#vm">VM State</a></li> - <li><a href="#window">Emulator Window</a></li> - <li><a href="#terminating">Terminating an Emulator Instance</a></li> - </ol></li> -<li><a href="#skins">Using Emulator Skins</a></li> -<li><a href="#multipleinstances">Running Multiple Instances of the Emulator</a></li> -<li><a href="#apps">Installing Applications on the Emulator</a></li> -<li><a href="#sdcard">SD Card Emulation</a> - <ol class="toc"> - <li><a href="#creatinga">Creating an SD card image using the android tool</li> - <li><a href="#creatingm">Creating an SD card image using mksdcard</a></li> - <li><a href="#copying">Copying Files to a Disk Image</a></li> - <li><a href="#loading">Loading the Disk Image at Emulator Startup</a></li> - </ol></li> -<li><a href="#troubleshooting">Troubleshooting Emulator Problems</a></li> -<li><a href="#limitations">Emulator Limitations</a></li> -</ol> -</td> - -</table> - -<a name="overview"></a> - -<h2>Overview</h2> - -<p>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. -</p> - -<p>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. </p> - -<p>Adding custom capabilities to the underlying QEMU services, the Android -emulator supports many hardware features likely to be found on mobile devices, -including: </p> - -<ul> - <li>An ARMv5 CPU and the corresponding memory-management unit (MMU)</li> - <li>A 16-bit LCD display</li> - <li>One or more keyboards (a Qwerty-based keyboard and associated Dpad/Phone -buttons)</li> - <li>A sound chip with output and input capabilities</li> - <li>Flash memory partitions (emulated through disk image files on the -development machine)</li> - <li>A GSM modem, including a simulated SIM Card</li> -</li> -</ul> - -<p>The sections below provide more information about the emulator and how to use -it for developing Android applications.</p> - -<a name="starting"></a> - -<h2>Starting and Stopping the Emulator</h2> - -<p>During development and testing of your application, you install and run your -application in the Android emulator. You can launch the emulator as a standalone -application, from a command line, or you can use it as part of your Eclipse -development environment. In either case, you specify the AVD configuration to -load and any startup options you want to use, as described in this document. -</p> - -<p>You can run your application on a single instance of the emulator or, -depending on your needs, you can start multiple emulator instances and run your -application in more than one emulated device. You can use the emulator's -built-in commands to simulate GSM phone calling or SMS between emulator -instances, and you can set up network redirections that allow emulators to send -data to one another. For more information, see <a href="#telephony">Telephony -Emulation</a>, <a href="#sms">SMS Emulation</a>, and -<a href="#emulatornetworking">Emulator Networking</a></p> - -<p>To start an instance of the emulator from the command line, change to the -<code>tools/</code> folder of the SDK. Enter <code>emulator</code> command -like this: </p> - -<pre>emulator -avd <avd_name></pre> - -<p>This initializes the emulator and loads an AVD configuration (see the next -section for more information about AVDs). You will see the emulator window -appear on your screen. </p> - -<p>If you are working in Eclipse, the ADT plugin for Eclipse installs your -application and starts the emulator automatically, when you run or debug -the application. You can specify emulator startup options in the Run/Debug -dialog, in the Target tab. When the emulator is running, you can issue -console commands as described later in this document.</p> - -<p>If you are not working in Eclipse, see <a href="#apps">Installing Applications -on the Emulator</a> for information about how to install your application.</p> - -<p>To stop an emulator instance, just close the emulator's window.</p> - -<a name="controlling"></a> - -<a name="avds"></a> - -<h2>Android Virtual Devices and the Emulator</h2> - -<p>To use the emulator, you first must create one or more AVD configurations. In each -configuration, you specify an Android platform to run in the emulator and the set of hardware -options and emulator skin you want to use. Then, when you launch the emulator, you specify -the AVD configuration that you want to load. </p> - -<p>To specify the AVD you want to load when starting the emulator, you use the -<code>-avd</code> argument, as shown in the previous section. </p> - -<p>Each AVD functions as an independent device, with its own private storage for -user data, SD card, and so on. When you launch the emulator with an AVD configuration, -it automatically loads the user data and SD card data from the AVD directory. By default, -the emulator stores the user data, SD card data, and cache in the AVD directory.</p> - -<p>To create and manage AVDs you use the android tool, a command-line utility -included in the SDK. For complete information about how to set up AVDs, see <a -href="{@docRoot}guide/developing/tools/avd.html">Android Virtual Devices</a>.</p> - -<h2>Controlling the Emulator</h2> - -<p>You can use emulator <a href="#startup-options">startup options</a> and <a -href="#console">console commands</a> to control the behaviors and -characteristics of the emulated environment itself. -</p> +<p> +<p>The Android SDK includes a mobile device emulator — a virtual mobile device +that runs on your computer. The emulator lets you develop and test +Android applications without using a physical device.</p> <p>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. </p> - -<p>The table below summarizes the mappings between the emulator keys and and -the keys of your keyboard. </p> - -<table border="0" style="clear:left;"> - <tr> - <th>Emulated Device Key </th> - <th>Keyboard Key </th> - </tr> - <tr> - <td>Home</td> - <td>HOME</td> - </tr> - <tr> - <td>Menu (left softkey)</td> - <td>F2 <em>or</em> Page-up button</td> - </tr> - <tr> - <td>Star (right softkey)</td> - <td>Shift-F2 <em>or </em>Page Down</td> - </tr> - <tr> - <td>Back</td> - <td>ESC</td> - </tr> - <tr> - <td>Call/dial button </td> - <td>F3</td> - </tr> - <tr> - <td>Hangup/end call button</td> - <td>F4</td> - </tr> - <tr> - <td>Search</td> - <td>F5 </td> - </tr> - <tr> - <td>Power button</td> - <td>F7 </td> - </tr> - <tr> - <td>Audio volume up button</td> - <td>KEYPAD_PLUS, Ctrl-5</td> - </tr> +pointer to "touch" the touchscreen and can use some keyboard keys to +invoke certain keys on the device. </p> - <tr> - <td>Audio volume down button</td> - <td>KEYPAD_MINUS, Ctrl-F6</td> - </tr> - <tr> - <td>Camera button</td> - <td>Ctrl-KEYPAD_5, Ctrl-F3</td> - </tr> - <tr> - <td>Switch to previous layout orientation (for example, portrait, landscape)</td> - <td>KEYPAD_7, Ctrl-F11</td> - </tr> - <tr> - <td>Switch to next layout orientation (for example, portrait, landscape)</td> - <td>KEYPAD_9, Ctrl-F12</td> - </tr> - <tr> - <td>Toggle cell networking on/off</td> - <td>F8</td> - </tr> - <tr> - <td>Toggle code profiling</td> - <td>F9 (only with <code>-trace</code> startup option)</td> - </tr> - <tr> - <td>Toggle fullscreen mode</td> - <td>Alt-Enter</td> - </tr> - <tr> - <td>Toggle trackball mode</td> - <td>F6</td> - </tr> - <tr> - <td>Enter trackball mode temporarily (while key is pressed)</td> - <td>Delete</td> - </tr> - <tr> - <td>DPad left/up/right/down</td> - <td>KEYPAD_4/8/6/2</td> - </tr> - <tr> - <td>DPad center click</td> - <td>KEYPAD_5</td> - </tr> - <tr> - <td>Onion alpha increase/decrease</td> - <td>KEYPAD_MULTIPLY(*) / KEYPAD_DIVIDE(/)</td> - </tr> -</table> +<p>This document is a reference to the available command line options and the keyboard mapping to device keys. +For a complete guide to using the Android Emulator, see +<a href="{@docRoot}guide/developing/devices/emulator.html">Using the Android Emulator</a>. -<p>Note that, to use keypad keys, you must first disable NumLock on your development computer. </p> -<a name="startup-options"></a> +<h2 id="startup-options">Emulator Startup Options</h2> -<h2> Emulator Startup Options</h2> <p>The emulator supports a variety of options that you can specify when launching the emulator, to control its appearance or behavior. Here's the command-line usage for launching the emulator with options: </p> <pre>emulator -avd <avd_name> [-<option> [<value>]] ... [-<qemu args>]</pre> -<p>The table below summarizes the available options.</p> +<p class="table-caption"><strong>Table 1.</strong>Emulator startup options</p> <table> <tr> @@ -377,8 +85,8 @@ Here's the command-line usage for launching the emulator with options: </p> <td><strong>Required</strong>. Specifies the AVD to load for this emulator instance.</td> <td>You must create an AVD configuration before launching the emulator. For - information, see <a href="{@docRoot}guide/developing/tools/avd.html">Android - Virtual Devices</a>.</td> + information, see <a href="{@docRoot}guide/developing/devices/managing-avds.html#createavd"> + Creating and Managing AVDs with AVD Manager</a>.</td> <tr> <td rowspan="7">Disk Images</td> <td><code>-cache <filepath></code></td> @@ -731,7 +439,8 @@ option. Using this option may yield unexpected and in some cases misleading results, since the density with which to render the skin may not be defined. AVDs let you associate each skin with a default density and override the default as needed. For more information, see <a -href="{@docRoot}guide/developing/tools/avd.html">Android Virtual Devices</a>. +href="{@docRoot}guide/developing/devices/managing-avds.html#createavd"> +Creating and Managing Virtual Devices with AVD Manager</a>. </td> </tr> <tr> @@ -740,1032 +449,100 @@ href="{@docRoot}guide/developing/tools/avd.html">Android Virtual Devices</a>. <td>See comments for <code>-skin</code>, above.</td></tr> </table> -<a name="diskimages"></a> - -<h2>Working with Emulator Disk Images</h2> - -<p>The emulator uses mountable disk images stored on your development machine to -simulate flash (or similar) partitions on an actual device. For example, it uses -disk image containing an emulator-specific kernel, the Android system, a -ramdisk image, and writeable images for user data and simulated SD card.</p> - -<p>To run properly, the emulator requires access to a specific set of disk image -files. By default, the Emulator always looks for the disk images in the -private storage area of the AVD in use. If no images exist there when -the Emulator is launched, it creates the images in the AVD directory based on -default versions stored in the SDK. </p> - -<p class="note"><strong>Note:</strong> The default storage location for -AVDs is in <code>~/.android/avd</code> on OS X and Linux, <code>C:\Documents and -Settings\<user>\.android\</code> on Windows XP, and -<code>C:\Users\<user>\.android\</code> -on Windows Vista.</p> - -<p>To let you use alternate or custom versions of the image files, the emulator -provides startup options that override the default locations and filenames of -the image files. When you use the options, the emulator searches for the image -file under the image name or location that you specify; if it can not locate the -image, it reverts to using the default names and location.</p> - -<p>The emulator uses three types of image files: default image files, runtime -image files, and temporary image files. The sections below describe how to -override the location/name of each type of file. </p> - -<a name="defaultimages"></a> -<h3>Default Images</h3> - -<p>When the emulator launches but does not find an existing user data image in -the active AVD's storage area, it creates a new one from a default version -included in the SDK. The default user data image is read-only. The image -files are read-only.</p> - -<p>The emulator provides the <code>-system <dir></code> startup option to -let you override the location under which the emulator looks for the default -user data image. </p> - -<p>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 <code>-system <dir></code>). </p> - - -<table> -<tr> - <th width="10%" >Name</th> - <th width="30%" >Description</th> - <th width="40%" >Comments</th> -</tr> - -<!-- -<tr> - <td><code>kernel-qemu.img</code></td> - <td>The emulator-specific Linux kernel image</td> - <td>Override using <code>-kernel <file></code></td> -</tr> - -<tr> - <td><code>ramdisk.img</code></td> - <td>The ramdisk image used to boot the system.</td> - <td>Override using <code>-ramdisk <file></code></td> -</tr> - -<tr> - <td><code>system.img</code></td> - <td>The <em>initial</em> Android system image.</td> - <td>Override using <code>-image <file></code></td> -</tr> ---> -<tr> - <td><code>userdata.img</code></td> - <td>The <em>initial</em> user-data disk image</td> - <td>Override using <code>-initdata <file></code>. Also see -<code>-data <file></code>, below.</td> -</tr> - -</table> - -<a name="runtimeimages"></a> -<h3>Runtime Images: User Data and SD Card</h3> - -<p>At runtime, the emulator reads and writes data on two disk images: a -user-data image and (optionally) an SD card image. This emulates the user-data -partition and removable storage media on actual device. </p> - -<p>The emulator provides a default user-data disk image. At startup, the emulator -creates the default image as a copy of the system user-data image (user-data.img), -described above. The emulator stores the new image with the files of the active AVD.</p> - -<!-- -<p>The emulator provides a startup option, <code>-datadir <dir></code>, -that you can use to override the location under which the emulator looks for the runtime -image files. </p> ---> - -<p>The emulator provides startup options to let you override the actual names and storage -locations of the runtime images to load, as described in the table below. When you use one -of these options, the emulator looks for the specified file(s) in the current working directory, -in the AVD directory, or in a custom location (if you specified a path with the filename). </p> - -<table> -<tr> - <th width="10%" >Name</th> - <th width="30%" >Description</th> - <th width="40%" >Comments</th> -</tr> -<tr> - <td><code>userdata-qemu.img</code></td> - <td>An image to which the emulator writes runtime user-data for a unique user.</td> - <td>Override using <code>-data <filepath></code>, where <code><filepath></code> is the -path the image, relative to the current working directory. If you supply a filename only, -the emulator looks for the file in the current working directory. If the file at <code><filepath></code> does -not exist, the emulator creates an image from the default userdata.img, stores it under the name you -specified, and persists user data to it at shutdown. </td> -</tr> - -<tr> - <td><code>sdcard.img</code></td> - <td>An image representing an SD card inserted into the emulated device.</td> - <td>Override using <code>-sdcard <filepath></code>, where <code><filepath></code> is the -path the image, relative to the current working directory. If you supply a filename only, -the emulator looks for the file in the current working directory. </td> -</tr> - -</table> - -<h4>User-Data Image</h4> - -<p>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. </p> - -<p>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. </p> - -<ul> -<li>If it finds a user-data image, it mounts the image and makes it available -to the system for reading/writing of user data. </li> -<li>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 <code>-data</code> startup option.</li> -</ul> - -<p class="note"><strong>Note:</strong> 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 <code>-d</code> option to specify an instance-specific storage area.</p> - -<h4>SD Card</h4> - -<P>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 <a href="#sdcard">SD Card Emulation</a></p> - -<p>You can also use the android tool to automatically create an SD Card image -for you, when creating an AVD. For more information, see <a -href="{@docRoot}guide/developing/tools/avd.html#options">Command-line options for AVDs</a>. - -<a name="temporaryimages"></a> -<h3>Temporary Images</h3> - -<p>The emulator creates two writeable images at startup that it deletes at -device power-off. The images are: </p> - -<ul> - <li>A writable copy of the Android system image</li> - <li>The <code>/cache</code> partition image</li> -</ul> - -<p>The emulator does not permit renaming the temporary system image or -persisting it at device power-off. </p> - -<p>The <code>/cache</code> partition image is initially empty, and is used by -the browser to cache downloaded web pages and images. The emulator provides an -<code>-cache <file></code>, which specifies the name of the file at which -to persist the <code>/cache</code> image at device power-off. If <code><file> -</code> does not exist, the emulator creates it as an empty file. </p> - -<p>You can also disable the use of the cache partition by specifying the -<code>-nocache</code> option at startup. </p> - - -<a name="emulatornetworking"></a> -<h2>Emulator Networking</h2> - -<p>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. -</p> - -<a name="networkaddresses"></a> -<h3>Network Address Space</h3> - -<p>Each instance of the emulator runs behind a virtual router/firewall service -that isolates it from your development machine's network interfaces and settings -and from the internet. An emulated device can not see your development machine -or other emulator instances on the network. Instead, it sees only that it is -connected through Ethernet to a router/firewall.</p> - -<p>The virtual router for each instance manages the 10.0.2/24 network address -space — all addresses managed by the router are in the form of -10.0.2.<xx>, where <xx> is a number. Addresses within this space are -pre-allocated by the emulator/router as follows:</p> - -<table> +<h2>Emulator Keyboard Mapping</h2> +<p>The table below summarizes the mappings between the emulator keys and and +the keys of your keyboard. </p> +<p class="table-caption"><strong>Table 2.</strong> Emulator keyboard mapping</p> +<table border="0" style="clear:left;"> <tr> - <th>Network Address</th> - <th>Description</th> + <th>Emulated Device Key </th> + <th>Keyboard Key </th> </tr> <tr> - <td>10.0.2.1</td> - <td>Router/gateway address </td> + <td>Home</td> + <td>HOME</td> </tr> <tr> - <td>10.0.2.2</td> - <td>Special alias to your host loopback interface (i.e., 127.0.0.1 on your -development machine)</td> + <td>Menu (left softkey)</td> + <td>F2 <em>or</em> Page-up button</td> </tr> <tr> - <td>10.0.2.3</td> - <td>First DNS server</td> + <td>Star (right softkey)</td> + <td>Shift-F2 <em>or </em>Page Down</td> </tr> <tr> - <td>10.0.2.4 / 10.0.2.5 / 10.0.2.6</td> - <td>Optional second, third and fourth DNS server (if any) </td> + <td>Back</td> + <td>ESC</td> </tr> <tr> - <td>10.0.2.15</td> - <td>The emulated device's own network/ethernet interface</td> + <td>Call/dial button </td> + <td>F3</td> </tr> <tr> - <td>127.0.0.1</td> - <td>The emulated device's own loopback interface </td> + <td>Hangup/end call button</td> + <td>F4</td> </tr> -</table> - -<p>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 -<em>not</em> see each other on the same network. For information about how to -let emulator instances communicate over TCP/UDP, see <a -href="#connecting">Connecting Emulator Instances</a>.</p> - -<p>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.</p> - -<p>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)</p> - -<a name="networkinglimitations"></a> -<h3>Local Networking Limitations</h3> - -<p>Each emulator instance runs behind a virtual router, but unlike an actual -device connected to a physical router, the emulated device doesn't have access -to a physical network. Instead it runs as part of a normal application on your -development machine. This means that it is subject to the same networking -limitations as other applications on your machine:</p> - -<ul> - <li>Communication with the emulated device may be blocked by a firewall -program running on your machine.</li> - <li>Communication with the emulated device may be blocked by another -(physical) firewall/router to which your machine is connected.</li> -</ul> - -<p>The emulator's virtual router should be able to handle all outbound TCP and -UDP connections/messages on behalf of the emulated device, provided your -development machine's network environment allows it to do so. There are no -built-in limitations on port numbers or ranges except the one imposed by your -host operating system and network.</p> - -<p>Depending on the environment, the emulator may not be able to support other -protocols (such as ICMP, used for "ping") might not be supported. Currently, the -emulator does not support IGMP or multicast. </p> - -<a name="redirections"></a> -<h3>Using Network Redirections</h3> - -<p>To communicate with an emulator instance behind its virtual router, you need -to set up network redirections on the virtual router. Clients can then connect -to a specified guest port on the router, while the router directs traffic -to/from that port to the emulated device's host port. </p> - -<p>To set up the network redirections, you create a mapping of host and guest -ports/addresses on the the emulator instance. There are two ways to set up -network redirections: using emulator console commands and using the ADB tool, as -described below. </p> - -<a name="consoleredir"></a> -<h4>Setting up Redirections through the Emulator Console</h4> - -<p>Each emulator instance provides a control console the you can connect to, to -issue commands that are specific to that instance. You can use the -<code>redir</code> console command to set up redirections as needed for an -emulator instance. </p> - -<p>First, determine the console port number for the target emulator instance. -For example, the console port number for the first emulator instance launched is -5554. Next, connect to the console of the target emulator instance, specifying -its console port number, as follows: </p> - -<pre><code>telnet localhost 5554</code></pre> - -<p>Once connected, use the <code>redir</code> command to work with redirections. -To add a redirection, use:</a>. </p> - -<pre><code>add <protocol>:<host-port>:<guest-port></code> -</pre> - -<p>where <code><protocol></code> is either <code>tcp</code> or <code>udp</code>, -and <code><host-port></code> and <code><guest-port></code> sets the -mapping between your own machine and the emulated system, respectively. </p> - -<p>For example, the following command sets up a redirection that will handle all -incoming TCP connections to your host (development) machine on 127.0.0.1:5000 -and will pass them through to the emulated system's 10.0.2.15:6000.:</p> - -<pre>redir add tcp:5000:6000</pre> - -<p>To delete a redirection, you can use the <code>redir del</code> command. To -list all redirections for a specific instance, you can use <code>redir -list</code>. For more information about these and other console commands, see -<a href="#console">Using the Emulator Console</a>. </p> - -<p>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, <code>redir</code> generates an error message to that effect. </p> - -<a name="adbredir"></a> -<h4>Setting Up Redirections through ADB</h4> - -<p>The Android Debug Bridge (ADB) tool provides port forwarding, an alternate -way for you to set up network redirections. For more information, see <a -href="{@docRoot}guide/developing/tools/adb.html#forwardports">Forwarding Ports</a> in the ADB -documentation.</p> - -<p>Note that ADB does not currently offer any way to remove a redirection, -except by killing the ADB server.</p> - -<a name="dns"></a> -<h3>Configuring the Emulator's DNS Settings</h3> - -<p>At startup, the emulator reads the list of DNS servers that your system is -currently using. It then stores the IP addresses of up to four servers on this -list and sets up aliases to them on the emulated addresses 10.0.2.3, 10.0.2.4, -10.0.2.5 and 10.0.2.6 as needed. </p> - -<p>On Linux and OS X, the emulator obtains the DNS server addresses by parsing -the file <code>/etc/resolv.conf</code>. On Windows, the emulator obtains the -addresses by calling the <code>GetNetworkParams()</code> API. Note that this -usually means that the emulator ignores the content of your "hosts" file -(<code>/etc/hosts</code> on Linux/OS X, <code>%WINDOWS%/system32/HOSTS</code> - on Windows).</P> - -<p>When starting the emulator at the command line, you can also use the -<code>-dns-server <serverList></code> option to manually specify the -addresses of DNS servers to use, where <serverList> is a comma-separated -list of server names or IP addresses. You might find this option useful if you -encounter DNS resolution problems in the emulated network (for example, an -"Unknown Host error" message that appears when using the web browser).</p> - -<a name="proxy"></a> -<h3>Using the Emulator with a Proxy</h3> - -<p>If your emulator must access the Internet through a proxy server, you can use -the <code>-http-proxy <proxy></code> option when starting the emulator, to -set up the appropriate redirection. In this case, you specify proxy information -in <code><proxy></code> in one of these formats:</p> - -<pre>http://<machineName>:<port></pre> - -<p>or</p> - -<pre>http://<username>:<password>@<machineName>:<port></pre> - -<p>The <code>-http-proxy</code> option forces the emulator to use the specified -HTTP/HTTPS proxy for all outgoing TCP connections. Redirection for UDP is not -currently supported.</p> - -<p>Alternatively, you can define the environment variable -<code>http_proxy</code> to the value you want to use for -<code><proxy></code>. In this case, you do not need to specify a value for -<code><proxy></code> in the <code>-http-proxy</code> command — the -emulator checks the value of the <code>http_proxy</code> environment variable at -startup and uses its value automatically, if defined. </p> - -<p>You can use the <code>-debug-proxy</code> option to diagnose proxy -connection problems.</p> - -<a name="connecting"></a> -<h3>Interconnecting Emulator Instances</h3> - -<p>To allow one emulator instance to communicate with another, you must set up -the necessary network redirections as illustrated below. </p> - -<p>Assume that your environment is</p> - -<ul> - <li>A is you development machine</li> - <li>B is your first emulator instance, running on A</li> - <li>C is your second emulator instance, running on A too</li> -</ul> - -<p>and you want to run a server on B, to which C will connect, here is how you -could set it up: </p> - -<ol> - <li>Set up the server on B, listening to -<code>10.0.2.15:<serverPort></code></li> - <li>On B's console, set up a redirection from -<code>A:localhost:<localPort></code> to <code> -B:10.0.2.15:<serverPort></code></li> - <li>On C, have the client connect to 10.0.2.2:<localPort></code></li> -</ol> - -<p>For example, if you wanted to run an HTTP server, you can select -<code><serverPort></code> as 80 and <code><localPort></code> as -8080:</p> - -<ul> - <li>B listens on 10.0.2.15:80</li> - <li>On B's console, issue <code>redir add tcp:8080:80</code></li> - <li>C connects to 10.0.2.2:8080</li> -</ul> - -<a name="calling"></a> -<h3>Sending a Voice Call or SMS to Another Emulator Instance</h3> - -<p>The emulator automatically forwards simulated voice calls and SMS messages from one instance to another. To send a voice call or SMS, you use the dialer application and SMS application (if available) installed on one emulator </p> - -<p>To initiate a simulated voice call to another emulator instance:</p> -<ol> -<li>Launch the dialer application on the originating emulator instance.</li> -<li>As the number to dial, enter the console port number of the instance you'd like to call. You can determine - the console port number of the target instance by checking its window title, where the - console port number is reported as "Android Emulator (<port>). </li> -<li>Press "Dial". A new inbound call appears in the target emulator instance. </li> -</ol> - -<p>To send an SMS message to another emulator instance, launch the SMS application (if available). Specify the console port number of the target emulator instance as as the SMS address, enter the message text, and send the message. The message is delivered to the target emulator instance. </p> - -<p>You can also connect to an emulator instance's console to simulate an incoming voice call or SMS. For more information, see <a href="#telephony">Telephony Emulation</a> and <a href="#sms">SMS Emulation</a>. - -<a name="console"></a> - -<h2>Using the Emulator Console</h2> - -<p>Each running emulator instance includes a console facility that lets you dynamically query and control the simulated device environment. For example, you can use the console to dynamically manage port redirections and network characteristics and simulate telephony events. To access the console and enter commands, you use telnet to connect to the console's port number. </p> -<p>To connect to the console of any running emulator instance at any time, use this command: </p> - -<pre>telnet localhost <console-port></pre> - -<p>An emulator instance occupies a pair of adjacent ports: a console port and an adb port. The port numbers differ by 1, with the adb port having the higher port number. The console of the first emulator instance running on a given machine uses console port 5554 and adb port 5555. Subsequent instances use port numbers increasing by two — for example, 5556/5557, 5558/5559, and so on. Up to 16 concurrent emulator instances can run a console facility. </p> - -<p>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:</p> - -<p><code>Android Emulator (5554)</code></p> - -<p>Alternatively, you can use the <code>adb devices</code> command, which prints a list of running emulator instances and their console port numbers. For more information, see <a href="{@docRoot}guide/developing/tools/adb.html#devicestatus">Querying for Emulator/Device Instances</a> in the adb documentation.</p> - -<p class="note">Note: The emulator listens for connections on ports 5554-5587 and accepts connections only from localhost.</p> - -<p>Once you are connected to the console, you can then enter <code>help [command]</code> to see a list of console commands and learn about specific commands. </p> - -<p>To exit the console session, use <code>quit</code> or <code>exit</code>.</p> - -<p>The sections below describe the major functional areas of the console.</p> - -<a name="portredirection"></a> - -<h3>Port Redirection</h3> -<p>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:</p> -<pre>redir <list|add|del> </pre> - -<p>The <code>redir</code> command supports the subcommands listed in the table below. </p> - -<table> -<tr> - <th width="25%" >Subcommand - <th width="30%" >Description</th> - <th width="35%">Comments</th> -</tr> - <tr> - <td><code>list</code></td> - <td>List the current port redirections.</td> - <td> </td> + <td>Search</td> + <td>F5 </td> </tr> - - -<tr> - <td><code>add <protocol>:<host-port>:<guest-port></code></td> - <td>Add a new port redirection.</td> -<td><li><protocol> must be either "tcp" or "udp"</li> -<li><host-port> is the port number to open on the host</li> -<li><guest-port> is the port number to route data to on the emulator/device</li></td> -</tr> -<tr> - <td><code>del <protocol>:<host-port></code></td> - <td>Delete a port redirection.</td> -<td>See above for meanings of <protocol> and <host-port>.</td> -</tr> -</table> - -<a name="geo"></a> -<h3>Geo Location Provider Emulation</h3> - -<p>The console provides commands to let you set the geo position used by an emulator emulated device. You can use the <code>geo</code> command to send a simple GPS fix to the emulator, without needing to use NMEA 1083 formatting. The usage for the command is: </p> - -<pre>geo <fix|nmea></pre> - -<p>The <code>geo</code> command supports the subcommands listed in the table below. </p> - -<table> -<tr> - <th width="25%" >Subcommand - <th width="30%" >Description</th> - <th width="35%">Comments</th> -</tr> - <tr> - <td><code>fix <longitude> <latitude> [<altitude>]</code></td> - <td>Send a simple GPS fix to the emulator instance.</td> - <td>Specify longitude and latitude in decimal degrees. Specify altitude in meters.</td> + <td>Power button</td> + <td>F7 </td> </tr> -<tr> - <td><code>nmea <sentence></code></td> - <td>Send an NMEA 0183 sentence to the emulated device, as if it were sent from an emulated GPS modem.</td> -<td><code><sentence></code> must begin with '$GP'. Only '$GPGGA' and '$GPRCM' sentences are currently supported.</td> -</tr> -</table> - -<p>You can issue the <code>geo</code> 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: - -<pre>LocationManager.getLastKnownLocation("gps")</pre> - -<p>For more information about the Location Manager, see {@link android.location.LocationManager} and its methods.</p> - -<a name="events"></a> -<h3>Hardware Events Emulation</h3> - -<p>You can use the <code>event</code> command to send various events to the emulator.The usage for the command is: </p> - -<pre>event <send|types|codes|text></pre> - -<p>The <code>event</code> command supports the subcommands listed in the table below. </p> - -<table> -<tr> - <th width="25 %" >Subcommand - <th width="30%" >Description</th> - <th width="35%">Comments</th> -</tr> - <tr> - <td><code>send <type>:<code>:<value> [...]</code></td> - <td>Send one or more events to the Android kernel. </td> - <td>You can use text names or integers for <code><type></code> and <code><value></code>.</td> + <td>Audio volume up button</td> + <td>KEYPAD_PLUS, Ctrl-5</td> </tr> -<tr> - <td><code>types</code></td> - <td>List all <code><type></code> string aliases supported by the <code>event</code> subcommands.</td> -<td> </td> -</tr> -<tr> - <td><code>codes <type></code></td> - <td>List all <code><codes></code> string aliases supported by the <code>event</code> - subcommands for the specified <code><type></code>.</td> -<td> </td> -</tr> -<tr> - <td><code>event text <message></code></td> - <td>Simulate keypresses to send the specified string of characters as a message,</td> -<td>The message must be a UTF-8 string. Unicode posts will be reverse-mapped according to the current device keyboard. Unsupported characters will be discarded silently.</td> -</tr> -</table> - -<a name="power"></a> -<h3>Device Power Characteristics</h3> - -<p>You can use the <code>power</code> command to control the simulated power state of the emulator instance.The usage for the command is: </p> -<pre>power <display|ac|status|present|health|capacity></pre> - -<p>The <code>event</code> command supports the subcommands listed in the table below. </p> - -<table> -<tr> - <th width="25 %" >Subcommand - <th width="30%" >Description</th> - <th width="35%">Comments</th> -</tr> - <tr> - <td><code>display</code></td> - <td>Display battery and charger state.</td> - <td> </td> - </tr> -<tr> - <td><code>ac <on|off></code></td> - <td>Set AC charging state to on or off. </td> -<td> </td> -</tr> -<tr> - <td><code>status <unknown|charging|discharging|not-charging|full></code></td> - <td>Change battery status as specified.</td> -<td> </td> -</tr> - -<tr> - <td><code>present <true|false></code></td> - <td>Set battery presence state.</td> -<td> </td> -</tr> -<tr> - <td><code>health <unknown|good|overheat|dead|overvoltage|failure></code></td> - <td>Set battery health state.</td> -<td> </td> -</tr> -<tr> - <td><code>power health <percent></code></td> - <td>Set remaining battery capacity state (0-100).</td> -<td> </td> -</tr> -</table> - -<a name="netstatus"></a> -<h3>Network Status</h3> - -<p>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 <code>netstatus</code> command. Here's an example of the command and its output. </p> - -<pre>network status -</pre> - -<a name="netdelay"></a> -<h3>Network Delay Emulation</h3> - -<p>The emulator lets you simulate various network latency levels, so that you can test your application in an environment more typical of the actual conditions in which it will run. You can set a latency level or range at emulator startup or you can use the console to change the latency dynamically, while the application is running in the emulator. </p> -<p>To set latency at emulator startup, use the <code>-netdelay</code> emulator option with a supported <code><delay></code> value, as listed in the table below. Here are some examples:</p> -<pre>emulator -netdelay gprs -emulator -netdelay 40 100</pre> - -<p>To make dynamic changes to network delay while the emulator is running, connect to the console and use the <code>netdelay</code> command with a supported <code><delay></code> value from the table below. </p> - -<pre>network delay gprs</pre> - -<p>The format of network <delay> is one of the following (numbers are milliseconds):</p> - -<table style="clear:right;width:100%;"> -<tr> - <th width="30%" >Value</td> - <th width="35%" >Description</th><th width="35%">Comments</th></tr> - - <tr><td><code>gprs</code></td><td>GPRS</td> - <td>(min 150, max 550)</td> + <td>Audio volume down button</td> + <td>KEYPAD_MINUS, Ctrl-F6</td> </tr> - -<tr><td><code>edge</code></td><td>EDGE/EGPRS</td> -<td>(min 80, max 400)</td> -</tr> -<tr><td><code>umts</code></td><td>UMTS/3G</td> -<td>(min 35, max 200)</td> -</tr> -<tr><td><code>none</code></td><td>No latency</td><td>(min 0, max 0)</td></tr> -<tr><td><code><num></code></td> -<td>Emulate an exact latency (milliseconds).</td> -<td> </td></tr> -<tr><td><code><min>:<max></code></td> -<td>Emulate an specified latency range (min, max milliseconds).</td> -<td> </td></tr> -</table> - -<a name="netspeed"></a> -<h3>Network Speed Emulation</h3> - -<p>The emulator also lets you simulate various network transfer rates. You can set a transfer rate or range at emulator startup or you can use the console to change the rate dynamically, while the application is running in the emulator. </p> -<p>To set the network speed at emulator startup, use the <code>-netspeed</code> emulator option with a supported <code><speed></code> value, as listed in the table below. Here are some examples:</p> -<pre>emulator -netspeed gsm -emulator -netspeed 14.4 80</pre> - -<p>To make dynamic changes to network speed while the emulator is running, connect to the console and use the <code>netspeed</code> command with a supported <code><speed></code> value from the table below. </p> - -<pre>network speed 14.4 80</pre> - -<p>The format of network <code><speed></code> is one of the following (numbers are -kilobits/sec):</p> -<table style="clear:right;width:100%;"> -<tbody> -<tr> - <th width="30%">Value</td> - <th width="35%">Description</th><th width="35%">Comments</th></tr> - <tr> - <td><code>gsm</code></td> - <td>GSM/CSD</td><td>(Up: 14.4, down: 14.4)</td></tr> -<tr> - <td><code>hscsd</code></td> - <td>HSCSD</td><td>(Up: 14.4, down: 43.2)</td></tr> -<tr> - <td><code>gprs</code></td> - <td>GPRS</td><td>(Up: 40.0, down: 80.0)</td></tr> -<tr> - <td><code>edge</code></td> - <td>EDGE/EGPRS</td> - <td>(Up: 118.4, down: 236.8)</td> -</tr> -<tr> - <td><code>umts</code></td> - <td>UMTS/3G</td><td>(Up: 128.0, down: 1920.0)</td></tr> -<tr> - <td><code>hsdpa</code></td> - <td>HSDPA</td><td>(Up: 348.0, down: 14400.0)</td></tr> -<tr> - <td><code>full</code></td> - <td>no limit</td><td>(Up: 0.0, down: 0.0)</td></tr> -<tr> - <td><code><num></code></td> - <td>Set an exact rate used for both upload and download.</td><td></td></tr> -<tr> - <td><code><up>:<down></code></td> - <td>Set exact rates for upload and download separately.</td><td></td></tr> -</table> - - -<a name="telephony"></a> - -<h3>Telephony Emulation</h3> - -<p>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. </p> -<p>You can use the console to access the emulator's telephony functions. After connecting to the console, you can use</p> -<pre>gsm <call|accept|busy|cancel|data|hold|list|voice|status> </pre> -<p>to invoke telephony functions. </p> -<p>The <code>gsm</code> command supports the subcommands listed in the table below. </p> -<table> + <td>Camera button</td> + <td>Ctrl-KEYPAD_5, Ctrl-F3</td> + </tr> <tr> - <th >Subcommand </th> - <th width="25%">Description</th> - <th>Comments</th> + <td>Switch to previous layout orientation (for example, portrait, landscape)</td> + <td>KEYPAD_7, Ctrl-F11</td> </tr> <tr> - <td><code>call <phonenumber></code></td> - <td>Simulate an inbound phone call from <phonenumber>.</td> - <td> </td> + <td>Switch to next layout orientation (for example, portrait, landscape)</td> + <td>KEYPAD_9, Ctrl-F12</td> </tr> <tr> - <td><code>accept <phonenumber></code></td> - <td>Accept an inbound call from <phonenumber> and change the call's state "active".</td> - <td>You can change a call's state to "active" only if its current state is "waiting" or "held".</td> + <td>Toggle cell networking on/off</td> + <td>F8</td> </tr> <tr> - <td><code>busy <phonenumber></code></td> - <td>Close an outbound call to <phonenumber> and change the call's state to "busy".</td> - <td>You can change a call's state to "busy" only if its current state is "waiting".</td> + <td>Toggle code profiling</td> + <td>F9 (only with <code>-trace</code> startup option)</td> </tr> <tr> - <td><code>cancel <phonenumber></code></td> - <td>Terminate an inbound or outbound phone call to/from <phonenumber>.</td> - <td> </td> + <td>Toggle fullscreen mode</td> + <td>Alt-Enter</td> </tr> <tr> - <td><code>data <state></code></td> - <td>Change the state of the GPRS data connection to <state>.</td> - <td>Supported <state> values are:<br /> - <li><code>unregistered</code> -- No network available</li> - <li><code>home</code> -- On local network, non-roaming</li> - <li><code>roaming</code> -- On roaming network</li> - <li><code>searching</code> -- Searching networks</li> - <li><code>denied</code> -- Emergency calls only</li> - <li><code>off</code> -- Same as 'unregistered'</li> - <li><code>on</code> -- same as 'home'</li> </td> + <td>Toggle trackball mode</td> + <td>F6</td> </tr> <tr> - <td><code>hold</code></td> - <td>Change the state of a call to "held". </td> - <td>You can change a call's state to "held" only if its current state is "active" or "waiting". </td> + <td>Enter trackball mode temporarily (while key is pressed)</td> + <td>Delete</td> </tr> <tr> - <td><code>list</code></td> - <td>List all inbound and outbound calls and their states.</td> - <td> </td> + <td>DPad left/up/right/down</td> + <td>KEYPAD_4/8/6/2</td> </tr> <tr> - <td><code>voice <state></code></td> - <td>Change the state of the GPRS voice connection to <state>.</td> - <td>Supported <state> values are:<br /> - <li><code>unregistered</code> -- No network available</li> - <li><code>home</code> -- On local network, non-roaming</li> - <li><code>roaming</code> -- On roaming network</li> - <li><code>searching</code> -- Searching networks</li> - <li><code>denied</code> -- Emergency calls only</li> - <li><code>off</code> -- Same as 'unregistered'</li> - <li><code>on</code> -- Same as 'home'</li></td> + <td>DPad center click</td> + <td>KEYPAD_5</td> </tr> - <tr> - <td><code>status</code></td> - <td>Report the current GSM voice/data state.</td> - <td>Values are those described for the <code>voice</code> and <code>data</code> commands.</td> + <td>Onion alpha increase/decrease</td> + <td>KEYPAD_MULTIPLY(*) / KEYPAD_DIVIDE(/)</td> </tr> </table> -<a name="sms"></a> - -<h3>SMS Emulation</h3> - -<p>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:</p> - -<pre>sms send <senderPhoneNumber> <textmessage></pre> - -<p>where <code><senderPhoneNumber></code> contains an arbitrary numeric string. </p> - -<p>The console forwards the SMS message to the Android framework, which passes it through to an application that handles that message type. </p> - -<a name="vm"></a> - -<h3>VM State</h3> - -<p>You can use the <code>vm</code> command to control the VM on an emulator instance.The usage for the command is: </p> - -<pre>vm <start|stop|status></pre> - -<p>The <code>vm</code> command supports the subcommands listed in the table below. </p> - -<table> -<tr> - <th width="25%" >Subcommand - <th width="30%" >Description</th> - <th width="35%">Comments</th> -</tr> -<tr> - <td><code>start</code></td> - <td>Start the VM on the instance. </td> - <td> </td> -</tr> -<tr> - <td><code>stop</code></td> - <td>Stop the VM on the instance. </td> - <td> </td> -</tr> -<tr> - <td><code>start</code></td> - <td>Display the current status of the VM (running or stopped). </td> - <td> </td> -</tr> -</table> - - -<a name="window"></a> - -<h3>Emulator Window</h3> - -<p>You can use the <code>window</code> command to manage the emulator window. The usage for the command is: </p> - -<pre>window <scale></pre> - -<p>The <code>vm</code> command supports the subcommands listed in the table below. </p> - -<table> -<tr> - <th width="25%" >Subcommand - <th width="30%" >Description</th> - <th width="35%">Comments</th> -</tr> -<tr> - <td><code>scale <scale></code></td> - <td>Scale the emulator window.</td> - <td><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.</td> -</tr> -</table> - - -<a name="terminating"></a> - -<h3>Terminating an Emulator Instance</h3> - -<p>You can terminate an emulator instance through the console, using the <code>kill</code> command.</p> - - -<a name="skins"></a> - -<h2>Using Emulator Skins</h2> - -<p>The Android SDK includes several Emulator skins that you can use to control the resolution and density of the emulated device's screen. To select a specific skin for running the emulator, create an AVD that uses that skin. Please do not use deprecated emulator options such as <code>-skin</code> to control the skin used by an emulator instance. For more information about AVDs, see <a -href="{@docRoot}guide/developing/tools/avd.html">Android Virtual Devices</a>. </p> - - -<a name="multipleinstances"></a> - -<h2>Running Multiple Emulator Instances</h2> - -<p>Through the AVDs configurations used by the emulator, you can run multiple -instances of the emulator concurrently, each with its own AVD configuration and -storage area for user data, SD card, and so on. You no longer need to use the -<code>-d</code> option when launching the emulator, to point to an -instance-specific storage area. </p> - -<a name="apps"></a> - -<h2>Installing Applications on the Emulator</h2> - -<p>If you don't have access to Eclipse or the ADT Plugin, you can install -your application on the emulator <a href="{@docRoot}guide/developing/tools/adb.html#move">using -the adb utility</a>. Before installing the application, you need to package it -in a .apk file using the <a href="{@docRoot}guide/developing/tools/aapt.html">Android Asset Packaging Tool</a>. -Once the application is installed, you can start the emulator from the command -line, as described in this document, using any startup options necessary. -When the emulator is running, you can also connect to the emulator instance's -console to issue commands as needed.</p> - -<p>As you update your code, you periodically package and install it on the emulator. -The emulator preserves the application and its state data across restarts, -in a user-data disk partition. To ensure that the application runs properly -as you update it, you may need to delete the emulator's user-data partition. -To do so, start the emulator with the <code>-wipe-data</code> option. -For more information about the user-data partition and other emulator storage, -see <a href="#diskimages">Working with Emulator Disk Images</a>.</p> - -<a name="sdcard"></a> -<a name="creating"></a> - -<h2>SD Card Emulation</h2> - -<p>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. </p> - -<p>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. </p> - -<p>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. </p> - -<p>The emulator supports emulated SDHC cards, so you can create an SD card image -of any size up to 128 gigabytes.</p> - -<h3 id="creatinga">Creating an SD card image using the android tool</h3> - -<p>The easiest way to create a new SD card is to use the android tool. When -creating an AVD, you simply specify the <code>-c</code> option, like this: </p> - -<pre>android create avd -n <avd_name> -t <targetID> -c <size>[K|M]</pre> - -<p>You can also use the <code>-c</code> option to specify a path to an SD card -image to use in the new AVD. For more information, see <a -href="{@docRoot}guide/developing/tools/avd.html">Android Virtual Devices</a>. -</p> - -<h3 id="creatingm">Creating an SD card image using mksdcard</h3> - -<p>You can use the mksdcard tool, included in the SDK, to create a FAT32 disk -image that you can load in the emulator at startup. You can access mksdcard in -the tools/ directory of the SDK and create a disk image like this: </p> - -<pre>mksdcard <size> <file></pre> - -<p>For example:</p> - -<pre>mksdcard 1024M sdcard1.iso</pre> - -<p>For more information, see <a href="{@docRoot}guide/developing/tools/othertools.html">Other Tools</a>. </p> - -<a name="copying"></a> -<h3>Copying Files to a Disk Image</h3> - -<p>Once you have created the disk image, you can copy files to it prior to -loading it in the emulator. To copy files, you can mount the image as a loop -device and then copy the files to it, or you can use a utility such as mtools to -copy the files directly to the image. The mtools package is available for Linux, -Mac, and Windows.</p> - -<a name="loading"></a> -<a name="step3" id="step3"></a> - -<h3>Loading the Disk Image at Emulator Startup</h3> - -<p>By default, the emulator loads the SD card image that is stored with the active -AVD (see the <code>-avd</code> startup option).</p> - -<p>Alternatively, you ca start the emulator with the -<code>-sdcard</code> flag and specify the name and path of your image (relative -to the current working directory): </p> - -<pre>emulator -sdcard <filepath></pre> - -<a name="troubleshooting"></a> - -<h2>Troubleshooting Emulator Problems</h2> - -<p>The adb utility sees the emulator as an actual physical device. For this reason, you might have to use the -d flag with some common adb commands, such as <code>install</code>. The -d flag lets you specify which of several connected devices to use as the target of a command. If you don't specify -d, the emulator will target the first device in its list. For more information about adb, see <a href="{@docRoot}guide/developing/tools/adb.html">Android Debug Bridge</a>.</p> - -<p>For emulators running on Mac OS X, if you see an error "Warning: No DNS servers found" when starting the emulator, check to see whether you have an <code>/etc/resolv.conf</code> file. If not, please run the following line in a command window:</p> - <pre>ln -s /private/var/run/resolv.conf /etc/resolv.conf</pre> - -<p>See <a href="{@docRoot}resources/faq/index.html">Frequently Asked Questions</a> for more troubleshooting information. </p> - -<a name="limitations"></a> - <h2>Emulator Limitations</h2> - <p>In this release, the limitations of the emulator include: </p> - <ul> - <li>No support for placing or receiving actual phone calls. You can simulate phone calls (placed and received) through the emulator console, however. </li> - <li>No support for USB connections</li> - <li>No support for camera/video capture (input).</li> - <li>No support for device-attached headphones</li> - <li>No support for determining connected state</li> - <li>No support for determining battery charge level and AC charging state</li> - <li>No support for determining SD card insert/eject</li> - <li>No support for Bluetooth</li> - </ul> +<p>Note that, to use keypad keys, you must first disable NumLock on your development computer. </p> diff --git a/docs/html/guide/developing/tools/hierarchy-viewer.jd b/docs/html/guide/developing/tools/hierarchy-viewer.jd index 431008c..ce660fc 100644 --- a/docs/html/guide/developing/tools/hierarchy-viewer.jd +++ b/docs/html/guide/developing/tools/hierarchy-viewer.jd @@ -1,98 +1,16 @@ page.title=Hierarchy Viewer @jd:body -<p>The Hierarchy Viewer application allows you to debug and optimize your user +<p>Hierarchy Viewer allows you to debug and optimize your user interface. It provides a visual representation of the layout's View hierarchy (the Layout View) and a magnified inspector of the display (the Pixel Perfect View). </p> -<p>To get the Hierarchy Viewer started:</p> -<ol> - <li>Connect your device or launch an emulator.</li> - <li>From a terminal, launch <code>hierarchyviewer</code> from your SDK - <code>/tools</code> directory. - </li> - <li>In the window that opens, you'll see a list of <strong>Devices</strong>. When a device is - selected, a list of currently active <strong>Windows</strong> is displayed - on the right. The <em><Focused Window></em> is the window currently in - the foreground, and also the default window loaded if you do not select another. - </li> - <li>Select the window that you'd like to inspect and click - <strong>Load View Hierarchy</strong>. 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. - </li> +<p>To start Hierarchy Viewer, enter the following command from the SDK <code>tools/</code> directory:</p> + <pre>hierarchyviewer</pre> </ol> -<p>If you've navigated to a different window on the device, press <strong>Refresh Windows</strong> -to refresh the list of available windows on the right.</p> - -<h2>Layout View</h2> -<p>The Layout View offers a look at the View layout and properties. It has three views:</p> -<ul> - <li>Tree View: a hierarchy diagram of the Views, on the left.</li> - <li>Properties View: a list of the selected View's properties, on the top-right.</li> - <li>Wire-frame View: a wire-frame drawing of the layout, on the bottom-right.</li> -</ul> -<br/> -<img src="{@docRoot}images/hierarchyviewer-layout.png" alt="" height="509" width="700" /> - -<p>Select a node in the Tree View to display the properties of that element in -the Properties View. When a node is selected, the Wire-frame View -also indicates the bounds of the element with a red rectangle. -Double click a node in the tree (or select it, and click <strong>Display -View</strong>) to open a new window with a rendering of that element.</p> - -<p>The Layout View includes a couple other helpful features for debugging your layout: -<strong>Invalidate</strong> and <strong>Request Layout</strong>. These buttons execute the -respective View calls, {@link android.view.View#invalidate()} and {@link android.view.View#requestLayout()}, -on the View element currently selected in the tree. Calling these methods on any View can -be very useful when simultaneously running a debugger on your application.</p> - -<p>The Tree View can be resized by adjusting the zoom slider, below -the diagram. The number of View elements in the window is also given here. You -should look for ways to minimize the number of Views. The fewer View elements there -are in a window, the faster it will perform.</p> - -<p>If you interact with the device and change the focused View, the diagram will not automatically refresh. -You must reload the Layout View by clicking <strong>Load View Hierarchy</strong>. - - -<h2>Pixel Perfect View</h2> -<p>The Pixel Perfect View provides a magnified look at the current device window. It has three views:</p> -<ul> - <li>Explorer View: shows the View hierarchy as a list, on the left.</li> - <li>Normal View: a normal view of the device window, in the middle.</li> - <li>Loupe View: a magnified, pixel-grid view of the device window, on the right.</li> -</ul> -<br/> -<img src="{@docRoot}images/hierarchyviewer-pixelperfect.png" alt="" height="509" width="700" /> - -<p>Click on an element in the Explorer View and a "layout box" will be drawn in the -Normal View to indicate the layout position of that element. The layout box uses multiple rectangles, to indicate the normal bounds, the padding and the margin (as needed). The purple or green rectangle indicates -the normal bounds of the element (the height and width). The inner white or black rectangle indicates -the content bounds, when padding is present. A black or white rectangle outside the normal purple/green -rectangle indicates any present margins. -(There are two colors for each rectangle, in order to provide the best contrast -based on the colors currently in the background.)</p> - -<p>A very handy feature for designing your UI is the ability to overlay an image in the Normal and Loupe -Views. For example, you might have a mock-up image of how you'd like to layout your interface. -By selecting <strong>Load...</strong> from the controls in the Normal View, you can choose the -image from your computer and it will be placed atop the preview. Your chosen image will anchor at the bottom left corner of the screen. You can then adjust the opacity of the overlay and begin fine-tuning your layout to match the mock-up.</p> - -<p>The Normal View and Loupe View refresh at regular intervals (5 seconds by default), but the -Explorer View does not. If you navigate away and focus on a different View, then you should refresh the -Explorer's hierarchy by clicking <strong>Load View Hierarchy</strong>. This is even true -when you're working in a window that holds multiple Views that are not always visible. If you do not, -although the previews will refresh, clicking a View in the Explorer will not provide the proper layout box -in the Normal View, because the hierarchy believes you are still focused on the prior View.</p> - -<p>Optional controls include:</p> -<ul> - <li><strong>Overlay</strong>: Load an overlay image onto the view and adjust its opacity.</li> - <li><strong>Refresh Rate</strong>: Adjust how often the Normal and Loupe View refresh their display.</li> - <li><strong>Zoom</strong>: Adjust the zoom level of the Loupe View.</li> -</ul> - +<p>For more information on how to use Hierarchy Viewer, see +<a href="{@docRoot}guide/developing/debugging/debugging-ui.html">Debugging and Profiling UIs</a> +</p> diff --git a/docs/html/guide/developing/tools/hprof-conv.jd b/docs/html/guide/developing/tools/hprof-conv.jd new file mode 100644 index 0000000..27000b4 --- /dev/null +++ b/docs/html/guide/developing/tools/hprof-conv.jd @@ -0,0 +1,14 @@ +page.title=HPROF Converter +@jd:body + +<p> +The <code>hprof-conv</code> tool converts the HPROF file that is +generated by the Android SDK tools to a standard format so you +can view the file in a profiling tool of your choice. </p> + +<pre> hprof-conv <infile> <outfile></pre> + +<p> +You can use "-" for <code><infile></code> or <code><outfile></code> +to specify stdin or stdout. +</p> diff --git a/docs/html/guide/developing/tools/index.jd b/docs/html/guide/developing/tools/index.jd index b3e4625..c603780 100644 --- a/docs/html/guide/developing/tools/index.jd +++ b/docs/html/guide/developing/tools/index.jd @@ -1,4 +1,4 @@ -page.title=Tools Overview +page.title=Tools @jd:body <img src="{@docRoot}assets/images/android_wrench.png" alt="" align="right"> @@ -10,99 +10,75 @@ includes a variety of other tools for debugging, packaging, and installing your applications on the emulator. </p> <dl> - <dt><a href="adt.html">Android Development Tools Plugin</a> (for the Eclipse IDE)</dt> - <dd>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.</dd> + <dt><a href="adb.html">Android Debug Bridge</a></dt> + <dd>A versatile tool lets you manage the state of an emulator instance + or Android-powered device.</dd> + + <dt><a href="android.html">android</a></dt> + <dd>Lets you manage AVDs, projects, and the installed components of the SDK. + </dd> + + <dt><a href="bmgr.html">bmgr</a></dt> + + <dd>Lets you interact with the Backup Manager on Android devices + supporting API Level 8 or greater. It provides commands to invoke 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. + </dd> + + <dt><a href="dmtracedump.html">dmtracedump</a></dt> + + <dd>Generates graphical call-stack diagrams from trace log files. + The tool uses the Graphviz Dot utility to create the graphical output, so you need to install + Graphviz before running <code>dmtracedump</code>. For more information on using <code>dmtracedump</code>, see + <a href="{@docRoot}guide/developing/debugging/debugging-tracing.html#dmtracedump">Profiling with + Traceview and dmtracedump</a> + </dd> + + <dt><a href="draw9patch.html">Draw 9-patch</a></dt> + <dd>Allows you to easily create a {@link android.graphics.NinePatch} graphic using a WYSIWYG editor. + It also previews stretched versions of the image, and highlights the area in which content is allowed. + </dd> + <dt><a href="emulator.html">Android Emulator</a></dt> <dd>A QEMU-based device-emulation tool that you can use to design, debug, and test your applications in an actual Android run-time environment. </dd> - <dt><a href="avd.html">Android Virtual Devices (AVDs)</a></dt> - <dd>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. </dd> - - <dt><a href="hierarchy-viewer.html">Hierarchy Viewer</a></dt> - <dd>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. - </dd> + <dt><a href="hprof-conv.html">hprof-conv</a></dt> - <dt><a href="layoutopt.html">layoutopt</a></dt> - <dd>This tool lets you quickly analyze your application's layouts for -efficiency. + <dd>Converts the HPROF file that is generated by the Android SDK tools to a + standard format so you can view the file in a profiling tool of your choice.</dd> + + <dt><a href="layoutopt.html">layoutopt</a></dt> + <dd>Lets you quickly analyze your application's layouts in order to + optimize them for efficiency. </dd> - <dt><a href="draw9patch.html">Draw 9-patch</a></dt> - <dd>The Draw 9-patch tool allows you to easily create a - {@link android.graphics.NinePatch} graphic using a WYSIWYG editor. It also previews stretched - versions of the image, and highlights the area in which content is allowed. - </dd> - - <dt><a href="ddms.html" >Dalvik Debug Monitor - Service</a> (ddms)</dt> - <dd>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. </dd> - - <dt><a href="adb.html" >Android Debug Bridge</a> (adb)</dt> - <dd>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. - <p>This is located in {@code <sdk>/platform-tools/}.</p></dd> - - <dt><a href="aapt.html">Android Asset - Packaging Tool</a> (aapt)</dt> - <dd>The aapt tool lets you create .apk files containing the binaries and - resources of Android applications.</dd> - - <dt><a href="aidl.html" >Android Interface - Description Language</a> (aidl)</dt> - <dd>Lets you generate code for an interprocess interface, such as what - a service might use.</dd> - - <dt><a href="adb.html#sqlite">sqlite3</a></dt> - <dd>Included as a convenience, this tool lets you access the SQLite data - files created and used by Android applications.</dd> - - <dt><a href="traceview.html" >Traceview</a></dt> - <dd> This tool produces graphical analysis views of trace log data that you - can generate from your Android application. </dd> - - <dt><a href="othertools.html#mksdcard">mksdcard</a></dt> - <dd>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).</dd> - - <dt><a href="othertools.html#dx">dx</a></dt> - <dd>The dx tool rewrites .class bytecode into Android bytecode - (stored in .dex files.)</dd> - - <dt><a href="monkey.html">UI/Application - Exerciser Monkey</a></dt> - <dd>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.</dd> + <dt><a href="mksdcard.html">logcat</a></dt> + <dd>Lets you read system log messages that are output on an Android device or emulator.</dd> + + <dt><a href="mksdcard.html">mksdcard</a></dt> + <dd>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).</dd> + + <dt><a href="monkey.html">Monkey</a></dt> + <dd>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.</dd> <dt><a href="monkeyrunner_concepts.html">monkeyrunner</a></dt> - <dd> - The monkeyrunner tool provides an API for writing Python programs that control an Android device - or emulator from outside of Android code. - </dd> - <dt><a href="othertools.html#android">android</a></dt> - <dd>A script that lets you manage AVDs and generate <a - href="http://ant.apache.org/" title="Ant">Ant</a> build files that - you can use to compile your Android applications. </dd> - - <dt><a href="zipalign.html">zipalign</a></dt> - <dd>An important .apk optimization tool. This tool ensures that all uncompressed data starts + <dd>Provides an API for writing programs that control an Android device + or emulator from outside of Android code.</dd> + + <dt><a href="proguard.html">ProGuard</a></dt> + <dd>Shrinks, optimizes, and obfuscates your code by removing unused code and renaming classes, + fields, and methods with semantically obscure names.</dd> + + <dt><a href="sqlite3.html">sqlite3</a></dt> + <dd>Lets you access the SQLite data files created and used by Android applications.</dd> + + <dt><a href="zipalign.html">zipalign</a></dt> + <dd>Optimizes <code>.apk</code> files by ensuring that all uncompressed data starts with a particular alignment relative to the start of the file. This should always be used to align .apk files after they have been signed.</dd> </dl> diff --git a/docs/html/guide/developing/tools/layoutopt.jd b/docs/html/guide/developing/tools/layoutopt.jd index f7c3d77..fdbf777 100644 --- a/docs/html/guide/developing/tools/layoutopt.jd +++ b/docs/html/guide/developing/tools/layoutopt.jd @@ -2,61 +2,20 @@ page.title=layoutopt @jd:body <p><code>layoutopt</code> 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. </p> - -<p>To run the tool, open a terminal and launch <code>layoutopt -<resources></code> from your SDK <code>tools/</code> directory. In the -command, supply a list of uncompiled resource xml files or directories that you -want to analyze. </p> - -<p>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. </p> - -<p>Here's an example of the output:</p> - -<pre>$ 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</pre> - -<p>The <code>layoutopt</code> 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 <a -href="{@docRoot}sdk/adding-components.html">Adding SDK Components</a>.</p> +layouts and layout hierarchies of your applications.<p> + +<p>This document is a reference to the available command line options. For more information and sample +output of the tool, see <a href="{@docRoot}guide/developing/debugging/debugging-ui.html#layoutopt.html"> +Optimizing layouts with layoutopt</a>.</p> <h3>Usage</h3> <p>To run <code>layoutopt</code> against a given list of layout resources:</p> -<pre>layoutopt <list of xml files or directories></pre> +<pre>layoutopt <file_or_directory> ...</pre> <p>For example:</p> <pre>$ layoutopt res/layout-land</pre> <pre>$ layoutopt res/layout/main.xml res/layout-land/main.xml</pre> + diff --git a/docs/html/guide/developing/tools/logcat.jd b/docs/html/guide/developing/tools/logcat.jd new file mode 100644 index 0000000..1577604 --- /dev/null +++ b/docs/html/guide/developing/tools/logcat.jd @@ -0,0 +1,104 @@ +page.title=logcat +@jd:body +<div></div> + + <p>The Android logging system provides a mechanism for collecting and viewing system debug + output. Logs from various applications and portions of the system are collected in a series of + circular buffers, which then can be viewed and filtered by the <code>logcat</code> command. You can use + <code>logcat</code> from an ADB shell to view the log messages.</p> + + <p>This document is a reference to the available command line options. For more information on <code>logcat</code>, see + <a href="{@docRoot}guide/developing/debugging/debugging-log.html">Reading and Writing Log Messages</a>. For more + information on accessing <code>logcat</code> from DDMS, instead of the command line, see the documentation for the + <a href="{@docRoot}guide/developing/debugging/ddms.html">Dalvik Debug Monitor Server</a>. + </p> + + <h3>Syntax</h3> + <pre> +[adb] logcat [<option>] ... [<filter-spec>] ... +</pre> + + <p>You can run <code>logcat</code> as an adb command or directly in a shell prompt + of your emulator or connected device. To view log output using adb, navigate to your SDK + <code>platform-tools/</code> directory and execute:/p> + <pre> +$ adb logcat +</pre> + + <p>You can create a shell connection to a device and execute:</p> + <pre> +$ adb shell +# logcat +</pre> + + <h3>Options</h3> + <p>The following table describes the command line options of <code>logcat</code>.</p> + + <table> + <tr> + <th>Option</th> + + <th>Description</th> + </tr> + + <tr> + <td><code>-b <buffer></code></td> + + <td>Loads an alternate log buffer for viewing, such as <code>event</code> or + <code>radio</code>. The <code>main</code> buffer is used by default. See <a href= + "#alternativebuffers">Viewing Alternative Log Buffers</a>.</td> + </tr> + + <tr> + <td><code>-c</code></td> + + <td>Clears (flushes) the entire log and exits.</td> + </tr> + + <tr> + <td><code>-d</code></td> + + <td>Dumps the log to the screen and exits.</td> + </tr> + + <tr> + <td><code>-f <filename></code></td> + + <td>Writes log message output to <code><filename></code>. The default is + <code>stdout</code>.</td> + </tr> + + <tr> + <td><code>-g</code></td> + + <td>Prints the size of the specified log buffer and exits.</td> + </tr> + + <tr> + <td><code>-n <count></code></td> + + <td>Sets the maximum number of rotated logs to <code><count></code>. The default value + is 4. Requires the <code>-r</code> option.</td> + </tr> + + <tr> + <td><code>-r <kbytes></code></td> + + <td>Rotates the log file every <code><kbytes></code> of output. The default value is + 16. Requires the <code>-f</code> option.</td> + </tr> + + <tr> + <td><code>-s</code></td> + + <td>Sets the default filter spec to silent.</td> + </tr> + + <tr> + <td><code>-v <format></code></td> + + <td>Sets the output format for log messages. The default is <code>brief</code> format. For a + list of supported formats, see <a href="#outputformat">Controlling Log Output + Format</a>.</td> + </tr> + </table> diff --git a/docs/html/guide/developing/tools/mksdcard.jd b/docs/html/guide/developing/tools/mksdcard.jd new file mode 100644 index 0000000..f70d6b7 --- /dev/null +++ b/docs/html/guide/developing/tools/mksdcard.jd @@ -0,0 +1,53 @@ +page.title=mksdcard +@jd:body + + <p>The <code>mksdcard</code> tool lets you quickly create a FAT32 disk image that you can load in the + emulator, to simulate the presence of an SD card in the device. Because you can specify an SD + card while creating an AVD in the AVD Manager, you usually use that feature to create an SD card. + This tool creates an SD card that is not bundled with an AVD, so it is useful for situations + where you need to share a virtual SD card between multiple emulators.</p> + + <h3>Usage</h3> + <pre> +mksdcard -l <label> <size> <file> +</pre> + + <h3>Options</h3> + The following table describes the command-line options of <code>mksdcard</code> + <table> + <tr> + <th>Option</th> + + <th>Description</th> + </tr> + + <tr> + <td><code>-l</code></td> + + <td>A volume label for the disk image to create.</td> + </tr> + + <tr> + <td><code>size</code></td> + + <td>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, <code>1048576K</code>, <code>1024M</code>.</td> + </tr> + + <tr> + <td><code>file</code></td> + + <td>The path/filename of the disk image to create.</td> + </tr> + </table> + + <p>Once you have created the disk image file, you can load it in the emulator at startup using + the emulator's <code>-sdcard</code> option. For more information, see <a href= + "{@docRoot}guide/developing/tools/emulator.html">Android Emulator</a>.</p> + + <p>The usage for the <code>-sdcard</code> option is as follows:</p> + <pre>emulator -sdcard <file></pre> + +<h3>Example</h3> +mksdcard -l mySdCard 1024M mySdCardFile.img
\ No newline at end of file diff --git a/docs/html/guide/developing/tools/monkey.jd b/docs/html/guide/developing/tools/monkey.jd index 9a2ab6f..6c05934 100644 --- a/docs/html/guide/developing/tools/monkey.jd +++ b/docs/html/guide/developing/tools/monkey.jd @@ -185,7 +185,7 @@ transitions invoked by your application.</td> <td>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 -<a href="{@docRoot}guide/developing/tools/traceview.html" title="traceview">Traceview</a> for more information +<a href="{@docRoot}guide/developing/debugging/debugging-tracing.html" title="traceview">Traceview</a> for more information on trace files.</td> </tr> diff --git a/docs/html/guide/developing/tools/othertools.html b/docs/html/guide/developing/tools/othertools.html new file mode 100644 index 0000000..a074f33 --- /dev/null +++ b/docs/html/guide/developing/tools/othertools.html @@ -0,0 +1,10 @@ +<html> +<head> +<meta http-equiv="refresh" content="0;url=http://developer.android.com/guide/developing/tools/index.html"> +<title>Redirecting...</title> +</head> +<body> +<p>You should be redirected. Please <a +href="http://developer.android.com/guide/developing/tools/index.html">click here</a>.</p> +</body> +</html>
\ No newline at end of file diff --git a/docs/html/guide/developing/tools/othertools.jd b/docs/html/guide/developing/tools/othertools.jd deleted file mode 100644 index 00f0b8d..0000000 --- a/docs/html/guide/developing/tools/othertools.jd +++ /dev/null @@ -1,95 +0,0 @@ -page.title=Other Tools -@jd:body - -<p>The sections below describe other tools that you can use when building -Android applications. </p> - -<p>All of the tools are included in the Android SDK and are accessible from the -<code><sdk>/tools/</code> directory.</p> - -<h2>Contents</h2> - -<dl> - <dt><a href="#android">android</a></dd> - <dt><a href="#mksdcard">mksdcard</a></dt> - <dt><a href="#dx">dx</a></dt> -</dl> - -<a name="activitycreator"></a> -<h2 id="android">android</h2> - -<p>{@code android} is an important development tool that lets you:</p> - -<ul> - <li>Create, delete, and view Android Virtual Devices (AVDs). See - <a href="{@docRoot}guide/developing/tools/avd.html">Android Virtual Devices</a>.</li> - <li>Create and update Android projects. See - <a href="{@docRoot}guide/developing/other-ide.html">Developing in Other IDEs</a>.</li> - <li>Update your Android SDK with new platforms, add-ons, and documentation. See - <a href="{@docRoot}sdk/adding-components.html">Adding SDK Components</a>.</li> -</ul> - -<p>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 <a href="{@docRoot}guide/developing/eclipse-adt.html">Developing -In Eclipse</a>. To update your SDK from Eclipse, see -<a href="{@docRoot}sdk/adding-components.html">Adding SDK Components</a>. -</p> - - -<a name="mksdcard"></a> - -<h2>mksdcard</h2> - -<p>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:</p> - -<pre>mksdcard [-l label] <size>[K|M] <file></pre> - -<p>The table below lists the available options/arguments</p> - -<table> -<tr> - <th>Argument</th> - <th>Description</th> -</tr> - -<tr> - <td><code>-l</code></td> - <td>A volume label for the disk image to create. </td> -</tr> - -<tr> - <td><code>size</code></td> - <td>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, <code>1048576K</code>, <code>1024M</code>.</td> -</tr> - -<tr> - <td><code>file</code></td> - <td>The path/filename of the disk image to create. </td> -</tr> - -</table> - -<p>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 -<a href="{@docRoot}guide/developing/tools/emulator.html">Android Emulator</a>.</p> - -<pre>emulator -sdcard <file></pre> - -<a name="dx"></a> - -<h2>dx</h2> - -<p>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 <code>dx --help</code>.</p> - - - - diff --git a/docs/html/guide/developing/tools/sqlite3.jd b/docs/html/guide/developing/tools/sqlite3.jd new file mode 100644 index 0000000..71e614f --- /dev/null +++ b/docs/html/guide/developing/tools/sqlite3.jd @@ -0,0 +1,57 @@ +page.title=sqlite3 +@jd:body + + <p>From a remote shell to your device or from your host machine, you can use the <a href= + "http://www.sqlite.org/sqlite.html">sqlite3</a> command-line program to manage SQLite databases + created by Android applications. The <code>sqlite3</code> tool includes many useful commands, + such as <code>.dump</code> to print out the contents of a table and <code>.schema</code> to print + the SQL CREATE statement for an existing table. The tool also gives you the ability to execute + SQLite commands on the fly.</p> + + <p>To use <code>sqlite3</code> from a remote shell:</p> + + <ol> + <li>Enter a remote shell by entering the following command: + <pre>adb [-d|-e|-s {<serialNumber>}] shell</pre> + </li> + + <li>From a remote shell, start the <code>sqlite3</code> tool by entering the following command: + <pre>sqlite3</pre> + + <p>You can also optionally specify a full path to a database that you want to explore. + Emulator/device instances store SQLite3 databases in the directory + <code>/data/data/<package_name>/databases/</code>.</p> + </li> + + <li>Once you invoke <code>sqlite3</code>, you can issue <code>sqlite3</code> commands in the + shell. To exit and return to the adb remote shell, enter <code>exit</code> or press + <code>CTRL+D</code>.</li> + </ol> + + + <p>Here's an example:</p> + <pre>$ adb -s emulator-5554 shell +# sqlite3 /data/data/com.example.google.rss.rssexample/databases/rssitems.db +SQLite version 3.3.12 +Enter ".help" for instructions +<em>.... enter commands, then quit...</em> +# sqlite> .exit +</pre> + + <p>To use <code>sqlite3</code> locally, instead of within a shell, + pull the database file from the device and start {@code sqlite3}:</p> + + <ol> + <li>Copy a database file from your device to your host machine: + <pre> +adb pull <database-file-on-device> +</pre> + </li> + + <li>Start the sqlite3 tool from the <code>/tools</code> directory, specifying the database + file: + <pre> +sqlite3 <database-file-on-host> +</pre> + </li> + </ol>
\ No newline at end of file diff --git a/docs/html/guide/developing/tools/traceview.jd b/docs/html/guide/developing/tools/traceview.jd index 95ae823..422fe00 100644 --- a/docs/html/guide/developing/tools/traceview.jd +++ b/docs/html/guide/developing/tools/traceview.jd @@ -1,319 +1,14 @@ -page.title=Traceview: A Graphical Log Viewer +page.title=Traceview @jd:body -<div id="qv-wrapper"> -<div id="qv"> +<p>Traceview is a graphical viewer for execution logs saved by your application. +Traceview can help you debug your application and profile its performance.</p> - <h2>In this document</h2> -<ol> - <li><a href="#creatingtracefiles">Creating Trace Files</a></li> - <li><a href="#copyingfiles">Copying Trace Files to a Host Machine</a></li> - <li><a href="#runningtraceview">Viewing Trace Files in Traceview</a> - <ol> - <li><a href="#timelinepanel">Timeline Panel</a></li> - <li><a href="#profilepanel">Profile Panel</a></li> - </ol></li> - <li><a href="#format">Traceview File Format</a> - <ol> - <li><a href="#datafileformat">Data File Format</a></li> - <li><a href="#keyfileformat">Key File Format</a></li> - </ol></li> - <li><a href="#knownissues">Traceview Known Issues</a></li> - <li><a href="#dmtracedump">Using dmtracedump</a></li> +<p>To start Traceview, enter the following command from the SDK <code>tools/</code> directory:</p> + <pre>traceview</pre> </ol> -</div> -</div> -<p>Traceview is a graphical viewer for execution logs -saved by your application. Traceview can help you debug your application and -profile its performance. The sections below describe how to use the program. </p> - -<a name="creatingtracefiles"></a> - -<h2>Creating Trace Files</h2> - -<p>To use Traceview, you need to generate log files containing the trace information you want to analyze. To do that, you include the {@link android.os.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. </p> -<p>To create the trace files, include the {@link android.os.Debug} class and call one - of the {@link android.os.Debug#startMethodTracing() startMethodTracing()} methods. - In the call, you specify a base name for the trace files that the system generates. - To stop tracing, call {@link android.os.Debug#stopMethodTracing() 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.</p> - -<pre> - // start tracing to "/sdcard/calc.trace" - Debug.startMethodTracing("calc"); - // ... - // stop tracing - Debug.stopMethodTracing(); -</pre> - -<p>When your application calls startMethodTracing(), the system creates a -file called <code><trace-base-name>.trace</code>. This contains the -binary method trace data and a mapping table with thread and method names.</p> - -<p>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. </p> - -<p>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. </p> - -<p>When using the Android emulator, you must create an SD card image upon which -the trace files will be written. For example, from the <code>/tools</code> directory, you -can create an SD card image named "imgcd" and mount it when launching the emulator like so:</p> -<pre> -<b>$</b> mksdcard 1024M ./imgcd -<b>$</b> emulator -sdcard ./imgcd -</pre> -<p>For more information, read about the -<a href="{@docRoot}guide/developing/tools/othertools.html#mksdcard">mksdcard tool</a>.</p> - -<p>The format of the trace files is described <a href="#format">later - in this document</a>. </p> - -<a name="copyingfiles"></a> - -<h2>Copying Trace Files to a Host Machine</h2> -<p>After your application has run and the system has created your trace files <code><trace-base-name>.trace</code> - on a device or emulator, you must copy those files to your development computer. You can use <code>adb pull</code> to copy - the files. Here's an example that shows how to copy an example file, - calc.trace, from the default location on the emulator to the /tmp directory on -the emulator host machine:</p> -<pre>adb pull /sdcard/calc.trace /tmp</pre> - - -<a name="runningtraceview"></a> - -<h2>Viewing Trace Files in Traceview</h2> -<p>To run traceview and view the trace files, enter <code>traceview <trace-base-name></code>. - For example, to run Traceview on the example files copied in the previous section, - you would use: </p> - <pre>traceview /tmp/calc</pre> - - <p>Traceview loads the log files and displays their data in a window that has two panels:</p> - <ul> - <li>A <a href="#timelinepanel">timeline panel</a> -- describes when each thread - and method started and stopped</li> - <li>A <a href="#timelinepanel">profile panel</a> -- provides a summary of what happened inside a method</li> - </ul> - <p>The sections below provide addition information about the traceview output panes. </p> - -<a name="timelinepanel"></a> - -<h3>Timeline Panel </h3> -<p>The image below shows a close up of the timeline panel. Each thread’s - execution is shown in its own row, with time increasing to the right. Each method - is shown in another color (colors are reused in a round-robin fashion starting - with the methods that have the most inclusive time). The thin lines underneath - the first row show the extent (entry to exit) of all the calls to the selected - method. The method in this case is LoadListener.nativeFinished() and it was - selected in the profile view. </p> -<p><img src="/images/traceview_timeline.png" alt="Traceview timeline panel" width="893" height="284"></p> -<a name="profilepanel"></a> -<h3>Profile Panel</h3> -<p>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.</p> -<p><img src="/images/traceview_profile.png" alt="Traceview profile panel." width="892" height="630"></p> - -<a name="format"></a> -<h2>Traceview File Format</h2> -<p>Tracing creates two distinct pieces of output: a <em>data</em> file, - which holds the trace data, and a <em>key</em> file, which - provides a mapping from binary identifiers to thread and method names. - The files are concatenated when tracing completes, into a - single <em>.trace</em> file. </p> - -<p class="note"><strong>Note:</strong> The previous version of Traceview did not concatenate -these files for you. If you have old key and data files that you'd still like to trace, you -can concatenate them yourself with <code>cat mytrace.key mytrace.data > mytrace.trace</code>.</p> - -<a name="datafileformat"></a> - -<h3>Data File Format</h3> -<p>The data file is binary, structured as - follows (all values are stored in little-endian order):</p> -<pre>* File format: -* header -* record 0 -* record 1 -* ... -* -* Header format: -* u4 magic 0x574f4c53 ('SLOW') -* u2 version -* u2 offset to data -* u8 start date/time in usec -* -* Record format: -* u1 thread ID -* u4 method ID | method action -* u4 time delta since start, in usec -</pre> -<p>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.</p> -<p><em>u8 start date/time in usec</em> is the output from gettimeofday(). - It's mainly there so that you can tell if the output was generated yesterday - or three months ago.</p> -<p><em>method action</em> sits in the two least-significant bits of the - <em>method</em> word. The currently defined meanings are: </p> -<ul> - <li>0 - method entry </li> - <li>1 - method exit </li> - <li>2 - method "exited" when unrolled by exception handling </li> - <li>3 - (reserved)</li> -</ul> -<p>An unsigned 32-bit integer can hold about 70 minutes of time in microseconds. +<p>For more information on how to use Traceview, see +<a href="{@docRoot}guide/developing/debugging/debugging-tracing.html">Profiling with Traceview and dmtracedump</a> </p> -<a name="keyfileformat"></a> - -<h3>Key File Format</h3> -<p>The key file is a plain text file divided into three sections. Each - section starts with a keyword that begins with '*'. If you see a '*' at the start - of a line, you have found the start of a new section.</p> -<p>An example file might look like this:</p> -<pre>*version -1 -clock=global -*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</pre> -<dl> - <dt><em>version section</em></dt> - <dd>The first line is the file version number, currently - 1. - The second line, <code>clock=global</code>, 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.</dd> - <dt><em>threads section</em></dt> - <dd>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.</dd> - <dt><em>methods section </em></dt> - <dd>One line per method entry or exit. A line consists of four pieces, - separated by tab marks: <em>method-ID</em> [TAB] <em>class-name</em> [TAB] - <em>method-name</em> [TAB] - <em>signature</em> . 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.</dd> -</dl> -<p>Neither the threads nor methods sections are sorted.</p> - -<a name="knownissues"></a> -<h2>Traceview Known Issues</h2> -<dl> - <dt>Threads</dt> - <dd>Traceview logging does not handle threads well, resulting in these two problems: -<ol> - <li> If a thread exits during profiling, the thread name is not emitted; </li> - <li>The VM reuses thread IDs. If a thread stops and another starts, they - may get the same ID. </li> -</ol> -</dd> - -<a name="dmtracedump"></a> - -<h2>Using dmtracedump</h2> - -<p>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.</p> - -<p>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.</p> - -<img src="{@docRoot}images/tracedump.png" width="485" height="401" style="margin-top:1em;"/> - -<p style="margin-top:1em;">For each node, dmtracedump shows <code><ref> <em>callname</em> (<inc-ms>, - <exc-ms>,<numcalls>)</code>, where</p> - -<ul> - <li><code><ref></code> -- Call reference number, as used in trace logs</li> - <li><code><inc-ms></code> -- Inclusive elapsed time (milliseconds spent in method, including all child methods)</li> - <li><code><exc-ms></code> -- Exclusive elapsed time (milliseconds spent in method, not including any child methods)</li> - <li><code><numcalls></code> -- Number of calls</li> -</ul> - -<p>The usage for dmtracedump is: </p> - -<pre>dmtracedump [-ho] [-s sortable] [-d trace-base-name] [-g outfile] <trace-base-name></pre> - -<p>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.</p> - -<table> -<tr> - <th>Option</td> - <th>Description</th> -</tr> - - <tr> - <td><code>-d <trace-base-name> </code></td> - <td>Diff with this trace name</td> - </tr> - <tr> - <td><code>-g <outfile> </code></td> - <td>Generate output to <outfile></td> - </tr> - <tr> - <td><code>-h </code></td> - <td>Turn on HTML output</td> - </tr> - <tr> - <td><code>-o </code></td> - <td>Dump the trace file instead of profiling</td> - </tr> - <tr> - <td><code>-d <trace-base-name> </code></td> - <td>URL base to the location of the sortable javascript file</td> - </tr> - <tr> - <td><code>-t <percent> </code></td> - <td>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%. </td> - </tr> - -</table> diff --git a/docs/html/guide/guide_toc.cs b/docs/html/guide/guide_toc.cs index 8b8dc86..dd4214e 100644 --- a/docs/html/guide/guide_toc.cs +++ b/docs/html/guide/guide_toc.cs @@ -58,6 +58,9 @@ <span class="zh-TW" style="display:none">應用程式基本原理</span> </a></li> + <li><a href="<?cs var:toroot ?>guide/topics/fundamentals/fragments.html"> + <span class="en">Fragments</span> + </a> <span class="new">new!</span></li> </ul> <ul> <li class="toggle-list"> @@ -71,6 +74,9 @@ <li><a href="<?cs var:toroot ?>guide/topics/ui/menus.html"> <span class="en">Creating Menus</span> </a></li> + <li><a href="<?cs var:toroot ?>guide/topics/ui/actionbar.html"> + <span class="en">Using the Action Bar</span> + </a> <span class="new">new!</span></li> <li><a href="<?cs var:toroot ?>guide/topics/ui/dialogs.html"> <span class="en">Creating Dialogs</span> </a></li> @@ -207,6 +213,9 @@ <li><a href="<?cs var:toroot ?>guide/topics/graphics/opengl.html"> <span class="en">3D with OpenGL</span> </a></li> + <li><a href="<?cs var:toroot ?>guide/topics/graphics/animation.html"> + <span class="en">Animation</span> + </a><span class="new">new!</span></li> </ul> </li> <li><a href="<?cs var:toroot ?>guide/topics/media/index.html"> @@ -268,27 +277,22 @@ <li> <a href="<?cs var:toroot?>guide/topics/testing/testing_android.html"> <span class="en">Testing Fundamentals</span></a> - <span class="new">new!</span> </li> <li> <a href="<?cs var:toroot?>guide/topics/testing/activity_testing.html"> <span class="en">Activity Testing</span></a> - <span class="new">new!</span> </li> <li> <a href="<?cs var:toroot?>guide/topics/testing/contentprovider_testing.html"> <span class="en">Content Provider Testing</span></a> - <span class="new">new!</span> </li> <li> <a href="<?cs var:toroot?>guide/topics/testing/service_testing.html"> <span class="en">Service Testing</span></a> - <span class="new">new!</span> </li> <li> <a href="<?cs var:toroot ?>guide/topics/testing/what_to_test.html"> <span class="en">What To Test</span></a> - <span class="new">new!</span> </li> </ul> @@ -353,32 +357,120 @@ <ul> <!--<li><a href="">Developing for Android</a></li> signing, upgrading, selecting a package name, select device profile, touch, trackball, dpad available, etc. --> - <li><a href="<?cs var:toroot ?>guide/developing/eclipse-adt.html"> - <span class="en">In Eclipse, with ADT</span> - <span class="de" style="display:none">In Eclipse, mit ADT</span> - <span class="es" style="display:none">En Eclipse, con ADT</span> - <span class="fr" style="display:none">Sous Eclipse, à l'aide du plugin ADT</span> - <span class="it" style="display:none">In Eclipse, con ADT</span> - <span class="ja" style="display:none">Eclipse 内で ADT を使用</span> - <span class="zh-CN" style="display:none">利用 ADT 在 Eclipse 中开发</span> - <span class="zh-TW" style="display:none">在加裝 ADT 工具的 Eclipse 環境中</span> - </a></li> - <li><a href="<?cs var:toroot ?>guide/developing/other-ide.html"> - <span class="en">In Other IDEs</span> - <span class="de" style="display:none">In anderen IDEs</span> - <span class="es" style="display:none">En otros entornos</span> - <span class="fr" style="display:none">Sous d'autres environnements</span> - <span class="it" style="display:none">In altri IDE</span> - <span class="ja" style="display:none">その他の統合開発環境</span> - <span class="zh-CN" style="display:none">在其他 IDE 中开发</span> - <span class="zh-TW" style="display:none">在其他開發環境中</span> - </a></li> - <li><a href="<?cs var:toroot ?>guide/developing/device.html"> - <span class="en">On a Device</span> - </a></li> - <li><a href="<?cs var:toroot ?>guide/developing/debug-tasks.html"> - <span class="en">Debugging Tasks</span> + <li> + <a href="<?cs var:toroot ?>guide/developing/index.html"> + <span class="en">Overview</span></a> + </li> + + <li class="toggle-list"> + <div> + <a href="<?cs var:toroot ?>guide/developing/devices/index.html"> + <span class="en">Creating and Managing Virtual Devices</span> + </a> + </div> + <ul> + <li> + <a href="<?cs var:toroot ?>guide/developing/devices/managing-avds.html"> + <span class="en">With AVD Manager</span> + </a> + </li> + <li> + <a href="<?cs var:toroot ?>guide/developing/devices/managing-avds-cmdline.html"> + <span class="en">On the Command Line</span> + </a> + </li> + <li> + <a href="<?cs var:toroot ?>guide/developing/devices/emulator.html"> + <span class="en">Using the Android Emulator</span> + </a> + </li> + </ul> + </li> + <li> + <a href="<?cs var:toroot ?>guide/developing/device.html"> + <span class="en">Connecting Hardware Devices</span> + </a> + </li> + + <li class="toggle-list"> + <div> + <a href="<?cs var:toroot ?>guide/developing/projects/index.html"> + <span class="en">Creating and Managing Projects</span> + </a> + </div> + <ul> + <li> + <a href="<?cs var:toroot ?>guide/developing/projects/projects-eclipse.html"> + <span class="en">In Eclipse with ADT</span> + </a> + </li> + <li> + <a href="<?cs var:toroot ?>guide/developing/projects/projects-cmdline.html"> + <span class="en">On the Command Line</span> + </a> + </li> + </ul> + </li> + + <li class="toggle-list"> + <div> + <a href="<?cs var:toroot ?>guide/developing/building/index.html"> + <span class="en">Building and Running Apps</span> + </a> + </div> + <ul> + <li><a href="<?cs var:toroot ?>guide/developing/building/building-eclipse.html"> + <span class="en">In Eclipse with ADT</span> </a></li> + <li><a href="<?cs var:toroot ?>guide/developing/building/building-cmdline.html"><span class="en">On the Command Line</span></a></li> + </ul> + </li> + + <li class="toggle-list"> + <div> + <a href="<?cs var:toroot ?>guide/developing/debugging/index.html"> + <span class="en">Debugging</span> + </a> + </div> + <ul> + <li> + <a href="<?cs var:toroot ?>guide/developing/debugging/debugging-projects.html"> + <span class="en">In Eclipse with ADT</span> + </a> + </li> + <li> + <a href="<?cs var:toroot ?>guide/developing/debugging/debugging-projects-cmdline.html"> + <span class="en">In Other IDEs</span> + </a> + </li> + <li> + <a href="<?cs var:toroot ?>guide/developing/debugging/ddms.html"> + <span class="en">Using DDMS</span> + </a> + </li> + <li> + <a href="<?cs var:toroot ?>guide/developing/debugging/debugging-log.html"> + <span class="en">Reading and Writing Log Messages</span> + </a> + </li> + <li> + <a href="<?cs var:toroot ?>guide/developing/debugging/debugging-ui.html"> + <span class="en">Debugging and Profiling UIs</span> + </a> + </li> + <li> + <a href="<?cs var:toroot ?>guide/developing/debugging/debugging-tracing.html"> + <span class="en">Profiling with Traceview and dmtracedump</span> + </a> + </li> + <li> + <a href="<?cs var:toroot ?>guide/developing/debugging/debugging-devtools.html"> + <span class="en">Using the Dev Tools App</span> + </a> + </li> + </ul> + </li> + <li class="toggle-list"> <div> <a href="<?cs var:toroot ?>guide/developing/testing/index.html"> @@ -388,71 +480,67 @@ <ul> <li> <a href="<?cs var:toroot ?>guide/developing/testing/testing_eclipse.html"> - <span class="en">Testing in Eclipse, with ADT</span> + <span class="en">In Eclipse with ADT</span> </a> </li> <li> <a href="<?cs var:toroot ?>guide/developing/testing/testing_otheride.html"> - <span class="en">Testing in Other IDEs</span> + <span class="en">In Other IDEs</span> </a> </li> </ul> </li> - <li class="toggle-list"> + + <li class="toggle-list"> <div><a href="<?cs var:toroot ?>guide/developing/tools/index.html"> <span class="en">Tools</span> </a></div> <ul> - <li><a href="<?cs var:toroot ?>guide/developing/tools/aapt.html">aapt</a></li> - <li><a href="<?cs var:toroot ?>guide/developing/tools/adb.html">adb</a></li> - <li><a href="<?cs var:toroot ?>guide/developing/tools/othertools.html#android">android</a></li> - <!--<li><a href="<?cs var:toroot ?>guide/developing/tools/adt.html">ADT Plugin</a></li>--> - <li><a href="<?cs var:toroot ?>guide/developing/tools/aidl.html">aidl</a></li> - <li><a href="<?cs var:toroot ?>guide/developing/tools/avd.html">AVDs</a></li> - <li><a href="<?cs var:toroot ?>guide/developing/tools/bmgr.html">bmgr</a></li> - <li><a href="<?cs var:toroot ?>guide/developing/tools/ddms.html">ddms</a></li> - <li><a href="<?cs var:toroot ?>guide/developing/tools/othertools.html#dx">dx</a></li> - <li><a href="<?cs var:toroot ?>guide/developing/tools/draw9patch.html">Draw 9-Patch</a></li> - <li><a href="<?cs var:toroot ?>guide/developing/tools/emulator.html">Emulator</a></li> - <li><a href="<?cs var:toroot ?>guide/developing/tools/hierarchy-viewer.html">Hierarchy Viewer</a></li> - <li><a href="<?cs var:toroot ?>guide/developing/tools/layoutopt.html">layoutopt</a></li> - <li><a href="<?cs var:toroot ?>guide/developing/tools/othertools.html#mksdcard">mksdcard</a></li> - <li><a href="<?cs var:toroot ?>guide/developing/tools/monkey.html">Monkey</a></li> + <li><a href="<?cs var:toroot ?>guide/developing/tools/adb.html">adb</a></li> + <li><a href="<?cs var:toroot ?>guide/developing/tools/android.html">android</a></li> + <li><a href="<?cs var:toroot ?>guide/developing/tools/aidl.html">aidl</a></li> + <li><a href="<?cs var:toroot ?>guide/developing/tools/bmgr.html">bmgr</a> + <li><a href="<?cs var:toroot ?>guide/developing/tools/dmtracedump.html">dmtracedump</a></li> + <li><a href="<?cs var:toroot ?>guide/developing/tools/draw9patch.html" >Draw 9-Patch</a></li> + <li><a href="<?cs var:toroot ?>guide/developing/tools/emulator.html">Emulator</a></li> + <li><a href="<?cs var:toroot ?>guide/developing/tools/hierarchy-viewer.html">Hierarchy Viewer</a></li> + <li><a href="<?cs var:toroot ?>guide/developing/tools/hprof-conv.html">hprof-conv</a></li> + <li><a href="<?cs var:toroot ?>guide/developing/tools/layoutopt.html">layoutopt</a></li> + <li><a href="<?cs var:toroot ?>guide/developing/tools/logcat.html">logcat</a></li> + <li><a href="<?cs var:toroot ?>guide/developing/tools/mksdcard.html">mksdcard</a></li> + + <li><a href="<?cs var:toroot ?>guide/developing/tools/monkey.html">Monkey</a></li> <li class="toggle-list"> <div> - <a href="<?cs var:toroot?>guide/developing/tools/monkeyrunner_concepts.html"> + <a href="<?cs var:toroot ?>guide/developing/tools/monkeyrunner_concepts.html"> <span class="en">monkeyrunner</span> </a> - <span class="new">new!</span> </div> <ul> <li> - <a href="<?cs var:toroot?>guide/developing/tools/MonkeyDevice.html"> + <a href="<?cs var:toroot ?>guide/developing/tools/MonkeyDevice.html"> <span class="en">MonkeyDevice</span> </a> - <span class="new">new!</span> </li> <li> - <a href="<?cs var:toroot?>guide/developing/tools/MonkeyImage.html"> + <a href="<?cs var:toroot ?>guide/developing/tools/MonkeyImage.html"> <span class="en">MonkeyImage</span> </a> - <span class="new">new!</span> </li> <li> - <a href="<?cs var:toroot?>guide/developing/tools/MonkeyRunner.html"> + <a href="<?cs var:toroot ?>guide/developing/tools/MonkeyRunner.html"> <span class="en">MonkeyRunner</span> </a> - <span class="new">new!</span> </li> </ul> </li> - <li><a href="<?cs var:toroot ?>guide/developing/tools/proguard.html">ProGuard</a> <span class="new">new!</span></li> + <li><a href="<?cs var:toroot ?>guide/developing/tools/proguard.html">ProGuard</a></li> <li><a href="<?cs var:toroot ?>guide/developing/tools/adb.html#sqlite">sqlite3</a></li> - <li><a href="<?cs var:toroot ?>guide/developing/tools/traceview.html" >Traceview</a></li> - <li><a href="<?cs var:toroot ?>guide/developing/tools/zipalign.html" >zipalign</a></li> - </ul> - </li> + <li><a href="<?cs var:toroot ?>guide/developing/tools/traceview.html">Traceview</a></li> + <li><a href="<?cs var:toroot ?>guide/developing/tools/zipalign.html">zipalign</a></li> + </ul> + </li> </ul> </li> @@ -581,19 +669,19 @@ <ul> <li><a href="<?cs var:toroot ?>guide/webapps/index.html"> <span class="en">Web Apps Overview</span> - </a> <span class="new">new!</span><!-- 11/1/10 --></li> + </a></li> <li><a href="<?cs var:toroot ?>guide/webapps/targeting.html"> <span class="en">Targeting Screens from Web Apps</span> - </a> <span class="new">new!</span><!-- 11/1/10 --></li> + </a></li> <li><a href="<?cs var:toroot ?>guide/webapps/webview.html"> <span class="en">Building Web Apps in WebView</span> - </a> <span class="new">new!</span><!-- 11/1/10 --></li> + </a></li> <li><a href="<?cs var:toroot ?>guide/webapps/debugging.html"> <span class="en">Debugging Web Apps</span> - </a> <span class="new">new!</span><!-- 11/1/10 --></li> + </a></li> <li><a href="<?cs var:toroot ?>guide/webapps/best-practices.html"> <span class="en">Best Practices for Web Apps</span> - </a> <span class="new">new!</span><!-- 11/1/10 --></li> + </a></li> </ul> </li> diff --git a/docs/html/guide/practices/design/performance.jd b/docs/html/guide/practices/design/performance.jd index f5588ac..fe69d7d 100644 --- a/docs/html/guide/practices/design/performance.jd +++ b/docs/html/guide/practices/design/performance.jd @@ -8,14 +8,13 @@ page.title=Designing for Performance <ol> <li><a href="#intro">Introduction</a></li> <li><a href="#optimize_judiciously">Optimize Judiciously</a></li> - <li><a href="#object_creation">Avoid Creating Objects</a></li> + <li><a href="#object_creation">Avoid Creating Unnecessary Objects</a></li> <li><a href="#myths">Performance Myths</a></li> <li><a href="#prefer_static">Prefer Static Over Virtual</a></li> <li><a href="#internal_get_set">Avoid Internal Getters/Setters</a></li> <li><a href="#use_final">Use Static Final For Constants</a></li> <li><a href="#foreach">Use Enhanced For Loop Syntax</a></li> - <li><a href="#avoid_enums">Avoid Enums Where You Only Need Ints</a></li> - <li><a href="#package_inner">Use Package Scope with Inner Classes</a></li> + <li><a href="#package_inner">Consider Package Instead of Private Access with Inner Classes</a></li> <li><a href="#avoidfloat">Use Floating-Point Judiciously</a> </li> <li><a href="#library">Know And Use The Libraries</a></li> <li><a href="#native_methods">Use Native Methods Judiciously</a></li> @@ -83,27 +82,31 @@ without.</p> test on that device.</p> <a name="object_creation"></a> -<h2>Avoid Creating Objects</h2> +<h2>Avoid Creating Unnecessary Objects</h2> <p>Object creation is never free. A generational GC with per-thread allocation pools for temporary objects can make allocation cheaper, but allocating memory is always more expensive than not allocating memory.</p> <p>If you allocate objects in a user interface loop, you will force a periodic -garbage collection, creating little "hiccups" in the user experience.</p> +garbage collection, creating little "hiccups" in the user experience. The +concurrent collector introduced in Gingerbread helps, but unnecessary work +should always be avoided.</p> <p>Thus, you should avoid creating object instances you don't need to. Some examples of things that can help:</p> <ul> - <li>When extracting strings from a set of input data, try - to return a substring of the original data, instead of creating a copy. - You will create a new String object, but it will share the char[] - with the data.</li> <li>If you have a method returning a string, and you know that its result will always be appended to a StringBuffer anyway, change your signature and implementation so that the function does the append directly, instead of creating a short-lived temporary object.</li> + <li>When extracting strings from a set of input data, try + to return a substring of the original data, instead of creating a copy. + You will create a new String object, but it will share the char[] + with the data. (The trade-off being that if you're only using a small + part of the original input, you'll be keeping it all around in memory + anyway if you go this route.)</li> </ul> <p>A somewhat more radical idea is to slice up multidimensional arrays into @@ -119,7 +122,7 @@ parallel single one-dimension arrays:</p> generally much better than a single array of custom (Foo,Bar) objects. (The exception to this, of course, is when you're designing an API for other code to access; in those cases, it's usually better to trade - correct API design for a small hit in speed. But in your own internal + good API design for a small hit in speed. But in your own internal code, you should try and be as efficient as possible.)</li> </ul> @@ -127,6 +130,7 @@ parallel single one-dimension arrays:</p> can. Fewer objects created mean less-frequent garbage collection, which has a direct impact on user experience.</p> +<a name="avoid_enums" id="avoid_enums"></a> <a name="myths" id="myths"></a> <h2>Performance Myths</h2> @@ -265,43 +269,18 @@ hand-written counted loop for performance-critical ArrayList iteration.</p> <p>(See also <em>Effective Java</em> item 46.)</p> -<a name="avoid_enums" id="avoid_enums"></a> -<h2>Avoid Enums Where You Only Need Ints</h2> - -<p>Enums are very convenient, but unfortunately can be painful when size -and speed matter. For example, this:</p> - -<pre>public enum Shrubbery { GROUND, CRAWLING, HANGING }</pre> - -<p>adds 740 bytes to your .dex file compared to the equivalent class -with three public static final ints. On first use, the -class initializer invokes the <init> method on objects representing each -of the enumerated values. Each object gets its own static field, and the full -set is stored in an array (a static field called "$VALUES"). That's a lot of -code and data, just for three integers. Additionally, this:</p> - -<pre>Shrubbery shrub = Shrubbery.GROUND;</pre> - -<p>causes a static field lookup. If "GROUND" were a static final int, -the compiler would treat it as a known constant and inline it.</p> - -<p>The flip side, of course, is that with enums you get nicer APIs and -some compile-time value checking. So, the usual trade-off applies: you should -by all means use enums for public APIs, but try to avoid them when performance -matters.</p> - -<p>If you're using <code>Enum.ordinal</code>, that's usually a sign that you -should be using ints instead. As a rule of thumb, if an enum doesn't have a -constructor and doesn't define its own methods, and it's used in -performance-critical code, you should consider <code>static final int</code> -constants instead.</p> - <a name="package_inner" id="package_inner"></a> -<h2>Use Package Scope with Inner Classes</h2> +<h2>Consider Package Instead of Private Access with Private Inner Classes</h2> <p>Consider the following class definition:</p> <pre>public class Foo { + private class Inner { + void stuff() { + Foo.this.doStuff(Foo.this.mValue); + } + } + private int mValue; public void run() { @@ -313,24 +292,19 @@ constants instead.</p> private void doStuff(int value) { System.out.println("Value is " + value); } - - private class Inner { - void stuff() { - Foo.this.doStuff(Foo.this.mValue); - } - } }</pre> -<p>The key things to note here are that we define an inner class (Foo$Inner) -that directly accesses a private method and a private instance field -in the outer class. This is legal, and the code prints "Value is 27" as -expected.</p> +<p>The key things to note here are that we define a private inner class +(<code>Foo$Inner</code>) that directly accesses a private method and a private +instance field in the outer class. This is legal, and the code prints "Value is +27" as expected.</p> -<p>The problem is that the VM considers direct access to Foo's private members -from Foo$Inner to be illegal because Foo and Foo$Inner are different classes, -even though the Java language allows an inner class to access an outer class' -private members. To bridge the gap, the compiler generates a couple of -synthetic methods:</p> +<p>The problem is that the VM considers direct access to <code>Foo</code>'s +private members from <code>Foo$Inner</code> to be illegal because +<code>Foo</code> and <code>Foo$Inner</code> are different classes, even though +the Java language allows an inner class to access an outer class' private +members. To bridge the gap, the compiler generates a couple of synthetic +methods:</p> <pre>/*package*/ static int Foo.access$100(Foo foo) { return foo.mValue; @@ -339,22 +313,19 @@ synthetic methods:</p> foo.doStuff(value); }</pre> -<p>The inner-class code calls these static methods whenever it needs to -access the "mValue" field or invoke the "doStuff" method in the outer -class. What this means is that the code above really boils down to a case -where you're accessing member fields through accessor methods instead of -directly. Earlier we talked about how accessors are slower than direct field +<p>The inner class code calls these static methods whenever it needs to +access the <code>mValue</code> field or invoke the <code>doStuff</code> method +in the outer class. What this means is that the code above really boils down to +a case where you're accessing member fields through accessor methods. +Earlier we talked about how accessors are slower than direct field accesses, so this is an example of a certain language idiom resulting in an "invisible" performance hit.</p> -<p>We can avoid this problem by declaring fields and methods accessed -by inner classes to have package scope, rather than private scope. -This runs faster and removes the overhead of the generated methods. -(Unfortunately it also means the fields could be accessed directly by other -classes in the same package, which runs counter to the standard -practice of making all fields private. Once again, if you're -designing a public API you might want to carefully consider using this -optimization.)</p> +<p>If you're using code like this in a performance hotspot, you can avoid the +overhead by declaring fields and methods accessed by inner classes to have +package access, rather than private access. Unfortunately this means the fields +can be accessed directly by other classes in the same package, so you shouldn't +use this in public API.</p> <a name="avoidfloat" id="avoidfloat"></a> <h2>Use Floating-Point Judiciously</h2> @@ -425,7 +396,7 @@ managed to optimize all your code away). We highly recommend you use Caliper to run your own microbenchmarks.</p> <p>You may also find -<a href="{@docRoot}guide/developing/tools/traceview.html">Traceview</a> useful +<a href="{@docRoot}guide/developing/debugging/debugging-tracing.html">Traceview</a> useful for profiling, but it's important to realize that it currently disables the JIT, which may cause it to misattribute time to code that the JIT may be able to win back. It's especially important after making changes suggested by Traceview diff --git a/docs/html/guide/practices/screens_support.jd b/docs/html/guide/practices/screens_support.jd index 5738bd6..520bd28 100644 --- a/docs/html/guide/practices/screens_support.jd +++ b/docs/html/guide/practices/screens_support.jd @@ -38,7 +38,7 @@ page.title=Supporting Multiple Screens <li><a href="{@docRoot}guide/topics/resources/providing-resources.html#AlternativeResources"> Providing Alternative Resources</a></li> - <li><a href="{@docRoot}guide/developing/tools/avd.html">Android Virtual Devices</a></li> + <li><a href="{@docRoot}guide/developing/devices/index.html">Creating and Managing Virtual Devices</a></li> </ol> </div> @@ -1205,7 +1205,7 @@ includes several emulator skins to get you started. You can use the Android AVD Manager or the <code>android</code> tool to create AVDs that use the various emulator skins and you can also set up custom AVDs to test densities other than the defaults. For general information about working with AVDs, see -<a href="{@docRoot}guide/developing/tools/avd.html">Android Virtual +<a href="{@docRoot}guide/developing/devices/index.html">Creating and Managing Virtual Devices</a>.</p> <p>The Android SDK provides a set of default emulator skins that you can use for diff --git a/docs/html/guide/publishing/app-signing.jd b/docs/html/guide/publishing/app-signing.jd index 101646e..93077a0 100644 --- a/docs/html/guide/publishing/app-signing.jd +++ b/docs/html/guide/publishing/app-signing.jd @@ -240,8 +240,8 @@ is enabled by using the <code>debug</code> option with the <code>ant</code> comm compile your app, the build script generates a keystore/key and signs the .apk for you. The script then also aligns the .apk with the <code>zipalign</code> tool. No other action on your part is needed. Read -<a href="{@docRoot}guide/developing/other-ide.html#DebugMode">Developing In Other IDEs: Building -in debug mode</a> for more information.</p> +<a href="{@docRoot}guide/developing/building/building-cmdline.html#DebugMode">Building and Running Apps +on the Command Line</a> for more information.</p> <h3 id="debugexpiry">Expiry of the Debug Certificate</h3> @@ -441,8 +441,8 @@ file in {@code bin/} will instead be <code><em><your_project_name></em>-release.apk</code>. With these steps automated for you, you're able to skip the manual procedures below (steps 3 and 4). To learn how to specify your keystore and alias in the {@code build.properties} file, -see <a href="{@docRoot}guide/developing/other-ide.html#ReleaseMode">Developing In Other -IDEs: Building in release mode</a>.</p> +see <a href="{@docRoot}guide/developing/building/building-cmdline.html#ReleaseMode"> +Building and Running Apps on the Command Line</a>.</p> diff --git a/docs/html/guide/publishing/licensing.jd b/docs/html/guide/publishing/licensing.jd index 40439f0..e099413 100644 --- a/docs/html/guide/publishing/licensing.jd +++ b/docs/html/guide/publishing/licensing.jd @@ -518,7 +518,7 @@ Android Virtual Devices.</li> </ol> <p>If you are not familiar with AVDs or how to use them, see <a -href="{@docRoot}guide/developing/tools/avd.html">Android Virtual Devices</a>.</p> +href="{@docRoot}guide/developing/devices/index.html">Creating and Managing Virtual Devices</a>.</p> <h4 id="project-update">Updating your project configuration</h4> @@ -628,12 +628,9 @@ version of the LVL.</p> share its code and resources across multiple applications. </p> <p style="margin-top:.5em;">If you aren't familiar with library projects or how -to use them, read more in <a -href="{@docRoot}guide/developing/eclipse-adt.html#libraryProject">Developing in -Eclipse with ADT</a> or <a -href="{@docRoot}guide/developing/other-ide.html#libraryProject">Developing in -Other IDEs</a>, as appropriate for your environment.</p> - +to use them, see <a href="{@docRoot}guide/developing/projects/index.html#LibraryProjects"> +Creating and Managing Projects</a>. +</p> </div> </div> @@ -669,9 +666,8 @@ predefined as a library project in its <code>default.properties</code> file, so no further configuration is needed. </p> <p>For more information about how to create an application project or work with -library projects in Eclipse, see <a -href="{@docRoot}guide/developing/eclipse-adt.html#CreatingAProject">Developing -in Eclipse with ADT</a>.</p> +library projects in Eclipse, see <a href="{@docRoot}guide/developing/projects/projects-eclipse.html"> +Creating and Managing Projects in Eclipse</a></p>. <h4>Copying the LVL sources to your application</h4> @@ -701,9 +697,9 @@ haven't done that already, do it now before continuing. </p> <p>Next, open the application's project properties window, as shown below. Select the "Android" properties group and click <strong>Add</strong>, then choose the LVL library project (com_android_vending_licensing) and click -<strong>OK</strong>. For more information, see -<a href="{@docRoot}guide/developing/eclipse-adt.html#libraryProject">Developing -in Eclipse with ADT</a></p> +<strong>OK</strong>. For more information, see +<a href="{@docRoot}developing/projects/projects-eclipse.html#SettingUpLibraryProject"> +Creating and Managing Projects in Eclipse</a></p>. <div style="margin-bottom:2em;"> @@ -730,11 +726,9 @@ properties, including the reference to the library project:</p> --library <em>path/to/my/library_project</em> </pre> -<p>For more information about working with library projects, see <a -href="{@docRoot}guide/developing/eclipse-adt.html#libraryProject">Developing -in Eclipse with ADT</a> or <a -href="{@docRoot}guide/developing/other-ide.html#libraryProject">Developing in -Other IDEs</a>, as appropriate for your environment.</p> +<p>For more information about working with library projects, +see <a href="{@docRoot}developing/projects/projects-cmdline.html#SettingUpLibraryProject"> +Creating and Managing Projects on the Command Line</a></p>. <h2 id="app-integration">Integrating the LVL with Your Application</h2> diff --git a/docs/html/guide/topics/advanced/aidl.jd b/docs/html/guide/topics/advanced/aidl.jd new file mode 100644 index 0000000..fef46ec --- /dev/null +++ b/docs/html/guide/topics/advanced/aidl.jd @@ -0,0 +1,387 @@ +page.title=Android Interface Definition Language (AIDL) +@jd:body + + + +<p>AIDL (Android Interface Definition Language) is similar to other IDLs you might have +worked with. It allows you to define the programming interface that both +the client and service agree upon in order to communicate with each other and allows for +interprocess communication (IPC). On Android, one process can not normally access the +memory of another process. So to talk, they need to decompose their objects into primitives that the +operating system can understand, and "marshall" the object across that boundary for you. The code to +do that marshalling is tedious to write, so Android handles it for you with AIDL.</p> + +<p class="note"><strong>Note:</strong> Using AIDL is necessary only if you allow clients from +different applications to access your service for IPC and want to handle multithreading in your +service. If you do not need to perform IPC across +different applications, you should create your interface <a href="Binder">implementing a +Binder</a> or, if you want to perform IPC, but do not need to handle multithreading, then you +should implement your interface <a href="#Messenger">using a Messenger</a>.</p> + +<p>Before you begin designing your AIDL interface, be aware that calls on to an AIDL interface are +direct function calls. You can not generally make assumptions about the thread in which the call +will happen. What happens is different depending on whether the call is from a thread in the +local process, or coming from a remote process. Specifically:</p> + +<ul> +<li>Calls from the local process are executed in the same thread that is making the call. If this is +your main UI thread, that thread will continue executing into the aidl interface. If it is another +thread, that is one that will be executing your code. Thus if only local threads are accessing the +interface, you can completely control which threads are executing in it (but if that is the case, +why are you defining an aidl interface at all?).</li> + +<li>Calls from a remote process are dispatched from a thread pool the platform maintains inside of +your own process. You must be prepared for incoming calls from unknown threads, with multiple calls +happening at the same time. In other words, an implementation of an aidl interface must be +completely thread-safe.</li> + +<li>The "oneway" keyword modifies the behavior of remote calls. When used, a remote call will not +block until its call completes; it simply sends the transaction data and immediately returns. The +implementation of the interface will eventually receive this as a regular call from the {@link +android.os.Binder} thread pool as a normal remote call. If "oneway" is used with a local call, +there is no impact and the call is still synchronous.</li> +</ul> + + +<h2 id="Defining">Defining an AIDL Interface</h2> + +<p>You must define your AIDL interface in an {@code .aidl} file using the Java +programming language syntax, then save it in the source code (in the {@code src/} directory) of both +the application hosting the service and any other application that will bind to the service.</p> + +<p>When you build the projects containing the {@code .aidl} file, the Android SDK tools generate an +{@link android.os.IBinder} class based on your AIDL interface (and saves the file in the {@code +gen/} directory). This class defines the APIs you can call to perform RPC as an interface—you +must implement the interface in your service.</p> + +<p>To create a bounded service using AIDL, follow these steps:</p> +<ol> + <li><a href="#CreateAidl">Create the .aidl file</a> + <p>This file defines the programming interface with method signatures.</p> + </li> + <li><a href="#ImplementTheInterface">Implement the interface</a> + <p>The Android SDK tools generate an interface in the Java programming language, based on your +{@code .aidl} file. This interface has an inner abstract class named {@code Stub} that extends +{@link android.os.Binder} and implements methods from your AIDL interface. You must extend the +{@code Stub} class and implement the methods.</p> + </li> + <li><a href="#ExposeTheInterface">Expose the interface to clients</a> + <p>Implement a {@link android.app.Service Service} and override {@link +android.app.Service#onBind onBind()} to return your implementation of the {@code Stub} +class.</p> + </li> +</ol> + +<p class="caution"><strong>Caution:</strong> Any changes that you make to your AIDL interface after +your first release must remain backward compatible in order to avoid breaking other applications +that use your service. That is, because your {@code .aidl} file must be copied to other applications +in order for them to access your service's interface, you must maintain support for the original +interface.</p> + + +<h3 id="CreateAidl">1. Create the .aidl file</h3> + +<p>AIDL uses a simple syntax that lets you declare an interface with one or more methods that can +take parameters and return values. The parameters and return values can be of any type, even other +AIDL-generated interfaces.</p> + +<p>The syntax for the {@code .aidl} file uses the Java programming language. The file defines a +single interface and requires only the interface declaration and method signatures.</p> + +<p>By default, AIDL supports the following data types:</p> + +<ul> + <li>All primitive types in the Java programming language ({@code int}, {@code long}, {@code +char}, {@code boolean}, etc.)</li> + <li>{@link java.lang.String}</li> + <li>{@link java.lang.CharSequence}</li> + <li>{@link java.util.List} + <p>All elements in the {@link java.util.List} must be one of the supported data types in this +list or one of the other AIDL-generated interfaces or parcelables you've declared. A {@link +java.util.List} may optionally be used as a "generic" class (e.g. <code>List<String></code>). +The actual concrete class that the other side will receive will always be an {@link +java.util.ArrayList}, although the method will be generated to use the {@link +java.util.List} interface.</p> + </li> + <li>{@link java.util.Map} + <p>All elements in the {@link java.util.Map} must be one of the supported data types in this +list or one of the other AIDL-generated interfaces or parcelables you've declared. Generic maps, +(such as those of the form +{@code Map<String,Integer>} are not supported. The actual concrete class that the other side +will receive will always be a {@link java.util.HashMap}, although the method will be generated to +use the {@link java.util.Map} interface.</p> + </li> +</ul> + +<p>You must include an {@code import} statement for each additional type not listed above, even if +they are defined in the same package as your interface.</p> + +<p>When defining methods for your service interface, be aware that:</p> +<ul> + <li>Methods can take zero or more parameters, and return a value or void.</li> + <li>All non-primitive parameters require a directional tag indicating which way the data will go. +Either <code>in</code>, <code>out</code>, or <code>inout</code> (see the example below). + <p>Primitives are <code>in</code> by default, and cannot be otherwise.</p> + <p class="caution"><strong>Caution:</strong> You should limit the direction to what is truly +needed, because marshalling parameters is expensive.</p></li> + <li>All code comments included in the {@code .aidl} file are included in the generated {@link +android.os.IBinder} interface (except for comments before the import and package +statements).</li> +</ul> + +<p>Here is an example {@code .aidl} file:</p> + +<pre> +// IRemoteService.aidl +package com.example.android; + +// Declare any non-default types here with import statements + +/** Example service interface */ +interface IRemoteService { + /** Request the process ID of this service, to do evil things with it. */ + int getPid(); + + /** Demonstrates some basic types that you can use as parameters + * and return values in AIDL. + */ + void basicTypes(int anInt, long aLong, boolean aBoolean, float aFloat, + double aDouble, String aString); +} +</pre> + +<p>Simply save your {@code .aidl} file in your project's {@code src/} directory and when you +build your application, the SDK tools will generate the binder class file in your project's +{@code gen/} directory. The generated file name matches the {@code .aidl} file name, but with a +{@code .java} extension (for example, {@code IRemoteService.aidl} results in {@code +IRemoteService.java}).</p> + +<p>If you use Eclipse, the incremental build generates the binder class almost immediately. If you +do not use Eclipse, then the Ant tool generates the binder class next time you build your +application—you should build your project with <code>ant debug</code> (or <code>ant +release</code>) as soon as you're finished writing the {@code .aidl} file, so that your code can +link against the generated class.</p> + + +<h3 id="ImplementTheInterface">2. Implement the interface</h3> + +<p>When you build your application, the Android SDK tools generate a {@code .java} interface file +named after your {@code .aidl} file. The generated interface includes a subclass named {@code Stub} +that is an abstract implementation of its parent interface (for example, {@code +YourInterface.Stub}) and declares all the methods from the {@code .aidl} file.</p> + +<p class="note"><strong>Note:</strong> {@code Stub} also +defines a few helper methods, most notably {@code asInterface()}, which takes an {@link +android.os.IBinder} (usually the one passed to a client's {@link +android.content.ServiceConnection#onServiceConnected onServiceConnected()} callback method) and +returns an instance of the stub interface. See the section <a href="#calling">Calling an IPC +Method</a> for more details on how to make this cast.</p></p> + +<p>To implement the interface generated from the {@code .aidl}, extend the generated {@link +android.os.Binder} interface (for example, {@code YourInterface.Stub}) and implement the methods +inherited from the {@code .aidl} file.</p> + +<p>Here is an example implementation of an interface called {@code IRemoteService} (defined by the +{@code IRemoteService.aidl} example, above) using an anonymous instance:</p> + +<pre> +private final IRemoteService.Stub mBinder = new IRemoteService.Stub() { + public int getPid(){ + return Process.myPid(); + } + public void basicTypes(int anInt, long aLong, boolean aBoolean, + float aFloat, double aDouble, String aString) { + // Does nothing + } +}; +</pre> + +<p>Now the {@code mBinder} is an instance of the {@code Stub} class (a {@link android.os.Binder}), +which defines the RPC interface for the service. In the next step, this instance is exposed to +clients so they can interact with the service.</p> + +<p>There are a few rules you should be aware of when implementing your AIDL interface: </p> +<ul> + <li>Incoming calls are not guaranteed to be executed on the main thread, so you need to think +about multithreading from the start and properly build your service to be thread-safe.</li> + <li>By default, RPC calls are synchronous. If you know that the service takes more than a few +milliseconds to complete a request, you should not call it from the activity's main thread, because +it might hang the application (Android might display an "Application is Not Responding" +dialog)—you should usually call them from a separate thread in the client. </li> + <li>No exceptions that you throw are sent back to the caller.</li> + <li>Only methods are supported; you cannot expose static fields in AIDL.</li> +</ul> + + +<h3 id="ExposeTheInterface">3. Expose the interface to clients</h3> + +<p>Once you've implemented the interface for your service, you need to expose it to +clients so they can bind to it. To expose the interface +for your service, extend {@link android.app.Service Service} and implement {@link +android.app.Service#onBind onBind()} to return an instance of your class that implements +the generated {@code Stub} (as discussed in the previous section). Here's an example +service that exposes the {@code IRemoteService} example interface to clients. </p> + +<pre> +public class RemoteService extends Service { + @Override + public void onCreate() { + super.onCreate(); + } + + @Override + public IBinder onBind(Intent intent) { + // Return the interface + return mBinder; + } + + private final IRemoteService.Stub mBinder = new IRemoteService.Stub() { + public int getPid(){ + return Process.myPid(); + } + public void basicTypes(int anInt, long aLong, boolean aBoolean, + float aFloat, double aDouble, String aString) { + // Does nothing + } + }; +} +</pre> + +<p>Now, when a client (such as an activity) calls {@link android.content.Context#bindService +bindService()} to connect to this service, the client's {@link +android.content.ServiceConnection#onServiceConnected onServiceConnected()} callback receives the +{@code mBinder} instance returned by the service's {@link android.app.Service#onBind onBind()} +method.</p> + +<p>The client must also have access to the interface class, so if the client and service are in +separate applications, then the client's application must have a copy of the {@code .aidl} file +in its {@code src/} directory (which generates the {@code android.os.Binder} +interface—providing the client access to the AIDL methods).</p> + +<p>When the client receives the {@link android.os.IBinder} in the {@link +android.content.ServiceConnection#onServiceConnected onServiceConnected()} callback, it must call +<code><em>YourServiceInterface</em>.Stub.asInterface(service)</code> to cast the returned +parameter to <code><em>YourServiceInterface</em></code> type. For example:</p> + +<pre> +IRemoteService mIRemoteService; +private ServiceConnection mConnection = new ServiceConnection() { + // Called when the connection with the service is established + public void onServiceConnected(ComponentName className, IBinder service) { + // Following the example above for an AIDL interface, + // this gets an instance of the IRemoteInterface, which we can use to call on the service + mIRemoteService = IRemoteService.Stub.asInterface(service); + } + + // Called when the connection with the service disconnects unexpectedly + public void onServiceDisconnected(ComponentName className) { + Log.e(TAG, "onServiceDisconnected"); + } +}; +</pre> + +<p>For more sample code, see the <a +href="{@docRoot}resources/samples/ApiDemos/src/com/example/android/apis/app/RemoteService.html">{@code +RemoteService.java}</a> class in <a +href="{@docRoot}resources/samples/ApiDemos/index.html">ApiDemos</a>.</p> + + + + + + + + +<h2 id="PassingObjects">Passing Objects over IPC</h2> + +<p>If you have a class that you would like to send from one process to another through +an IPC interface, you can do that. However, you must ensure that the code for your class is +available to the other side of the IPC and the class must support the {@link +android.os.Parcelable} interface, in order for the objects to be decomposed into primitives and +marshalled across processes by the Android system.</p> + +<p>There are five parts to making a class support the {@link android.os.Parcelable} protocol:</b> +<ol> +<li>Make your class implement the {@link android.os.Parcelable} interface.</li> +<li>Implement {@link android.os.Parcelable#writeToParcel writeToParcel}, which takes the +current state of the object and writes it to a {@link android.os.Parcel}.</li> +<li>Add a static field called <code>CREATOR</code> to your class which is an object implementing +the {@link android.os.Parcelable.Creator Parcelable.Creator} interface.</li> +<li>Finally, create an {@code .aidl} file that declares your parcelable class (as shown for the +{@code Rect.aidl} file, below). + <p>If you are using a custom build process, do <em>not</em> add the {@code .aidl} file to your +build. Similar to a header file in the C language, this {@code .aidl} file isn't compiled.</p></li> +</ol> + +<p>AIDL will use these methods and fields in the code it generates to marshall and unmarshall +your objects.</p> + +<p>For example, here is a {@code Rect.aidl} file to create a {@code Rect} class that's +parcelable:</p> + +<pre> +package android.graphics; + +// Declare Rect so AIDL can find it and knows that it implements +// the parcelable protocol. +parcelable Rect; +</pre> + +<p>And here is an example of how the {@link android.graphics.Rect} class implements the +{@link android.os.Parcelable} protocol.</p> + +<pre> +import android.os.Parcel; +import android.os.Parcelable; + +public final class Rect implements Parcelable { + public int left; + public int top; + public int right; + public int bottom; + + public static final Parcelable.Creator<Rect> CREATOR = new +Parcelable.Creator<Rect>() { + public Rect createFromParcel(Parcel in) { + return new Rect(in); + } + + public Rect[] newArray(int size) { + return new Rect[size]; + } + }; + + 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(); + } +} +</pre> + +<p>The marshalling in the {@code Rect} class is pretty simple. Take a look at the other +methods on {@link android.os.Parcel} to see the other kinds of values you can write +to a Parcel.</p> + +<p class="warning"><strong>Warning:</strong> Don't forget the security implications of receiving +data from other processes. In this case, the {@code Rect} will read four numbers from the {@link +android.os.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 <a +href="{@docRoot}guide/topics/security/security.html">Security and Permissions</a> for more +information about how to keep your application secure from malware.</p> + diff --git a/docs/html/guide/topics/fundamentals.jd b/docs/html/guide/topics/fundamentals.jd index a095087..1658fa6 100644 --- a/docs/html/guide/topics/fundamentals.jd +++ b/docs/html/guide/topics/fundamentals.jd @@ -19,6 +19,7 @@ page.title=Application Fundamentals <li><a href="#lmodes">Launch modes</a></li> <li><a href="#clearstack">Clearing the stack</a></li> <li><a href="#starttask">Starting tasks</a></li> + <li><a href="#commonpatterns">Common patterns</a></li> </ol></li> <li><a href="#procthread">Processes and Threads</a> <ol> @@ -51,10 +52,9 @@ page.title=Application Fundamentals <p> Android applications are written in the Java programming language. The compiled Java code — along with any data and resource -files required by the application — is bundled by the -<a href="{@docRoot}guide/developing/tools/aapt.html"><code>aapt</code> -tool</a> into an <i>Android package</i>, an archive file -marked by an {@code .apk} suffix. This file is the vehicle +files required by the application — is bundled into an +<i>Android package</i>, an archive file +marked by an {@code .apk} suffix. This file is the vehicle for distributing the application and installing it on mobile devices; it's the file users download to their devices. All the code in a single {@code .apk} file is considered to be one <i>application</i>. @@ -294,8 +294,8 @@ onActivityResult()}</code> method. <li><p>A service is started (or new instructions are given to an ongoing service) by passing an Intent object to <code>{@link android.content.Context#startService Context.startService()}</code>. -Android calls the service's <code>{@link android.app.Service#onStart -onStart()}</code> method and passes it the Intent object.</p> +Android calls the service's <code>{@link android.app.Service#onStartCommand +onStartCommand()}</code> method and passes it the Intent object.</p> <p> Similarly, an intent can be passed to <code>{@link @@ -424,7 +424,7 @@ elements for broadcast receivers, and <code><a href="{@docRoot}guide/topics/manifest/provider-element.html"><provider></a></code> elements for content providers. Activities, services, and content providers that are not declared in the manifest are not visible to the system and are -consequently never run. However, broadcast receivers can either be +consequently never run. However, broadcast receivers can either be declared in the manifest, or they can be created dynamically in code (as {@link android.content.BroadcastReceiver} objects) and registered with the system by calling @@ -892,6 +892,60 @@ See <a href="#clearstack">Clearing the stack</a>, earlier. </p> +<h3 id="commonpatterns">Common patterns</h3> + +<p> +In most cases an application won't use any flags or special features. +This gives the standard interaction the user expects: launching the application +brings any existing task to the foreground, or starts the main activity in +a new task if there isn't one. +</p> + +<p> +If an application posts notifications, it needs to decide how the user's +selection of a notification should impact any currently running task. The +current suggested behavior is that any current tasks be completely removed, +replaced with a new task containing a stack of activities representing where +the user is jumping in to the app. This can be accomplished with a combination +of the {@link android.app.PendingIntent#getActivities PendingIntent.getActivities()} +method and {@link android.content.Intent#FLAG_ACTIVITY_CLEAR_TASK Intent.FLAG_ACTIVITY_CLEAR_TASK}. +</p> + +<p> +For example, here is sample code to build an array of Intents to launch an +application into an activity three levels deep. The first Intent is always +the main Intent of the application as started by the launcher. The exact +details of the Intent data will of course depend on your application. +</p> + +{@sample development/samples/ApiDemos/src/com/example/android/apis/app/StatusBarNotifications.java + intent_array} + +<p> +In some cases an application may not want to directly launch its application +from a notification, but instead go to a intermediate summary activity. To +accomplish this, the summary activity should be given a task affinity that +is different from the main application (one will typically give it no affinity, +that is "") so that it does not get launched into any existing application task. +</p> + +{@sample development/samples/ApiDemos/AndroidManifest.xml no_task_affinity} + +<p> +The PendingIntent to launch this then does not need to supply anything special: +</p> + +{@sample development/samples/ApiDemos/src/com/example/android/apis/app/IncomingMessage.java + pending_intent} + +<p> +If an application implements an app widget, it should generally use the same +approach as the first one for notifications: when the user taps on the app +widget it should throw away any current task of the application and start a +new task with potentially multiple activities representing the state the +user is jumping in to. +</p> + <h2 id="procthread">Processes and Threads</h2> <p> @@ -1510,9 +1564,9 @@ a music playback service could create the thread where the music will be played in {@code onCreate()}, and then stop the thread in {@code onDestroy()}.</li> <li><p>The <b>active lifetime</b> of a service begins with a call to -<code>{@link android.app.Service#onStart onStart()}</code>. This method +<code>{@link android.app.Service#onStartCommand onStartCommand()}</code>. This method is handed the Intent object that was passed to {@code startService()}. -The music service would open the Intent to discover which music to +The music service would open the Intent to discover which music to play, and begin the playback.</p> <p> @@ -1527,7 +1581,7 @@ services, whether they're started by <code>{@link android.content.Context#startService Context.startService()}</code> or <code>{@link android.content.Context#bindService Context.bindService()}</code>. -However, {@code onStart()} is called only for services started by {@code +However, {@code onStartCommand()} is called only for services started by {@code startService()}. </p> @@ -1631,7 +1685,7 @@ to the activity that the user is interacting with.</p></li> <li><p>It has a {@link android.app.Service} object that's executing one of its lifecycle callbacks (<code>{@link android.app.Service#onCreate -onCreate()}</code>, <code>{@link android.app.Service#onStart onStart()}</code>, +onCreate()}</code>, <code>{@link android.app.Service#onStartCommand onStartCommand()}</code>, or <code>{@link android.app.Service#onDestroy onDestroy()}</code>).</p></li> <li><p>It has a {@link android.content.BroadcastReceiver} object that's diff --git a/docs/html/guide/topics/fundamentals/activities.jd b/docs/html/guide/topics/fundamentals/activities.jd new file mode 100644 index 0000000..b616ab8 --- /dev/null +++ b/docs/html/guide/topics/fundamentals/activities.jd @@ -0,0 +1,762 @@ +page.title=Activities +parent.title=Application Fundamentals +parent.link=index.html +@jd:body + +<div id="qv-wrapper"> +<div id="qv"> +<h2>Quickview</h2> +<ul> + <li>An activity provides a user interface for a single screen in your application</li> + <li>Activities can move into the background and then be resumed with their state restored</li> +</ul> + +<h2>In this document</h2> +<ol> + <li><a href="#Creating">Creating an Activity</a> + <ol> + <li><a href="#UI">Implementing a user interface</a></li> + <li><a href="#Declaring">Declaring the activity in the manifest</a></li> + </ol> + </li> + <li><a href="#StartingAnActivity">Starting an Activity</a> + <ol> + <li><a href="#StartingAnActivityForResult">Starting an Activity for a Result</a></li> + </ol> + </li> + <li><a href="#Lifecycle">Managing the Activity Lifecycle</a> + <ol> + <li><a href="#ImplementingLifecycleCallbacks">Implementing the lifecycle callbacks</a></li> + <li><a href="#SavingActivityState">Saving activity state</a></li> + <li><a href="#ConfigurationChanges">Handling configuration changes</a></li> + <li><a href="#CoordinatingActivities">Coordinating activities</a></li> + </ol> + </li> +</ol> + +<h2>Key classes</h2> +<ol> + <li>{@link android.app.Activity}</li> +</ol> + +<h2>See also</h2> +<ol> + <li><a href="{@docRoot}resources/tutorials/hello-world.html">Hello World Tutorial</a></li> + <li><a href="{@docRoot}guide/topics/fundamentals/tasks-and-back-stack">Tasks and Back +Stack</a></li> +</ol> + +</div> +</div> + + + +<p>An {@link android.app.Activity} is an application component that provides a screen with which +users can interact in order to do something, such as dial the phone, take a photo, send an email, or +view a map. Each activity is given a window in which to draw its user interface. The window +typically fills the screen, but may be smaller than the screen and float on top of other +windows.</p> + +<p> An application usually consists of multiple activities that are loosely bound +to each other. Typically, one activity in an application is specified as the "main" activity, which +is presented to the user when launching the application for the first time. Each +activity can then start another activity in order to perform different actions. Each time a new +activity starts, the previous activity is stopped, but the system preserves the activity +in a stack (the "back stack"). When a new activity starts, it is pushed onto the back stack and +takes user focus. The back stack abides to the basic "last in, first out" queue mechanism, +so, when the user is done with the current activity and presses the BACK key, it +is popped from the stack (and destroyed) and the previous activity resumes. (The back stack is +discussed more in the <a href="{@docRoot}guide/topics/fundamentals/tasks-and-back-stack.html">Tasks +and Back Stack</a> document.)</p> + +<p>When an activity is stopped because a new activity starts, it is notified of this change in state +through the activity's lifecycle callback methods. +There are several callback methods that an activity might receive, due to a change in its +state—whether the system is creating it, stopping it, resuming it, or destroying it—and +each callback provides you the opportunity to perform specific work that's +appropriate to that state change. For instance, when stopped, your activity should release any +large objects, such as network or database connections. When the activity resumes, you can +reacquire the necessary resources and resume actions that were interrupted. These state transitions +are all part of the activity lifecycle.</p> + +<p>The rest of this document discusses the basics of how to build and use an activity, +including a complete discussion of how the activity lifecycle works, so you can properly manage +the transition between various activity states.</p> + + + +<h2 id="Creating">Creating an Activity</h2> + +<p>To create an activity, you must create a subclass of {@link android.app.Activity} (or +an existing subclass of it). In your subclass, you need to implement callback methods that the +system calls when the activity transitions between various states of its lifecycle, such as when +the activity is being created, stopped, resumed, or destroyed. The two most important callback +methods are:</p> + +<dl> + <dt>{@link android.app.Activity#onCreate onCreate()}</dt> + <dd>You must implement this method. The system calls this when creating your + activity. Within your implementation, you should initialize the essential components of your +activity. + Most importantly, this is where you must call {@link android.app.Activity#setContentView + setContentView()} to define the layout for the activity's user interface.</dd> + <dt>{@link android.app.Activity#onPause onPause()}</dt> + <dd>The system calls this method as the first indication that the user is leaving your +activity (though it does not always mean the activity is being destroyed). This is usually where you +should commit any changes that should be persisted beyond the current user session (because +the user might not come back).</dd> +</dl> + +<p>There are several other lifecycle callback methods that you should use in order to provide a +fluid user experience between activities and handle unexpected interuptions that cause your activity +to be stopped and even destroyed. All of the lifecycle callback methods are discussed later, in +the section about <a href="#Lifecycle">Managing the Activity Lifecycle</a>.</p> + + + +<h3 id="UI">Implementing a user interface</h3> + +<p> The user interface for an activity is provided by a hierarchy of views—objects derived +from the {@link android.view.View} class. Each view controls a particular rectangular space +within the activity's window and can respond to user interaction. For example, a view might be a +button that initiates an action when the user touches it.</p> + +<p>Android provides a number of ready-made views that you can use to design and organize your +layout. "Widgets" are views that provide a visual (and interactive) elements for the screen, such +as a button, text field, checkbox, or just an image. "Layouts" are views derived from {@link +android.view.ViewGroup} that provide a unique layout model for its child views, such as a linear +layout, a grid layout, or relative layout. You can also subclass the {@link android.view.View} and +{@link android.view.ViewGroup} classes (or existing subclasses) to create your own widgets and +layouts and apply them to your activity layout.</p> + +<p>The most common way to define a layout using views is with an XML layout file saved in your +application resources. This way, you can maintain the design of your user interface separately from +the source code that defines the activity's behavior. You can set the layout as the UI for your +activity with {@link android.app.Activity#setContentView(int) setContentView()}, passing the +resource ID for the layout. However, you can also create new {@link android.view.View}s in your +activity code and build a view hierarchy by inserting new {@link +android.view.View}s into a {@link android.view.ViewGroup}, then use that layout by passing the root +{@link android.view.ViewGroup} to {@link android.app.Activity#setContentView(View) +setContentView()}.</p> + +<p>For information about creating a user interface, see the <a +href="{@docRoot}guide/topics/ui/index.html">User Interface</a> documentation.</p> + + + +<h3 id="Declaring">Declaring the activity in the manifest</h3> + +<p>You must declare your activity in the manifest file in order for it to +be accessible to the system. To decalare your activity, open your manifest file and add an <a +href="{@docRoot}guide/topics/manifest/activity-element.html">{@code <activity>}</a> element +as a child of the <a +href="{@docRoot}guide/topics/manifest/application-element.html">{@code <application>}</a> +element. For example:</p> + +<pre> +<manifest ... > + <application ... > + <activity android:name=".ExampleActivity" /> + ... + </application ... > + ... +</manifest > +</pre> + +<p>There are several other attributes that you can include in this element, to define properties +such as the label for the activity, an icon for the activity, or a theme to style the activity's +UI. See the <a +href="{@docRoot}guide/topics/manifest/activity-element.html">{@code <activity>}</a> element +reference for more information about available attributes.</p> + + +<h4>Using intent filters</h4> + +<p>An <a href="{@docRoot}guide/topics/manifest/activity-element.html">{@code +<activity>}</a> element can also specify various intent filters—using the <a +href="{@docRoot}guide/topics/manifest/intent-filter-element.html">{@code +<intent-filter>}</a> element—in order to declare how other application components may +activate it.</p> + +<p>When you create a new application using the Android SDK tools, the stub activity +that's created for you automatically includes an intent filter that declares the activity +responds to the "main" action and should be placed in the "launcher" category. The intent filter +looks like this:</p> + +<pre> +<activity android:name=".ExampleActivity" android:icon="@drawable/app_icon"> + <intent-filter> + <action android:name="android.intent.action.MAIN" /> + <category android:name="android.intent.category.LAUNCHER" /> + </intent-filter> +</activity> +</pre> + +<p>The <a href="{@docRoot}guide/topics/manifest/action-element.html">{@code +<action>}</a> element specifies that this is the "main" entry point to the application. The <a +href="{@docRoot}guide/topics/manifest/category-element.html">{@code +<category>}</a> element specifies that this activity should be listed in the +system's application launcher (to allow users to launch this activity).</p> + +<p>If you intend for your application to be self-contained and not allow other applications to +activate its activities, then you don't need any other intent filters. Only one activity should +have the "main" action and "launcher" category, as in the previous example. Activities that +you don't want to make available to other applications should have no intent filters and you can +start them yourself using explicit intents (as discussed in the following section).</p> + +<p>However, if you want your activity to respond to implicit intents that are delivered from +other applications (and your own), then you must define additional intent filters for your +activity. For each type of intent to which you want to respond, you must include an <a +href="{@docRoot}guide/topics/manifest/intent-filter-element.html">{@code +<intent-filter>}</a> that includes an +<a href="{@docRoot}guide/topics/manifest/action-element.html">{@code +<action>}</a> element and, optionally, a <a +href="{@docRoot}guide/topics/manifest/category-element.html">{@code +<category>}</a> element and/or a <a +href="{@docRoot}guide/topics/manifest/data-element.html">{@code +<data>}</a> element. These elements specify the type of intent to which your activity can +respond.</p> + +<p>For more information about how your activities can respond to intents, see the <a +href="{@docRoot}guide/topics/intents/intents-filters.html">Intents and Intent Filters</a> +document.</p> + + + +<h2 id="StartingAnActivity">Starting an Activity</h2> + +<p>You can start another activity by calling {@link android.app.Activity#startActivity + startActivity()}, passing it an {@link android.content.Intent} that describes the activity you + want to start. The intent specifies either the exact activity you want to start or describes the + type of action you want to perform (and the system selects the appropriate activity for you, +which + can even be from a different application). An intent can also carry small amounts of data to be + used by the activity that is started.</p> + +<p>When working within your own application, you'll often need to simply launch a known activity. + You can do so by creating an intent that explicitly defines the activity you want to start, +using the class name. For example, here's how one activity starts another activity named {@code +SignInActivity}:</p> + +<pre> +Intent intent = new Intent(this, SignInActivity.class); +startActivity(intent); +</pre> + +<p>However, your application might also want to perform some action, such as send an email, text + message, or status update, using data from your activity. In this case, your application might + not have its own activities to perform such actions, so you can instead leverage the activities + provided by other applications on the device, which can perform the actions for you. This is where +intents are really valuable—you can create an intent that describes an action you want to +perform and the system + launches the appropriate activity from another application. If there are + multiple activities that can handle the intent, then the user can select which one to use. For + example, if you want to allow the user to send an email message, you can create the + following intent:</p> + +<pre> +Intent intent = new Intent(Intent.ACTION_SEND); +intent.putExtra(Intent.EXTRA_EMAIL, recipientArray); +startActivity(intent); +</pre> + +<p>The {@link android.content.Intent#EXTRA_EMAIL} extra added to the intent is a string array of + email addresses to which the email should be sent. When an email application responds to this + intent, it reads the string array provided in the extra and places them in the "to" field of the + email composition form. In this situation, the email application's activity starts and when the + user is done, your activity resumes.</p> + + + + +<h3 id="StartingAnActivityForResult">Starting an activity for a result</h3> + +<p>Sometimes, you might want to receive a result from the activity that you start. In that case, + start the activity by calling {@link android.app.Activity#startActivityForResult + startActivityForResult()} (instead of {@link android.app.Activity#startActivity + startActivity()}). To then receive the result from the subsequent +activity, implement the {@link android.app.Activity#onActivityResult onActivityResult()} callback + method. When the subsequent activity is done, it returns a result in an {@link +android.content.Intent} to your {@link android.app.Activity#onActivityResult onActivityResult()} +method.</p> + +<p>For example, perhaps you want the user to pick one of their contacts, so your activity can +do something with the information in that contact. Here's how you can create such an intent and +handle the result:</p> + +<pre> +private void pickContact() { + // Create an intent to "pick" a contact, as defined by the content provider URI + Intent intent = new Intent(Intent.ACTION_PICK, Contacts.CONTENT_URI); + startActivityForResult(intent, PICK_CONTACT_REQUEST); +} + +@Override +protected void onActivityResult(int requestCode, int resultCode, Intent data) { + // If the request went well (OK) and the request was PICK_CONTACT_REQUEST + if (resultCode == Activity.RESULT_OK && requestCode == PICK_CONTACT_REQUEST) { + // Perform a query to the contact's content provider for the contact's name + Cursor cursor = getContentResolver().query(data.getData(), + new String[] {Contacts.DISPLAY_NAME}, null, null, null); + if (cursor.moveToFirst()) { // True if the cursor is not empty + int columnIndex = cursor.getColumnIndex(Contacts.DISPLAY_NAME); + String name = cursor.getString(columnIndex); + // Do something with the selected contact's name... + } + } +} +</pre> + +<p>This example shows the basic logic you should use in your {@link +android.app.Activity#onActivityResult onActivityResult()} method in order to handle an +activity result. The first condition checks whether the request was successful—if it was, then +the {@code resultCode} will be {@link android.app.Activity#RESULT_OK}—and whether the request +to which this result is responding is known—in this case, the {@code requestCode} matches the +second parameter sent with {@link android.app.Activity#startActivityForResult +startActivityForResult()}. From there, the code handles the activity result by querying the +data returned in an {@link android.content.Intent} (the {@code data} parameter).</p> + +<p>What happens is, a {@link +android.content.ContentResolver} performs a query against a content provider, which returns a +{@link android.database.Cursor} that allows the queried data to be read. For more information, see +the <a +href="{@docRoot}guide/topics/providers/content-providers.html">Content Providers</a> document.</p> + +<p>For more information about using intents, see the <a +href="{@docRoot}guide/topics/intents/intents-filters.html">Intents and Intent +Filters</a> document.</p> + + +<h2 id="ShuttingDown">Shutting Down an Activity</h2> + +<p>You can shut down an activity by calling its {@link android.app.Activity#finish +finish()} method. You can also shut down a separate activity that you previously started by calling +{@link android.app.Activity#finishActivity finishActivity()}.</p> + +<p class="note"><strong>Note:</strong> In most cases, you should not explicitly finish an activity +using these methods. As discussed in the following section about the activity lifecycle, the +Android system manages the life of an activity for you, so you do not need to finish your own +activities. Calling these methods could adversely affect the expected user +experience and should only be used when you absolutely do not want the user to return to this +instance of the activity.</p> + + +<h2 id="Lifecycle">Managing the Activity Lifecycle</h2> + +<p>Managing the lifecycle of your activities by implementing callback methods is +crucial to developing a strong +and flexible application. The lifecycle of an activity is directly affected by its association with +other activities, its task and back stack.</p> + +<p>An activity can exist in essentially three states:</p> + +<dl> + <dt><i>Resumed</i></dt> + <dd>The activity is in the foreground of the screen and has user focus. (This state is +also sometimes referred to as "running".)</dd> + + <dt><i>Paused</i></dt> + <dd>Another activity is in the foreground and has focus, but this one is still visible. That is, +another activity is visible on top of this one and that activity is partially transparent or doesn't +cover the entire screen. A paused activity is completely alive (the {@link android.app.Activity} +object is retained in memory, it maintains all state and member information, and remains attached to +the window manager), but can be killed by the system in extremely low memory situations.</dd> + + <dt><i>Stopped</i></dt> + <dd>The activity is completely obscured by another activity (the activity is now in the +"background"). A stopped activity is also still alive (the {@link android.app.Activity} +object is retained in memory, it maintains all state and member information, but is <em>not</em> +attached to the window manager). However, it is no longer visible to the user and it +can be killed by the system when memory is needed elsewhere.</dd> +</dl> + +<p>If an activity is paused or stopped, the system can drop it from memory either by asking it to +finish (calling its {@link android.app.Activity#finish finish()} method), or simply killing its +process. When the activity is opened again (after being finished or killed), it must be created all +over.</p> + + + +<h3 id="ImplementingLifecycleCallbacks">Implementing the lifecycle callbacks</h3> + +<p>When an activity transitions into and out of the different states described above, it is notified +through various callback methods. All of the callback methods are hooks that you +can override to do appropriate work when the state of your activity changes. The following skeleton +activity includes each of the fundamental lifecycle methods:</p> + + +<pre> +public class ExampleActivity extends Activity { + @Override + public void {@link android.app.Activity#onCreate onCreate}(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + // The activity is being created. + } + @Override + protected void {@link android.app.Activity#onStart onStart()} { + super.onStart(); + // The activity is about to become visible. + } + @Override + protected void {@link android.app.Activity#onResume onResume()} { + super.onResume(); + // The activity has become visible (it is now "resumed"). + } + @Override + protected void {@link android.app.Activity#onPause onPause()} { + super.onPause(); + // Another activity is taking focus (this activity is about to be "paused"). + } + @Override + protected void {@link android.app.Activity#onStop onStop()} { + super.onStop(); + // The activity is no longer visible (it is now "stopped") + } + @Override + protected void {@link android.app.Activity#onDestroy onDestroy()} { + super.onDestroy(); + // The activity is about to be destroyed. + } +} +</pre> + +<p class="note"><strong>Note:</strong> Your implementation of these lifecycle methods must +always call the superclass implementation before doing any work, as shown in the examples above.</p> + +<p>Taken together, these methods define the entire lifecycle of an activity. By implementing these +methods, you can monitor three nested loops in the activity lifecycle: </p> + +<ul> +<li>The <b>entire lifetime</b> of an activity happens between the call to {@link +android.app.Activity#onCreate onCreate()} and the call to {@link +android.app.Activity#onDestroy}. Your activity should perform setup of +"global" state (such as defining layout) in {@link android.app.Activity#onCreate onCreate()}, and +release all remaining resources in {@link android.app.Activity#onDestroy}. For example, if your +activity has a thread running in the background to download data from the network, it might create +that thread in {@link android.app.Activity#onCreate onCreate()} and then stop the thread in {@link +android.app.Activity#onDestroy}.</li> + +<li><p>The <b>visible lifetime</b> of an activity happens between the call to {@link +android.app.Activity#onStart onStart()} and the call to {@link +android.app.Activity#onStop onStop()}. During this time, the user can see the activity +on-screen and interact with it. For example, {@link android.app.Activity#onStop onStop()} is called +when a new activity starts and this one is no longer visible. Between these two methods, you can +maintain resources that are needed to show the activity to the user. For example, you can register a +{@link android.content.BroadcastReceiver} in {@link +android.app.Activity#onStart onStart()} to monitor changes that impact your UI, and unregister +it in {@link android.app.Activity#onStop onStop()} when the user can no longer see what you are +displaying. The system might call {@link android.app.Activity#onStart onStart()} and {@link +android.app.Activity#onStop onStop()} multiple times during the entire lifetime of the activity, as +the activity alternates between being visible and hidden to the user.</p></li> + +<li><p>The <b>foreground lifetime</b> of an activity happens between the call to {@link +android.app.Activity#onResume onResume()} and the call to {@link android.app.Activity#onPause +onPause()}. During this time, the activity is in front of all other activities on screen and has +user input focus. An activity can frequently transition in and out of the foreground—for +example, {@link android.app.Activity#onPause onPause()} is called when the device goes to sleep or +when a dialog appears. Because this state can transition often, the code in these two methods should +be fairly lightweight in order to avoid slow transitions that make the user wait.</p></li> +</ul> + +<p>Figure 1 illustrates these loops and the paths an activity might take between states. +The rectangles represent the callback methods you can implement to perform operations when +the activity transitions between states. <p> + +<img src="{@docRoot}images/activity_lifecycle.png" alt="" /> +<p class="img-caption"><strong>Figure 1.</strong> The activity lifecycle.</p> + +<p>The same lifecycle callback methods are listed in table 1, which describes each of the callback +methods in more detail and locates each one within the +activity's overall lifecycle, including whether the system can kill the activity after the +callback method completes.</p> + +<p class="table-caption"><strong>Table 1.</strong> A summary of the activity lifecycle's +callback methods.</p> + +<table border="2" width="85%" frame="hsides" rules="rows"> +<colgroup align="left" span="3"></colgroup> +<colgroup align="left"></colgroup> +<colgroup align="center"></colgroup> +<colgroup align="center"></colgroup> + +<thead> +<tr><th colspan="3">Method</th> <th>Description</th> <th>Killable after?</th> <th>Next</th></tr> +</thead> + +<tbody> +<tr> + <td colspan="3" align="left"><code>{@link android.app.Activity#onCreate onCreate()}</code></td> + <td>Called when the activity is first created. + This is where you should do all of your normal static set up — + create views, bind data to lists, and so on. This method is passed + a Bundle object containing the activity's previous state, if that + state was captured (see <a href="#actstate">Saving Activity State</a>, + later). + <p>Always followed by {@code onStart()}.</p></td> + <td align="center">No</td> + <td align="center">{@code onStart()}</td> +</tr> + +<tr> + <td rowspan="5" style="border-left: none; border-right: none;"> </td> + <td colspan="2" align="left"><code>{@link android.app.Activity#onRestart +onRestart()}</code></td> + <td>Called after the activity has been stopped, just prior to it being + started again. + <p>Always followed by {@code onStart()}</p></td> + <td align="center">No</td> + <td align="center">{@code onStart()}</td> +</tr> + +<tr> + <td colspan="2" align="left"><code>{@link android.app.Activity#onStart onStart()}</code></td> + <td>Called just before the activity becomes visible to the user. + <p>Followed by {@code onResume()} if the activity comes + to the foreground, or {@code onStop()} if it becomes hidden.</p></td> + <td align="center">No</td> + <td align="center">{@code onResume()} <br/>or<br/> {@code onStop()}</td> +</tr> + +<tr> + <td rowspan="2" style="border-left: none;"> </td> + <td align="left"><code>{@link android.app.Activity#onResume onResume()}</code></td> + <td>Called just before the activity starts + interacting with the user. At this point the activity is at + the top of the activity stack, with user input going to it. + <p>Always followed by {@code onPause()}.</p></td> + <td align="center">No</td> + <td align="center">{@code onPause()}</td> +</tr> + +<tr> + <td align="left"><code>{@link android.app.Activity#onPause onPause()}</code></td> + <td>Called when the system is about to start resuming another + activity. This method is typically used to commit unsaved changes to + persistent data, stop animations and other things that may be consuming + CPU, and so on. It should do whatever it does very quickly, because + the next activity will not be resumed until it returns. + <p>Followed either by {@code onResume()} if the activity + returns back to the front, or by {@code onStop()} if it becomes + invisible to the user.</td> + <td align="center"><strong style="color:#800000">Yes</strong></td> + <td align="center">{@code onResume()} <br/>or<br/> {@code onStop()}</td> +</tr> + +<tr> + <td colspan="2" align="left"><code>{@link android.app.Activity#onStop onStop()}</code></td> + <td>Called when the activity is no longer visible to the user. This + may happen because it is being destroyed, or because another activity + (either an existing one or a new one) has been resumed and is covering it. + <p>Followed either by {@code onRestart()} if + the activity is coming back to interact with the user, or by + {@code onDestroy()} if this activity is going away.</p></td> + <td align="center"><strong style="color:#800000">Yes</strong></td> + <td align="center">{@code onRestart()} <br/>or<br/> {@code onDestroy()}</td> +</tr> + +<tr> + <td colspan="3" align="left"><code>{@link android.app.Activity#onDestroy +onDestroy()}</code></td> + <td>Called before the activity is destroyed. This is the final call + that the activity will receive. It could be called either because the + activity is finishing (someone called <code>{@link android.app.Activity#finish + finish()}</code> on it), or because the system is temporarily destroying this + instance of the activity to save space. You can distinguish + between these two scenarios with the <code>{@link + android.app.Activity#isFinishing isFinishing()}</code> method.</td> + <td align="center"><strong style="color:#800000">Yes</strong></td> + <td align="center"><em>nothing</em></td> +</tr> +</tbody> +</table> + +<p>The column labeled "Killable after?" indicates whether or not the system can +kill the process hosting the activity at any time <em>after the method returns</em>, without +executing another line of the activity's code. Three methods are marked "yes": ({@link +android.app.Activity#onPause +onPause()}, {@link android.app.Activity#onStop onStop()}, and {@link android.app.Activity#onDestroy +onDestroy()}). Because {@link android.app.Activity#onPause onPause()} is the first +of the three, once the activity is created, {@link android.app.Activity#onPause onPause()} is the +last method that's guaranteed to be called before the process <em>can</em> be killed—if +the system must recover memory in an emergency, then {@link +android.app.Activity#onStop onStop()} and {@link android.app.Activity#onDestroy onDestroy()} might +not be called. Therefore, you should use {@link android.app.Activity#onPause onPause()} to write +crucial persistent data (such as user edits) to storage. However, you should be selective about +what information must be retained during {@link android.app.Activity#onPause onPause()}, because any +blocking procedures in this method block the transition to the next activity and slow the user +experience.</p> + +<p> Methods that are marked "No" in the <b>Killable</b> column protect the process hosting the +activity from being killed from the moment they are called. Thus, an activity is killable +from the time {@link android.app.Activity#onPause onPause()} returns to the time +{@link android.app.Activity#onResume onResume()} is called. It will not again be killable until +{@link android.app.Activity#onPause onPause()} is again called and returns. </p> + +<p class="note"><strong>Note:</strong> An activity that's not technically "killable" by this +definition in table 1 might still be killed by the system—but that would happen only in +extreme circumstances when there is no other recourse. When an activity might be killed is +discussed more in the <a +href="{@docRoot}guide/topics/fundamentals/processes-and-threading.html">Processes and +Threading</a> document.</p> + + +<h3 id="SavingActivityState">Saving activity state</h3> + +<p>The introduction to <a href="Lifecycle">Managing the Activity Lifecycle</a> briefly mentions that +when an activity is paused or stopped, the state of the activity is retained. This is true because +the {@link android.app.Activity} object is still held in memory when it is paused or +stopped—all information about its members and current state is still alive. Thus, any changes +the user made within the activity are retained in memory, so that when the activity returns to the +foreground (when it "resumes"), those changes are still there.</p> + +<div class="figure" style="width:615px"> +<img src="{@docRoot}images/fundamentals/restore_instance.png" alt="" /> +<p class="img-caption"><strong>Figure 2.</strong> The two ways in which an activity returns to user +focus with its state intact: either the activity is stopped, then resumed and the activity state +remains intact (left), or the activity is destroyed, then recreated and the activity must restore +the previous activity state (right).</p> +</div> + +<p>However, when the system destroys an activity in order to recover memory, the {@link +android.app.Activity} object is destroyed, so the system cannot simply resume it with its state +intact. Instead, the system must recreate the {@link android.app.Activity} object if the user +navigates back to it. Yet, the user is unaware +that the system destroyed the activity and recreated it and, thus, probably +expects the activity to be exactly as it was. In this situation, you can ensure that +important information about the activity state is preserved by implementing an additional +callback method that allows you to save information about the state of your activity and then +restore it when the the system recreates the activity.</p> + +<p>The callback method in which you can save information about the current state of your activity is +{@link android.app.Activity#onSaveInstanceState onSaveInstanceState()}. The system calls this method +before making the activity vulnerable to being destroyed and passes it +a {@link android.os.Bundle} object. The {@link android.os.Bundle} is where you can store +state information about the activity as name-value pairs, using methods such as {@link +android.os.Bundle#putString putString()}. Then, if the system kills your activity's +process and the user navigates back to your activity, the system passes the {@link +android.os.Bundle} to {@link android.app.Activity#onCreate onCreate()} so you can restore the +activity state you saved during {@link android.app.Activity#onSaveInstanceState +onSaveInstanceState()}. If there is no state information to restore, then the {@link +android.os.Bundle} passed to {@link android.app.Activity#onCreate onCreate()} is null.</p> + +<p class="note"><strong>Note:</strong> There's no guarantee that {@link +android.app.Activity#onSaveInstanceState onSaveInstanceState()} will be called before your +activity is destroyed, because there are cases in which it won't be necessary to save the state +(such as when the user leaves your activity using the BACK key, because the user is explicitly +closing the activity). If the method is called, it is always called before {@link +android.app.Activity#onStop onStop()} and possibly before {@link android.app.Activity#onPause +onPause()}.</p> + +<p>However, even if you do nothing and do not implement {@link +android.app.Activity#onSaveInstanceState onSaveInstanceState()}, some of the activity state is +restored by the {@link android.app.Activity} class's default implementation of {@link +android.app.Activity#onSaveInstanceState onSaveInstanceState()}. Specifically, the default +implementation calls {@link +android.view.View#onSaveInstanceState onSaveInstanceState()} for every {@link android.view.View} +in the layout, which allows each view to provide information about itself +that should be saved. Almost every widget in the Android framework implements this method as +appropriate, such that any visible changes to the UI are automatically saved and restored when your +activity is recreated. For example, the {@link android.widget.EditText} widget saves any text +entered by the user and the {@link android.widget.CheckBox} widget saves whether it's checked or +not. The only work required by you is to provide a unique ID (with the <a +href="{@docRoot}guide/topics/resources/layout-resource.html#idvalue">{@code android:id}</a> +attribute) for each widget you want to save its state. If a widget does not have an ID, then it +cannot save its state.</p> + +<div class="sidebox-wrapper"> +<div class="sidebox"> +<p>You can also explicitly stop a view in your layout from saving its state by setting the +{@link android.R.attr#saveEnabled android:saveEnabled} attribute to {@code "false"} or by calling +the {@link android.view.View#setSaveEnabled setSaveEnabled()} method. Usually, you should not +disable this, but you might if you want to restore the state of the activity UI differently.</p> +</div> +</div> + +<p>Although the default implementation of {@link +android.app.Activity#onSaveInstanceState onSaveInstanceState()} saves useful information about +your activity's UI, you still might need to override it to save additional information. +For example, you might need to save member values that changed during the activity's life (which +might correlate to values restored in the UI, but the members that hold those UI values are not +restored, by default).</p> + +<p>Because the default implementation of {@link +android.app.Activity#onSaveInstanceState onSaveInstanceState()} helps save the state of the UI, if +you override the method in order to save additional state information, you should always call the +superclass implementation of {@link android.app.Activity#onSaveInstanceState onSaveInstanceState()} +before doing any work.</p> + +<p class="note"><strong>Note:</strong> Because {@link android.app.Activity#onSaveInstanceState +onSaveInstanceState()} is not guaranteed +to be called, you should use it only to record the transient state of the activity (the state of +the UI)—you should never use it to store persistent data. Instead, you should use {@link +android.app.Activity#onPause onPause()} to store persistent data (such as data that should be saved +to a database) when the user leaves the activity.</p> + +<p>A good way to test your application's ability to restore its state is to simply rotate the +device so that the screen orientation changes. When the screen orientation changes, the system +destroys and recreates the activity in order to apply alternative resources that might be available +for the new orientation. For this reason alone, it's very important that your activity +completely restores its state when it is recreated, because users regularly rotate the screen while +using applications.</p> + + +<h3 id="ConfigurationChanges">Handling configuration changes</h3> + +<p>Some device configurations can change during runtime (such as screen orientation, keyboard +availability, and language). When such a change occurs, Android restarts the running Activity +({@link android.app.Activity#onDestroy} is called, followed immediately by {@link +android.app.Activity#onCreate onCreate()}). The restart behavior is +designed to help your application adapt to new configurations by automatically reloading your +application with alternative resources that you've provided. If you design your activity to +properly handle this event, it will be more resilient to unexpected events in the activity +lifecycle.</p> + +<p>The best way to handle a configuration change, such as a change in the screen orientation, is + to simply preserve the state of your application using {@link + android.app.Activity#onSaveInstanceState onSaveInstanceState()} and {@link +android.app.Activity#onRestoreInstanceState onRestoreInstanceState()} (or {@link +android.app.Activity#onCreate onCreate()}), as discussed in the previous section.</p> + +<p>For a detailed discussion about configuration changes that happen at runtime and how you should +handle them, read <a href="{@docRoot}guide/topics/resources/runtime-changes.html">Handling +Runtime Changes</a>.</p> + + + +<h3 id="CoordinatingActivities">Coordinating activities</h3> + + <p>When one activity starts another, they both experience lifecycle transitions. The first activity +pauses and stops (though, it won't stop if it's still visible in the background), while the other +activity is created. In case these activities share data saved to disc or elsewhere, it's important +to understand that the first activity is not completely stopped before the second one is created. +Rather, the process of starting the second one overlaps with the process of stopping the first +one.</p> + +<p>The order of lifecycle callbacks is well defined, particularly when the two activities are in the +same process and one is starting the other. Here's the order of operations that occur when Activity +A starts Acivity B: </p> + +<ol> +<li>Activity A's {@link android.app.Activity#onPause onPause()} method executes.</li> + +<li>Activity B's {@link android.app.Activity#onCreate onCreate()}, {@link +android.app.Activity#onStart onStart()}, and {@link android.app.Activity#onResume onResume()} +methods execute in sequence. (Activity B now has user focus.)</li> + +<li>Then, if Activity A is no longer visible on screen, its {@link +android.app.Activity#onStop onStop()} method executes.</li> +</ol> + + <p>This predictable sequence of lifecycle callbacks allows you to manage the transition of +information from one activity to another. For example, if you must write to a database when the +first activity stops so that the following activity can read it, then you should write to the +database during {@link android.app.Activity#onPause onPause()} instead of during {@link +android.app.Activity#onStop onStop()}.</p> + + +<h2>Beginner's Path</h2> + +<p>For more information about how Android maintains a history of activities and +enables user multitasking, continue with the <b><a +href="{@docRoot}guide/topics/fundamentals/tasks-and-back-stack.html">Tasks and Back +Stack</a></b> document.</p> diff --git a/docs/html/guide/topics/fundamentals/bound-services.jd b/docs/html/guide/topics/fundamentals/bound-services.jd new file mode 100644 index 0000000..e5d626c --- /dev/null +++ b/docs/html/guide/topics/fundamentals/bound-services.jd @@ -0,0 +1,675 @@ +page.title=Bound Services +parent.title=Services +parent.link=services.html +@jd:body + + +<div id="qv-wrapper"> +<ol id="qv"> +<h2>Quickview</h2> +<ul> + <li>A bound service allows other components to bind to it, in order to interact with it and +perform interprocess communication</li> + <li>A bound service is destroyed once all clients unbind, unless the service was also started</li> +</ul> +<h2>In this document</h2> +<ol> + <li><a href="#Basics">The Basics</a></li> + <li><a href="#Creating">Creating a Bound Service</a> + <ol> + <li><a href="#Binder">Extending the Binder class</a></li> + <li><a href="#Messenger">Using a Messenger</a></li> + </ol> + </li> + <li><a href="#Binding">Binding to a Service</a></li> + <li><a href="#Lifecycle">Managing the Lifecycle of a Bound Service</a></li> +</ol> + +<h2>Key classes</h2> +<ol> + <li>{@link android.app.Service}</li> + <li>{@link android.content.ServiceConnection}</li> + <li>{@link android.os.IBinder}</li> +</ol> + +<h2>Samples</h2> +<ol> + <li><a href="{@docRoot}resources/samples/ApiDemos/src/com/example/android/apis/app/RemoteService.html">{@code + RemoteService}</a></li> + <li><a href="{@docRoot}resources/samples/ApiDemos/src/com/example/android/apis/app/LocalService.html">{@code + LocalService}</a></li> +</ol> + +<h2>See also</h2> +<ol> + <li><a href="{@docRoot}guide/topics/fundamentals/services.html">Services</a></li> +</ol> +</div> + + +<p>A bound service is the server in a client-server interface. A bound service allows components +(such as activities) to bind to the service, send requests, receive responses, and even perform +interprocess communication (IPC). A bound service typically lives only while it serves another +application component and does not run in the background indefinitely.</p> + +<p>This document shows you how to create a bound service, including how to bind +to the service from other application components. However, you should also refer to the <a +href="{@docRoot}guide/topics/fundamentals/services.html">Services</a> document for additional +information about services in general, such as how to deliver notifications from a service, set +the service to run in the foreground, and more.</p> + + +<h2 id="Basics">The Basics</h2> + +<p>A bound service is an implementation of the {@link android.app.Service} class that allows +other applications to bind to it and interact with it. To provide binding for a +service, you must implement the {@link android.app.Service#onBind onBind()} callback method. This +method returns an {@link android.os.IBinder} object that defines the programming interface that +clients can use to interact with the service.</p> + +<div class="sidebox-wrapper"> +<div class="sidebox"> + <h3>Binding to a Started Service</h3> + +<p>As discussed in the <a href="{@docRoot}guide/topics/fundamentals/services.html">Services</a> +document, you can create a service that is both started and bound. That is, the service can be +started by calling {@link android.content.Context#startService startService()}, which allows the +service to run indefinitely, and also allow a client to bind to the service by calling {@link +android.content.Context#bindService bindService()}. + <p>If you do allow your service to be started and bound, then when the service has been +started, the system does <em>not</em> destroy the service when all clients unbind. Instead, you must +explicitly stop the service, by calling {@link android.app.Service#stopSelf stopSelf()} or {@link +android.content.Context#stopService stopService()}.</p> + +<p>Although you should usually implement either {@link android.app.Service#onBind onBind()} +<em>or</em> {@link android.app.Service#onStartCommand onStartCommand()}, it's sometimes necessary to +implement both. For example, a music player might find it useful to allow its service to run +indefinitely and also provide binding. This way, an activity can start the service to play some +music and the music continues to play even if the user leaves the application. Then, when the user +returns to the application, the activity can bind to the service to regain control of playback.</p> + +<p>Be sure to read the section about <a href="#Lifecycle">Managing the Lifecycle of a Bound +Service</a>, for more information about the service lifecycle when adding binding to a +started service.</p> +</div> +</div> + +<p>A client can bind to the service by calling {@link android.content.Context#bindService +bindService()}. When it does, it must provide an implementation of {@link +android.content.ServiceConnection}, which monitors the connection with the service. The {@link +android.content.Context#bindService bindService()} method returns immediately without a value, but +when the Android system creates the connection between the +client and service, it calls {@link +android.content.ServiceConnection#onServiceConnected onServiceConnected()} on the {@link +android.content.ServiceConnection}, to deliver the {@link android.os.IBinder} that +the client can use to communicate with the service.</p> + +<p>Multiple clients can connect to the service at once. However, the system calls your service's +{@link android.app.Service#onBind onBind()} method to retrieve the {@link android.os.IBinder} only +when the first client binds. The system then delivers the same {@link android.os.IBinder} to any +additional clients that bind, without calling {@link android.app.Service#onBind onBind()} again.</p> + +<p>When the last client unbinds from the service, the system destroys the service (unless the +service was also started by {@link android.content.Context#startService startService()}).</p> + +<p>When you implement your bound service, the most important part is defining the interface +that your {@link android.app.Service#onBind onBind()} callback method returns. There are a few +different ways you can define your service's {@link android.os.IBinder} interface and the following +section discusses each technique.</p> + + + +<h2 id="Creating">Creating a Bound Service</h2> + +<p>When creating a service that provides binding, you must provide an {@link android.os.IBinder} +that provides the programming interface that clients can use to interact with the service. There +are three ways you can define the interface:</p> + +<dl> + <dt><a href="#Binder">Extending the Binder class</a></dt> + <dd>If your service is private to your own application and runs in the same process as the client +(which is common), you should create your interface by extending the {@link android.os.Binder} class +and returning an instance of it from +{@link android.app.Service#onBind onBind()}. The client receives the {@link android.os.Binder} and +can use it to directly access public methods available in either the {@link android.os.Binder} +implementation or even the {@link android.app.Service}. + <p>This is the preferred technique when your service is merely a background worker for your own +application. The only reason you would not create your interface this way is because +your service is used by other applications or across separate processes.</dd> + + <dt><a href="#Messenger">Using a Messenger</a></dt> + <dd>If you need your interface to work across different processes, you can create +an interface for the service with a {@link android.os.Messenger}. In this manner, the service +defines a {@link android.os.Handler} that responds to different types of {@link +android.os.Message} objects. This {@link android.os.Handler} +is the basis for a {@link android.os.Messenger} that can then share an {@link android.os.IBinder} +with the client, allowing the client to send commands to the service using {@link +android.os.Message} objects. Additionally, the client can define a {@link android.os.Messenger} of +its own so the service can send messages back. + <p>This is the simplest way to perform interprocess communication (IPC), because the {@link +android.os.Messenger} queues all requests into a single thread so that you don't have to design +your service to be thread-safe.</p> + </dd> + + <dt>Using AIDL</dt> + <dd>AIDL (Android Interface Definition Language) performs all the work to decompose objects into +primitives that the operating system can understand and marshall them across processes to perform +IPC. The previous technique, using a {@link android.os.Messenger}, is actually based on AIDL as +its underlying structure. As mentioned above, the {@link android.os.Messenger} creates a queue of +all the client requests in a single thread, so the service receives requests one at a time. If, +however, you want your service to handle multiple requests simultaneously, then you can use AIDL +directly. In this case, your service must be capable of multi-threading and be built thread-safe. + <p>To use AIDL directly, you must +create an {@code .aidl} file that defines the programming interface. The Android SDK tools use +this file to generate an abstract class that implements the interface and handles IPC, which you +can then extend within your service.</p> + </dd> +</dl> + + <p class="note"><strong>Note:</strong> Most applications <strong>should not</strong> use AIDL to +create a bound service, because it may require multithreading capabilities and +can result in a more complicated implementation. As such, AIDL is not suitable for most applications +and this document does not discuss how to use it for your service. If you're certain that you need +to use AIDL directly, see the <a href="{@docRoot}guide/topics/advanced/aidl.html">AIDL</a> +document.</p> + + + + +<h3 id="Binder">Extending the Binder class</h3> + +<p>If your service is used only by the local application and does not need to work across processes, +then you can implement your own {@link android.os.Binder} class that provides your client direct +access to public methods in the service.</p> + +<p class="note"><strong>Note:</strong> This works only if the client and service are in the same +application and process, which is most common. For example, this would work well for a music +application that needs to bind an activity to its own service that's playing music in the +background.</p> + +<p>Here's how to set it up:</p> +<ol> + <li>In your service, create an instance of {@link android.os.Binder} that either: + <ul> + <li>contains public methods that the client can call</li> + <li>returns the current {@link android.app.Service} instance, which has public methods the +client can call</li> + <li>or, returns an instance of another class hosted by the service with public methods the +client can call</li> + </ul> + <li>Return this instance of {@link android.os.Binder} from the {@link +android.app.Service#onBind onBind()} callback method.</li> + <li>In the client, receive the {@link android.os.Binder} from the {@link +android.content.ServiceConnection#onServiceConnected onServiceConnected()} callback method and +make calls to the bound service using the methods provided.</li> +</ol> + +<p class="note"><strong>Note:</strong> The reason the service and client must be in the same +application is so the client can cast the returned object and properly call its APIs. The service +and client must also be in the same process, because this technique does not perform any +marshalling across processes.</p> + +<p>For example, here's a service that provides clients access to methods in the service through +a {@link android.os.Binder} implementation:</p> + +<pre> +public class LocalService extends Service { + // Binder given to clients + private final IBinder mBinder = new LocalBinder(); + // Random number generator + private final Random mGenerator = new Random(); + + /** + * Class used for the client Binder. Because we know this service always + * runs in the same process as its clients, we don't need to deal with IPC. + */ + public class LocalBinder extends Binder { + LocalService getService() { + // Return this instance of LocalService so clients can call public methods + return LocalService.this; + } + } + + @Override + public IBinder onBind(Intent intent) { + return mBinder; + } + + /** method for clients */ + public int getRandomNumber() { + return mGenerator.nextInt(100); + } +} +</pre> + +<p>The {@code LocalBinder} provides the {@code getService()} method for clients to retrieve the +current instance of {@code LocalService}. This allows clients to call public methods in the +service. For example, clients can call {@code getRandomNumber()} from the service.</p> + +<p>Here's an activity that binds to {@code LocalService} and calls {@code getRandomNumber()} +when a button is clicked:</p> + +<pre> +public class BindingActivity extends Activity { + LocalService mService; + boolean mBound = false; + + @Override + protected void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + setContentView(R.layout.main); + } + + @Override + protected void onStart() { + super.onStart(); + // Bind to LocalService + Intent intent = new Intent(this, LocalService.class); + bindService(intent, mConnection, Context.BIND_AUTO_CREATE); + } + + @Override + protected void onStop() { + super.onStop(); + // Unbind from the service + if (mBound) { + unbindService(mConnection); + mBound = false; + } + } + + /** Called when a button is clicked (the button in the layout file attaches to + * this method with the android:onClick attribute) */ + public void onButtonClick(View v) { + if (mBound) { + // Call a method from the LocalService. + // However, if this call were something that might hang, then this request should + // occur in a separate thread to avoid slowing down the activity performance. + int num = mService.getRandomNumber(); + Toast.makeText(this, "number: " + num, Toast.LENGTH_SHORT).show(); + } + } + + /** Defines callbacks for service binding, passed to bindService() */ + private ServiceConnection mConnection = new ServiceConnection() { + + @Override + public void onServiceConnected(ComponentName className, + IBinder service) { + // We've bound to LocalService, cast the IBinder and get LocalService instance + LocalBinder binder = (LocalBinder) service; + mService = binder.getService(); + mBound = true; + } + + @Override + public void onServiceDisconnected(ComponentName arg0) { + mBound = false; + } + }; +} +</pre> + +<p>The above sample shows how the client binds to the service using an implementation of +{@link android.content.ServiceConnection} and the {@link +android.content.ServiceConnection#onServiceConnected onServiceConnected()} callback. The next +section provides more information about this process of binding to the service.</p> + +<p class="note"><strong>Note:</strong> The example above doesn't explicitly unbind from the service, +but all clients should unbind at an appropriate time (such as when the activity pauses).</p> + +<p>For more sample code, see the <a +href="{@docRoot}resources/samples/ApiDemos/src/com/example/android/apis/app/LocalService.html">{@code +LocalService.java}</a> class and the <a +href="{@docRoot}resources/samples/ApiDemos/src/com/example/android/apis/app/LocalServiceActivities.html">{@code +LocalServiceActivities.java}</a> class in <a +href="{@docRoot}resources/samples/ApiDemos/index.html">ApiDemos</a>.</p> + + + + + +<h3 id="Messenger">Using a Messenger</h3> + +<div class="sidebox-wrapper"> +<div class="sidebox"> + <h4>Compared to AIDL</h4> + <p>When you need to perform IPC, using a {@link android.os.Messenger} for your interface is +simpler than implementing it with AIDL, because {@link android.os.Messenger} queues +all calls to the service, whereas, a pure AIDL interface sends simultaneous requests to the +service, which must then handle multi-threading.</p> + <p>For most applications, the service doesn't need to perform multi-threading, so using a {@link +android.os.Messenger} allows the service to handle one call at a time. If it's important +that your service be multi-threaded, then you should use <a +href="{@docRoot}guide/topics/advanced/aidl.html">AIDL</a> to define your interface.</p> +</div> +</div> + +<p>If you need your service to communicate with remote processes, then you can use a +{@link android.os.Messenger} to provide the interface for your service. This technique allows +you to perform interprocess communication (IPC) without the need to use AIDL.</p> + +<p>Here's a summary of how to use a {@link android.os.Messenger}:</p> + +<ul> + <li>The service implements a {@link android.os.Handler} that receives a callback for each +call from a client.</li> + <li>The {@link android.os.Handler} is used to create a {@link android.os.Messenger} object +(which is a reference to the {@link android.os.Handler}).</li> + <li>The {@link android.os.Messenger} creates an {@link android.os.IBinder} that the service +returns to clients from {@link android.app.Service#onBind onBind()}.</li> + <li>Clients use the {@link android.os.IBinder} to instantiate the {@link android.os.Messenger} +(that references the service's {@link android.os.Handler}), which the client uses to send +{@link android.os.Message} objects to the service.</li> + <li>The service receives each {@link android.os.Message} in its {@link +android.os.Handler}—specifically, in the {@link android.os.Handler#handleMessage +handleMessage()} method.</li> +</ul> + + +<p>In this way, there are no "methods" for the client to call on the service. Instead, the +client delivers "messages" ({@link android.os.Message} objects) that the service receives in +its {@link android.os.Handler}.</p> + +<p>Here's a simple example service that uses a {@link android.os.Messenger} interface:</p> + +<pre> +public class MessengerService extends Service { + /** Command to the service to display a message */ + static final int MSG_SAY_HELLO = 1; + + /** + * Handler of incoming messages from clients. + */ + class IncomingHandler extends Handler { + @Override + public void handleMessage(Message msg) { + switch (msg.what) { + case MSG_SAY_HELLO: + Toast.makeText(getApplicationContext(), "hello!", Toast.LENGTH_SHORT).show(); + break; + default: + super.handleMessage(msg); + } + } + } + + /** + * Target we publish for clients to send messages to IncomingHandler. + */ + final Messenger mMessenger = new Messenger(new IncomingHandler()); + + /** + * When binding to the service, we return an interface to our messenger + * for sending messages to the service. + */ + @Override + public IBinder onBind(Intent intent) { + Toast.makeText(getApplicationContext(), "binding", Toast.LENGTH_SHORT).show(); + return mMessenger.getBinder(); + } +} +</pre> + +<p>Notice that the {@link android.os.Handler#handleMessage handleMessage()} method in the +{@link android.os.Handler} is where the service receives the incoming {@link android.os.Message} +and decides what to do, based on the {@link android.os.Message#what} member.</p> + +<p>All that a client needs to do is create a {@link android.os.Messenger} based on the {@link +android.os.IBinder} returned by the service and send a message using {@link +android.os.Messenger#send send()}. For example, here's a simple activity that binds to the +service and delivers the {@code MSG_SAY_HELLO} message to the service:</p> + +<pre> +public class ActivityMessenger extends Activity { + /** Messenger for communicating with the service. */ + Messenger mService = null; + + /** Flag indicating whether we have called bind on the service. */ + boolean mBound; + + /** + * 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 object we can use to + // interact with the service. We are communicating with the + // service using a Messenger, so here we get a client-side + // representation of that from the raw IBinder object. + mService = new Messenger(service); + mBound = true; + } + + 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; + mBound = false; + } + }; + + public void sayHello(View v) { + if (!mBound) return; + // Create and send a message to the service, using a supported 'what' value + Message msg = Message.obtain(null, MessengerService.MSG_SAY_HELLO, 0, 0); + try { + mService.send(msg); + } catch (RemoteException e) { + e.printStackTrace(); + } + } + + @Override + protected void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + setContentView(R.layout.main); + } + + @Override + protected void onStart() { + super.onStart(); + // Bind to the service + bindService(new Intent(this, MessengerService.class), mConnection, + Context.BIND_AUTO_CREATE); + } + + @Override + protected void onStop() { + super.onStop(); + // Unbind from the service + if (mBound) { + unbindService(mConnection); + mBound = false; + } + } +} +</pre> + +<p>Notice that this example does not show how the service can respond to the client. If you want the +service to respond, then you need to also create a {@link android.os.Messenger} in the client. Then +when the client receives the {@link android.content.ServiceConnection#onServiceConnected +onServiceConnected()} callback, it sends a {@link android.os.Message} to the service that includes +the client's {@link android.os.Messenger} in the {@link android.os.Message#replyTo} parameter +of the {@link android.os.Messenger#send send()} method.</p> + +<p>You can see an example of how to provide two-way messaging in the <a +href="{@docRoot}resources/samples/ApiDemos/src/com/example/android/apis/app/MessengerService.html">{@code +MessengerService.java}</a> (service) and <a +href="{@docRoot}resources/samples/ApiDemos/src/com/example/android/apis/app/MessengerServiceActivities.html">{@code +MessengerServiceActivities.java}</a> (client) samples.</p> + + + + + +<h2 id="Binding">Binding to a Service</h2> + +<p>Application components (clients) can bind to a service by calling +{@link android.content.Context#bindService bindService()}. The Android +system then calls the service's {@link android.app.Service#onBind +onBind()} method, which returns an {@link android.os.IBinder} for interacting with the service.</p> + +<p>The binding is asynchronous. {@link android.content.Context#bindService +bindService()} returns immediately and does <em>not</em> return the {@link android.os.IBinder} to +the client. To receive the {@link android.os.IBinder}, the client must create an instance of {@link +android.content.ServiceConnection} and pass it to {@link android.content.Context#bindService +bindService()}. The {@link android.content.ServiceConnection} includes a callback method that the +system calls to deliver the {@link android.os.IBinder}.</p> + +<p class="note"><strong>Note:</strong> Only activities, services, and content providers can bind +to a service—you <strong>cannot</strong> bind to a service from a broadcast receiver.</p> + +<p>So, to bind to a service from your client, you must: </p> +<ol> + <li>Implement {@link android.content.ServiceConnection}. + <p>Your implementation must override two callback methods:</p> + <dl> + <dt>{@link android.content.ServiceConnection#onServiceConnected onServiceConnected()}</dt> + <dd>The system calls this to deliver the {@link android.os.IBinder} returned by +the service's {@link android.app.Service#onBind onBind()} method.</dd> + <dt>{@link android.content.ServiceConnection#onServiceDisconnected +onServiceDisconnected()}</dt> + <dd>The Android system calls this when the connection to the service is unexpectedly +lost, such as when the service has crashed or has been killed. This is <em>not</em> called when the +client unbinds.</dd> + </dl> + </li> + <li>Call {@link +android.content.Context#bindService bindService()}, passing the {@link +android.content.ServiceConnection} implementation. </li> + <li>When the system calls your {@link android.content.ServiceConnection#onServiceConnected +onServiceConnected()} callback method, you can begin making calls to the service, using +the methods defined by the interface.</li> + <li>To disconnect from the service, call {@link +android.content.Context#unbindService unbindService()}. + <p>When your client is destroyed, it will unbind from the service, but you should always unbind +when you're done interacting with the service or when your activity pauses so that the service can +shutdown while its not being used. (Appropriate times to bind and unbind is discussed +more below.)</p> + </li> +</ol> + +<p>For example, the following snippet connects the client to the service created above by +<a href="#Binder">extending the Binder class</a>, so all it must do is cast the returned +{@link android.os.IBinder} to the {@code LocalService} class and request the {@code +LocalService} instance:</p> + +<pre> +LocalService mService; +private ServiceConnection mConnection = new ServiceConnection() { + // Called when the connection with the service is established + public void onServiceConnected(ComponentName className, IBinder service) { + // Because we have bound to an explicit + // service that is running in our own process, we can + // cast its IBinder to a concrete class and directly access it. + LocalBinder binder = (LocalBinder) service; + mService = binder.getService(); + mBound = true; + } + + // Called when the connection with the service disconnects unexpectedly + public void onServiceDisconnected(ComponentName className) { + Log.e(TAG, "onServiceDisconnected"); + mBound = false; + } +}; +</pre> + +<p>With this {@link android.content.ServiceConnection}, the client can bind to a service by passing +this it to {@link android.content.Context#bindService bindService()}. For example:</p> + +<pre> +Intent intent = new Intent(this, LocalService.class); +bindService(intent, mConnection, Context.BIND_AUTO_CREATE); +</pre> + +<ul> + <li>The first parameter of {@link android.content.Context#bindService bindService()} is an +{@link android.content.Intent} that explicitly names the service to bind (thought the intent +could be implicit).</li> +<li>The second parameter is the {@link android.content.ServiceConnection} object.</li> +<li>The third parameter is a flag indicating options for the binding. It should usually be {@link +android.content.Context#BIND_AUTO_CREATE} in order to create the service if its not already alive. +Other possible values are {@link android.content.Context#BIND_DEBUG_UNBIND} +and {@link android.content.Context#BIND_NOT_FOREGROUND}, or {@code 0} for none.</li> +</ul> + + +<h3>Additional notes</h3> + +<p>Here are some important notes about binding to a service:</p> +<ul> + <li>You should always trap {@link android.os.DeadObjectException} exceptions, which are thrown +when the connection has broken. This is the only exception thrown by remote methods.</li> + <li>Objects are reference counted across processes. </li> + <li>You should usually pair the binding and unbinding during +matching bring-up and tear-down moments of the client's lifecycle. For example: + <ul> + <li>If you only need to interact with the service while your activity is visible, you +should bind during {@link android.app.Activity#onStart onStart()} and unbind during {@link +android.app.Activity#onStop onStop()}.</li> + <li>If you want your activity to receive responses even while it is stopped in the +background, then you can bind during {@link android.app.Activity#onCreate onCreate()} and unbind +during {@link android.app.Activity#onDestroy onDestroy()}. Beware that this implies that your +activity needs to use the service the entire time it's running (even in the background), so if +the service is in another process, then you increase the weight of the process and it becomes +more likely that the system will kill it.</li> + </ul> + <p class="note"><strong>Note:</strong> You should usually <strong>not</strong> bind and unbind +during your activity's {@link android.app.Activity#onResume onResume()} and {@link +android.app.Activity#onPause onPause()}, because these callbacks occur at every lifecycle transition +and you should keep the processing that occurs at these transitions to a minimum. Also, if +multiple activities in your application bind to the same service and there is a transition between +two of those activities, the service may be destroyed and recreated as the current activity unbinds +(during pause) before the next one binds (during resume). (This activity transition for how +activities coordinate their lifecycles is described in the <a +href="{@docRoot}guide/topics/fundamentals/activities.html#CoordinatingActivities">Activities</a> +document.)</p> +</ul> + +<p>For more sample code, showing how to bind to a service, see the <a +href="{@docRoot}resources/samples/ApiDemos/src/com/example/android/apis/app/RemoteService.html">{@code +RemoteService.java}</a> class in <a +href="{@docRoot}resources/samples/ApiDemos/index.html">ApiDemos</a>.</p> + + + + + +<h2 id="Lifecycle">Managing the Lifecycle of a Bound Service</h2> + +<div class="figure" style="width:588px"> +<img src="{@docRoot}images/fundamentals/service_binding_tree_lifecycle.png" alt="" /> +<p class="img-caption"><strong>Figure 1.</strong> The lifecycle for a service that is started +and also allows binding.</p> +</div> + +<p>When a service is unbound from all clients, the Android system destroys it (unless it was also +started with {@link android.app.Service#onStartCommand onStartCommand()}). As such, you don't have +to manage the lifecycle of your service if it's purely a bound +service—the Android system manages it for you based on whether it is bound to any clients.</p> + +<p>However, if you choose to implement the {@link android.app.Service#onStartCommand +onStartCommand()} callback method, then you must explicitly stop the service, because the +service is now considered to be <em>started</em>. In this case, the service runs until the service +stops itself with {@link android.app.Service#stopSelf()} or another component calls {@link +android.content.Context#stopService stopService()}, regardless of whether it is bound to any +clients.</p> + +<p>Additionally, if your service is started and accepts binding, then when the system calls +your {@link android.app.Service#onUnbind onUnbind()} method, you can optionally return +{@code true} if you would like to receive a call to {@link android.app.Service#onRebind +onRebind()} the next time a client binds to the service (instead of receiving a call to {@link +android.app.Service#onBind onBind()}). {@link android.app.Service#onRebind +onRebind()} returns void, but the client still receives the {@link android.os.IBinder} in its +{@link android.content.ServiceConnection#onServiceConnected onServiceConnected()} callback. +Below, figure 1 illustrates the logic for this kind of lifecycle.</p> + +<p>For more information about the lifecycle of an started service, see the <a +href="{@docRoot}guide/topics/fundamentals/services.html#Lifecycle">Services</a> document.</p> + + + + diff --git a/docs/html/guide/topics/fundamentals/fragments.jd b/docs/html/guide/topics/fundamentals/fragments.jd new file mode 100644 index 0000000..9eceef1 --- /dev/null +++ b/docs/html/guide/topics/fundamentals/fragments.jd @@ -0,0 +1,815 @@ +page.title=Fragments +@jd:body + +<div id="qv-wrapper"> +<div id="qv"> + + <h2>Quickview</h2> + <ul> + <li>Fragments decompose application functionality and UI into reusable modules</li> + <li>Add multiple fragments to a screen to avoid switching activities</li> + <li>Fragments have their own lifecycle, state, and back stack</li> + <li>Fragments require API Level "Honeycomb" or greater</li> + </ul> + + <h2>In this document</h2> + <ol> + <li><a href="#Design">Design Philosophy</a></li> + <li><a href="#Creating">Creating a Fragment</a> + <ol> + <li><a href="#UI">Adding a user interface</a></li> + <li><a href="#Adding">Adding a fragment to an activity</a></li> + </ol> + </li> + <li><a href="#Managing">Managing Fragments</a></li> + <li><a href="#Transactions">Performing Fragment Transactions</a></li> + <li><a href="#CommunicatingWithActivity">Communicating with the Activity</a> + <ol> + <li><a href="#EventCallbacks">Creating event callbacks to the activity</a></li> + <li><a href="#ActionBar">Adding items to the Action Bar</a></li> + </ol> + </li> + <li><a href="#Lifecycle">Handling the Fragment Lifecycle</a> + <ol> + <li><a href="#CoordinadingWithActivity">Coordinating with the activity lifecycle</a></li> + </ol> + </li> + <li><a href="#Example">Example</a></li> + </ol> + + <h2>Key classes</h2> + <ol> + <li>{@link android.app.Fragment}</li> + <li>{@link android.app.FragmentManager}</li> + <li>{@link android.app.FragmentTransaction}</li> + </ol> + + <h2>Related samples</h2> + <ol> + <li><a +href="{@docRoot}resources/samples/ApiDemos/src/com/example/android/apis/app/index.html#Fragment">ApiDemos</a></li> + </ol> +</div> +</div> + +<p>A {@link android.app.Fragment} represents a behavior or a portion of user interface in an +{@link android.app.Activity}. You can combine multiple fragments in a single activity to build a +multi-pane UI and reuse a fragment in multiple activities. You can think of a fragment as a +modular section of an activity, which has its own lifecycle, receives its own input events, and +which you can add or remove while the activity is running.</p> + +<p>A fragment must always be embedded in an activity and the fragment's lifecycle is directly +affected by the host activity's lifecycle. For example, when the activity is paused, so are all +fragments in it, and when the activity is destroyed, so are all fragments. However, while an +activity is running (it is in the <em>resumed</em> <a +href="{@docRoot}guide/topics/fundamentals/activities.html#Lifecycle">lifecycle state</a>), you can +manipulate each fragment independently, such as add or remove them. When you perform such a +fragment transaction, you can also add it to a back stack that's managed by the +activity—each back stack entry in the activity is a record of the fragment transaction that +occurred. The back stack allows the user to reverse a fragment transaction (navigate backwards), +by pressing the BACK key.</p> + +<p>When you add a fragment as a part of your activity layout, it lives in a {@link +android.view.ViewGroup} inside the activity's view hierarchy and defines its own layout of views. +You can insert a fragment into your activity layout by declaring the fragment in the activity's +layout file, as a {@code <fragment>} element, or from your application code by adding it to an +existing {@link android.view.ViewGroup}. However, a fragment is not required to be a part of the +activity layout; you may also use a fragment as an invisible worker for the activity.</p> + +<p>This document describes how to build your application to use fragments, including +how fragments can maintain their state when added to the activity's back stack, share +events with the activity and other fragments in the activity, contribute to the activity's action +bar, and more.</p> + + +<h2 id="Design">Design Philosophy</h2> + +<p>Android introduced fragments in Android 3.0 (API Level "Honeycomb"), primarily to support more +dynamic and flexible UI designs on large screens, such as tablets. Because a +tablet's screen is much larger than that of a mobile phone, there's more room to combine and +interchange UI components. Fragments allow such designs without the need for you to manage complex +changes to the view hierarchy. By dividing the layout of an activity into fragments, you become able +to modify the activity's appearance at runtime and preserve those changes in a back stack +that's managed by the activity.</p> + +<p>For example, a news application can use one fragment to show a list of articles on the +left and another fragment to display an article on the right—both fragments appear in one +activity, side by side, and each fragment has its own set of lifecycle callback methods and handle +their own user input events. Thus, instead of using one activity to select an article and another +activity to read the article, the user can select an article and read it all within the same +activity, as illustrated in figure 1.</p> + +<img src="{@docRoot}images/fundamentals/fragments.png" alt="" /> +<p class="img-caption"><strong>Figure 1.</strong> An example of how two UI modules that are +typically separated into two activities can be combined into one activity, using fragments.</p> + + +<p>A fragment should be a modular and reusable component in your application. That is, because the +fragment defines its own layout and its own behavior using its own lifecycle callbacks, you +can include one fragment in multiple activities. This is especially important because it allows you +to adapt your user experience to different screen sizes. For instance, you might include multiple +fragments in an activity only when the screen size is sufficiently large, and, when it is not, +launch separate activities that use different fragments.</p> + +<p>For example—to continue with the news application example—the application can embed +two +fragments in <em>Activity A</em>, when running on an extra large screen (a tablet, for example). +However, on a normal-sized screen (a phone, for example), +there's not be enough room for both fragments, so <em>Activity A</em> includes only the fragment for +the list of articles, and when the user selects an article, it starts <em>Activity B</em>, which +includes the fragment to read the article. Thus, the application supports both design patterns +suggested in figure 1.</p> + + + +<h2 id="Creating">Creating a Fragment</h2> + +<div class="figure" style="width:314px"> +<img src="{@docRoot}images/fragment_lifecycle.png" alt="" /> +<p class="img-caption"><strong>Figure 2.</strong> The lifecycle of a fragment (while its +activity is running).</p> +</div> + +<p>To create a fragment, you must create a subclass of {@link android.app.Fragment} (or an existing +subclass of it). The {@link android.app.Fragment} class has code that looks a lot like +an {@link android.app.Activity}. It contains callback methods similar to an activity, such +as {@link android.app.Fragment#onCreate onCreate()}, {@link android.app.Fragment#onStart onStart()}, +{@link android.app.Fragment#onPause onPause()}, and {@link android.app.Fragment#onStop onStop()}. In +fact, if you're converting an existing Android application to use fragments, you might simply move +code from your activity's callback methods into the respective callback methods of your +fragment.</p> + +<p>Usually, you should implement at least the following lifecycle methods:</p> + +<dl> + <dt>{@link android.app.Fragment#onCreate onCreate()}</dt> + <dd>The system calls this when creating the fragment. Within your implementation, you should +initialize essential components of the fragment that you want to retain when the fragment is +paused or stopped, then resumed.</dd> + <dt>{@link android.app.Fragment#onCreateView onCreateView()}</dt> + <dd>The system calls this when it's time for the fragment to draw its user interface for the +first time. To draw a UI for your fragment, you must return a {@link android.view.View} from this +method that is the root of your fragment's layout. You can return null if the fragment does not +provide a UI.</dd> + <dt>{@link android.app.Activity#onPause onPause()}</dt> + <dd>The system calls this method as the first indication that the user is leaving the +fragment (though it does not always mean the fragment is being destroyed). This is usually where you +should commit any changes that should be persisted beyond the current user session (because +the user might not come back).</dd> +</dl> + +<p>Most applications should implement at least these three methods for every fragment, but there are +several other callback methods you should also use to handle various stages of the +fragment lifecycle. All the lifecycle callback methods are discussed more later, in the section +about <a href="#Lifecycle">Handling the Fragment Lifecycle</a>.</p> + + +<p>There are also a few subclasses that you might want to extend, instead of the base {@link +android.app.Fragment} class:</p> + +<dl> + <dt>{@link android.app.DialogFragment}</dt> + <dd>Displays a floating dialog. Using this class to create a dialog is a good alternative to using +the dialog helper methods in the {@link android.app.Activity} class, because you can +incorporate a fragment dialog into the back stack of fragments managed by the activity, +allowing the user to return to a dismissed fragment.</dd> + + <dt>{@link android.app.ListFragment}</dt> + <dd>Displays a list of items that are managed by an adapter (such as a {@link +android.widget.SimpleCursorAdapter}), similar to {@link android.app.ListActivity}. It provides +several methods for managing a list view, such as the {@link +android.app.ListFragment#onListItemClick(ListView,View,int,long) onListItemClick()} callback to +handle click events.</dd> + + <dt>{@link android.preference.PreferenceFragment}</dt> + <dd>Displays a hierarchy of {@link android.preference.Preference} objects as a list, similar to +{@link android.preference.PreferenceActivity}. This is useful when creating a "settings" +activity for your application.</dd> +</dl> + + +<h3 id="UI">Adding a user interface</h3> + +<p>A fragment is usually used as part of an activity's user interface and contributes its own +layout to the activity.</p> + +<p>To provide a layout for a fragment, you must implement the {@link +android.app.Fragment#onCreateView onCreateView()} callback method, which the Android system calls +when it's time for the fragment to draw its layout. Your implementation of this method must return a +{@link android.view.View} that is the root of your fragment's layout.</p> + +<p class="note"><strong>Note:</strong> If your fragment is a subclass of {@link +android.app.ListFragment}, the default implementation returns a {@link android.widget.ListView} from +{@link android.app.Fragment#onCreateView onCreateView()}, so you don't need to implement it.</p> + +<p>To return a layout from {@link +android.app.Fragment#onCreateView onCreateView()}, you can inflate it from a <a +href="{@docRoot}guide/topics/resources/layout-resource.html">layout resource</a> defined in XML. To +help you do so, {@link android.app.Fragment#onCreateView onCreateView()} provides a +{@link android.view.LayoutInflater} object.</p> + +<p>For example, here's a subclass of {@link android.app.Fragment} that loads a layout from the +{@code example_fragment.xml} file:</p> + +<pre> +public static class ExampleFragment extends Fragment { + @Override + public View onCreateView(LayoutInflater inflater, ViewGroup container, + Bundle savedInstanceState) { + // Inflate the layout for this fragment + return inflater.inflate(R.layout.example_fragment, container, false); + } +} +</pre> + +<div class="sidebox-wrapper"> +<div class="sidebox"> + <h3>Creating a layout</h3> + <p>In the sample above, {@code R.layout.example_fragment} is a reference to a layout resource +named {@code example_fragment.xml} saved in the application resources. For information about how to +create a layout in XML, see the <a href="{@docRoot}guide/topics/ui/index.html">User Interface</a> +documentation.</p> +</div> +</div> + +<p>The {@code container} parameter passed to {@link android.app.Fragment#onCreateView +onCreateView()} is the parent {@link android.view.ViewGroup} (from the activity's layout) in which +your fragment layout +will be inserted. The {@code savedInstanceState} parameter is a {@link android.os.Bundle} that +provides data about the previous instance of the fragment, if the fragment is being resumed +(restoring state is discussed more in the section about <a href="#Lifecycle">Handling the +Fragment Lifecycle</a>).</p> + +<p>The {@link android.view.LayoutInflater#inflate(int,ViewGroup,boolean) inflate()} method takes +three arguments:</p> +<ul> + <li>The resource ID of the layout you want to inflate.</li> + <li>The {@link android.view.ViewGroup} to be the parent of the inflated layout. Passing the {@code +container} is important in order for the system to apply layout parameters to the root view of the +inflated layout, specified by the parent view in which it's going.</li> + <li>A boolean indicating whether the inflated layout should be attached to the {@link +android.view.ViewGroup} (the second parameter) during inflation. (In this case, this +is false because the system is already inserting the inflated layout into the {@code +container}—passing true would create a redundant view group in the final layout.)</li> +</ul> + +<p>Now you've seen how to create a fragment that provides a layout. Next, you need to add +the fragment to your activity.</p> + + + +<h3 id="Adding">Adding a fragment to an activity</h3> + +<p>Usually, a fragment contributes a portion of UI to the host activity, which is embedded as a part +of the activity's overall view hierarchy. There are two ways you can add a fragment to the activity +layout:</p> + +<ul> + <li><b>Declare the fragment inside the activity's layout file.</b> +<p>In this case, you can +specify layout properties for the fragment as if it were a view. For example, here's the layout +file for an activity with two fragments:</p> +<pre> +<?xml version="1.0" encoding="utf-8"?> +<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" + android:orientation="horizontal" + android:layout_width="match_parent" + android:layout_height="match_parent"> + <fragment android:name="com.example.news.ArticleListFragment" + android:id="@+id/list" + android:layout_weight="1" + android:layout_width="0dp" + android:layout_height="match_parent" /> + <fragment android:name="com.example.news.ArticleReaderFragment" + android:id="@+id/viewer" + android:layout_weight="2" + android:layout_width="0dp" + android:layout_height="match_parent" /> +</LinearLayout> +</pre> + <p>The {@code android:name} attribute in the {@code <fragment>} specifies the {@link +android.app.Fragment} class to instantiate in the layout.</p> + +<p>When the system creates this activity layout, it instantiates each fragment specified in the +layout and calls the {@link android.app.Fragment#onCreateView onCreateView()} method for each one, +to retrieve each fragment's layout. The system inserts the {@link android.view.View} returned by the +fragment directly in place of the {@code <fragment>} element.</p> + +<div class="note"> + <p><strong>Note:</strong> Each fragment requires a unique identifier that +the system can use to restore the fragment if the activity is restarted (and which you can use to +capture the fragment to perform transactions, such as remove it). There are three ways to provide an +ID for a fragment:</p> + <ul> + <li>Supply the {@code android:id} attribute with a unique ID.</li> + <li>Supply the {@code android:tag} attribute with a unique string.</li> + <li>If you provide neither of the previous two, the system uses the ID of the container +view.</li> + </ul> +</div> + </li> + + <li><b>Or, programmatically add the fragment to an existing {@link android.view.ViewGroup}.</b> +<p>At any time while your activity is running, you can add fragments to your activity layout. You +simply need to specify a {@link +android.view.ViewGroup} in which to place the fragment.</p> + <p>To make fragment transactions in your activity (such as add, remove, or replace a +fragment), you must use APIs from {@link android.app.FragmentTransaction}. You can get an instance +of {@link android.app.FragmentTransaction} from your {@link android.app.Activity} like this:</p> + +<pre> +FragmentManager fragmentManager = {@link android.app.Activity#getFragmentManager()} +FragmentTransaction fragmentTransaction = fragmentManager.{@link android.app.FragmentManager#beginTransaction()}; +</pre> + +<p>You can then add a fragment using the {@link +android.app.FragmentTransaction#add(int,Fragment) add()} method, specifying the fragment to add and +the view in which to insert it. For example:</p> + +<pre> +ExampleFragment fragment = new ExampleFragment(); +fragmentTransaction.add(R.id.fragment_container, fragment); +fragmentTransaction.commit(); +</pre> + + <p>The first argument passed to {@link android.app.FragmentTransaction#add(int,Fragment) add()} +is the {@link android.view.ViewGroup} in which the fragment should be placed, specified by +resource ID, and the second parameter is the fragment to add.</p> + <p>Once you've made your changes with +{@link android.app.FragmentTransaction}, you must +call {@link android.app.FragmentTransaction#commit} for the changes to take effect.</p> + </li> +</ul> + + +<h4 id="AddingWithoutUI">Adding a fragment without a UI</h4> + +<p>The examples above show how to add a fragment to your activity in order to provide a UI. However, +you can also use a fragment to provide a background behavior for the activity without presenting +additional UI.</p> + +<p>To add a fragment without a UI, add the fragment from the activity using {@link +android.app.FragmentTransaction#add(Fragment,String)} (supplying a unique string "tag" for the +fragment, rather than a view ID). This adds the fragment, but, because it's not associated with a +view in the activity layout, it does not receive a call to {@link +android.app.Fragment#onCreateView onCreateView()}. So you don't need to implement that method.</p> + +<p>Supplying a string tag for the fragment isn't strictly for non-UI fragments—you can also +supply string tags to fragments that do have a UI—but if the fragment does not have a +UI, then the string tag is the only way to identify it. If you want to get the fragment from the +activity later, you need to use {@link android.app.FragmentManager#findFragmentByTag +findFragmentByTag()}.</p> + +<p>For an example activity that uses a fragment as a background worker, without a UI, see the <a +href="{@docRoot}resources/samples/ApiDemos/src/com/example/android/apis/app/FragmentRetainInstance.html">{@code +FragmentRetainInstance.java}</a> sample.</p> + + + +<h2 id="Managing">Managing Fragments</h2> + +<p>To manage the fragments in your activity, you need to use {@link android.app.FragmentManager}. To +get it, call {@link android.app.Activity#getFragmentManager()} from your activity.</p> + +<p>Some things that you can do with {@link android.app.FragmentManager} include:</p> + +<ul> + <li>Get fragments that exist in the activity, with {@link +android.app.FragmentManager#findFragmentById findFragmentById()} (for fragments that provide a UI in +the activity layout) or {@link android.app.FragmentManager#findFragmentByTag +findFragmentByTag()} (for fragments that do or don't provide a UI).</li> + <li>Pop fragments off the back stack, with {@link +android.app.FragmentManager#popBackStack()} (simulating a BACK command by the user).</li> + <li>Register a listener for changes to the back stack, with {@link +android.app.FragmentManager#addOnBackStackChangedListener addOnBackStackChangedListener()}.</li> +</ul> + +<p>For more information about these methods and others, refer to the {@link +android.app.FragmentManager} class documentation.</p> + +<p>As demonstrated in the previous section, you can also use {@link android.app.FragmentManager} +to open a {@link android.app.FragmentTransaction}, which allows you to perform transactions, such as +add and remove fragments.</p> + + +<h2 id="Transactions">Performing Fragment Transactions</h2> + +<p>A great feature about using fragments in your activity is the ability to add, remove, replace, +and perform other actions with them, in response to user interaction. Each set of changes that you +commit to the activity is called a transaction and you can perform one using APIs in {@link +android.app.FragmentTransaction}. You can also save each transaction to a back stack managed by the +activity, allowing the user to navigate backward through the fragment changes (similar to navigating +backward through activities).</p> + +<p>You can acquire an instance of {@link android.app.FragmentTransaction} from the {@link +android.app.FragmentManager} like this:</p> + +<pre> +FragmentManager fragmentManager = {@link android.app.Activity#getFragmentManager()}; +FragmentTransaction fragmentTransaction = fragmentManager.{@link android.app.FragmentManager#beginTransaction()}; +</pre> + +<p>Each transaction is a set of changes that you want to perform at the same time. You can set +up all the changes you want to perform for a given transaction using methods such as {@link +android.app.FragmentTransaction#add add()}, {@link android.app.FragmentTransaction#remove remove()}, +and {@link android.app.FragmentTransaction#replace replace()}. Then, to apply the transaction +to the activity, you must call {@link android.app.FragmentTransaction#commit()}.</p> +</dl> + +<p>Before you call {@link +android.app.FragmentTransaction#commit()}, however, you might want to call {@link +android.app.FragmentTransaction#addToBackStack addToBackStack()}, in order to add the transaction +to a back stack of fragment transactions. This back stack is managed by the activity and allows +the user to return to the previous fragment state, by pressing the BACK key.</p> + +<p>For example, here's how you can replace one fragment with another, and preserve the previous +state in the back stack:</p> + +<pre> +// Create new fragment and transaction +Fragment newFragment = new ExampleFragment(); +FragmentTransaction transaction = getFragmentManager().beginTransaction(); + +// Replace whatever is in the fragment_container view with this fragment, +// and add the transaction to the back stack +transaction.replace(R.id.fragment_container, newFragment); +transaction.addToBackStack(null); + +// Commit the transaction +transaction.commit(); +</pre> + +<p>In this example, {@code newFragment} replaces whatever fragment (if any) is currently in the +layout container identified by the {@code R.id.fragment_container} ID. By calling {@link +android.app.FragmentTransaction#addToBackStack addToBackStack()}, the replace transaction is +saved to the back stack so the user can reverse the transaction and bring back the +previous fragment by pressing the BACK key.</p> + +<p>If you add multiple changes to the transaction (such as another {@link +android.app.FragmentTransaction#add add()} or {@link android.app.FragmentTransaction#remove +remove()}) and call {@link +android.app.FragmentTransaction#addToBackStack addToBackStack()}, then all changes applied +before you call {@link android.app.FragmentTransaction#commit commit()} are added to the +back stack as a single transaction and the BACK key will reverse them all together.</p> + +<p>The order in which you add changes to a {@link android.app.FragmentTransaction} doesn't matter, +except:</p> +<ul> + <li>You must call {@link android.app.FragmentTransaction#commit()} last</li> + <li>If you're adding multiple fragments to the same container, then the order in which +you add them determines the order they appear in the view hierarchy</li> +</ul> + +<p>If you do not call {@link android.app.FragmentTransaction#addToBackStack(String) +addToBackStack()} when you perform a transaction that removes a fragment, then that fragment is +destroyed when the transaction is committed and the user cannot navigate back to it. Whereas, if you +do call {@link android.app.FragmentTransaction#addToBackStack(String) addToBackStack()} when +removing a fragment, then the fragment is <em>stopped</em> and will be resumed if the user navigates +back.</p> + +<p class="note"><strong>Tip:</strong> For each fragment transaction, you can apply a transition +animation, by calling {@link android.app.FragmentTransaction#setTransition setTransition()} before +you commit.</p> + +<p>Calling {@link android.app.FragmentTransaction#commit()} does not perform the transaction +immediately. Rather, it schedules it to run on the activity's UI thread (the "main" thread) as soon +as the thread is able to do so. If necessary, however, you may call {@link +android.app.FragmentManager#executePendingTransactions()} from your UI thread to immediately execute +transactions submitted by {@link android.app.FragmentTransaction#commit()}. Doing so is +usually not necessary unless the transaction is a dependency for jobs in other threads.</p> + +<p class="caution"><strong>Caution:</strong> You can commit a transaction using {@link +android.app.FragmentTransaction#commit commit()} only prior to the activity <a +href="{@docRoot}guide/topics/fundamentals/activities.html#SavingActivityState">saving its +state</a> (when the user leaves the activity). If you attempt to commit after that point, an +exception will be thrown. This is because the state after the commit can be lost if the activity +needs to be restored. For situations in which its okay that you lose the commit, use {@link +android.app.FragmentTransaction#commitAllowingStateLoss()}.</p> + + + + +<h2 id="CommunicatingWithActivity">Communicating with the Activity</h2> + +<p>Although a {@link android.app.Fragment} is implemented as an object that's independent from an +{@link android.app.Activity} and can be used inside multiple activities, a given instance of +a fragment is directly tied to the activity that contains it.</p> + +<p>Specifically, the fragment can access the {@link android.app.Activity} instance with {@link +android.app.Fragment#getActivity()} and easily perform tasks such as find a view in the +activity layout:</p> + +<pre> +View listView = {@link android.app.Fragment#getActivity()}.{@link android.app.Activity#findViewById findViewById}(R.id.list); +</pre> + +<p>Likewise, your activity can call methods in the fragment by acquiring a reference to the +{@link android.app.Fragment} from {@link android.app.FragmentManager}, using {@link +android.app.FragmentManager#findFragmentById findFragmentById()} or {@link +android.app.FragmentManager#findFragmentByTag findFragmentByTag()}. For example:</p> + +<pre> +ExampleFragment fragment = (ExampleFragment) getFragmentManager().findFragmentById(R.id.example_fragment); +</pre> + + +<h4 id="EventCallbacks">Creating event callbacks to the activity</h4> + +<p>In some cases, you might need a fragment to share events with the activity. A good way to do that +is to define a callback interface inside the fragment and require that the host activity implement +it. When the activity receives a callback through the interface, it can share the information with +other fragments in the layout as necessary.</p> + +<p>For example, if a news application has two fragments in an activity—one to show a list of +articles (fragment A) and another to display an article (fragment B)—then fragment A must tell +the activity when a list item is selected so that it can tell fragment B to display the article. In +this case, the {@code OnArticleSelectedListener} interface is declared inside fragment A:</p> + +<pre> +public static class FragmentA extends ListFragment { + ... + // Container Activity must implement this interface + public interface OnArticleSelectedListener { + public void onArticleSelected(Uri articleUri); + } + ... +} +</pre> + +<p>Then the activity that hosts the fragment implements the {@code OnArticleSelectedListener} +interface and +overrides {@code onArticleSelected()} to notify fragment B of the event from fragment A. To ensure +that the host activity implements this interface, fragment A's {@link +android.app.Fragment#onAttach onAttach()} callback method (which the system calls when adding +the fragment to the activity) instantiates an instance of {@code OnArticleSelectedListener} by +casting the {@link android.app.Activity} that is passed into {@link android.app.Fragment#onAttach +onAttach()}:</p> + +<pre> +public static class FragmentA extends ListFragment { + OnArticleSelectedListener mListener; + ... + @Override + public void onAttach(Activity activity) { + super.onAttach(activity); + try { + mListener = (OnArticleSelectedListener) activity; + } catch (ClassCastException e) { + throw new ClassCastException(activity.toString() + " must implement OnArticleSelectedListener"); + } + } + ... +} +</pre> + +<p>If the activity has not implemented the interface, then the fragment throws a +{@link java.lang.ClassCastException}. +On success, the {@code mListener} member holds a reference to activity's implementation of +{@code OnArticleSelectedListener}, so that fragment A can share events with the activity by calling +methods defined by the {@code OnArticleSelectedListener} interface. For example, if fragment A is an +extension of {@link android.app.ListFragment}, each time +the user clicks a list item, the system calls {@link android.app.ListFragment#onListItemClick +onListItemClick()} in the fragment, which then calls {@code onArticleSelected()} to share +the event with the activity:</p> + +<pre> +public static class FragmentA extends ListFragment { + OnArticleSelectedListener mListener; + ... + @Override + public void onListItemClick(ListView l, View v, int position, long id) { + // Append the clicked item's row ID with the content provider Uri + Uri noteUri = ContentUris.{@link android.content.ContentUris#withAppendedId withAppendedId}(ArticleColumns.CONTENT_URI, id); + // Send the event and Uri to the host activity + mListener.onArticleSelected(noteUri); + } + ... +} +</pre> + +<p>The {@code id} parameter passed to {@link +android.app.ListFragment#onListItemClick onListItemClick()} is the row ID of the clicked item, +which the activity (or other fragment) uses to fetch the article from the application's {@link +android.content.ContentProvider}.</p> + +<p><!--To see a complete implementation of this kind of callback interface, see the <a +href="{@docRoot}resources/samples/NotePad/index.html">NotePad sample</a>. -->More information about +using a content provider is available in the <a +href="{@docRoot}guide/topics/providers/content-providers.html">Content Providers</a> document.</p> + + + +<h3 id="ActionBar">Adding items to the Action Bar</h3> + +<p>Your fragments can contribute menu items to the activity's <a +href="{@docRoot}guide/topics/ui/menus.html#options-menu">Options Menu</a> (and, consequently, the <a +href="{@docRoot}guide/topics/ui/actionbar.html">Action Bar</a>) by implementing +{@link android.app.Fragment#onCreateOptionsMenu(Menu,MenuInflater) onCreateOptionsMenu()}. In order +for this method to receive calls, however, you must call {@link +android.app.Fragment#setHasOptionsMenu(boolean) setHasOptionsMenu()} during {@link +android.app.Fragment#onCreate(Bundle) onCreate()}, to indicate that the fragment +would like to add items to the Options Menu (otherwise, the fragment will not receive a call to +{@link android.app.Fragment#onCreateOptionsMenu onCreateOptionsMenu()}).</p> + +<p>Any items that you then add to the Options Menu from the fragment are appended to the existing +menu items. The fragment also receives callbacks to {@link +android.app.Fragment#onOptionsItemSelected(MenuItem) onOptionsItemSelected()} when a menu item +is selected.</p> + +<p>You can also register a view in your fragment layout to provide a context menu by calling {@link +android.app.Fragment#registerForContextMenu(View) registerForContextMenu()}. When the user opens +the context menu, the fragment receives a call to {@link +android.app.Fragment#onCreateContextMenu(ContextMenu,View,ContextMenu.ContextMenuInfo) +onCreateContextMenu()}. When the user selects an item, the fragment receives a call to {@link +android.app.Fragment#onContextItemSelected(MenuItem) onContextItemSelected()}.</p> + +<p class="note"><strong>Note:</strong> Although your fragment receives an on-item-selected callback +for each menu item it adds, the activity is first to receive the respective callback when the user +selects a menu item. If the activity's implementation of the on-item-selected callback does not +handle the selected item, then the event is passed to the fragment's callback. This is true for +the Options Menu and context menus.</p> + +<p>For more information about menus, see <a href="{@docRoot}guide/topics/ui/menus.html">Creating +Menus</a> and <a href="{@docRoot}guide/topics/ui/actionbar.html">Using the Action Bar</a>.</p> + + + + +<h2 id="Lifecycle">Handling the Fragment Lifecycle</h2> + +<div class="figure" style="width:403px"> +<img src="{@docRoot}images/activity_fragment_lifecycle.png" alt=""/> +<p class="img-caption"><strong>Figure 3.</strong> The activity lifecycle's affect on the fragment +lifecycle.</p> +</div> + +<p>Managing the lifecycle of a fragment is a lot like managing the lifecycle of an activity. Like +an activity, a fragment can exist in three states:</p> + +<dl> + <dt><i>Resumed</i></dt> + <dd>The fragment is visible in the running activity.</dd> + + <dt><i>Paused</i></dt> + <dd>Another activity is in the foreground and has focus, but the activity in which this +fragment lives is still visible (the foreground activity is partially transparent or doesn't +cover the entire screen).</dd> + + <dt><i>Stopped</i></dt> + <dd>The fragment is not visible. Either the host activity has been stopped or the +fragment has been removed from the activity but added to the back stack. A stopped fragment is +still alive (all state and member information is retained by the system). However, it is no longer +visible to the user and will be killed if the activity is killed.</dd> +</dl> + +<p>Also like an activity, you can retain the state of a fragment using a {@link +android.os.Bundle}, in case the activity's process is killed and you need to restore the +fragment state when the activity is recreated. You can save the state during the fragment's {@link +android.app.Fragment#onSaveInstanceState onSaveInstanceState()} callback and restore it during +either {@link android.app.Fragment#onCreate onCreate()}, {@link +android.app.Fragment#onCreateView onCreateView()}, or {@link +android.app.Fragment#onActivityCreated onActivityCreated()}. For more information about saving +state, see the <a +href="{@docRoot}guide/topics/fundamentals/activities.html#SavingActivityState">Activities</a> +document.</p> + +<p>The most significant difference in lifecycle between an activity and a fragment is how one is +stored in its respective back stack. An activity is placed into a back stack of activities +that's managed by the system when it's stopped, by default (so that the user can navigate back +to it with the BACK key, as discussed in <a +href="{@docRoot}guide/topics/fundamentals/tasks-and-back-stack.html">Tasks and Back Stack</a>). +However, a fragment is placed into a back stack managed by the host activity only when you +explicitly request that the instance be saved by calling {@link +android.app.FragmentTransaction#addToBackStack(String) addToBackStack()} during a transaction that +removes the fragment.</p> + +<p>Otherwise, managing the fragment lifecycle is very similar to managing the activity +lifecycle. So, the same practices for <a +href="{@docRoot}guide/topics/fundamentals/activities.html#Lifecycle">managing the activity +lifecycle</a> also apply to fragments. What you also need to understand, though, is how the life +of the activity affects the life of the fragment.</p> + + +<h3 id="CoordinatingWithActivity">Coordinating with the activity lifecycle</h3> + +<p>The lifecycle of the activity in which the fragment lives directly affects the lifecycle of the +fragment, such that each lifecycle callback for the activity results in a similar callback for each +fragment. For example, when the activity receives {@link android.app.Activity#onPause}, each +fragment in the activity receives {@link android.app.Fragment#onPause}.</p> + +<p>Fragments have a few extra lifecycle callbacks, however, that handle unique interaction with the +activity in order to perform actions such as build and destroy the fragment's UI. These additional +callback methods are:</p> + +<dl> + <dt>{@link android.app.Fragment#onAttach onAttach()}</dt> + <dd>Called when the fragment has been associated with the activity (the {@link +android.app.Activity} is passed in here).</dd> + <dt>{@link android.app.Fragment#onCreateView onCreateView()}</dt> + <dd>Called to create the view hierarchy associated with the fragment.</dd> + <dt>{@link android.app.Fragment#onActivityCreated onActivityCreated()}</dt> + <dd>Called when the activity's {@link android.app.Activity#onCreate +onCreate()} method has returned.</dd> + <dt>{@link android.app.Fragment#onDestroyView onDestroyView()}</dt> + <dd>Called when the view hierarchy associated with the fragment is being removed.</dd> + <dt>{@link android.app.Fragment#onDetach onDetach()}</dt> + <dd>Called when the fragment is being disassociated from the activity.</dd> +</dl> + +<p>The flow of a fragment's lifecycle, as it is affected by its host activity, is illustrated +by figure 3. In this figure, you can see how each successive state of the activity determines which +callback methods a fragment may receive. For example, when the activity has received its {@link +android.app.Activity#onCreate onCreate()} callback, a fragment in the activity receives no more than +the {@link android.app.Fragment#onActivityCreated onActivityCreated()} callback.</p> + +<p>Once the activity reaches the resumed state, you can freely add and remove fragments to the +activity. Thus, only while the activity is in the resumed state can the lifecycle of a fragment +change independently.</p> + +<p>However, when the activity leaves the resumed state, the fragment again is pushed through its +lifecycle by the activity.</p> + + + + +<h2 id="Example">Example</h2> + +<p>To bring everything discussed in this document together, here's an example of an activity +using two fragments to create a two-pane layout. The activity below includes one fragment to +show a list of Shakespeare play titles and another to show a summary of the play when selected +from the list. It also demonstrates how to provide different configurations of the fragments, +based on the screen configuration.</p> + +<p class="note"><strong>Note:</strong> The complete source code for this activity is available in +<a href="resources/samples/ApiDemos/src/com/example/android/apis/app/FragmentLayout.html">{@code +FragmentLayout.java}</a>.</p> + +<p>The main activity applies a layout in the usual way, during {@link +android.app.Activity#onCreate onCreate()}:</p> + +{@sample development/samples/ApiDemos/src/com/example/android/apis/app/FragmentLayout.java main} + +<p>The layout applied is {@code fragment_layout.xml}:</p> + +{@sample development/samples/ApiDemos/res/layout-land/fragment_layout.xml layout} + +<p>Using this layout, the system instantiates the {@code TitlesFragment} (which lists the play +titles) as soon as the activity loads the layout, while the {@link android.widget.FrameLayout} +(where the fragment for showing the play summary will go) consumes space on the right side of the +screen, but remains empty at first. As you'll see below, it's not until the user selects an item +from the list that a fragment is placed into the {@link android.widget.FrameLayout}.</p> + +<p>However, not all screen configurations are wide enough to show both the list of +plays and the summary, side by side. So, the layout above is used only for the landscape +screen configuration, by saving it at {@code res/layout-land/fragment_layout.xml}.</p> + +<p>Thus, when the screen is in portrait orientation, the system applies the following layout, which +is saved at {@code res/layout/fragment_layout.xml}:</p> + +{@sample development/samples/ApiDemos/res/layout/fragment_layout.xml layout} + +<p>This layout includes only {@code TitlesFragment}. This means that, when the device is in +portrait orientation, only the list of play titles is visible. So, when the user clicks a list +item in this configuration, the application will start a new activity to show the summary, +instead of loading a second fragment.</p> + +<p>Next, you can see how this is accomplished in the fragment classes. First is {@code +TitlesFragment}, which shows the list of Shakespeare play titles. This fragment extends {@link +android.app.ListFragment} and relies on it to handle most of the list view work.</p> + +<p>As you inspect this code, notice that there are two possible behaviors when the user clicks a +list item: depending on which of the two layouts is active, it can either create and display a new +fragment to show the details in the same activity (adding the fragment to the {@link +android.widget.FrameLayout}), or start a new activity (where the fragment can be shown).</p> + +{@sample development/samples/ApiDemos/src/com/example/android/apis/app/FragmentLayout.java titles} + +<p>The second fragment, {@code DetailsFragment} shows the play summary for the item selected from +the list from {@code TitlesFragment}:</p> + +{@sample development/samples/ApiDemos/src/com/example/android/apis/app/FragmentLayout.java details} + +<p>Recall from the {@code TitlesFragment} class, that, if the user clicks a list item and the +current layout does <em>not</em> include the {@code R.id.details} view (which is where the +{@code DetailsFragment} belongs), then the application starts the {@code DetailsActivity} +activity to display the content of the item.</p> + +<p>Here is the {@code DetailsActivity}, which simply embeds the {@code DetailsFragment} to display +the selected play summary when the screen is in portrait orientation:</p> + +{@sample development/samples/ApiDemos/src/com/example/android/apis/app/FragmentLayout.java +details_activity} + +<p>Notice that this activity finishes itself if the configuration is landscape, so that the main +activity can take over and display the {@code DetailsFragment} alongside the {@code TitlesFragment}. +This can happen if the user begins the {@code DetailsActivity} while in portrait orientation, but +then rotates to landscape (which restarts the current activity).</p> + + +<p>For more samples using fragments (and complete source files for this example), +see the sample code available in <a +href="{@docRoot}resources/samples/ApiDemos/src/com/example/android/apis/app/index.html#Fragment"> +ApiDemos</a> (available for download from the <a +href="{@docRoot}resources/samples/get.html">Samples SDK component</a>).</p> + + diff --git a/docs/html/guide/topics/fundamentals/services.jd b/docs/html/guide/topics/fundamentals/services.jd new file mode 100644 index 0000000..df1eace --- /dev/null +++ b/docs/html/guide/topics/fundamentals/services.jd @@ -0,0 +1,860 @@ +page.title=Services +parent.title=Application Fundamentals +parent.link=index.html +@jd:body + +<div id="qv-wrapper"> +<ol id="qv"> +<h2>Quickview</h2> +<ul> + <li>A service can run in the background to perform work even while the user is in a different +application</li> + <li>A service can allow other components to bind to it, in order to interact with it and +perform interprocess communication</li> + <li>A service runs in the main thread of the application that hosts it, by default</li> +</ul> +<h2>In this document</h2> +<ol> +<li><a href="#Basics">The Basics</a></li> +<ol> + <li><a href="#Declaring">Declaring a service in the manifest</a></li> +</ol> +<li><a href="#CreatingAService">Creating a Started Service</a> + <ol> + <li><a href="#ExtendingIntentService">Extending the IntentService class</a></li> + <li><a href="#ExtendingService">Extending the Service class</a></li> + <li><a href="#StartingAService">Starting a service</a></li> + <li><a href="#Stopping">Stopping a service</a></li> + </ol> +</li> +<li><a href="#CreatingBoundService">Creating a Bound Service</a></li> +<li><a href="#Notifications">Sending Notifications to the User</a></li> +<li><a href="#Foreground">Running a Service in the Foreground</a></li> +<li><a href="#Lifecycle">Managing the Lifecycle of a Service</a> +<ol> + <li><a href="#LifecycleCallbacks">Implementing the lifecycle callbacks</a></li> +</ol> +</li> +</ol> + +<h2>Key classes</h2> +<ol> + <li>{@link android.app.Service}</li> + <li>{@link android.app.IntentService}</li> +</ol> + +<h2>Samples</h2> +<ol> + <li><a href="{@docRoot}resources/samples/ApiDemos/src/com/example/android/apis/app/ServiceStartArguments.html">{@code + ServiceStartArguments}</a></li> + <li><a href="{@docRoot}resources/samples/ApiDemos/src/com/example/android/apis/app/LocalService.html">{@code + LocalService}</a></li> +</ol> + +<h2>See also</h2> +<ol> +<li><a href="{@docRoot}guide/topics/fundamentals/bound-services.html">Bound Services</a></li> +</ol> + +</div> + + +<p>A {@link android.app.Service} is an application component that can perform +long-running operations in the background and does not provide a user interface. Another +application component can start a service and it will continue to run in the background even if the +user switches to another application. Additionally, a component can bind to a service to +interact with it and even perform interprocess communication (IPC). For example, a service might +handle network transactions, play music, perform file I/O, or interact with a content provider, all +from the background.</p> + +<p>A service can essentially take two forms:</p> + +<dl> + <dt>Started</dt> + <dd>A service is "started" when an application component (such as an activity) starts it by +calling {@link android.content.Context#startService startService()}. Once started, a service +can run in the background indefinitely, even if the component that started it is destroyed. Usually, +a started service performs a single operation and does not return a result to the caller. +For example, it might download or upload a file over the network. When the operation is done, the +service should stop itself.</dd> + <dt>Bound</dt> + <dd>A service is "bound" when an application component binds to it by calling {@link +android.content.Context#bindService bindService()}. A bound service offers a client-server +interface that allows components to interact with the service, send requests, get results, and even +do so across processes with interprocess communication (IPC). A bound service runs only as long as +another application component is bound to it. Multiple components can bind to the service at once, +but when all of them unbind, the service is destroyed.</dd> +</dl> + +<p>Although this documentation generally discusses these two types of services separately, your +service can work both ways—it can be started (to run indefinitely) and also allow binding. +It's simply a matter of whether you implement a couple callback methods: {@link +android.app.Service#onStartCommand onStartCommand()} to allow components to start it and {@link +android.app.Service#onBind onBind()} to allow binding.</p> + +<p>Regardless of whether your application is started, bound, or both, any application component +can use the service (even from a separate application), in the same way that any component can use +an activity—by starting it with an {@link android.content.Intent}. However, you can declare +the service as private, in the manifest file, and block access from other applications. This is +discussed more in the section about <a href="#Declaring">Declaring the service in the +manifest</a>.</p> + +<p class="caution"><strong>Caution:</strong> A service runs in the +main thread of its hosting process—the service does <strong>not</strong> create its own thread +and does <strong>not</strong> run in a separate process (unless you specify otherwise). This means +that, if your service is going to do any CPU intensive work or blocking operations (such as MP3 +playback or networking), you should create a new thread within the service to do that work. By using +a separate thread, you will reduce the risk of Application Not Responding (ANR) errors and the +application's main thread can remain dedicated to user interaction with your activities.</p> + + +<h2 id="Basics">The Basics</h2> + +<div class="sidebox-wrapper"> +<div class="sidebox"> + <h3>Should you use a service or a thread?</h3> + <p>A service is simply a component that can run in the background even when the user is not +interacting with your application. Thus, you should create a service only if that is what you +need.</p> + <p>If you need to perform work outside your main thread, but only while the user is interacting +with your application, then you should probably instead create a new thread and not a service. For +example, if you want to play some music, but only while your activity is running, you might create +a thread in {@link android.app.Activity#onCreate onCreate()}, start running it in {@link +android.app.Activity#onStart onStart()}, then stop it in {@link android.app.Activity#onStop +onStop()}. Also consider using {@link android.os.AsyncTask} or {@link android.os.HandlerThread}, +instead of the traditional {@link java.lang.Thread} class. See the <a +href="{@docRoot}guide/topics/fundamentals/processes-and-threading.html#Threads">Processes and +Threading</a> document for more information about threads.</p> + <p>Remember that if you do use a service, it still runs in your application's main thread by +default, so you should still create a new thread within the service if it performs intensive or +blocking operations.</p> +</div> +</div> + +<p>To create a service, you must create a subclass of {@link android.app.Service} (or one +of its existing subclasses). In your implementation, you need to override some callback methods that +handle key aspects of the service lifecycle and provide a mechanism for components to bind to +the service, if appropriate. The most important callback methods you should override are:</p> + +<dl> + <dt>{@link android.app.Service#onStartCommand onStartCommand()}</dt> + <dd>The system calls this method when another component, such as an activity, +requests that the service be started, by calling {@link android.content.Context#startService +startService()}. Once this method executes, the service is started and can run in the +background indefinitely. If you implement this, it is your responsibility to stop the service when +its work is done, by calling {@link android.app.Service#stopSelf stopSelf()} or {@link +android.content.Context#stopService stopService()}. (If you only want to provide binding, you don't +need to implement this method.)</dd> + <dt>{@link android.app.Service#onBind onBind()}</dt> + <dd>The system calls this method when another component wants to bind with the +service (such as to perform RPC), by calling {@link android.content.Context#bindService +bindService()}. In your implementation of this method, you must provide an interface that clients +use to communicate with the service, by returning an {@link android.os.IBinder}. You must always +implement this method, but if you don't want to allow binding, then you should return null.</dd> + <dt>{@link android.app.Service#onCreate()}</dt> + <dd>The system calls this method when the service is first created, to perform one-time setup +procedures (before it calls either {@link android.app.Service#onStartCommand onStartCommand()} or +{@link android.app.Service#onBind onBind()}). If the service is already running, this method is not +called.</dd> + <dt>{@link android.app.Service#onDestroy()}</dt> + <dd>The system calls this method when the service is no longer used and is being destroyed. +Your service should implement this to clean up any resources such as threads, registered +listeners, receivers, etc. This is the last call the service receives.</dd> +</dl> + +<p>If a component starts the service by calling {@link +android.content.Context#startService startService()} (which results in a call to {@link +android.app.Service#onStartCommand onStartCommand()}), then the service +remains running until it stops itself with {@link android.app.Service#stopSelf()} or another +component stops it by calling {@link android.content.Context#stopService stopService()}.</p> + +<p>If a component calls +{@link android.content.Context#bindService bindService()} to create the service (and {@link +android.app.Service#onStartCommand onStartCommand()} is <em>not</em> called), then the service runs +only as long as the component is bound to it. Once the service is unbound from all clients, the +system destroys it.</p> + +<p>The Android system will force-stop a service only when memory is low and it must recover system +resources for the activity that has user focus. If the service is bound to an activity that has user +focus, then it's less likely to be killed, and if the service is declared to <a +href="#Foreground">run in the foreground</a> (discussed later), then it will almost never be killed. +Otherwise, if the service was started and is long-running, then the system will lower its position +in the list of background tasks over time and the service will become highly susceptible to +killing—if your service is started, then you must design it to gracefully handle restarts +by the system. If the system kills your service, it restarts it as soon as resources become +available again (though this also depends on the value you return from {@link +android.app.Service#onStartCommand onStartCommand()}, as discussed later). For more information +about when the system might destroy a service, see the <a +href="{@docRoot}guide/topics/fundamentals/processes-and-threading.html">Processes and Threading</a> +document.</p> + +<p>In the following sections, you'll see how you can create each type of service and how to use +it from other application components.</p> + + + +<h3 id="Declaring">Declaring a service in the manifest</h3> + +<p>Like activities (and other components), you must declare all services in your application's +manifest file.</p> + +<p>To decalare your service, add a <a +href="{@docRoot}guide/topics/manifest/service-element.html">{@code <service>}</a> element +as a child of the <a +href="{@docRoot}guide/topics/manifest/application-element.html">{@code <application>}</a> +element. For example:</p> + +<pre> +<manifest ... > + ... + <application ... > + <service android:name=".ExampleService" /> + ... + </application> +</manifest> +</pre> + +<p>There are other attributes you can include in the <a +href="{@docRoot}guide/topics/manifest/service-element.html">{@code <service>}</a> element to +define properties such as permissions required to start the service and the process in +which the service should run. See the <a +href="{@docRoot}guide/topics/manifest/service-element.html">{@code <service>}</a> element +reference for more information.</p> + +<p>Just like an activity, a service can define intent filters that allow other components to +invoke the service using implicit intents. By declaring intent filters, components +from any application installed on the user's device can potentially start your service if your +service declares an intent filter that matches the intent another application passes to {@link +android.content.Context#startService startService()}.</p> + +<p>If you plan on using your service only locally (other applications do not use it), then you +don't need to (and should not) supply any intent filters. Without any intent filters, you must +start the service using an intent that explicitly names the service class. More information +about <a href="#StartingAService">starting a service</a> is discussed below.</p> + +<p>Additionally, you can ensure that your service is private to your application only if +you include the <a +href="{@docRoot}guide/topics/manifest/service-element.html#exported">{@code android:exported}</a> +attribute and set it to {@code "false"}. This is effective even if your service supplies intent +filters.</p> + +<p>For more information about creating intent filters for your service, see the <a +href="{@docRoot}guide/topics/intents/intents-filters.html">Intents and Intent Filters</a> +document.</p> + + + +<h2 id="CreatingStartedService">Creating a Started Service</h2> + +<div class="sidebox-wrapper"> +<div class="sidebox"> + <h2>Targeting Android 1.6 or lower</h2> + <p>If you're building an application for Android 1.6 or lower, you need +to implement {@link android.app.Service#onStart onStart()}, instead of {@link +android.app.Service#onStartCommand onStartCommand()} (in Android 2.0, +{@link android.app.Service#onStart onStart()} was deprecated in favor of {@link +android.app.Service#onStartCommand onStartCommand()}).</p> + <p>For more information about providing compatibility with versions of Android older than 2.0, see +the {@link android.app.Service#onStartCommand onStartCommand()} documentation.</p> +</div> +</div> + +<p>A started service is one that another component starts by calling {@link +android.content.Context#startService startService()}, resulting in a call to the service's +{@link android.app.Service#onStartCommand onStartCommand()} method.</p> + +<p>When a service is started, it has a lifecycle that's independent of the +component that started it and the service can run in the background indefinitely, even if +the component that started it is destroyed. As such, the service should stop itself when its job +is done by calling {@link android.app.Service#stopSelf stopSelf()}, or another component can stop it +by calling {@link android.content.Context#stopService stopService()}.</p> + +<p>An application component such as an activity can start the service by calling {@link +android.content.Context#startService startService()} and passing an {@link android.content.Intent} +that specifies the service and includes any data for the service to use. The service receives +this {@link android.content.Intent} in the {@link android.app.Service#onStartCommand +onStartCommand()} method.</p> + +<p>For instance, suppose an activity needs to save some data to an online database. The activity can +start a companion service and deliver it the data to save by passing an intent to {@link +android.content.Context#startService startService()}. The service receives the intent in {@link +android.app.Service#onStartCommand onStartCommand()}, connects to the Internet and performs the +database transaction. When the transaction is done, the service stops itself and it is +destroyed.</p> + +<p class="caution"><strong>Caution:</strong> A services runs in the same process as the application +in which it is declared and in the main thread of that application, by default. So, if your service +performs intensive or blocking operations while the user interacts with an activity from the same +application, the service will slow down activity performance. To avoid impacting application +performance, you should start a new thread inside the service.</p> + +<p>Traditionally, there are two classes you can extend to create a started service:</p> +<dl> + <dt>{@link android.app.Service}</dt> + <dd>This is the base class for all services. When you extend this class, it's important that +you create a new thread in which to do all the service's work, because the service uses your +application's main thread, by default, which could slow the performance of any activity your +application is running.</dd> + <dt>{@link android.app.IntentService}</dt> + <dd>This is a subclass of {@link android.app.Service} that uses a worker thread to handle all +start requests, one at a time. This is the best option if you don't require that your service +handle multiple requests simultaneously. All you need to do is implement {@link +android.app.IntentService#onHandleIntent onHandleIntent()}, which receives the intent for each +start request so you can do the background work.</dd> +</dl> + +<p>The following sections describe how you can implement your service using either one for these +classes.</p> + + +<h3 id="ExtendingIntentService">Extending the IntentService class</h3> + +<p>Because most started services don't need to handle multiple requests simultaneously +(which can actually be a dangerous multi-threading scenario), it's probably best if you +implement your service using the {@link android.app.IntentService} class.</p> + +<p>The {@link android.app.IntentService} does the following:</p> + +<ul> + <li>Creates a default worker thread that executes all intents delivered to {@link +android.app.Service#onStartCommand onStartCommand()} separate from your application's main +thread.</li> + <li>Creates a work queue that passes one intent at a time to your {@link +android.app.IntentService#onHandleIntent onHandleIntent()} implementation, so you never have to +worry about multi-threading.</li> + <li>Stops the service after all start requests have been handled, so you never have to call +{@link android.app.Service#stopSelf}.</li> + <li>Provides default implementation of {@link android.app.IntentService#onBind onBind()} that +returns null.</li> + <li>Provides a default implementation of {@link android.app.IntentService#onStartCommand +onStartCommand()} that sends the intent to the work queue and then to your {@link +android.app.IntentService#onHandleIntent onHandleIntent()} implementation.</li> +</ul> + +<p>All this adds up to the fact that all you need to do is implement {@link +android.app.IntentService#onHandleIntent onHandleIntent()} to do the work provided by the +client. (Though, you also need to provide a small constructor for the service.)</p> + +<p>Here's an example implementation of {@link android.app.IntentService}:</p> + +<pre> +public class HelloIntentService extends IntentService { + + /** + * A constructor is required, and must call the super {@link android.app.IntentService#IntentService} + * constructor with a name for the worker thread. + */ + public HelloIntentService() { + super("HelloIntentService"); + } + + /** + * The IntentService calls this method from the default worker thread with + * the intent that started the service. When this method returns, IntentService + * stops the service, as appropriate. + */ + @Override + protected void onHandleIntent(Intent intent) { + // Normally we would do some work here, like download a file. + // For our sample, we just sleep for 5 seconds. + long endTime = System.currentTimeMillis() + 5*1000; + while (System.currentTimeMillis() < endTime) { + synchronized (this) { + try { + wait(endTime - System.currentTimeMillis()); + } catch (Exception e) { + } + } + } + } +} +</pre> + +<p>That's all you need: a constructor and an implementation of {@link +android.app.IntentService#onHandleIntent onHandleIntent()}.</p> + +<p>If you decide to also override other callback methods, such as {@link +android.app.IntentService#onCreate onCreate()}, {@link +android.app.IntentService#onStartCommand onStartCommand()}, or {@link +android.app.IntentService#onDestroy onDestroy()}, be sure to call the super implementation, so +that the {@link android.app.IntentService} can properly handle the life of the worker thread.</p> + +<p>For example, {@link android.app.IntentService#onStartCommand onStartCommand()} must return +the default implementation (which is how the intent gets delivered to {@link +android.app.IntentService#onHandleIntent onHandleIntent()}):</p> + +<pre> +@Override +public int onStartCommand(Intent intent, int flags, int startId) { + Toast.makeText(this, "service starting", Toast.LENGTH_SHORT).show(); + return super.onStartCommand(intent,flags,startId); +} +</pre> + +<p>Besides {@link android.app.IntentService#onHandleIntent onHandleIntent()}, the only method +from which you don't need to call the super class is {@link android.app.IntentService#onBind +onBind()} (but you only need to implement that if your service allows binding).</p> + +<p>In the next section, you'll see how the same kind of service is implemented when extending +the base {@link android.app.Service} class, which is a lot more code, but which might be +appropriate if you need to handle simultaneous start requests.</p> + + +<h3 id="ExtendingService">Extending the Service class</h3> + +<p>As you saw in the previous section, using {@link android.app.IntentService} makes your +implementation of a started service very simple. If, however, you require your service to +perform multi-threading (instead of processing start requests through a work queue), then you +can extend the {@link android.app.Service} class to handle each intent.</p> + +<p>For comparison, the following example code is an implementation of the {@link +android.app.Service} class that performs the exact same work as the example above using {@link +android.app.IntentService}. That is, for each start request, it uses a worker thread to perform the +job and processes only one request at a time.</p> + +<pre> +public class HelloService extends Service { + private Looper mServiceLooper; + private ServiceHandler mServiceHandler; + + // Handler that receives messages from the thread + private final class ServiceHandler extends Handler { + public ServiceHandler(Looper looper) { + super(looper); + } + @Override + public void handleMessage(Message msg) { + // Normally we would do some work here, like download a file. + // For our sample, we just sleep for 5 seconds. + long endTime = System.currentTimeMillis() + 5*1000; + while (System.currentTimeMillis() < endTime) { + synchronized (this) { + try { + wait(endTime - System.currentTimeMillis()); + } catch (Exception e) { + } + } + } + // Stop the service using the startId, so that we don't stop + // the service in the middle of handling another job + stopSelf(msg.arg1); + } + } + + @Override + public void onCreate() { + // Start up the thread running the service. Note that we create a + // separate thread because the service normally runs in the process's + // main thread, which we don't want to block. We also make it + // background priority so CPU-intensive work will not disrupt our UI. + HandlerThread thread = new HandlerThread("ServiceStartArguments", + Process.THREAD_PRIORITY_BACKGROUND); + thread.start(); + + // Get the HandlerThread's Looper and use it for our Handler + mServiceLooper = thread.getLooper(); + mServiceHandler = new ServiceHandler(mServiceLooper); + } + + @Override + public int onStartCommand(Intent intent, int flags, int startId) { + Toast.makeText(this, "service starting", Toast.LENGTH_SHORT).show(); + + // For each start request, send a message to start a job and deliver the + // start ID so we know which request we're stopping when we finish the job + Message msg = mServiceHandler.obtainMessage(); + msg.arg1 = startId; + mServiceHandler.sendMessage(msg); + + // If we get killed, after returning from here, restart + return START_STICKY; + } + + @Override + public IBinder onBind(Intent intent) { + // We don't provide binding, so return null + return null; + } + + @Override + public void onDestroy() { + Toast.makeText(this, "service done", Toast.LENGTH_SHORT).show(); + } +} +</pre> + +<p>As you can see, it's a lot more work than using {@link android.app.IntentService}.</p> + +<p>However, because you handle each call to {@link android.app.Service#onStartCommand +onStartCommand()} yourself, you can perform multiple requests simultaneously. That's not what +this example does, but if that's what you want, then you can create a new thread for each +request and run them right away (instead of waiting for the previous request to finish).</p> + +<p>Notice that the {@link android.app.Service#onStartCommand onStartCommand()} method must return an +integer. The integer is a value that describes how the system should continue the service in the +event that the system kills it (as discussed above, the default implementation for {@link +android.app.IntentService} handles this for you, though you are able to modify it). The return value +from {@link android.app.Service#onStartCommand onStartCommand()} must be one of the following +constants:</p> + +<dl> + <dt>{@link android.app.Service#START_NOT_STICKY}</dt> + <dd>If the system kills the service after {@link android.app.Service#onStartCommand +onStartCommand()} returns, <em>do not</em> recreate the service, unless there are pending +intents to deliver. This is the safest option to avoid running your service when not necessary +and when your application can simply restart any unfinished jobs.</dd> + <dt>{@link android.app.Service#START_STICKY}</dt> + <dd>If the system kills the service after {@link android.app.Service#onStartCommand +onStartCommand()} returns, recreate the service and call {@link +android.app.Service#onStartCommand onStartCommand()}, but <em>do not</em> redeliver the last intent. +Instead, the system calls {@link android.app.Service#onStartCommand onStartCommand()} with a +null intent, unless there were pending intents to start the service, in which case, +those intents are delivered. This is suitable for media players (or similar services) that are not +executing commands, but running indefinitely and waiting for a job.</dd> + <dt>{@link android.app.Service#START_REDELIVER_INTENT}</dt> + <dd>If the system kills the service after {@link android.app.Service#onStartCommand +onStartCommand()} returns, recreate the service and call {@link +android.app.Service#onStartCommand onStartCommand()} with the last intent that was delivered to the +service. Any pending intents are delivered in turn. This is suitable for services that are +actively performing a job that should be immediately resumed, such as downloading a file.</dd> +</dl> +<p>For more details about these return values, see the linked reference documentation for each +constant.</p> + + + +<h3 id="StartingAService">Starting a Service</h3> + +<p>You can start a service from an activity or other application component by passing an +{@link android.content.Intent} (specifying the service to start) to {@link +android.content.Context#startService startService()}. The Android system calls the service's {@link +android.app.Service#onStartCommand onStartCommand()} method and passes it the {@link +android.content.Intent}. (You should never call {@link android.app.Service#onStartCommand +onStartCommand()} directly.)</p> + +<p>For example, an activity can start the example service in the previous section ({@code +HelloSevice}) using an explicit intent with {@link android.content.Context#startService +startService()}:</p> + +<pre> +Intent intent = new Intent(this, HelloService.class); +startService(intent); +</pre> + +<p>The {@link android.content.Context#startService startService()} method returns immediately and +the Android system calls the service's {@link android.app.Service#onStartCommand +onStartCommand()} method. If the service is not already running, the system first calls {@link +android.app.Service#onCreate onCreate()}, then calls {@link android.app.Service#onStartCommand +onStartCommand()}.</p> + +<p>If the service does not also provide binding, the intent delivered with {@link +android.content.Context#startService startService()} is the only mode of communication between the +application component and the service. However, if you want the service to send a result back, then +the client that starts the service can create a {@link android.app.PendingIntent} for a broadcast +(with {@link android.app.PendingIntent#getBroadcast getBroadcast()}) and deliver it to the service +in the {@link android.content.Intent} that starts the service. The service can then use the +broadcast to deliver a result.</p> + +<p>Multiple requests to start the service result in multiple corresponding calls to the service's +{@link android.app.Service#onStartCommand onStartCommand()}. However, only one request to stop +the service (with {@link android.app.Service#stopSelf stopSelf()} or {@link +android.content.Context#stopService stopService()}) is required to stop it.</p> + + +<h3 id="Stopping">Stopping a service</h3> + +<p>A started service must manage its own lifecycle. That is, the system does not stop or +destroy the service unless it must recover system memory and the service +continues to run after {@link android.app.Service#onStartCommand onStartCommand()} returns. So, +the service must stop itself by calling {@link android.app.Service#stopSelf stopSelf()} or another +component can stop it by calling {@link android.content.Context#stopService stopService()}.</p> + +<p>Once requested to stop with {@link android.app.Service#stopSelf stopSelf()} or {@link +android.content.Context#stopService stopService()}, the system destroys the service as soon as +possible.</p> + +<p>However, if your service handles multiple requests to {@link +android.app.Service#onStartCommand onStartCommand()} concurrently, then you shouldn't stop the +service when you're done processing a start request, because you might have since received a new +start request (stopping at the end of the first request would terminate the second one). To avoid +this problem, you can use {@link android.app.Service#stopSelf(int)} to ensure that your request to +stop the service is always based on the most recent start request. That is, when you call {@link +android.app.Service#stopSelf(int)}, you pass the ID of the start request (the <code>startId</code> +delivered to {@link android.app.Service#onStartCommand onStartCommand()}) to which your stop request +corresponds. Then if the service received a new start request before you were able to call {@link +android.app.Service#stopSelf(int)}, then the ID will not match and the service will not stop.</p> + +<p class="caution"><strong>Caution:</strong> It's important that your application stops its services +when it's done working, to avoid wasting system resources and consuming battery power. If necessary, +other components can stop the service by calling {@link +android.content.Context#stopService stopService()}. Even if you enable binding for the service, +you must always stop the service yourself if it ever received a call to {@link +android.app.Service#onStartCommand onStartCommand()}.</p> + +<p>For more information about the lifecycle of a service, see the section below about <a +href="#Lifecycle">Managing the Lifecycle of a Service</a>.</p> + + + +<h2 id="CreatingBoundService">Creating a Bound Service</h2> + +<p>A bound service is one that allows application components to bind to it by calling {@link +android.content.Context#bindService bindService()} in order to create a long-standing connection +(and generally does not allow components to <em>start</em> it by calling {@link +android.content.Context#startService startService()}).</p> + +<p>You should create a bound service when you want to interact with the service from activities +and other components in your application or to expose some of your application's functionality to +other applications, through interprocess communication (IPC).</p> + +<p>To create a bound service, you must implement the {@link +android.app.Service#onBind onBind()} callback method to return an {@link android.os.IBinder} that +defines the interface for communication with the service. Other application components can then call +{@link android.content.Context#bindService bindService()} to retrieve the interface and +begin calling methods on the service. The service lives only to serve the application component that +is bound to it, so when there are no components bound to the service, the system destroys it +(you do <em>not</em> need to stop a bound service in the way you must when the service is started +through {@link android.app.Service#onStartCommand onStartCommand()}).</p> + +<p>To create a bound service, the first thing you must do is define the interface that specifies +how a client can communicate with the service. This interface between the service +and a client must be an implementation of {@link android.os.IBinder} and is what your service must +return from the {@link android.app.Service#onBind +onBind()} callback method. Once the client receives the {@link android.os.IBinder}, it can begin +interacting with the service through that interface.</p> + +<p>Multiple clients can bind to the service at once. When a client is done interacting with the +service, it calls {@link android.content.Context#unbindService unbindService()} to unbind. Once +there are no clients bound to the service, the system destroys the service.</p> + +<p>There are multiple ways to implement a bound service and the implementation is more +complicated than a started service, so the bound service discussion appears in a separate +document about <a +href="{@docRoot}guide/topics/fundamentals/bound-services.html">Bound Services</a>.</p> + + + +<h2 id="Notifications">Sending Notifications to the User</h2> + +<p>Once running, a service can notify the user of events using <a +href="{@docRoot}guide/topics/ui/notifiers/toasts.html">Toast Notifications</a> or <a +href="{@docRoot}guide/topics/ui/notifiers/notifications.html">Status Bar Notifications</a>.</p> + +<p>A toast notification is a message that appears on the surface of the current window for a +moment then disappears, while a status bar notification provides an icon in the status bar with a +message, which the user can select in order to take an action (such as start an activity).</p> + +<p>Usually, a status bar notification is the best technique when some background work has completed +(such as a file completed +downloading) and the user can now act on it. When the user selects the notification from the +expanded view, the notification can start an activity (such as to view the downloaded file).</p> + +<p>See the <a +href="{@docRoot}guide/topics/ui/notifiers/toasts.html">Toast Notifications</a> or <a +href="{@docRoot}guide/topics/ui/notifiers/notifications.html">Status Bar Notifications</a> +developer guides for more information.</p> + + + +<h2 id="Foreground">Running a Service in the Foreground</h2> + +<p>A foreground service is a service that's considered to be something the +user is actively aware of and thus not a candidate for the system to kill when low on memory. A +foreground service must provide a notification for the status bar, which is placed under the +"Ongoing" heading, which means that the notification cannot be dismissed unless the service is +either stopped or removed from the foreground.</p> + +<p>For example, a music player that plays music from a service should be set to run in the +foreground, because the user it explicitly aware +of its operation. The notification in the status bar might indicate the current song and allow +the user to launch an activity to interact with the music player.</p> + +<p>To request that your service run in the foreground, call {@link +android.app.Service#startForeground startForeground()}. This method takes two parameters: an integer +that uniquely identifies the notification and the {@link +android.app.Notification} for the status bar. For example:</p> + +<pre> +Notification notification = new Notification(R.drawable.icon, getText(R.string.ticker_text), + System.currentTimeMillis()); +Intent notificationIntent = new Intent(this, ExampleActivity.class); +PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0); +notification.setLatestEventInfo(this, getText(R.string.notification_title), + getText(R.string.notification_message), pendingIntent); +startForeground(ONGOING_NOTIFICATION, notification); +</pre> + + +<p>To remove the service from the foreground, call {@link +android.app.Service#stopForeground stopForeground()}. This method takes a boolean, indicating +whether to remove the status bar notification as well. This method does <em>not</em> stop the +service. However, if you stop the service while it's still running in the foreground, then the +notification is also removed.</p> + +<p class="note"><strong>Note:</strong> The methods {@link +android.app.Service#startForeground startForeground()} and {@link +android.app.Service#stopForeground stopForeground()} were introduced in Android 2.0 (API Level +5). In order to run your service in the foreground on older versions of the platform, you must +use the previous {@code setForeground()} method—see the {@link +android.app.Service#startForeground startForeground()} documentation for information about how +to provide backward compatibility.</p> + +<p>For more information about notifications, see <a +href="{@docRoot}guide/topics/ui/notifiers/notifications.html">Creating Status Bar +Notifications</a>.</p> + + + +<h2 id="Lifecycle">Managing the Lifecycle of a Service</h2> + +<p>The lifecycle of a service is much simpler than that of an activity. However, it's even more important +that you pay close attention to how your service is created and destroyed, because a service +can run in the background without the user being aware.</p> + +<p>The service lifecycle—from when it's created to when it's destroyed—can follow two +different paths:</p> + +<ul> +<li>A started service + <p>The service is created when another component calls {@link +android.content.Context#startService startService()}. The service then runs indefinitely and must +stop itself by calling {@link +android.app.Service#stopSelf() stopSelf()}. Another component can also stop the +service by calling {@link android.content.Context#stopService +stopService()}. When the service is stopped, the system destroys it..</p></li> + +<li>A bound service + <p>The service is created when another component (a client) calls {@link +android.content.Context#bindService bindService()}. The client then communicates with the service +through an {@link android.os.IBinder} interface. The client can close the connection by calling +{@link android.content.Context#unbindService unbindService()}. Multiple clients can bind to +the same service and when all of them unbind, the system destroys the service. (The service +does <em>not</em> need to stop itself.)</p></li> +</ul> + +<p>These two paths are not entirely separate. That is, you can bind to a service that was already +started with {@link android.content.Context#startService startService()}. For example, a background +music service could be started by calling {@link android.content.Context#startService +startService()} with an {@link android.content.Intent} that identifies the music to play. Later, +possibly when the user wants to exercise some control over the player or get information about the +current song, an activity can bind to the service by calling {@link +android.content.Context#bindService bindService()}. In cases like this, {@link +android.content.Context#stopService stopService()} or {@link android.app.Service#stopSelf +stopSelf()} does not actually stop the service until all clients unbind. </p> + + +<h3 id="LifecycleCallbacks">Implementing the lifecycle callbacks</h3> + +<p>Like an activity, a service has lifecycle callback methods that you can implement to monitor +changes in the service's state and perform work at the appropriate times. The following skeleton +service demonstrates each of the lifecycle methods:</p> + + +<div class="figure" style="width:432px"> +<img src="{@docRoot}images/service_lifecycle.png" alt="" /> +<p class="img-caption"><strong>Figure 2.</strong> The service lifecycle. The diagram on the left +shows the lifecycle when the service is created with {@link android.content.Context#startService +startService()} and the diagram on the right shows the lifecycle when the service is created +with {@link android.content.Context#bindService bindService()}.</p> +</div> + +<pre> +public class ExampleService extends Service { + int mStartMode; // indicates how to behave if the service is killed + IBinder mBinder; // interface for clients that bind + boolean mAllowRebind; // indicates whether onRebind should be used + + @Override + public void {@link android.app.Service#onCreate onCreate}() { + // The service is being created + } + @Override + public int {@link android.app.Service#onStartCommand onStartCommand}(Intent intent, int flags, int startId) { + // The service is starting, due to a call to {@link android.content.Context#startService startService()} + return <em>mStartMode</em>; + } + @Override + public IBinder {@link android.app.Service#onBind onBind}(Intent intent) { + // A client is binding to the service with {@link android.content.Context#bindService bindService()} + return <em>mBinder</em>; + } + @Override + public boolean {@link android.app.Service#onUnbind onUnbind}(Intent intent) { + // All clients have unbound with {@link android.content.Context#unbindService unbindService()} + return <em>mAllowRebind</em>; + } + @Override + public void {@link android.app.Service#onRebind onRebind}(Intent intent) { + // A client is binding to the service with {@link android.content.Context#bindService bindService()}, + // after onUnbind() has already been called + } + @Override + public void {@link android.app.Service#onDestroy onDestroy}() { + // The service is no longer used and is being destroyed + } +} +</pre> + +<p class="note"><strong>Note:</strong> Unlike the activity lifecycle callback methods, you are +<em>not</em> required to call the superclass implementation of these callback methods.</p> + +<p>By implementing these methods, you can monitor two nested loops of the service's lifecycle: </p> + +<ul> +<li>The <strong>entire lifetime</strong> of a service happens between the time {@link +android.app.Service#onCreate onCreate()} is called and the time {@link +android.app.Service#onDestroy} returns. Like an activity, a service does its initial setup in +{@link android.app.Service#onCreate onCreate()} and releases all remaining resources in {@link +android.app.Service#onDestroy onDestroy()}. For example, a +music playback service could create the thread where the music will be played in {@link +android.app.Service#onCreate onCreate()}, then stop the thread in {@link +android.app.Service#onDestroy onDestroy()}. + +<p>The {@link android.app.Service#onCreate onCreate()} and {@link android.app.Service#onDestroy +onDestroy()} methods are called for all services, whether +they're created by {@link android.content.Context#startService startService()} or {@link +android.content.Context#bindService bindService()}.</p></li> + +<li>The <strong>active lifetime</strong> of a service begins with a call to either {@link +android.app.Service#onStartCommand onStartCommand()} or {@link android.app.Service#onBind onBind()}. +Each method is handed the {@link +android.content.Intent} that was passed to either {@link android.content.Context#startService +startService()} or {@link android.content.Context#bindService bindService()}, respectively. +<p>If the service is started, the active lifetime ends the same time that the entire lifetime +ends (the service is still active even after {@link android.app.Service#onStartCommand +onStartCommand()} returns). If the service is bound, the active lifetime ends when {@link +android.app.Service#onUnbind onUnbind()} returns.</p> +</li> +</ul> + +<p class="note"><strong>Note:</strong> Although a started service is stopped by a call to +either {@link android.app.Service#stopSelf stopSelf()} or {@link +android.content.Context#stopService stopService()}, there is not a respective callback for the +service (there's no {@code onStop()} callback). So, unless the service is bound to a client, +the system destroys it when the service is stopped—{@link +android.app.Service#onDestroy onDestroy()} is the only callback received.</p> + +<p>Figure 2 illustrates the typical callback methods for a service. Although the figure separates +services that are created by {@link android.content.Context#startService startService()} from those +created by {@link android.content.Context#bindService bindService()}, keep +in mind that any service, no matter how it's started, can potentially allow clients to bind to it. +So, a service that was initially started with {@link android.app.Service#onStartCommand +onStartCommand()} (by a client calling {@link android.content.Context#startService startService()}) +can still receive a call to {@link android.app.Service#onBind onBind()} (when a client calls +{@link android.content.Context#bindService bindService()}).</p> + +<p>For more information about creating a service that provides binding, see the <a +href="{@docRoot}guide/topics/fundamentals/bound-services.html">Bound Services</a> document, +which includes more information about the {@link android.app.Service#onRebind onRebind()} +callback method in the section about <a +href="{@docRoot}guide/topics/fundamentals/bound-services.html#Lifecycle">Managing the Lifecycle of +a Bound Service</a>.</p> + + + +<h2>Beginner's Path</h2> + +<p>To learn how to query data from the system or other applications (such as contacts or media +stored on the device), continue with the <b><a +href="{@docRoot}guide/topics/providers/content-providers.html">Content Providers</a></b> +document.</p> diff --git a/docs/html/guide/topics/fundamentals/tasks-and-back-stack.jd b/docs/html/guide/topics/fundamentals/tasks-and-back-stack.jd new file mode 100644 index 0000000..47dc547 --- /dev/null +++ b/docs/html/guide/topics/fundamentals/tasks-and-back-stack.jd @@ -0,0 +1,568 @@ +page.title=Tasks and Back Stack +parent.title=Application Fundamentals +parent.link=index.html +@jd:body + +<div id="qv-wrapper"> +<div id="qv"> +<h2>Quickview</h2> +<ul> + <li>All activities belong to a task</li> + <li>A task contains a collection of activities in the order in which the user interacts with +them</li> + <li>Tasks can move to the background and retain the state of each activity in order for the user +to perform other tasks without loosing their work</li> +</ul> + +<h2>In this document</h2> +<ol> +<li><a href="#ActivityState">Saving Activity State</a></li></li> +<li><a href="#ManagingTasks">Managing Tasks</a> + <ol> + <li><a href="#TaskLaunchModes">Defining launch modes</a></li> + <li><a href="#Affinities">Handling affinities</a></li> + <li><a href="#Clearing">Clearing the back stack</a></li> + <li><a href="#Starting">Starting a task</a></li> + </ol> +</li> +</ol> + +<h2>See also</h2> +<ol> + <li><a><a href="{@docRoot}videos/index.html#v=fL6gSd4ugSI">Application Lifecycle video</a></li> + <li><a +href="{@docRoot}guide/topics/manifest/activity-element.html">{@code <activity>} manifest +element</a></li> +</ol> +</div> +</div> + + +<p>An application usually contains multiple <a +href="{@docRoot}guide/topics/fundamentals/activities.html">activities</a>. Each activity +should be designed around a specific kind of action the user can perform and can start other +activities. For example, an email application might have one activity to show a list of new email. +When the user selects an email, a new activity opens to view that email.</p> + +<p>An activity can even start activities that exist in other applications on the device. For +example, if your application wants to send an email, you can define an intent to perform a "send" +action and include some data, such as an email address and a message. An activity from another +application that declares itself to handle this kind of intent then opens. In this case, the intent +is to send an email, so an email application's "compose" activity starts (if multiple activities +support the same intent, then the system lets the user select which one to use). When the email is +sent, your activity resumes and it seems as if the email activity was part of your application. Even +though the activities may be from different applications, Android maintains this seamless user +experience by keeping both activities in the same <em>task</em>.</p> + +<p>A task is a collection of activities that users interact with +when performing a certain job. The activities are arranged in a stack (the "back stack"), in the +order in which each activity is opened.</p> + +<!-- SAVE FOR WHEN THE FRAGMENT DOC IS ADDED +<div class="sidebox-wrapper"> +<div class="sidebox"> +<h3>Adding fragments to a task's back stack</h3> + +<p>Your activity can also include {@link android.app.Fragment}s to the back stack. For example, +suppose you have a two-pane layout using fragments, one of which is a list view (fragment A) and the +other being a layout to display an item from the list (fragment B). When the user selects an item +from the list, fragment B is replaced by a new fragment (fragment C). In this case, it might be +desireable for the user to navigate back to reveal fragment B, using the BACK key.</p> +<p>In order to add fragment B to the back stack so that this is possible, you must call {@link +android.app.FragmentTransaction#addToBackStack addToBackStack()} before you {@link +android.app.FragmentTransaction#commit()} the transaction that replaces fragment B with fragment +C.</p> +<p>For more information about using fragments and adding them to the back stack, see the {@link +android.app.Fragment} class documentation.</p> + +</div> +</div> +--> + +<p>The device Home screen is the starting place for most tasks. When the user touches an icon in the +application +launcher (or a shortcut on the Home screen), that application's task comes to the foreground. If no +task exists for the application (the application has not been used recently), then a new task +is created and the "main" activity for that application opens as the root activity in the stack.</p> + +<p>When the current activity starts another, the new activity is pushed on the top of the stack and +takes focus. The previous activity remains in the stack, but is stopped. When an activity +stops, the system retains the current state of its user interface. When the user presses the BACK +key, the current activity is popped from the top of the stack (the activity is destroyed) and the +previous activity resumes (the previous state of its UI is restored). Activities in the stack are +never rearranged, only pushed and popped from the stack—pushed onto the stack when started by +the current activity and popped off when the user leaves it using the BACK key. As such, the back +stack operates as a "last in, first out" object structure. Figure 1 visualizes +this behavior with a timeline showing the progress between activities along with the current back +stack at each point in time.</p> + +<img src="{@docRoot}images/fundamentals/diagram_backstack.png" alt="" /> +<p class="img-caption"><strong>Figure 1.</strong> A representation of how each new activity in a +task adds an item to the back stack. When the user presses the BACK key, the current activity is +destroyed and the previous activity resumes.</p> + + +<p>If the user continues to press BACK, then each activity in the stack is popped off to reveal the +previous one, until the user returns to the Home screen (or to whichever activity was running when +the task began). When all activities are removed from the stack, the task no longer exists.</p> + +<div class="figure" style="width:369px"> +<img src="{@docRoot}images/fundamentals/diagram_multitasking.png" alt="" /> <p +class="img-caption"><strong>Figure 2.</strong> Two tasks: Task A is in the background, waiting +to be resumed, while Task B receives user interaction in the foreground.</p> +</div> +<div class="figure" style="width:178px"> + <img src="{@docRoot}images/fundamentals/diagram_multiple_instances.png" alt="" /> <p +class="img-caption"><strong>Figure 3.</strong> A single activity is instantiated multiple times.</p> +</div> + +<p>A task is a cohesive unit that can move to the "background" when users begin a new task or go +to the Home screen, via the HOME key. While in the background, all the activities in the task are +stopped, but the back stack for the task remains intact—the task has simply lost focus while +another task takes place, as shown in figure 2. A task can then return to the "foreground" so users +can pick up where they left off. Suppose, for example, that the current task (Task A) has three +activities in its stack—two under the current activity. The user presses the HOME key, then +starts a new application from the application launcher. When the Home screen appears, Task A goes +into the background. When the new application starts, the system starts a task for that application +(Task B) with its own stack of activities. After interacting with +that application, the user returns Home again and selects the application that originally +started Task A. Now, Task A comes to the +foreground—all three activities in its stack are intact and the activity at the top of the +stack resumes. At +this point, the user can also switch back to Task B by going Home and selecting the application icon +that started that task (or by touching and holding the HOME key to reveal recent tasks and selecting +one). This is an example of multitasking on Android.</p> + +<p class="note"><strong>Note:</strong> Multiple tasks can be held in the background at once. +However, if the user is running many background tasks at the same time, the system might begin +destroying background activities in order to recover memory, causing the activity states to be lost. +See the following section about <a href="#ActivityState">Activity state</a>.</p> + +<p>Because the activities in the back stack are never rearranged, if your application allows +users to start a particular activity from more than one activity, a new instance of +that activity is created and popped onto the stack (rather than bringing any previous instance of +the activity to the top). As such, one activity in your application might be instantiated multiple +times (even from different tasks), as shown in figure 3. As such, if the user navigates backward +using the BACK key, each instance of the activity is revealed in the order they were opened (each +with their own UI state). However, you can modify this behavior if you do not want an activity to be +instantiated more than once. How to do so is discussed in the later section about <a +href="#ManagingTasks">Managing Tasks</a>.</p> + + +<p>To summarize the default behavior for activities and tasks:</p> + +<ul> + <li>When Activity A starts Activity B, Activity A is stopped, but the system retains its state +(such as scroll position and text entered into forms). +If the user presses the BACK key while in Activity B, Activity A resumes with its state +restored.</li> + <li>When the user leaves a task by pressing the HOME key, the current activity is stopped and +its task goes into the background. The system retains the state of every activity in the task. If +the user later resumes the task by selecting the launcher icon that began the task, the task comes +to the foreground and resumes the activity at the top of the stack.</li> + <li>If the user presses the BACK key, the current activity is popped from the stack and +destroyed. The previous activity in the stack is resumed. When an activity is destroyed, the system +<em>does not</em> retain the activity's state.</li> + <li>Activities can be instantiated multiple times, even from other tasks.</li> +</ul> + + +<h2 id="ActivityState">Saving Activity State</h2> + +<p>As discussed above, the system's default behavior preserves the state of an activity when it is +stopped. This way, when users navigate back to a previous activity, its user interface appears +the way they left it. However, you can—and <strong>should</strong>—proactively retain +the state of your activities using callback methods, in case the activity is destroyed and must +be recreated.</p> + +<p>When the system stops one of your activities (such as when a new activity starts or the task +moves to the background), the system might destroy that activity completely if it needs to recover +system memory. When this happens, information about the activity state is lost. If this happens, the +system still +knows that the activity has a place in the back stack, but when the activity is brought to the +top of the stack the system must recreate it (rather than resume it). In order to +avoid loosing the user's work, you should proactively retain it by implementing the {@link +android.app.Activity#onSaveInstanceState onSaveInstanceState()} callback +methods in your activity.</p> + +<p>For more information about how to save your activity state, see the <a +href="{@docRoot}guide/topics/fundamentals/activities.html#SavingActivityState">Activities</a> +document.</p> + + + +<h2 id="ManagingTasks">Managing Tasks</h2> + +<p>The way Android manages tasks and the back stack, as described above—by placing all +activities started in succession in the same task and in a "last in, first out" stack—works +great for most applications and you shouldn't have to worry about how your activities are associated +with tasks or how they exist in the back stack. However, you might decide that you want to interrupt +the normal behavior. Perhaps you want an activity in your application to begin a new task when it is +started (instead of being placed within the current task); or, when you start an activity, you want +to bring forward an existing instance of it (instead of creating a new +instance on top of the back stack); or, you want your back stack to be cleared of all +activitiesstart an activity except for the root activity when the user leaves the task.</p> + +<p>You can do these things and more, with attributes in the +<a href="{@docRoot}guide/topics/manifest/activity-element.html">{@code +<activity>}</a> manifest element and with flags in the intent that you pass to {@link +android.app.Activity#startActivity startActivity()}.</p> + +<p>In this regard, the the principal <a +href="{@docRoot}guide/topics/manifest/activity-element.html">{@code <activity>}</a> +attributes you can use are:</p> + +<ul class="nolist"> + <li><a href="{@docRoot}guide/topics/manifest/activity-element.html#aff">{@code +taskAffinity}</a></li> + <li><a href="{@docRoot}guide/topics/manifest/activity-element.html#lmode">{@code +launchMode}</a></li> + <li><a href="{@docRoot}guide/topics/manifest/activity-element.html#reparent">{@code +allowTaskReparenting}</a></li> + <li><a href="{@docRoot}guide/topics/manifest/activity-element.html#clear">{@code +clearTaskOnLaunch}</a></li> + <li><a href="{@docRoot}guide/topics/manifest/activity-element.html#always">{@code +alwaysRetainTaskState}</a></li> + <li><a href="{@docRoot}guide/topics/manifest/activity-element.html#finish">{@code +finishOnTaskLaunch}</a></li> +</ul> + +<p>And the principal intent flags you can use are:</p> + +<ul class="nolist"> + <li>{@link android.content.Intent#FLAG_ACTIVITY_NEW_TASK}</li> + <li>{@link android.content.Intent#FLAG_ACTIVITY_CLEAR_TOP}</li> + <li>{@link android.content.Intent#FLAG_ACTIVITY_SINGLE_TOP}</li> +</ul> + +<p>In the following sections, you'll see how you can use these manifest attributes and intent +flags to define how activities are associated with tasks and how the behave in the back stack.</p> + + +<p class="caution"><strong>Caution:</strong> Most applications should not interrupt the default +behavior for activities and tasks. If you determine that it's necessary for your activity to modify +the default behaviors, use caution and be sure to test the usability of the activity during +launch and when navigating back to it from other activities and tasks with the BACK key. Be sure +to test for navigation behaviors that might conflict with the user's expected behavior.</p> + + +<h3 id="TaskLaunchModes">Defining launch modes</h3> + +<p>Launch modes allow you to define how a new instance of an activity is associated with the +current task. You can define different launch modes in two ways:</p> +<ul class="nolist"> + <li><a href="#ManifestForTasks">Using the manifest file</a> + <p>When you declare an activity in your manifest file, you can specify how the activity +should associate with tasks when it starts.</li> + <li><a href="#IntentFlagsForTasks">Using Intent flags</a> + <p>When you call {@link android.app.Activity#startActivity startActivity()}, +you can include a flag in the {@link android.content.Intent} that declares how (or +whether) the new activity should associate with the current task.</p></li> +</ul> + +<p>As such, if Activity A starts Activity B, Activity B can define in its manifest how it +should associate with the current task (if at all) and Activity A can also request how Activity +B should associate with current task. If both activities define how Activity B +should associate with a task, then Activity A's request (as defined in the intent) is honored +over Activity B's request (as defined in its manifest).</p> + +<p class="note"><strong>Note:</strong> Some the launch modes available in the manifest +are not available as flags for an intent and, likewise, some launch modes available as flags +for an intent cannot be defined in the manifest.</p> + + +<h4 id="ManifestForTasks">Using the manifest file</h4> + +<p>When declaring an activity in your manifest file, you can specify how the activity should +associate with a task using the <a +href="{@docRoot}guide/topics/manifest/activity-element.html">{@code <activity>}</a> +element's <a href="{@docRoot}guide/topics/manifest/activity-element.html#lmode">{@code +launchMode}</a> attribute.</p> + +<p>The <a href="{@docRoot}guide/topics/manifest/activity-element.html#lmode">{@code +launchMode}</a> attribute specifies an instruction on how the activity should be launched into a +task. There are four different launch modes you can assign to the +<code><a href="{@docRoot}guide/topics/manifest/activity-element.html#lmode">launchMode</a></code> +attribute:</p> + +<dl> +<dt>{@code "standard"} (the default mode)</dt> + <dd>Default. The system creates a new instance of the activity in the task from +which it was started and routes the intent to it. The activity can be instantiated multiple times, +each instance can belong to different tasks, and one task can have multiple instances.</dd> +<dt>{@code "singleTop"}</dt> + <dd>If an instance of the activity already exists at the top of the current task, the system +routes the intent to that instance through a call to its {@link +android.app.Activity#onNewIntent onNewIntent()} method, rather than creating a new instance of the +activity. The activity can be instantiated multiple times, each instance can +belong to different tasks, and one task can have multiple instances (but only if the the +activity at the top of the back stack is <em>not</em> an existing instance of the activity). + <p>For example, suppose a task's back stack consists of root activity A with activities B, C, +and D on top (the stack is A-B-C-D; D is on top). An intent arrives for an activity of type D. +If D has the default {@code "standard"} launch mode, a new instance of the class is launched and the +stack becomes A-B-C-D-D. However, if D's launch mode is {@code "singleTop"}, the existing instance +of D is deliverd the intent through {@link +android.app.Activity#onNewIntent onNewIntent()}, because it's at the top of the stack—the +stack remains A-B-C-D. However, if an intent arrives for an activity of type B, then a new +instance of B is added to the stack, even if its launch mode is {@code "singleTop"}.</p> + <p class="note"><strong>Note:</strong> When a new instance of an activity is created, +the user can press the BACK key to return to the previous activity. But when an existing instance of +an activity handles a new intent, the user cannot press the BACK key to return to the state of +the activity before the new intent arrived in {@link android.app.Activity#onNewIntent +onNewIntent()}.</p> +</dd> + +<dt>{@code "singleTask"}</dt> + <dd>The system creates a new task and instantiates the activity at the root of the new task. +However, if an instance of the activity already exists in a separate task, the system routes the +intent to the existing instance through a call to its {@link +android.app.Activity#onNewIntent onNewIntent()} method, rather than creating a new instance. Only +one instance of the activity can exist at a time. + <p class="note"><strong>Note:</strong> Although the activity starts in a new task, the +BACK key still returns the user to the previous activity.</p></dd> +<dt>{@code "singleInstance"}.</dt> + <dd>Same as {@code "singleTask"}, except that the system doesn't launch any other activities into +the task holding the instance. The activity is always the single and only member of its task; +any activities started by this one open in a separate task.</dd> +</dl> + + +<p>As another example, the Android Browser application declares that the web browser activity should +always open in its own task—by specifying the {@code singleTask} launch mode in the <a +href="{@docRoot}guide/topics/manifest/activity-element.html">{@code <activity>}</a> element. +This means that if your application issues an +intent to open the Android Browser, its activity is <em>not</em> placed in the same +task as your application. Instead, either a new task starts for the Browser or, if the Browser +already has a task running in the background, that task is brought forward to handle the new +intent.</p> + +<p>Regardless of whether an activity starts in a new task or in the same task as the activity that +started it, the BACK key always takes the user to the previous activity. However, if you +start an activity from your task (Task A) that specifies the {@code singleTask} launch mode, then +that activity might have an instance in the background that belongs to a task with its own back +stack (Task B). In this +case, when Task B is brought forward to handle a new intent, the BACK key first navigates +backward through the activities in Task B before returning to +the top-most activity in Task A. Figure 4 visualizes this type of scenario.</p> + +<img src="{@docRoot}images/fundamentals/diagram_backstack_singletask_multiactivity.png" alt="" /> +<p class="img-caption"><strong>Figure 4.</strong> A representation of how an activity with +launch mode "singleTask" is added to the back stack. If the activity is already a part of a +background task with its own back stack (Task B), then the entire back stack also comes +forward, on top of the current task (Task A).</p> + +<p>For more information about using launch modes in the manifest file, see the +<code><a href="{@docRoot}guide/topics/manifest/activity-element.html"><activity></a></code> +element documentation, where the {@code launchMode} attribute and the accepted values are +discussed more.</p> + +<p class="note"><strong>Note:</strong> The behaviors that you specify for your activity with the <a +href="{@docRoot}guide/topics/manifest/activity-element.html#lmode">{@code launchMode}</a> attribute +can be overriden by flags included with the intent that start your activity, as discussed in the +next section.</p> + + + +<h4 id="#IntentFlagsForTasks">Using Intent flags</h4> + +<p>When starting an activity, you can modify the default association of an activity to its task +by including flags in the intent that you deliver to {@link +android.app.Activity#startActivity startActivity()}. The flags you can use to modify the +default behavior are:</p> + +<p> + <dt>{@link android.content.Intent#FLAG_ACTIVITY_NEW_TASK}</dt> + <dd>Start the activity in a new task. If a task is already running for the activity you are now +starting, that task is brought to the foreground with its last state restored and the activity +receives the new intent in {@link android.app.Activity#onNewIntent onNewIntent()}. + <p>This produces the same behavior as the {@code "singleTask"} <a +href="{@docRoot}guide/topics/manifest/activity-element.html#lmode">{@code launchMode}</a> value, +discussed in the previous section.</p></dd> + <dt>{@link android.content.Intent#FLAG_ACTIVITY_SINGLE_TOP}</dt> + <dd>If the activity being started is the current activity (at the top of the back stack), then +the existing instance receives a call to {@link android.app.Activity#onNewIntent onNewIntent()}, +instead of creating a new instance of the activity. + <p>This produces the same behavior as the {@code "singleTop"} <a +href="{@docRoot}guide/topics/manifest/activity-element.html#lmode">{@code launchMode}</a> value, +discussed in the previous section.</p></dd> + <dt>{@link android.content.Intent#FLAG_ACTIVITY_CLEAR_TOP}</dt> + <dd>If the activity being started is already running in the current task, then instead +of launching a new instance of that activity, all of the other activities on top of it are +destroyed and this intent is delivered to the resumed instance of the activity (now on top), +through {@link android.app.Activity#onNewIntent onNewIntent()}). + <p>There is no value for the <a +href="{@docRoot}guide/topics/manifest/activity-element.html#lmode">{@code launchMode}</a> +attribute that produces this behavior.</p> + <p>{@code FLAG_ACTIVITY_CLEAR_TOP} is most often used in conjunction with {@code +FLAG_ACTIVITY_NEW_TASK}. When used together, these flags are a way of locating an existing activity +in another task and putting it in a position where it can respond to the intent. </p> + <p class="note"><strong>Note:</strong> If the launch mode of the designated activity is {@code +"standard"}, it too is removed from the stack and a new instance is launched in its place to handle +the incoming intent. That's because a new instance is always created for a new intent when the +launch mode is {@code "standard"}. </p> +</dd> +</dl> + + + + + +<h3 id="Affinities">Handling affinities</h3> + +<p>The <em>affinity</em> indicates which task an activity prefers to belong to. By default, all the +activities from the same application have an affinity for each other. So, by default, all +activities in the same application prefer to be in the same task. However, you can modify +the default affinity for an activity. Activities defined in +different applications can share an affinity, or activities defined in the same application can be +assigned different task affinities.</p> + +<p>You can modify the affinity for any given activity with the <a +href="{@docRoot}guide/topics/manifest/activity-element.html#aff">{@code taskAffinity}</a> attribute +of the <a href="{@docRoot}guide/topics/manifest/activity-element.html">{@code <activity>}</a> +element.</p> + +<p>The <a +href="{@docRoot}guide/topics/manifest/activity-element.html#aff">{@code taskAffinity}</a> +attribute takes a string value, which must be unique from the default package name +declared in the <a href="{@docRoot}guide/topics/manifest/manifest-element.html">{@code +<manifest>}</a> element, because the system uses that name to identify the default task +affinity for the application.</p> + +<p>The affinity comes into play in two circumstances:</p> +<ul> + <li>When the intent that launches an activity contains the {@link +android.content.Intent#FLAG_ACTIVITY_NEW_TASK} flag. + +<p>A new activity is, by default, launched into the task of the activity +that called {@link android.app.Activity#startActivity startActivity()}. It's pushed onto the same +back stack as the caller. However, if the intent passed to {@link +android.app.Activity#startActivity startActivity()} contains the {@link +android.content.Intent#FLAG_ACTIVITY_NEW_TASK} +flag, the system looks for a different task to house the new activity. Often, it's a new task. +However, it doesn't have to be. If there's already an existing task with the same affinity as the +new activity, the activity is launched into that task. If not, it begins a new task.</p> + +<p>If this flag causes an activity to begin a new task and the user presses the HOME key to leave +it, there must be some way for the user to navigate back to the task. Some entities (such as the +notification manager) always start activities in an external task, never as part of their own, so +they always put {@code FLAG_ACTIVITY_NEW_TASK} in the intents they pass to {@link +android.app.Activity#startActivity startActivity()}. If you have an activity that can be invoked by +an external entity that might use this flag, take care that the user has a independent way to get +back to the task that's started, such as with a launcher icon (the root activity of the task +has a {@link android.content.Intent#CATEGORY_LAUNCHER} intent filter; see the <a +href="#Starting">Starting a task</a> section below).</p> +</li> + + <li>When an activity has its <a +href="{@docRoot}guide/topics/manifest/activity-element.html#reparent">{@code +allowTaskReparenting}</a> attribute set to {@code "true"}. + <p>In this case, the activity can move from the task it starts to the task it has an affinity +for, when that task comes to the foreground.</p> + <p>For example, suppose that an activity that reports weather conditions in selected cities is +defined as part of a travel application. It has the same affinity as other activities in the same +application (the default application affinity) and it allows re-parenting with this attribute. +When one of your activities starts the weather reporter activity, it initially belongs to the same +task as your activity. However, when the travel application's task comes to the foreground, the +weather reporter activity is reassigned to that task and displayed within it.</p> +</li> +</ul> + +<p class="note"><strong>Tip:</strong> If an {@code .apk} file contains more than one "application" +from the user's point of view, you probably want to use the <a +href="{@docRoot}guide/topics/manifest/activity-element.html#aff">{@code taskAffinity}</a> +attribute to assign different affinities to the activities associated with each "application".</p> + + + +<h3 id="Clearing">Clearing the back stack</h3> + +<p>If the user leaves a task for a long time, the system clears the task of all activities except +the root activity. When the user returns to the task again, only the root activity is restored. +The system behaves this way, because, after an extended amount of time, users likely have abandoned +what they were doing before and are returning to the task to begin something new. </p> + +<p>There are some activity attributes that you can use to modify this behavior: </p> + +<dl> +<dt><code><a +href="{@docRoot}guide/topics/manifest/activity-element.html#always">alwaysRetainTaskState</a></code> +</dt> +<dd>If this attribute is set to {@code "true"} in the root activity of a task, +the default behavior just described does not happen. +The task retains all activities in its stack even after a long period.</dd> + +<dt><code><a +href="{@docRoot}guide/topics/manifest/activity-element.html#clear">clearTaskOnLaunch</a></code></dt> +<dd>If this attribute is set to {@code "true"} in the root activity of a task, +the stack is cleared down to the root activity whenever the user leaves the task +and returns to it. In other words, it's the opposite of <a +href="{@docRoot}guide/topics/manifest/activity-element.html#always">{@code +alwaysRetainTaskState}</a>. The user always returns to the task in its +initial state, even after a leaving the task for only a moment.</dd> + +<dt><code><a +href="{@docRoot}guide/topics/manifest/activity-element.html#finish">finishOnTaskLaunch</a></code> +</dt> +<dd>This attribute is like <a +href="{@docRoot}guide/topics/manifest/activity-element.html#clear">{@code clearTaskOnLaunch}</a>, +but it operates on a +single activity, not an entire task. It can also cause any activity to go +away, including the root activity. When it's set to {@code "true"}, the +activity remains part of the task only for the current session. If the user +leaves and then returns to the task, it is no longer present.</dd> +</dl> + + + + +<h3 id="Starting">Starting a task</h3> + +<p>You can set up an activity as the entry point for a task by giving it an intent filter with +{@code "android.intent.action.MAIN"} as the specified action and {@code +"android.intent.category.LAUNCHER"} as the specified category. For example:</p> + +<pre> +<activity ... > + <intent-filter ... > + <action android:name="android.intent.action.MAIN" /> + <category android:name="android.intent.category.LAUNCHER" /> + </intent-filter> + ... +</activity> +</pre> + +<p>An intent filter of this kind causes an icon and label for the +activity to be displayed in the application launcher, giving users a way to launch the activity and +to return to the task that it creates any time after it has been launched. +</p> + +<p>This second ability is important: Users must be able to leave a task and then come back to it +later using this activity launcher. For this reason, the two <a href="#LaunchModes">launch +modes</a> that mark activities as always initiating a task, {@code "singleTask"} and "{@code +"singleInstance"}, should be used only when the activity has an {@link +android.content.Intent#ACTION_MAIN} +and a {@link android.content.Intent#CATEGORY_LAUNCHER} +filter. Imagine, for example, what could happen if the filter is missing: An intent launches a +{@code "singleTask"} activity, initiating a new task, and the user spends some time working in +that task. The user then presses the HOME key. The task is now sent to the background and not +visible. Because it is not represented in the application launcher, the user has no way to return to +the task. +</p> + +<p>For those cases where you don't want the user to be able to return to an activity, set the + <code><a +href="{@docRoot}guide/topics/manifest/activity-element.html"><activity></a></code> element's +<a href="{@docRoot}guide/topics/manifest/activity-element.html#finish">{@code +finishOnTaskLaunch}</a> to {@code "true"} (see <a +href="#Clearing">Clearing the stack</a>).</p> + + + + +<h2>Beginner's Path</h2> + +<p>For more information about how to use intents to +activate other application components and publish the intents to which your components +respond, continue with the <b><a +href="{@docRoot}guide/topics/intents/intents-filters.html">Intents and Intent +Filters</a></b> document.</p> diff --git a/docs/html/guide/topics/graphics/2d-graphics.jd b/docs/html/guide/topics/graphics/2d-graphics.jd index 13a86dd..6594568 100644 --- a/docs/html/guide/topics/graphics/2d-graphics.jd +++ b/docs/html/guide/topics/graphics/2d-graphics.jd @@ -17,8 +17,6 @@ parent.link=index.html <li><a href="#shape-drawable">Shape Drawable</a></li> <!-- <li><a href="#state-list">StateListDrawable</a></li> --> <li><a href="#nine-patch">Nine-patch</a></li> - <li><a href="#tween-animation">Tween Animation</a></li> - <li><a href="#frame-animation">Frame Animation</a></li> </ol> </div> </div> @@ -61,7 +59,7 @@ extension (E.g., <code>my_image.png</code> is referenced as <var>my_image</var>) <p class="note"><strong>Note:</strong> Image resources placed in <code>res/drawable/</code> may be automatically optimized with lossless image compression by the -<a href="{@docRoot}guide/developing/tools/aapt.html">aapt</a> tool. For example, a true-color PNG that does +<code>aapt</code> tool during the build process. For example, a true-color PNG that does not require more than 256 colors may be converted to an 8-bit PNG with a color palette. This will result in an image of equal quality but which requires less memory. So be aware that the image binaries placed in this directory can change during the build. If you plan on reading @@ -262,9 +260,9 @@ and saved into the <code>res/drawable/</code> directory of your project. <p> The border is used to define the stretchable and static areas of the image. You indicate a stretchable section by drawing one (or more) 1-pixel-wide - black line(s) in the left and top part of the border. (You can have as - many stretchable sections as you want.) The relative size of the stretchable - sections stays the same, so the largest sections always remain the largest. + black line(s) in the left and top part of the border (the other border pixels should + be fully transparent or white). You can have as many stretchable sections as you want: + their relative size stays the same, so the largest sections always remain the largest. </p> <p> You can also define an optional drawable section of the image (effectively, @@ -328,172 +326,4 @@ Notice how the width and height of the button varies with the text, and the back stretches to accommodate it. </p> -<img src="{@docRoot}images/ninepatch_examples.png" alt=""/> - - -<h2 id="tween-animation">Tween Animation</h2> - -<p>A tween animation can perform a series of simple transformations (position, size, rotation, and transparency) on -the contents of a View object. So, if you have a TextView object, you can move, rotate, grow, or shrink the text. -If it has a background image, the background image will be transformed along with the text. -The {@link android.view.animation animation package} provides all the classes used in a tween animation.</p> - -<p>A sequence of animation instructions defines the tween animation, defined by either XML or Android code. -Like defining a layout, an XML file is recommended because it's more readable, reusable, and swappable -than hard-coding the animation. In the example below, we use XML. (To learn more about defining an animation -in your application code, instead of XML, refer to the -{@link android.view.animation.AnimationSet} class and other {@link android.view.animation.Animation} subclasses.)</p> - -<p>The animation instructions define the transformations that you want to occur, when they will occur, -and how long they should take to apply. Transformations can be sequential or simultaneous — -for example, you can have the contents of a TextView move from left to right, and then -rotate 180 degrees, or you can have the text move and rotate simultaneously. Each transformation -takes a set of parameters specific for that transformation (starting size and ending size -for size change, starting angle and ending angle for rotation, and so on), and -also a set of common parameters (for instance, start time and duration). To make -several transformations happen simultaneously, give them the same start time; -to make them sequential, calculate the start time plus the duration of the preceding transformation. -</p> - -<p>The animation XML file belongs in the <code>res/anim/</code> directory of your Android project. -The file must have a single root element: this will be either a single <code><alpha></code>, -<code><scale></code>, <code><translate></code>, <code><rotate></code>, interpolator element, -or <code><set></code> element that holds groups of these elements (which may include another -<code><set></code>). By default, all animation instructions are applied simultaneously. -To make them occur sequentially, you must specify the <code>startOffset</code> attribute, as shown in the example below. -</p> - -<p>The following XML from one of the ApiDemos is used to stretch, -then simultaneously spin and rotate a View object. -</p> -<pre> -<set android:shareInterpolator="false"> - <scale - android:interpolator="@android:anim/accelerate_decelerate_interpolator" - android:fromXScale="1.0" - android:toXScale="1.4" - android:fromYScale="1.0" - android:toYScale="0.6" - android:pivotX="50%" - android:pivotY="50%" - android:fillAfter="false" - android:duration="700" /> - <set android:interpolator="@android:anim/decelerate_interpolator"> - <scale - android:fromXScale="1.4" - android:toXScale="0.0" - android:fromYScale="0.6" - android:toYScale="0.0" - android:pivotX="50%" - android:pivotY="50%" - android:startOffset="700" - android:duration="400" - android:fillBefore="false" /> - <rotate - android:fromDegrees="0" - android:toDegrees="-45" - android:toYScale="0.0" - android:pivotX="50%" - android:pivotY="50%" - android:startOffset="700" - android:duration="400" /> - </set> -</set> -</pre> -<p>Screen coordinates (not used in this example) are (0,0) at the upper left hand corner, -and increase as you go down and to the right.</p> - -<p>Some values, such as pivotX, can be specified relative to the object itself or relative to the parent. -Be sure to use the proper format for what you want ("50" for 50% relative to the parent, or "50%" for 50% -relative to itself).</p> - -<p>You can determine how a transformation is applied over time by assigning an -{@link android.view.animation.Interpolator}. Android includes -several Interpolator subclasses that specify various speed curves: for instance, -{@link android.view.animation.AccelerateInterpolator} tells -a transformation to start slow and speed up. Each one has an attribute value that can be applied in the XML.</p> - -<p>With this XML saved as <code>hyperspace_jump.xml</code> in the <code>res/anim/</code> directory of the -project, the following Java code will reference it and apply it to an {@link android.widget.ImageView} object -from the layout. -</p> -<pre> -ImageView spaceshipImage = (ImageView) findViewById(R.id.spaceshipImage); -Animation hyperspaceJumpAnimation = AnimationUtils.loadAnimation(this, R.anim.hyperspace_jump); -spaceshipImage.startAnimation(hyperspaceJumpAnimation); -</pre> - -<p>As an alternative to <code>startAnimation()</code>, you can define a starting time for the animation with -<code>{@link android.view.animation.Animation#setStartTime(long) Animation.setStartTime()}</code>, -then assign the animation to the View with -<code>{@link android.view.View#setAnimation(android.view.animation.Animation) View.setAnimation()}</code>. -</p> - -<p>For more information on the XML syntax, available tags and attributes, see <a -href="{@docRoot}guide/topics/resources/animation-resource.html">Animation Resources</a>.</p> - -<p class="note"><strong>Note:</strong> Regardless of how your animation may move or resize, the bounds of the -View that holds your animation will not automatically adjust to accommodate it. Even so, the animation will still -be drawn beyond the bounds of its View and will not be clipped. However, clipping <em>will occur</em> -if the animation exceeds the bounds of the parent View.</p> - - -<h2 id="frame-animation">Frame Animation</h2> - -<p>This is a traditional animation in the sense that it is created with a sequence of different -images, played in order, like a roll of film. The {@link android.graphics.drawable.AnimationDrawable} -class is the basis for frame animations.</p> - -<p>While you can define the frames of an animation in your code, using the -{@link android.graphics.drawable.AnimationDrawable} class API, it's more simply accomplished with a single XML -file that lists the frames that compose the animation. Like the tween animation above, the XML file for this kind -of animation belongs in the <code>res/drawable/</code> directory of your Android project. In this case, -the instructions are the order and duration for each frame of the animation.</p> - -<p>The XML file consists of an <code><animation-list></code> element as the root node and a series -of child <code><item></code> nodes that each define a frame: a drawable resource for the frame and the frame duration. -Here's an example XML file for a frame-by-frame animation:</p> -<pre> -<animation-list xmlns:android="http://schemas.android.com/apk/res/android" - android:oneshot="true"> - <item android:drawable="@drawable/rocket_thrust1" android:duration="200" /> - <item android:drawable="@drawable/rocket_thrust2" android:duration="200" /> - <item android:drawable="@drawable/rocket_thrust3" android:duration="200" /> -</animation-list> -</pre> - -<p>This animation runs for just three frames. By setting the <code>android:oneshot</code> attribute of the -list to <var>true</var>, it will cycle just once then stop and hold on the last frame. If it is set <var>false</var> then -the animation will loop. With this XML saved as <code>rocket_thrust.xml</code> in the <code>res/drawable/</code> directory -of the project, it can be added as the background image to a View and then called to play. Here's an example Activity, -in which the animation is added to an {@link android.widget.ImageView} and then animated when the screen is touched:</p> -<pre> -AnimationDrawable rocketAnimation; - -public void onCreate(Bundle savedInstanceState) { - super.onCreate(savedInstanceState); - setContentView(R.layout.main); - - ImageView rocketImage = (ImageView) findViewById(R.id.rocket_image); - rocketImage.setBackgroundResource(R.drawable.rocket_thrust); - rocketAnimation = (AnimationDrawable) rocketImage.getBackground(); -} - -public boolean onTouchEvent(MotionEvent event) { - if (event.getAction() == MotionEvent.ACTION_DOWN) { - rocketAnimation.start(); - return true; - } - return super.onTouchEvent(event); -} -</pre> -<p>It's important to note that the <code>start()</code> method called on the AnimationDrawable cannot be -called during the <code>onCreate()</code> method of your Activity, because the AnimationDrawable is not yet fully attached -to the window. If you want to play the animation immediately, without -requiring interaction, then you might want to call it from the -<code>{@link android.app.Activity#onWindowFocusChanged(boolean) onWindowFocusChanged()}</code> method in -your Activity, which will get called when Android brings your window into focus.</p> - -<p>For more information on the XML syntax, available tags and attributes, see <a -href="{@docRoot}guide/topics/resources/animation-resource.html">Animation Resources</a>.</p> - +<img src="{@docRoot}images/ninepatch_examples.png" alt=""/>
\ No newline at end of file diff --git a/docs/html/guide/topics/graphics/animation.jd b/docs/html/guide/topics/graphics/animation.jd new file mode 100644 index 0000000..83a4e1d --- /dev/null +++ b/docs/html/guide/topics/graphics/animation.jd @@ -0,0 +1,828 @@ +page.title=Animation +@jd:body + <div id="qv-wrapper"> + <div id="qv"> + <h2>In this document</h2> + + <ol> + <li> + <a href="#property-animation">Property Animation</a> + + <ol> + <li><a href="#value-animator">Animating with ValueAnimator</a></li> + + <li><a href="#object-animator">Animating with ObjectAnimator</a></li> + + <li><a href="#type-evaluator">Using a TypeEvaluator</a></li> + + <li><a href="#interpolators">Using interpolators</a></li> + + <li><a href="#keyframes">Specifying keyframes</a></li> + + <li><a href="#choreography">Choreographing multiple animations with AnimatorSet</a></li> + + <li><a href="#declaring-xml">Declaring animations in XML</a></li> + </ol> + </li> + + <li> + <a href="#view-animation">View Animation</a> + + <ol> + <li><a href="#tween-animation">Tween animation</a></li> + + <li><a href="#frame-animation">Frame animation</a></li> + </ol> + </li> + </ol> + + <h2>Key classes</h2> + + <ol> + <li><code><a href= + "/reference/android/animation/ValueAnimator.html">ValueAnimator</a></code></li> + + <li><code><a href= + "/reference/android/animation/ObjectAnimator.html">ObjectAnimator</a></code></li> + + <li><code><a href= + "/reference/android/animation/TypeEvaluator.html">TypeEvaluator</a></code></li> + </ol> + + <h2>Related samples</h2> + + <ol> + <li><a href="{@docRoot}resources/samples/ApiDemos/src/com/example/android/apis/animation/index.html">API Demos</a></li> + </ol> + + </div> + </div> + + <p>The Android system provides a flexible animation system that allows you to animate + almost anything, either programmatically or declaratively with XML. There are two + animation systems that you can choose from: <a href="#property-animation">property + animation</a> and <a href="#view-animation">view animation</a>. You can use whichever + system that matches your needs, but use only one system for each object that you + are animating.</p> + + <h2 id="property-animation">Property Animation</h2> + + <p>Introduced in Android 3.0, the property animation system allows you to animate + object properties of any type. <code>int</code>, <code>float</code>, + and hexadecimal color values are supported by default. You can animate any other type by telling the + system how to calculate the values for that given type.</p> + + <p>The property animation system allows you to define many aspects of an animation, + such as:</p> + + <ul> + <li>Duration</li> + + <li>Repeat amount and behavior</li> + + <li>Type of time interpolation</li> + + <li>Animator sets to play animations together, sequentially, or after specified + delays</li> + + <li>Frame refresh delay</li> + + </ul> + + <p>Most of the property animation system's features can be found in + {@link android.animation android.animation}. Because the + <a href="#view-animation">view animation</a> system already + defines many interpolators in {@link android.view.animation android.view.animation}, + you will use those to define your animation's interpolation in the property animation + system as well. + </p> + + <p>The following items are the main components of the property animation system:</p> + + <dl> + <dt><strong>Animators</strong></dt> + + <dd> + The {@link android.animation.Animator} class provides the basic structure for + creating animations. You normally do not use this class directly as it only provides + minimal functionality that must be extended to fully support animating values. + The following subclasses extend {@link android.animation.Animator}, which you might find more useful: + + <ul> + <li>{@link android.animation.ValueAnimator} is the main timing engine for + property animation and computes the values for the property to be animated. + {@link android.animation.ValueAnimator} only computes the animation values and is + not aware of the specific object and property that is being animated or what the + values might be used for. You must listen for updates to values calculated by the + {@link android.animation.ValueAnimator} and process the data with your own logic. + See the section about <a href="#value-animator">Animating with ValueAnimator</a> + for more information.</li> + + <li>{@link android.animation.ObjectAnimator} is a subclass of {@link + android.animation.ValueAnimator} and allows you to set a target object and object + property to animate. This class is aware of the object and property to be + animated, and updates the property accordingly when it computes a new value for + the animation. See the section about <a href="#object-animator"> + Animating with ObjectAnimator</a> for more information.</li> + + <li>{@link android.animation.AnimatorSet} provides a mechanism to group + animations together so that they are rendered in relation to one another. You can + set animations to play together, sequentially, or after a specified delay. + See the section about <a href="#choreography"> + Choreographing multiple animations with Animator Sets</a> for more information.</li> + </ul> + </dd> + + <dt><strong>Evaluators</strong></dt> + + <dd> + <p>If you are animating an object property that is <em>not</em> an <code>int</code>, + <code>float</code>, or color, implement the {@link android.animation.TypeEvaluator} + interface to specify how to compute the object property's animated values. You give + a {@link android.animation.TypeEvaluator} the timing data that is provided by an + {@link android.animation.Animator} class, the animation's start and end value, and + provide logic that computes the animated values of the property based on this data.</p> + + <p>You can also specify a custom {@link android.animation.TypeEvaluator} for + <code>int</code>, <code>float</code>, and color values as well, if you want to + process those types differently than the default behavior.</p> + + <p>See <a href="#type-evaluator">Using a TypeEvaluator</a> for more information on + how to write a custom evaluator.</p> + </dd> + + <dt><strong>Interpolators</strong></dt> + + <dd> + <p>A time interpolator defines how specific values in an animation are calculated + as a function of time. For example, you can specify animations to happen linearly + across the whole animation, meaning the animation moves evenly the entire time, or + you can specify animations to use non-linear time, for example, using acceleration + or deceleration at the beginning or end of the animation.</p> + + <p>The Android system provides a set of common interpolators in + {@link android.view.animation android.view.animation}. If none of these suits your needs, you + can implement the {@link android.animation.TimeInterpolator} interface and create + your own. See <a href="#interpolators">Using interpolators</a> for more information on + how to write a custom interpolator.</p> + </dd> + </dl> + + + <p>The <code>com.example.android.apis.animation</code> package in the <a href= + "{@docRoot}resources/samples/ApiDemos/src/com/example/android/apis/animation/index.html"> + API Demos</a> sample project also provides a good overview and many examples on how to + use the property animation system.</p> + + + <h3>How the property animation system calculates animated values</h3> + + <p>When you call {@link android.animation.ValueAnimator#start start()} to begin an animation, + the {@link android.animation.ValueAnimator} calculates + an <em>elapsed fraction</em> between 0 and 1, based on the duration of the animation + and how much time has elapsed. The elapsed fraction represents the percentage of time + that the animation has completed, 0 meaning 0% and 1 meaning 100%. The Animator then + calls the {@link android.animation.TimeInterpolator} that is currently set, + to calculate an <em>eased fraction</em>, + which is a modified value of the elapsed fraction that takes into account the interpolator that + is set (time interpolation is often referred to as <em>easing</em>). The eased fraction + is the final value that is used to animate the property.</p> + + <p>Once the eased fraction is calculated, {@link android.animation.ValueAnimator} calls + the appropriate {@link android.animation.TypeEvaluator} to calculate the final value of + the property that you are animating, based on the eased fraction, the starting value, + and ending value of the animation.</p> + + <h3 id="value-animator">Animating with ValueAnimator</h3> + + <p>The {@link android.animation.ValueAnimator} class lets you animate values of some + type for the duration of an animation by specifying a set of <code>int</code>, + <code>float</code>, or color values to animate over and the duration of the animation. + You obtain a {@link android.animation.ValueAnimator} by calling one of its factory + methods: {@link android.animation.ValueAnimator#ofInt ofInt()}, + {@link android.animation.ValueAnimator#ofFloat ofFloat()}, + or {@link android.animation.ValueAnimator#ofObject ofObject()}. For example:</p> + + <pre>ValueAnimator animation = ValueAnimator.ofFloat(0f, 1f); +animation.setDuration(1000); +animation.start(); +</pre> + + <p>In this code, the {@link android.animation.ValueAnimator} starts + calculating the values of the animation, between 0 and 1, for + a duration of 1000 ms, when the <code>start()</code> method runs.</p> + + <p>You can also specify a custom type to animate by doing the following:</p> + + <pre>ValueAnimator animation = ValueAnimator.ofObject(new MyTypeEvaluator(), startPropertyValue, endPropertyValue); +animation.setDuration(1000); +animation.start(); +</pre> + + <p>In this code, the {@link android.animation.ValueAnimator} starts + calculating the values of the animation, between <code>startPropertyValue</code> and + <code>endPropertyValue</code> using the logic supplied by <code>MyTypeEvaluator</code> + for a duration of 1000 ms, when the {@link android.animation.ValueAnimator#start start()} + method runs.</p> + + <p>The previous code snippets, however, do not affect an object, because the {@link + android.animation.ValueAnimator} does not operate on objects or properties directly. To + use the results of a {@link android.animation.ValueAnimator}, you must define listeners + in the {@link android.animation.ValueAnimator} to appropriately handle important events + during the animation's lifespan, such as frame updates. You can implement the following + interfaces to create listeners for {@link android.animation.ValueAnimator}:</p> + + <ul> + <li>{@link android.animation.Animator.AnimatorListener} + + <ul> + <li>{@link android.animation.Animator.AnimatorListener#onAnimationStart + onAnimationStart()} - Called when the animation starts</li> + + <li>{@link android.animation.Animator.AnimatorListener#onAnimationEnd + onAnimationEnd()} - Called when the animation ends.</li> + + <li>{@link android.animation.Animator.AnimatorListener#onAnimationRepeat + onAnimationRepeat()} - Called when the animation repeats itself.</li> + + <li>{@link android.animation.Animator.AnimatorListener#onAnimationCancel + onAnimationCancel()} - Called when the animation is canceled.</li> + </ul> + </li> + + <li>{@link android.animation.ValueAnimator.AnimatorUpdateListener} + + <ul> + <li> + <p>{@link + android.animation.ValueAnimator.AnimatorUpdateListener#onAnimationUpdate + onAnimationUpdate()} - called on every frame of the animation. + Listen to this event to use the calculated values generated by + {@link android.animation.ValueAnimator} during an animation. To use the value, + query the {@link android.animation.ValueAnimator} object passed into the event + to get the current animated value with the + {@link android.animation.ValueAnimator#getAnimatedValue getAnimatedValue()} method.</p> + + <p>If you are animating your own custom object (not View objects), this + callback must also call the {@link android.view.View#invalidate invalidate()} + method to force a redraw of the screen. If you are animating View objects, + {@link android.view.View#invalidate invalidate()} is automatically called when + a property of the View is changed.</p> + </li> + </ul> + + <p>You can extend the {@link android.animation.AnimatorListenerAdapter} class + instead of implementing the {@link android.animation.Animator.AnimatorListener} + interface, if you do not want to implement all of the methods of the {@link + android.animation.Animator.AnimatorListener} interface. The {@link + android.animation.AnimatorListenerAdapter} class provides empty implementations of the + methods that you can choose to override.</p> + </li> + </ul> + + <p>For example, the <a href= + "{@docRoot}resources/samples/ApiDemos/src/com/example/android/apis/animation/BouncingBalls.html"> + Bouncing Balls</a> sample in the API demos creates an {@link + android.animation.AnimatorListenerAdapter} for just the {@link + android.animation.Animator.AnimatorListener#onAnimationEnd onAnimationEnd()} + callback:</p> + + <pre>ValueAnimator fadeAnim = ObjectAnimator.ofFloat(newBall, "alpha", 1f, 0f); +fadeAnim.setDuration(250); +fadeAnim.addListener(new AnimatorListenerAdapter() { +public void onAnimationEnd(Animator animation) { + balls.remove(((ObjectAnimator)animation).getTarget()); +}</pre> + + <h3 id="object-animator">Animating with ObjectAnimator</h3> + + <p>The {@link android.animation.ObjectAnimator} is a subclass of the {@link + android.animation.ValueAnimator} (discussed in the previous section) + and combines the timing engine and value computation + of {@link android.animation.ValueAnimator} with the ability to animate a named property + of a target object. This makes animating any object much easier, as you no longer need + to implement the {@link android.animation.ValueAnimator.AnimatorUpdateListener}, because + the animated property updates automatically.</p> + + <p>Instantiating an {@link android.animation.ObjectAnimator} is similar to a {@link + android.animation.ValueAnimator}, but you also specify the object and that object's + property (as a String) that you want to animate:</p> + <pre>ObjectAnimator anim = ObjectAnimator.ofFloat(foo, "alpha", 0f, 1f); +anim.setDuration(1000); +anim.start();</pre> + + <p>To have the {@link android.animation.ObjectAnimator} update properties correctly, + you must do the following:</p> + + <ul> + <li>The object property that you are animating must have a setter function in the + form of <code>set<propertyName>()</code>. Because the {@link + android.animation.ObjectAnimator} automatically updates the property during + animation, it must be able to access the property with this setter method. For + example, if the property name is <code>foo</code>, you need to have a + <code>setFoo()</code> method. If this setter method does not exist, you have three + options: + + <ul> + <li>Add the setter method to the class if you have the rights to do so.</li> + + <li>Use a wrapper class that you have rights to change and have that wrapper + receive the value with a valid setter method and forward it to the original + object.</li> + + <li>Use {@link android.animation.ValueAnimator} instead.</li> + </ul> + </li> + + <li>If you specify only one value for the <code>values...</code> parameter, + in one of the {@link android.animation.ObjectAnimator} factory methods, it is assumed to be + the ending value of the animation. Therefore, the object property that you are + animating must have a getter function that is used to obtain the starting value of + the animation. The getter function must be in the form of + <code>get<propertyName>()</code>. For example, if the property name is + <code>foo</code>, you need to have a <code>getFoo()</code> method.</li> + + <li>The getter (if needed) and setter methods of the property that you are animating must + return the same type as the starting and ending values that you specify to {@link + android.animation.ObjectAnimator}. For example, you must have + <code>targetObject.setPropName(float)</code> and + <code>targetObject.getPropName(float)</code> if you construct the following {@link + android.animation.ObjectAnimator}: + <pre>ObjectAnimator.ofFloat(targetObject, "propName", 1f)</pre> + </li> + </ul> + + <h3 id="type-evaluator">Using a TypeEvaluator</h3> + + <p>If you want to animate a type that is unknown to the Android system, + you can create your own evaluator by implementing the {@link + android.animation.TypeEvaluator} interface. The types that are known by the Android + system are <code>int</code>, <code>float</code>, or a color, which are supported by the + {@link android.animation.IntEvaluator}, {@link android.animation.FloatEvaluator}, and + {@link android.animation.ArgbEvaluator} type evaluators.</p> + + <p>There is only one method to implement in the {@link android.animation.TypeEvaluator} + interface, the {@link android.animation.TypeEvaluator#evaluate evaluate()} method. + This allows the animator that you are using to return an + appropriate value for your animated property at the current point of the animation. The + {@link android.animation.FloatEvaluator} class demonstrates how to do this:</p> + <pre>public class FloatEvaluator implements TypeEvaluator { + + public Object evaluate(float fraction, Object startValue, Object endValue) { + float startFloat = ((Number) startValue).floatValue(); + return startFloat + fraction * (((Number) endValue).floatValue() - startFloat); + } +}</pre> + + <p class="note"><strong>Note:</strong> When {@link android.animation.ValueAnimator} (or + {@link android.animation.ObjectAnimator}) runs, it calculates a current elapsed + fraction of the animation (a value between 0 and 1) and then calculates an eased + version of that depending on what interpolator that you are using. The eased fraction + is what your {@link android.animation.TypeEvaluator} receives through the <code>fraction</code> + parameter, so you do not have to take into account the interpolator + when calculating animated values.</p> + + <h3 id="interpolators">Using interpolators</h3> + + <p>An interpolator define how specific values in an animation are + calculated as a function of time. For example, you can specify animations to happen + linearly across the whole animation, meaning the animation moves evenly the entire + time, or you can specify animations to use non-linear time, for example, using + acceleration or deceleration at the beginning or end of the animation.</p> + + <p>Interpolators in the animation system receive a fraction from Animators that represent the elapsed time + of the animation. Interpolators modify this fraction to coincide with the type of + animation that it aims to provide. The Android system provides a set of common + interpolators in the {@link android.view.animation android.view.animation package}. If + none of these suit your needs, you can implement the {@link + android.animation.TimeInterpolator} interface and create your own.</p> + + <p>As an example, how the default interpolator {@link + android.view.animation.AccelerateDecelerateInterpolator} and the {@link + android.view.animation.LinearInterpolator} calculate eased fractions are compared below. The {@link + android.view.animation.LinearInterpolator} has no effect on the elapsed fraction, + because a linear interpolation is calculated the same way as the elapsed fraction. The + {@link android.view.animation.AccelerateDecelerateInterpolator} accelerates into the + animation and decelerates out of it. The following methods define the logic for these + interpolators:</p> + + <p><strong>AccelerateDecelerateInterpolator</strong></p> + <pre>public float getInterpolation(float input) { + return (float)(Math.cos((input + 1) * Math.PI) / 2.0f) + 0.5f; +}</pre> + + <p><strong>LinearInterpolator</strong></p> + <pre>public float getInterpolation(float input) { + return input; +}</pre> + + <p>The following table represents the approximate values that are calculated by these + interpolators for an animation that lasts 1000ms:</p> + + <table> + <tr> + <th>ms elapsed</th> + + <th>Elapsed fraction/Eased fraction (Linear)</th> + + <th>Eased fraction (Accelerate/Decelerate)</th> + </tr> + + <tr> + <td>0</td> + + <td>0</td> + + <td>0</td> + </tr> + + <tr> + <td>200</td> + + <td>.2</td> + + <td>.1</td> + </tr> + + <tr> + <td>400</td> + + <td>.4</td> + + <td>.345</td> + </tr> + + <tr> + <td>600</td> + + <td>.6</td> + + <td>.8</td> + </tr> + + <tr> + <td>800</td> + + <td>.8</td> + + <td>.9</td> + </tr> + + <tr> + <td>1000</td> + + <td>1</td> + + <td>1</td> + </tr> + </table> + + <p>As the table shows, the {@link android.view.animation.LinearInterpolator} changes + the values at the same speed, .2 for every 200ms that passes. The {@link + android.view.animation.AccelerateDecelerateInterpolator} changes the values faster than + {@link android.view.animation.LinearInterpolator} between 200ms and 600ms and slower + between 600ms and 1000ms.</p> + + <h3 id="keyframes">Specifying keyframes</h3> + + <p>A {@link android.animation.Keyframe} object consists of a time/value pair that lets + you define a specific state at a specific time of an animation. Each keyframe can also + have its own interpolator to control the behavior of the animation in the interval + between the previous keyframe's time and the time of this keyframe.</p> + + <p>To instantiate a {@link android.animation.Keyframe} object, you must use one of the + factory methods, {@link android.animation.Keyframe#ofInt ofInt()}, {@link + android.animation.Keyframe#ofFloat ofFloat()}, or {@link + android.animation.Keyframe#ofObject ofObject()} to obtain the appropriate type of + {@link android.animation.Keyframe}. You then call the {@link + android.animation.PropertyValuesHolder#ofKeyframe ofKeyframe()} factory method to + obtain a {@link android.animation.PropertyValuesHolder} object. Once you have the + object, you can obtain an animator by passing in the {@link + android.animation.PropertyValuesHolder} object and the object to animate. The following + code snippet demonstrates how to do this:</p> + <pre>Keyframe kf0 = Keyframe.ofFloat(0f, 0f); +Keyframe kf1 = Keyframe.ofFloat(.9999f, 360f); +Keyframe kf2 = Keyframe.ofFloat(1f, 0f); +PropertyValuesHolder pvhRotation = PropertyValuesHolder.ofKeyframe("rotation", kf0, kf1, kf2); +ObjectAnimator rotationAnim = ObjectAnimator.ofPropertyValuesHolder(target, pvhRotation) +rotationAnim.setDuration(5000ms); +</pre> +<p>For a more complete example on how to use keyframes, see the <a href= +"{@docRoot}resources/samples/ApiDemos/src/com/example/android/apis/animation/MultiPropertyAnimation.html"> + MultiPropertyAnimation</a> sample in APIDemos.</p> + + <h3 id="choreography">Choreographing multiple animations with AnimatorSet</h3> + + <p>In many cases, you want to play an animation that depends on when another animation + starts or finishes. The Android system lets you bundle animations together into an + {@link android.animation.AnimatorSet}, so that you can specify whether to start animations + simultaneously, sequentially, or after a specified delay. You can also nest {@link + android.animation.AnimatorSet} objects within each other.</p> + + <p>The following sample code taken from the <a href= + "{@docRoot}resources/samples/ApiDemos/src/com/example/android/apis/animation/BouncingBalls.html"> + Bouncing Balls</a> sample (modified for simplicity) plays the following + {@link android.animation.Animator} objects in the following manner:</p> + + <ol> + <li>Plays <code>bounceAnim</code>.</li> + + <li>Plays <code>squashAnim1</code>, <code>squashAnim2</code>, + <code>stretchAnim1</code>, and <code>stretchAnim2</code> at the same time.</li> + + <li>Plays <code>bounceBackAnim</code>.</li> + + <li>Plays <code>fadeAnim</code>.</li> + </ol> + <pre>AnimatorSet bouncer = new AnimatorSet(); +bouncer.play(bounceAnim).before(squashAnim1); +bouncer.play(squashAnim1).with(squashAnim2); +bouncer.play(squashAnim1).with(stretchAnim1); +bouncer.play(squashAnim1).with(stretchAnim2); +bouncer.play(bounceBackAnim).after(stretchAnim2); +ValueAnimator fadeAnim = ObjectAnimator.ofFloat(newBall, "alpha", 1f, 0f); +fadeAnim.setDuration(250); +AnimatorSet animatorSet = new AnimatorSet(); +animatorSet.play(bouncer).before(fadeAnim); +animatorSet.start(); +</pre> + + <p>For a more complete example on how to use animator sets, see the <a href= + "{@docRoot}resources/samples/ApiDemos/src/com/example/android/apis/animation/BouncingBalls.html"> + Bouncing Balls</a> sample in APIDemos.</p> + + <h3 id="declaring-xml">Declaring animations in XML</h3> + + <p>As with <a href="#view-animation">view animation</a>, you can declare property animations with + XML instead of doing it programmatically. The following Android classes also have XML + declaration support with the following XML tags:</p> + + <ul> + <li>{@link android.animation.ValueAnimator} - <code><animator></code></li> + + <li>{@link android.animation.ObjectAnimator} - <code><objectAnimator></code></li> + + <li>{@link android.animation.AnimatorSet} - <code><AnimatorSet></code></li> + </ul> + + <p>Both <code><animator></code> ({@link android.animation.ValueAnimator}) and + <code><objectAnimator></code> ({@link android.animation.ObjectAnimator}) have the + following attributes:</p> + + <dl> + <dt><code>android:duration</code></dt> + <dd>The number of milliseconds that the animation runs.</dd> + + <dt><code>android:valueFrom</code> and <code>android:valueTo</code></dt> + <dd>The values being animated + between. These are restricted to numbers (<code>float</code> or <code>int</code>) in + XML. They can be <code>float</code>, <code>int</code>, or any kind of + <code>Object</code> when creating animations programmatically.</dd> + + <dt><code>android:valueType</code></dt> + <dd>Set to either <code>"floatType"</code> or <code>"intType"</code>.</dd> + + <dt><code>android:startDelay</code></dt> + <dd>The delay, in milliseconds, before the animation begins + playing (after calling {@link android.animation.ValueAnimator#start start()}).</dd> + + <dt><code>android:repeatCount</code></dt> + <dd>How many times to repeat an animation. Set to + <code>"-1"</code> for infinite repeating or to a positive integer. For example, a value of + <code>"1"</code> means that the animation is repeated once after the initial run of the + animation, so the animation plays a total of two times. The default value is + <code>"0"</code>.</dd> + + <dt><code>android:repeatMode</code></dt> + <dd>How an animation behaves when it reaches the end of the + animation. <code>android:repeatCount</code> must be set to a positive integer or + <code>"-1"</code> for this attribute to have an effect. Set to <code>"reverse"</code> to + have the animation reverse direction with each iteration or <code>"repeat"</code> to + have the animation loop from the beginning each time.</dd> + </dl> + + <p>The <code>objectAnimator</code> ({@link android.animation.ObjectAnimator}) element has the + additional attribute <code>propertyName</code>, that lets you specify the name of the + property being animated. The <code>objectAnimator</code> element does not expose a + <code>target</code> attribute, however, so you cannot set the object to animate in the + XML declaration. You have to inflate the XML resource by calling + {@link android.animation.AnimatorInflater#loadAnimator loadAnimator()} and call + {@link android.animation.ObjectAnimator#setTarget setTarget()} to set the target object, before calling + {@link android.animation.ObjectAnimator#start start()}.</p> + + <p>The <code>set</code> element ({@link android.animation.AnimatorSet}) exposes a single + attribute, <code>ordering</code>. Set this attribute to <code>together</code> (default) + to play all the animations in this set at once. Set this attribute to + <code>sequentially</code> to play the animations in the order they are declared.</p> + + <p>You can specify nested <code>set</code> tags to further group animations together. + The animations that you want to group together should be children of the + <code>set</code> tag and can define their own <code>ordering</code> attribute.</p> + + <p>As an example, this XML code creates an {@link android.animation.AnimatorSet} object + that animates x and y at the same time (<code>together</code> is the default ordering + when nothing is specified), then runs an animation that fades an object out:</p> + <pre><set android:ordering="sequentially"> + <set> + <objectAnimator + android:propertyName="x" + android:duration="500" + android:valueTo="400" + android:valueType="int"/> + <objectAnimator + android:propertyName="y" + android:duration="500" + android:valueTo="300" + android:valueType="int"/> + </set> + <objectAnimator + android:propertyName="alpha" + android:duration="500" + android:valueTo="0f"/> +</set></pre> + + <p>In order to run this animation, you must inflate the XML resources in your code to + an {@link android.animation.AnimatorSet} object, and then set the target objects for all of + the animations before starting the animation set. Calling {@link + android.animation.AnimatorSet#setTarget setTarget()} sets a single target object for + all children of the {@link android.animation.AnimatorSet}.</p> + + <h2 id="view-animation">View Animation</h2>You can use View Animation in any View + object to perform tweened animation and frame by frame animation. Tween animation + calculates the animation given information such as the start point, end point, size, + rotation, and other common aspects of an animation. Frame by frame animation lets you + load a series of Drawable resources one after another to create an animation. + + <h3 id="tween-animation">Tween Animation</h3> + + <p>A tween animation can perform a series of simple transformations (position, size, + rotation, and transparency) on the contents of a View object. So, if you have a + {@link android.widget.TextView} object, you can move, rotate, grow, or shrink the text. If it has a background + image, the background image will be transformed along with the text. The {@link + android.view.animation animation package} provides all the classes used in a tween + animation.</p> + + <p>A sequence of animation instructions defines the tween animation, defined by either + XML or Android code. As with defining a layout, an XML file is recommended because it's + more readable, reusable, and swappable than hard-coding the animation. In the example + below, we use XML. (To learn more about defining an animation in your application code, + instead of XML, refer to the {@link android.view.animation.AnimationSet} class and + other {@link android.view.animation.Animation} subclasses.)</p> + + <p>The animation instructions define the transformations that you want to occur, when + they will occur, and how long they should take to apply. Transformations can be + sequential or simultaneous — for example, you can have the contents of a TextView + move from left to right, and then rotate 180 degrees, or you can have the text move and + rotate simultaneously. Each transformation takes a set of parameters specific for that + transformation (starting size and ending size for size change, starting angle and + ending angle for rotation, and so on), and also a set of common parameters (for + instance, start time and duration). To make several transformations happen + simultaneously, give them the same start time; to make them sequential, calculate the + start time plus the duration of the preceding transformation.</p> + + <p>The animation XML file belongs in the <code>res/anim/</code> directory of your + Android project. The file must have a single root element: this will be either a single + <code><alpha></code>, <code><scale></code>, <code><translate></code>, + <code><rotate></code>, interpolator element, or <code><set></code> element + that holds groups of these elements (which may include another + <code><set></code>). By default, all animation instructions are applied + simultaneously. To make them occur sequentially, you must specify the + <code>startOffset</code> attribute, as shown in the example below.</p> + + <p>The following XML from one of the ApiDemos is used to stretch, then simultaneously + spin and rotate a View object.</p> + <pre><set android:shareInterpolator="false"> + <scale + android:interpolator="@android:anim/accelerate_decelerate_interpolator" + android:fromXScale="1.0" + android:toXScale="1.4" + android:fromYScale="1.0" + android:toYScale="0.6" + android:pivotX="50%" + android:pivotY="50%" + android:fillAfter="false" + android:duration="700" /> + <set android:interpolator="@android:anim/decelerate_interpolator"> + <scale + android:fromXScale="1.4" + android:toXScale="0.0" + android:fromYScale="0.6" + android:toYScale="0.0" + android:pivotX="50%" + android:pivotY="50%" + android:startOffset="700" + android:duration="400" + android:fillBefore="false" /> + <rotate + android:fromDegrees="0" + android:toDegrees="-45" + android:toYScale="0.0" + android:pivotX="50%" + android:pivotY="50%" + android:startOffset="700" + android:duration="400" /> + </set> +</set></pre> + + <p>Screen coordinates (not used in this example) are (0,0) at the upper left hand + corner, and increase as you go down and to the right.</p> + + <p>Some values, such as pivotX, can be specified relative to the object itself or + relative to the parent. Be sure to use the proper format for what you want ("50" for + 50% relative to the parent, or "50%" for 50% relative to itself).</p> + + <p>You can determine how a transformation is applied over time by assigning an {@link + android.view.animation.Interpolator}. Android includes several Interpolator subclasses + that specify various speed curves: for instance, {@link + android.view.animation.AccelerateInterpolator} tells a transformation to start slow and + speed up. Each one has an attribute value that can be applied in the XML.</p> + + <p>With this XML saved as <code>hyperspace_jump.xml</code> in the + <code>res/anim/</code> directory of the project, the following code will reference + it and apply it to an {@link android.widget.ImageView} object from the layout.</p> + <pre> +ImageView spaceshipImage = (ImageView) findViewById(R.id.spaceshipImage); +Animation hyperspaceJumpAnimation = AnimationUtils.loadAnimation(this, R.anim.hyperspace_jump); +spaceshipImage.startAnimation(hyperspaceJumpAnimation); +</pre> + + <p>As an alternative to <code>startAnimation()</code>, you can define a starting time + for the animation with <code>{@link android.view.animation.Animation#setStartTime(long) + Animation.setStartTime()}</code>, then assign the animation to the View with + <code>{@link android.view.View#setAnimation(android.view.animation.Animation) + View.setAnimation()}</code>.</p> + + <p>For more information on the XML syntax, available tags and attributes, see <a href= + "{@docRoot}guide/topics/resources/animation-resource.html">Animation Resources</a>.</p> + + <p class="note"><strong>Note:</strong> Regardless of how your animation may move or + resize, the bounds of the View that holds your animation will not automatically adjust + to accommodate it. Even so, the animation will still be drawn beyond the bounds of its + View and will not be clipped. However, clipping <em>will occur</em> if the animation + exceeds the bounds of the parent View.</p> + + <h3 id="frame-animation">Frame Animation</h3> + + <p>This is a traditional animation in the sense that it is created with a sequence of + different images, played in order, like a roll of film. The {@link + android.graphics.drawable.AnimationDrawable} class is the basis for frame + animations.</p> + + <p>While you can define the frames of an animation in your code, using the {@link + android.graphics.drawable.AnimationDrawable} class API, it's more simply accomplished + with a single XML file that lists the frames that compose the animation. Like the tween + animation above, the XML file for this kind of animation belongs in the + <code>res/drawable/</code> directory of your Android project. In this case, the + instructions are the order and duration for each frame of the animation.</p> + + <p>The XML file consists of an <code><animation-list></code> element as the root + node and a series of child <code><item></code> nodes that each define a frame: a + drawable resource for the frame and the frame duration. Here's an example XML file for + a frame-by-frame animation:</p> + <pre> +<animation-list xmlns:android="http://schemas.android.com/apk/res/android" + android:oneshot="true"> + <item android:drawable="@drawable/rocket_thrust1" android:duration="200" /> + <item android:drawable="@drawable/rocket_thrust2" android:duration="200" /> + <item android:drawable="@drawable/rocket_thrust3" android:duration="200" /> +</animation-list> +</pre> + + <p>This animation runs for just three frames. By setting the + <code>android:oneshot</code> attribute of the list to <var>true</var>, it will cycle + just once then stop and hold on the last frame. If it is set <var>false</var> then the + animation will loop. With this XML saved as <code>rocket_thrust.xml</code> in the + <code>res/drawable/</code> directory of the project, it can be added as the background + image to a View and then called to play. Here's an example Activity, in which the + animation is added to an {@link android.widget.ImageView} and then animated when the + screen is touched:</p> + <pre>AnimationDrawable rocketAnimation; + +public void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + setContentView(R.layout.main); + + ImageView rocketImage = (ImageView) findViewById(R.id.rocket_image); + rocketImage.setBackgroundResource(R.drawable.rocket_thrust); + rocketAnimation = (AnimationDrawable) rocketImage.getBackground(); +} + +public boolean onTouchEvent(MotionEvent event) { + if (event.getAction() == MotionEvent.ACTION_DOWN) { + rocketAnimation.start(); + return true; + } + return super.onTouchEvent(event); +}</pre> + + <p>It's important to note that the <code>start()</code> method called on the + AnimationDrawable cannot be called during the <code>onCreate()</code> method of your + Activity, because the AnimationDrawable is not yet fully attached to the window. If you + want to play the animation immediately, without requiring interaction, then you might + want to call it from the <code>{@link + android.app.Activity#onWindowFocusChanged(boolean) onWindowFocusChanged()}</code> + method in your Activity, which will get called when Android brings your window into + focus.</p> + + <p>For more information on the XML syntax, available tags and attributes, see <a href= + "{@docRoot}guide/topics/resources/animation-resource.html">Animation Resources</a>.</p>
\ No newline at end of file diff --git a/docs/html/guide/topics/location/obtaining-user-location.jd b/docs/html/guide/topics/location/obtaining-user-location.jd index bc782d2..3b450f0 100644 --- a/docs/html/guide/topics/location/obtaining-user-location.jd +++ b/docs/html/guide/topics/location/obtaining-user-location.jd @@ -421,8 +421,8 @@ lat/long coordinates, with a GPX file for route playback, or a KML file for mult <li>Use a KML file describing individual place marks for sequenced playback to the device.</li> </ul> -<p>For more information on using DDMS to spoof location data, see the -<a href="{@docRoot}guide/developing/tools/ddms.html#emulator-control">Using DDMS guide</a>. +<p>For more information on using DDMS to spoof location data, see +<a href="{@docRoot}guide/developing/debugging/ddms.html">Using DDMS</a>. <h3 id="MockGeo">Using the "geo" command in the emulator console</h3> @@ -451,4 +451,4 @@ lat/long coordinates, with a GPX file for route playback, or a KML file for mult </ol> <p>For information about how to connect to the emulator console, see -<a href="{@docRoot}guide/developing/tools/emulator.html#console">Using the Emulator Console</a>.</p> +<a href="{@docRoot}guide/developing/devices/emulator.html#console">Using the Emulator Console</a>.</p> diff --git a/docs/html/guide/topics/manifest/activity-element.jd b/docs/html/guide/topics/manifest/activity-element.jd index e030a4c..2648cb7 100644 --- a/docs/html/guide/topics/manifest/activity-element.jd +++ b/docs/html/guide/topics/manifest/activity-element.jd @@ -290,7 +290,8 @@ activity is ignored. The activity is not re-parented, but destroyed. <dd>An icon representing the activity. The icon is displayed to users when a representation of the activity is required on-screen. For example, icons for activities that initiate tasks are displayed in the launcher window. -The icon is often accompanied by a label (see the {@code label} attribute). +The icon is often accompanied by a label (see the <a href="#label">{@code +android:label}</a> attribute). </p> <p> diff --git a/docs/html/guide/topics/manifest/application-element.jd b/docs/html/guide/topics/manifest/application-element.jd index 9ac07fd..1fadc6e 100644 --- a/docs/html/guide/topics/manifest/application-element.jd +++ b/docs/html/guide/topics/manifest/application-element.jd @@ -12,6 +12,7 @@ page.title=<application> android:<a href="#icon">icon</a>="<i>drawable resource</i>" android:<a href="#killrst">killAfterRestore</a>=["true" | "false"] android:<a href="#label">label</a>="<i>string resource</i>" + android:<a href="#logo">logo</a>="<i>drawable resource</i>" android:<a href="#space">manageSpaceActivity</a>="<i>string</i>" android:<a href="#nm">name</a>="<i>string</i>" android:<a href="#prmsn">permission</a>="<i>string</i>" @@ -121,7 +122,7 @@ each of the application's components. See the individual <p> This attribute must be set as a reference to a drawable resource containing -the image definition. There is no default icon. +the image (for example {@code "@drawable/icon"}). There is no default icon. </p></dd> <dt><a name="killrst"></a>{@code android:killAfterRestore}</dt> @@ -154,6 +155,11 @@ However, as a convenience while you're developing the application, it can also be set as a raw string. </p></dd> +<dt><a name="logo"></a>{@code android:logo}</dt> +<dd>A logo for the application as whole, and the default logo for activities. +<p>This attribute must be set as a reference to a drawable resource containing +the image (for example {@code "@drawable/logo"}). There is no default logo.</p></dd> + <dt><a name="space"></a>{@code android:manageSpaceActivity}</dt> <dd>The fully qualified name of an Activity subclass that the system can launch to let users manage the memory occupied by the application diff --git a/docs/html/guide/topics/media/index.jd b/docs/html/guide/topics/media/index.jd index 8e18754..e355212 100644 --- a/docs/html/guide/topics/media/index.jd +++ b/docs/html/guide/topics/media/index.jd @@ -115,9 +115,8 @@ Resume playback from where you paused with <p>{@link android.media.MediaPlayer#stop() stop()} and {@link android.media.MediaPlayer#pause() pause()} work the same as discussed above.</p> - <p class="note"><strong>Note:</strong> It is possible that <code>mp</code> could be - null, so good code should <code>null</code> check after the <code>new</code>. - Also, <code>IllegalArgumentException</code> and <code>IOException</code> either + <p class="note"><strong>Note:</strong> + <code>IllegalArgumentException</code> and <code>IOException</code> either need to be caught or passed on when using <code>setDataSource()</code>, since the file you are referencing may not exist.</p> <p class="note"><strong>Note:</strong> diff --git a/docs/html/guide/topics/resources/drawable-resource.jd b/docs/html/guide/topics/resources/drawable-resource.jd index d9f619f..cee8fc3 100644 --- a/docs/html/guide/topics/resources/drawable-resource.jd +++ b/docs/html/guide/topics/resources/drawable-resource.jd @@ -74,7 +74,7 @@ android:drawable="@color/green"}).</p> alias resource ID in XML.</p> <p class="note"><strong>Note:</strong> Bitmap files may be automatically optimized with lossless -image compression by the <a href="{@docRoot}guide/developing/tools/aapt.html">aapt</a> tool. For +image compression by the <code>aapt</code> tool during the build process. For example, a true-color PNG that does not require more than 256 colors may be converted to an 8-bit PNG with a color palette. This will result in an image of equal quality but which requires less memory. So be aware that the image binaries placed in this directory can change during the build. If diff --git a/docs/html/guide/topics/resources/menu-resource.jd b/docs/html/guide/topics/resources/menu-resource.jd index cde72bd..33c782b 100644 --- a/docs/html/guide/topics/resources/menu-resource.jd +++ b/docs/html/guide/topics/resources/menu-resource.jd @@ -36,22 +36,26 @@ In XML: <code>@[<em>package</em>:]menu.<em>filename</em></code> <?xml version="1.0" encoding="utf-8"?> <<a href="#menu-element">menu</a> xmlns:android="http://schemas.android.com/apk/res/android"> <<a href="#item-element">item</a> android:id="@[+][<em>package</em>:]id/<em>resource_name</em>" - android:menuCategory=["container" | "system" | "secondary" | "alternative"] - android:orderInCategory="<em>integer</em>" android:title="<em>string</em>" android:titleCondensed="<em>string</em>" android:icon="@[package:]drawable/<em>drawable_resource_name</em>" + android:onClick="<em>method name</em>" + android:showAsAction=["ifRoom" | "never" | "withText" | "always"] + android:actionLayout="@[package:]layout/<em>layout_resource_name</em>" + android:actionViewClass="<em>class name</em>" android:alphabeticShortcut="<em>string</em>" android:numericShortcut="<em>string</em>" android:checkable=["true" | "false"] android:visible=["visible" | "invisible" | "gone"] - android:enabled=["enabled" | "disabled"] /> + android:enabled=["enabled" | "disabled"] + android:menuCategory=["container" | "system" | "secondary" | "alternative"] + android:orderInCategory="<em>integer</em>" /> <<a href="#group-element">group</a> android:id="@[+][<em>package</em>:]id/<em>resource name</em>" - android:menuCategory=["container" | "system" | "secondary" | "alternative"] - android:orderInCategory="<em>integer</em>" android:checkableBehavior=["none" | "all" | "single"] android:visible=["visible" | "invisible" | "gone"] - android:enabled=["enabled" | "disabled"] > + android:enabled=["enabled" | "disabled"] + android:menuCategory=["container" | "system" | "secondary" | "alternative"] + android:orderInCategory="<em>integer</em>" > <<a href="#item-element">item</a> /> </group> <<a href="#item-element">item</a> > @@ -73,95 +77,155 @@ In XML: <code>@[<em>package</em>:]menu.<em>filename</em></code> <p class="caps">attributes:</p> <dl class="atn-list"> <dt><code>xmlns:android</code></dt> - <dd><em>String</em>. <strong>Required.</strong> Defines the XML namespace, which must be - <code>"http://schemas.android.com/apk/res/android"</code>. + <dd><em>XML namespace</em>. <strong>Required.</strong> Defines the XML namespace, which +must be <code>"http://schemas.android.com/apk/res/android"</code>. </dl> </dd> - <dt id="group-element"><code><group></code></dt> - <dd>A menu group (to create a collection of items that share traits, such as whether they are -visible, enabled, or checkable). Contains one or more <code><item></code> elements. Must be a -child of a <code><menu></code> element. + + <dt id="item-element"><code><item></code></dt> + <dd>A menu item. May contain a <code><menu></code> element (for a Sub + Menu). Must be a child of a <code><menu></code> or <code><group></code> element. <p class="caps">attributes:</p> <dl class="atn-list"> <dt><code>android:id</code></dt> <dd><em>Resource ID</em>. A unique resource ID. To create a new resource ID for this item, use the form: -<code>"@+id/<em>name</em>"</code>. The plus symbol indicates that this should be created as a new ID.</dd> +<code>"@+id/<em>name</em>"</code>. The plus symbol indicates that this should be created as a new +ID.</dd> + <dt><code>android:title</code></dt> + <dd><em>String resource</em>. The menu title as a string resource or raw string.</dd> + <dt><code>android:titleCondensed</code></dt> + <dd><em>String resource</em>. A condensed title as a string resource or a raw string. This +title is used for situations in which the normal title is too long.</dd> + + <dt><code>android:icon</code></dt> + <dd><em>Drawable resource</em>. An image to be used as the menu item icon.</dd> + + <dt><code>android:onClick</code></dt> + <dd><em>Method name</em>. The method to call when this menu item is clicked. The +method must be declared in the activity as public and accept a {@link android.view.MenuItem} as its +only parameter, which indicates the item clicked. This method takes precedence over the standard +callback to {@link android.app.Activity#onOptionsItemSelected onOptionsItemSelected()}. See the +example at the bottom. + <p class="warning"><strong>Warning:</strong> If you obfuscate your code using <a +href="{@docRoot}guide/developing/tools/proguard.html">ProGuard</a> (or a similar tool), +be sure to exclude the method you specify in this attribute from renaming, because it can break the +functionality.</p> + <p>Introduced in API Level HONEYCOMB.</p></dd> + + <dt><code>android:showAsAction</code></dt> + <dd><em>Keyword</em>. When and how this item should appear as an action item in the Action +Bar. A menu item can appear as an action item only when the activity includes an {@link +android.app.ActionBar} (introduced in API Level HONEYCOMB). Valid values: + <table> + <tr><th>Value</th><th>Description</th></tr> + <tr><td><code>ifRoom</code></td><td>Only place this item in the Action Bar if +there is room for it.</td></tr> + <tr><td><code>withText</code></td><td>Also include the title text (defined +by {@code android:title}) with the action item. You can include this value along with one +of the others as a flag set, by separating them with a pipe {@code |}.</td></tr> + <tr><td><code>never</code></td><td>Never place this item in the Action Bar.</td></tr> + <tr><td><code>always</code></td><td>Always place this item in the Action Bar. +Avoid using this unless it's critical that the item always appear in the action +bar. Setting multiple items to always appear as action items can result in them overlapping +with other UI in the action bar.</td></tr> + </table> + <p>See <a href="{@docRoot}guide/topics/ui/actionbar.html">Using the Action Bar</a> for +more information.</p> + <p>Introduced in API Level HONEYCOMB.</p> + </dd> + + <dt><code>android:actionViewLayout</code></dt> + <dd><em>Layout resource</em>. A layout to use as the action view. + <p>See <a href="{@docRoot}guide/topics/ui/actionbar.html">Using the Action Bar</a> for +more information.</p> + <p>Introduced in API Level HONEYCOMB.</p></dd> + + <dt><code>android:actionViewClassName</code></dt> + <dd><em>Class name</em>. A fully-qualified class name for the {@link android.view.View} +to use as the action view. + <p>See <a href="{@docRoot}guide/topics/ui/actionbar.html">Using the Action Bar</a> for +more information.</p> + <p class="warning"><strong>Warning:</strong> If you obfuscate your code using <a +href="{@docRoot}guide/developing/tools/proguard.html">ProGuard</a> (or a similar tool), +be sure to exclude the class you specify in this attribute from renaming, because it can break the +functionality.</p> + <p>Introduced in API Level HONEYCOMB.</p></dd> + + + <dt><code>android:alphabeticShortcut</code></dt> + <dd><em>Char</em>. A character for the alphabetic shortcut key.</dd> + <dt><code>android:numericShortcut</code></dt> + <dd><em>Integer</em>. A number for the numeric shortcut key.</dd> + <dt><code>android:checkable</code></dt> + <dd><em>Boolean</em>. "true" if the item is checkable.</dd> + <dt><code>android:checked</code></dt> + <dd><em>Boolean</em>. "true" if the item is checked by default.</dd> + <dt><code>android:visible</code></dt> + <dd><em>Boolean</em>. "true" if the item is visible by default.</dd> + <dt><code>android:enabled</code></dt> + <dd><em>Boolean</em>. "true" if the item is enabled by default.</dd> <dt><code>android:menuCategory</code></dt> <dd><em>Keyword</em>. Value corresponding to {@link android.view.Menu} {@code CATEGORY_*} - constants, which define the group's priority. Valid values: + constants, which define the item's priority. Valid values: <table> <tr><th>Value</th><th>Description</th></tr> - <tr><td><code>container</code></td><td>For groups that are part of a + <tr><td><code>container</code></td><td>For items that are part of a container.</td></tr> - <tr><td><code>system</code></td><td>For groups that are provided by the + <tr><td><code>system</code></td><td>For items that are provided by the system.</td></tr> - <tr><td><code>secondary</code></td><td>For groups that are user-supplied secondary + <tr><td><code>secondary</code></td><td>For items that are user-supplied secondary (infrequently used) options.</td></tr> - <tr><td><code>alternative</code></td><td>For groups that are alternative actions + <tr><td><code>alternative</code></td><td>For items that are alternative actions on the data that is currently displayed.</td></tr> </table> </dd> <dt><code>android:orderInCategory</code></dt> - <dd><em>Integer</em>. The default order of the items within the category.</dd> + <dd><em>Integer</em>. The order of "importance" of the item, within a group.</dd> + </dl> + </dd> + + <dt id="group-element"><code><group></code></dt> + <dd>A menu group (to create a collection of items that share traits, such as whether they are +visible, enabled, or checkable). Contains one or more <code><item></code> elements. Must be a +child of a <code><menu></code> element. + <p class="caps">attributes:</p> + <dl class="atn-list"> + <dt><code>android:id</code></dt> + <dd><em>Resource ID</em>. A unique resource ID. To create a new resource ID for this item, +use the form: +<code>"@+id/<em>name</em>"</code>. The plus symbol indicates that this should be created as a new +ID.</dd> <dt><code>android:checkableBehavior</code></dt> <dd><em>Keyword</em>. The type of checkable behavior for the group. Valid values: <table> <tr><th>Value</th><th>Description</th></tr> <tr><td><code>none</code></td><td>Not checkable</td></tr> <tr><td><code>all</code></td><td>All items can be checked (use checkboxes)</td></tr> - <tr><td><code>single</code></td><td>Only one item can be checked (use radio buttons)</td></tr> + <tr><td><code>single</code></td><td>Only one item can be checked (use radio +buttons)</td></tr> </table> </dd> <dt><code>android:visible</code></dt> <dd><em>Boolean</em>. "true" if the group is visible.</dd> <dt><code>android:enabled</code></dt> <dd><em>Boolean</em>. "true" if the group is enabled.</dd> - </dl> - </dd> - <dt id="item-element"><code><item></code></dt> - <dd>A menu item. May contain a <code><menu></code> element (for a Sub - Menu). Must be a child of a <code><menu></code> or <code><group></code> element. - <p class="caps">attributes:</p> - <dl class="atn-list"> - <dt><code>android:id</code></dt> - <dd><em>Resource ID</em>. A unique resource ID. To create a new resource ID for this item, use the form: -<code>"@+id/<em>name</em>"</code>. The plus symbol indicates that this should be created as a new ID.</dd> <dt><code>android:menuCategory</code></dt> <dd><em>Keyword</em>. Value corresponding to {@link android.view.Menu} {@code CATEGORY_*} - constants, which define the item's priority. Valid values: + constants, which define the group's priority. Valid values: <table> <tr><th>Value</th><th>Description</th></tr> - <tr><td><code>container</code></td><td>For items that are part of a + <tr><td><code>container</code></td><td>For groups that are part of a container.</td></tr> - <tr><td><code>system</code></td><td>For items that are provided by the + <tr><td><code>system</code></td><td>For groups that are provided by the system.</td></tr> - <tr><td><code>secondary</code></td><td>For items that are user-supplied secondary + <tr><td><code>secondary</code></td><td>For groups that are user-supplied secondary (infrequently used) options.</td></tr> - <tr><td><code>alternative</code></td><td>For items that are alternative actions + <tr><td><code>alternative</code></td><td>For groups that are alternative actions on the data that is currently displayed.</td></tr> </table> </dd> <dt><code>android:orderInCategory</code></dt> - <dd><em>Integer</em>. The order of "importance" of the item, within a group.</dd> - <dt><code>android:title</code></dt> - <dd><em>String</em>. The menu title.</dd> - <dt><code>android:titleCondensed</code></dt> - <dd><em>String</em>. A condensed title, for situations in which the normal title is -too long.</dd> - <dt><code>android:icon</code></dt> - <dd><em>Drawable resource</em>. An image to be used as the menu item icon.</dd> - <dt><code>android:alphabeticShortcut</code></dt> - <dd><em>Char</em>. A character for the alphabetic shortcut key.</dd> - <dt><code>android:numericShortcut</code></dt> - <dd><em>Integer</em>. A number for the numeric shortcut key.</dd> - <dt><code>android:checkable</code></dt> - <dd><em>Boolean</em>. "true" if the item is checkable.</dd> - <dt><code>android:checked</code></dt> - <dd><em>Boolean</em>. "true" if the item is checked by default.</dd> - <dt><code>android:visible</code></dt> - <dd><em>Boolean</em>. "true" if the item is visible by default.</dd> - <dt><code>android:enabled</code></dt> - <dd><em>Boolean</em>. "true" if the item is enabled by default.</dd> + <dd><em>Integer</em>. The default order of the items within the category.</dd> </dl> </dd> </dl> @@ -174,17 +238,21 @@ too long.</dd> <menu xmlns:android="http://schemas.android.com/apk/res/android"> <item android:id="@+id/item1" android:title="@string/item1" - android:icon="@drawable/group_item1_icon" /> + android:icon="@drawable/group_item1_icon" + android:showAsAction="ifRoom|withText"/> <group android:id="@+id/group"> <item android:id="@+id/group_item1" + android:onClick="onGroupItemClick" android:title="@string/group_item1" android:icon="@drawable/group_item1_icon" /> <item android:id="@+id/group_item2" + android:onClick="onGroupItemClick" android:title="G@string/group_item2" android:icon="@drawable/group_item2_icon" /> </group> <item android:id="@+id/submenu" - android:title="@string/submenu_title" > + android:title="@string/submenu_title" + android:showAsAction="ifRoom|withText" > <menu> <item android:id="@+id/submenu_item1" android:title="@string/submenu_item1" /> @@ -192,15 +260,24 @@ too long.</dd> </item> </menu> </pre> - <p>This application code will inflate the menu from the {@link -android.app.Activity#onCreateOptionsMenu(Menu)} callback:</p> + <p>The following application code inflates the menu from the {@link +android.app.Activity#onCreateOptionsMenu(Menu)} callback and also declares the on-click +callback for two of the items:</p> <pre> public boolean onCreateOptionsMenu(Menu menu) { - MenuInflater inflater = getMenuInflater(); - inflater.inflate(R.menu.example_menu, menu); - return true; + MenuInflater inflater = getMenuInflater(); + inflater.inflate(R.menu.example_menu, menu); + return true; +} + +public void onGroupItemClick(MenuItem item) { + // One of the group items (using the onClick attribute) was clicked + // The item parameter passed here indicates which item it is + // All other menu item clicks are handled by {@link android.app.Activity#onOptionsItemSelected onOptionsItemSelected()} } </pre> +<p class="note"><strong>Note:</strong> The {@code android:showAsAction} attribute is +available only on Android X.X (API Level HONEYCOMB) and greater.</p> </dd> <!-- end example --> diff --git a/docs/html/guide/topics/resources/string-resource.jd b/docs/html/guide/topics/resources/string-resource.jd index 81c5d55..2db38f1 100644 --- a/docs/html/guide/topics/resources/string-resource.jd +++ b/docs/html/guide/topics/resources/string-resource.jd @@ -12,8 +12,8 @@ your application with strings:</p> <dd>XML resource that provides a single string.</dd> <dt><a href="#StringArray">String Array</a></dt> <dd>XML resource that provides an array of strings.</dd> - <dt><a href="#Plurals">Plurals</a></dt> - <dd>XML resource that carries different strings for different pluralizations + <dt><a href="#Plurals">Quantity Strings (Plurals)</a></dt> + <dd>XML resource that carries different strings for different quantities of the same word or phrase.</dd> </dl> @@ -218,13 +218,30 @@ getStringArray}(R.array.planets_array); -<h2 id="Plurals">Plurals</h2> +<h2 id="Plurals">Quantity Strings (Plurals)</h2> -<p>A pair of strings that each provide a different plural form of the same word or phrase, -which you can collectively reference from the application. When you request the plurals -resource using a method such as {@link android.content.res.Resources#getQuantityString(int,int) -getQuantityString()}, you must pass a "count", which will determine the plural form you -require and return that string to you.</p> +<p>Different languages have different rules for grammatical agreement with quantity. In English, +for example, the quantity 1 is a special case. We write "1 book", but for any other quantity we'd +write "<i>n</i> books". This distinction between singular and plural is very common, but other +languages make finer distinctions. The full set supported by Android is <code>zero</code>, +<code>one</code>, <code>two</code>, <code>few</code>, <code>many</code>, and <code>other</code>. + +<p>The rules for deciding which case to use for a given language and quantity can be very complex, +so Android provides you with methods such as +{@link android.content.res.Resources#getQuantityString(int,int) getQuantityString()} to select +the appropriate resource for you. + +<p>Note that the selection is made based on grammatical necessity. A string for <code>zero</code> +in English will be ignored even if the quantity is 0, because 0 isn't grammatically different +from 2, or any other number except 1 ("zero books", "one book", "two books", et cetera). +Don't be misled either by the fact that, say, <code>two</code> sounds like it could only apply to +the quantity 2: a language may require that 2, 12, 102 (et cetera) are all treated like one +another but differently to other quantities. Rely on your translator to know what distinctions +their language actually insists upon. + +<p>It's often possible to avoid quantity strings by using quantity-neutral formulations such as +"Books: 1". This will make your life and your translators' lives easier, if it's a style that's +in keeping with your application. <p class="note"><strong>Note:</strong> A plurals collection is a simple resource that is referenced using the value provided in the {@code name} attribute (not the name of the XML @@ -251,7 +268,7 @@ In Java: <code>R.plurals.<em>plural_name</em></code> <<a href="#plurals-element">plurals</a> name="<em>plural_name</em>"> <<a href="#plurals-item-element">item</a> - quantity=["one" | "other"] + quantity=["zero" | "one" | "two" | "few" | "many" | "other"] ><em>text_string</em></item> </plurals> </resources> @@ -285,16 +302,27 @@ Styling</a>, below, for information about to properly style and format your stri <p class="caps">attributes:</p> <dl class="atn-list"> <dt><code>quantity</code></dt> - <dd><em>Keyword</em>. A value indicating the case in which this string should be used. Valid -values: + <dd><em>Keyword</em>. A value indicating when this string should be used. Valid +values, with non-exhaustive examples in parentheses: <table> <tr><th>Value</th><th>Description</th></tr> <tr> - <td>{@code one}</td><td>When there is one (a singular string).</td> + <td>{@code zero}</td><td>When the language requires special treatment of the number 0 (as in Arabic).</td> + </tr> + <tr> + <td>{@code one}</td><td>When the language requires special treatment of numbers like one (as with the number 1 in English and most other languages; in Russian, any number ending in 1 but not ending in 11 is in this class).</td> + </tr> + <tr> + <td>{@code two}</td><td>When the language requires special treatment of numbers like two (as in Welsh).</td> + </tr> + <tr> + <td>{@code few}</td><td>When the language requires special treatment of "small" numbers (as with 2, 3, and 4 in Czech; or numbers ending 2, 3, or 4 but not 12, 13, or 14 in Polish).</td> </tr> <tr> - <td>{@code other}</td><td>When the quantity is anything other than one (a plural -string, but also used when the count is zero).</td> + <td>{@code many}</td><td>When the language requires special treatment of "large" numbers (as with numbers ending 11-99 in Maltese).</td> + </tr> + <tr> + <td>{@code other}</td><td>When the language does not require special treatment of the given quantity.</td> </tr> </table> </dd> @@ -315,6 +343,17 @@ string, but also used when the count is zero).</td> </plurals> </resources> </pre> + <p>XML file saved at {@code res/values-pl/strings.xml}:</p> +<pre> +<?xml version="1.0" encoding="utf-8"?> +<resources> + <plurals name="numberOfSongsAvailable"> + <item quantity="one">Znaleziono jedną piosenkę.</item> + <item quantity="few">Znaleziono %d piosenki.</item> + <item quantity="other">Znaleziono %d piosenek.</item> + </plurals> +</resources> +</pre> <p>Java code:</p> <pre> int count = getNumberOfsongsAvailable(); diff --git a/docs/html/guide/topics/testing/testing_android.jd b/docs/html/guide/topics/testing/testing_android.jd index d4b0dcc..6f3048c 100755 --- a/docs/html/guide/topics/testing/testing_android.jd +++ b/docs/html/guide/topics/testing/testing_android.jd @@ -625,9 +625,8 @@ The <a href="{@docRoot}guide/developing/tools/monkey.html">UI/Application Exerci </p> <p> When possible, you should run these tests on an actual device. If this is not possible, you can - use the <a href="{@docRoot}guide/developing/tools/emulator.html">Android Emulator</a> with - <a href="{@docRoot}guide/developing/tools/avd.html">Android Virtual Devices</a> configured for - the hardware, screens, and versions you want to test. + use the <a href="{@docRoot}guide/developing/devices/emulator.html">Android Emulator</a> with + Android Virtual Devices configured for the hardware, screens, and versions you want to test. </p> <h2 id="NextSteps">Next Steps</h2> <p> diff --git a/docs/html/guide/topics/ui/actionbar.jd b/docs/html/guide/topics/ui/actionbar.jd new file mode 100644 index 0000000..b8d1928 --- /dev/null +++ b/docs/html/guide/topics/ui/actionbar.jd @@ -0,0 +1,850 @@ +page.title=Using the Action Bar +parent.title=User Interface +parent.link=index.html +@jd:body + +<div id="qv-wrapper"> +<div id="qv"> + + <h2>Quickview</h2> + <ul> + <li>A replacement for the title bar that includes the application icon and activity title</li> + <li>Provides action items from the Options Menu and modes of navigating around the +application</li> + <li>Supports custom views, including an embedded search box</li> + <li>Requires API Level 11</li> + </ul> + + <h2>In this document</h2> + <ol> + <li><a href="#Adding">Adding the Action Bar</a> + <ol> + <li><a href="#Removing">Removing the Action Bar</a></li> + </ol> + </li> + <li><a href="#ActionItems">Adding Action Items</a> + <ol> + <li><a href="#Home">Using the app icon as an action item</a></li> + </ol> + </li> + <li><a href="#ActionView">Adding an Action View</a></li> + <li><a href="#Tabs">Adding Tabs</a></li> + <li><a href="#Dropdown">Adding Drop-down Navigation</a></li> + <li><a href="#Style">Styling the Action Bar</a></li> + </ol> + + <h2>Key classes</h2> + <ol> + <li>{@link android.app.ActionBar}</li> + <li>{@link android.view.Menu}</li> + </ol> + + <h2>See also</h2> + <ol> + <li><a href="{@docRoot}guide/topics/ui/menus.html">Creating Menus</a></li> + </ol> +</div> +</div> + +<p>The Action Bar is a widget for activities that replaces the traditional title bar at +the top of the screen. By default, the Action Bar includes the application logo on the left side, +followed by the activity title, and any available items from the Options Menu on the right side. The +Action Bar offers several useful features, including the ability to:</p> + +<ul> + <li>Display items from the <a +href="{@docRoot}guide/topics/ui/menus.html#OptionsMenu">Options Menu</a> directly in the Action +Bar, as "action +items"—providing instant access to key user actions. + <p>Menu items that do not appear as action items are placed in the overflow menu, revealed +by a drop-down list in the Action Bar.</p></li> + <li>Provide tabs for navigating between <a +href="{@docRoot}guide/topics/fundamentals/fragments.html">fragments</a>.</li> + <li>Provide a drop-down list for navigation.</li> + <li>Provide interactive "action views" in place of action items (such as a search box).</li> +</ul> + +<img src="{@docRoot}images/ui/actionbar.png" height="36" alt="" /> + +<p class="img-caption"><strong>Figure 1.</strong> A screenshot of the Action Bar in the Email +application, containing action items to compose new email and refresh the inbox.</p> + + +<h2 id="Adding">Adding the Action Bar</h2> + +<p>The Action Bar is included by default in all activities that target Android 3.0 or greater. More +specifically, all activities that use the new "holographic" theme include the Action Bar, and any +application that targets Android 3.0 automatically receives this theme. An application is considered +to "target" Android 3.0 when it has set either the {@code android:minSdkVersion} or {@code +android:targetSdkVersion} attribute in the <a +href="{@docRoot}guide/topics/manifest/uses-sdk-element.html">{@code <uses-sdk>}</a> element to +{@code "11"} or greater. For example:</p> + +<pre> +<manifest xmlns:android="http://schemas.android.com/apk/res/android" + package="com.example.helloworld" + android:versionCode="1" + android:versionName="1.0"> + <uses-sdk android:minSdkVersion="4" + <b>android:targetSdkVersion="11"</b> /> + <application ... > + ... + </application> +</manifest> +</pre> + +<p>In this example, the application requires a minimum version of API +Level 4 (Android 1.6), but it also targets API Level 11 (Android 3.0). This way, when +the application is installed on a device running Android 3.0 or greater, the system applies the +holographic theme to each activity, and thus, each activity includes the Action Bar.</p> + +<p>However, if you want to use Action Bar APIs, such as to add tabs or modify Action Bar styles, +you need to set the {@code android:minSdkVersion} to {@code "11"}, so you can access the +{@link android.app.ActionBar} class.</p> + + +<h3 id="Removing">Removing the Action Bar</h3> + +<p>If you want to remove the Action Bar for a particular activity, set the activity theme to +{@link android.R.style#Theme_Holo_NoActionBar Theme.Holo.NoActionBar}. For example:</p> + +<pre> +<activity android:theme="@android:style/Theme.Holo.NoActionBar"> +</pre> + +<p class="note"><strong>Tip:</strong> If you have a custom activity theme in which you'd like to +remove the Action Bar, set the {@link android.R.styleable#Theme_windowActionBar +android:windowActionBar} style property {@code false}. See <a href="#Style">Styling the Action +Bar</a> for more about Action Bar styles.</p> + +<p>You can also hide the Action Bar at runtime by calling {@link android.app.ActionBar#hide}, +then show it again by calling {@link android.app.ActionBar#show}. For example:</p> + +<pre> +ActionBar actionBar = getActionBar(); +actionBar.hide(); +</pre> + +<p>When the Action Bar hides, the system adjusts your activity content to fill all the +available screen space.</p> + +<p class="note"><strong>Note:</strong> If you remove the Action Bar using a theme, then the +window will not allow the Action Bar at all, so you cannot add it at runtime—calling +{@link android.app.Activity#getActionBar getActionBar()} will return null.</p> + + +<h2 id="ActionItems">Adding Action Items</h2> + +<p>An action item is simply a menu item from the <a +href="{@docRoot}guide/topics/ui/menus.html#OptionsMenu">Options Menu</a> which you declare should +appear directly in the Action Bar. An action item can include an icon and/or text. If a menu +item does not appear as an action item, then the system places it in the overflow menu, which +the user can open with the menu icon on the right side of the Action Bar.</p> + +<div class="figure" style="width:359px"> + <img src="{@docRoot}images/ui/actionbar-item-withtext.png" height="57" alt="" /> + <p class="img-caption"><strong>Figure 2.</strong> A screenshot from an Action Bar with two +action items and the overflow menu.</p> +</div> + +<p>When the activity first starts, the system populates the Action Bar and overflow menu by calling +{@link android.app.Activity#onCreateOptionsMenu onCreateOptionsMenu()} for your activity. As +discussed in the guide to <a href="{@docRoot}guide/topics/ui/menus.html">Creating Menus</a>, it's in +this callback method that you define the Options Menu for the activity.</p> + +<p>You can specify a menu item to appear as an action item—if there is room +for it—from your <a href="{@docRoot}guide/topics/resources/menu-resource.html">menu +resource</a> by declaring {@code +android:showAsAction="ifRoom"} for the {@code <item>} element. This way, the menu item appears +in the Action Bar for quick access only if there is room available for it. If there's not +enough room, the item is placed the overflow menu (revealed by the menu icon on the right side +of the Action Bar).</p> + +<p>You can also declare a menu item to appear as an action item from your application code, by +calling {@link android.view.MenuItem#setShowAsAction setShowAsAction()} on the {@link +android.view.MenuItem} and passing {@link android.view.MenuItem#SHOW_AS_ACTION_IF_ROOM}.</p> + +<p>If your menu item supplies both a title and an icon, then the action item shows only +the icon by defult. If you want to include the text with the action item, add the "with +text" flag: in XML, add {@code withText} to the {@code android:showAsAction} attribute or, in +your application code, use the {@link android.view.MenuItem#SHOW_AS_ACTION_WITH_TEXT} flag when +calling {@link android.view.MenuItem#setShowAsAction setShowAsAction()}. Figure 2 shows an Action +Bar that has two action items with text and the icon for the overflow menu.</p> + +<p>Here's an example of how you can declare a menu item as an action item in a <a +href="{@docRoot}guide/topics/resources/menu-resource.html">menu resource</a> file:</p> +<pre> +<?xml version="1.0" encoding="utf-8"?> +<menu xmlns:android="http://schemas.android.com/apk/res/android"> + <item android:id="@+id/menu_add" + android:icon="@drawable/ic_menu_save" + android:title="@string/menu_save" + <b>android:showAsAction="ifRoom|withText"</b> /> +</menu> +</pre> + +<p>In this case, both the {@code ifRoom} and {@code withText} flags are set, so that when this +item appears as an action item, it includes the title text along with the icon.</p> + +<p>A menu item placed in the Action Bar triggers the same callback methods as other items in the +Options Menu. When the user selects an action item, your activity receives a call to +{@link android.app.Activity#onOptionsItemSelected(MenuItem) onOptionsItemSelected()}, passing the +item ID.</p> + +<p class="note"><strong>Note:</strong> If you added the menu item from a fragment, then the +respective {@link +android.app.Fragment#onOptionsItemSelected(MenuItem) onOptionsItemSelected()} method is called +for that fragment. However the activity gets a chance to handle it first, so the system calls {@link +android.app.Activity#onOptionsItemSelected(MenuItem) onOptionsItemSelected()} on the activity +before calling the fragment.</p> + +<p>You can also declare an item to <em>always</em> appear as an action item, but you should avoid +doing so, because it can create a cluttered UI if there are too many action items and they might +collide with other elements in the Action Bar.</p> + +<p>For more information about menus, see the <a +href="{@docRoot}guide/topics/ui/menus.html#options-menu">Creating Menus</a> developer guide.</p> + + +<h3 id="Home">Using the app icon as an action item</h3> + +<p>By default, your application icon appears in the Action Bar on the left side. It also responds +to user interaction (when the user taps it, it visually responds the same way action +items do) and it's your responsibility to do something when the user taps it.</p> + +<img src="{@docRoot}images/ui/actionbar.png" height="36" alt="" /> +<p class="img-caption"><strong>Figure 3.</strong> Email's Action Bar, with the +application icon on the left.</p> + +<p>The normal behavior should be for your application to return to the "home" activity or the +initial state (such as when the activity hasn't changed, but fragments have changed) when the user +taps the icon. If the user is already at home or the initial state, then you don't need to do +anything.</p> + +<p>When the user taps the icon, the system calls your activity's {@link +android.app.Activity#onOptionsItemSelected onOptionsItemSelected()} method with the {@code +android.R.id.home} ID. So, you need to add a condition to your {@link +android.app.Activity#onOptionsItemSelected onOptionsItemSelected()} method to listen for {@code +android.R.id.home} and perform the appropriate action, such as start the home activity or pop recent +fragment transactions off the stack.</p> + +<p>If you respond to the application icon by returning to the home activity, you should include +the {@link android.content.Intent#FLAG_ACTIVITY_CLEAR_TOP} flag in the {@link +android.content.Intent}. With this flag, if the activity you're starting already exists in the +current task, then all activities on top of it are destroyed and it is brought to the front. +You should favor this approach, because going "home" is an action that's equivalent to "going +back" and you should usually not create a new instance of the home activity. Otherwise, you +might end up with a long stack of activities in the current task.</p> + +<p>For example, here's an implementation of {@link android.app.Activity#onOptionsItemSelected +onOptionsItemSelected()} that returns to the application's "home" activity:</p> + +<pre> +@Override +public boolean onOptionsItemSelected(MenuItem item) { + switch (item.getItemId()) { + case android.R.id.home: + // app icon in Action Bar clicked; go home + Intent intent = new Intent(this, HomeActivity.class); + intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); + startActivity(intent); + return true; + default: + return super.onOptionsItemSelected(item); + } +} +</pre> + + + + +<h4>Using the app icon to navigate "up"</h4> + +<div class="figure" style="width:144px"> + <img src="{@docRoot}images/ui/actionbar-logo.png" height="140" alt="" /> + <p class="img-caption"><strong>Figure 4.</strong> The standard icon for the Email application +(top) and the "up" icon (bottom).</p> +</div> + +<p>You can also use the application icon to provide "up" navigation for the user. This is especially +useful when your application is composed of activities that generally appear in a certain order and +you want to facilitate the ability for the user to navigate up the activity hierarchy +(regardless of how they entered the current activity).</p> + +<p>The way you respond to this event is the same as when navigating home (as +discussed above, except you start a different activity, based on the current activity). All you +need to do to indicate to the user that the behavior is different is set the Action Bar to "show +home as up." You can do so by calling {@link android.app.ActionBar#setDisplayHomeAsUpEnabled +setDisplayHomeAsUpEnabled(true)} on your activity's {@link android.app.ActionBar}. When you do, the +system draws your application icon with an arrow indicating the up behavior, as shown in figure +4.</p> + +<p>For example, here's how you can show the application icon as an "up" action:</p> + +<pre> +@Override +protected void onStart() { + super.onStart(); + ActionBar actionBar = this.getActionBar(); + actionBar.setDisplayHomeAsUpEnabled(true); +} +</pre> + +<p>Then, your activity should respond to the user tapping the icon, from the {@link +android.app.Activity#onOptionsItemSelected +onOptionsItemSelected()}, by listening for the {@code android.R.id.home} ID (as shown above). In +this case, when navigating up, it's even more important that you use the {@link +android.content.Intent#FLAG_ACTIVITY_CLEAR_TOP} flag in the {@link android.content.Intent}, so that +you don't create a new instance of the parent activity if one already exists.</p> + + + + +<h2 id="ActionView">Adding an Action View</h2> + +<div class="figure" style="width:429px"> + <img src="{@docRoot}images/ui/actionbar-actionview.png" alt="" /> + <p class="img-caption"><strong>Figure 5.</strong> An action view with a {@link +android.widget.SearchView} widget.</p> +</div> + +<p>An action view is a widget that appears in the Action Bar as a substitute for an action +item. For example, if you have an item in the Options Menu for "Search", you can add an action view +for the item that provides a {@link android.widget.SearchView} widget in the Action Bar whenever +the item is enabled as an action item.</p> + +<p>When adding an action view for a menu item, it's important that you still allow the item to +behave as a normal menu item when it does not appear in the Action Bar. For example, a menu item to +perform a search should, by default, bring up the <a +href="{@docRoot}guide/topics/search/search-dialog.html">search dialog</a>, but if the item is +placed in the Action Bar, the action view appears with a {@link android.widget.SearchView} +widget. Figure 4 shows an example of the {@link android.widget.SearchView} widget in an action +view.</p> + +<p>The best way to declare an action view for an item is in your <a +href="{@docRoot}guide/topics/resources/menu-resource.html">menu resource</a>, using the {@code +android:actionLayout} or {@code android:actionViewClass} attribute:</p> + +<ul> + <li>The value for {@code android:actionLayout} must be a resource pointer to a layout file. +For example: +<pre> +<?xml version="1.0" encoding="utf-8"?> +<menu xmlns:android="http://schemas.android.com/apk/res/android"> + <item android:id="@+id/menu_search" + android:title="Search" + android:icon="@drawable/ic_menu_search" + android:showAsAction="ifRoom" + <b>android:actionLayout="@layout/searchview"</b> /> +</menu> +</pre> +</li> + + <li>The value for {@code android:actionViewClass} must be a fully-qualified class name for +the {@link android.view.View} you want to use. For example: +<pre> +<?xml version="1.0" encoding="utf-8"?> +<menu xmlns:android="http://schemas.android.com/apk/res/android"> + <item android:id="@+id/menu_search" + android:title="Search" + android:icon="@drawable/ic_menu_search" + android:showAsAction="ifRoom" + <b>android:actionViewClass="android.widget.SearchView"</b> /> +</menu> +</pre></li> +</ul> + +<p class="note">You must include {@code android:showAsAction="ifRoom"} in order for the item to +appear as an action view when room is available. If necessary, however, you can force the item to +always appear as an action view by setting {@code android:showAsAction} to {@code "always"}.</p> + +<p>Now, when the menu item is displayed as an action item, it's action view appears instead of +the icon and/or title text. However, if there's not enough room in the Action Bar, the item appears +in the overflow menu as a normal menu item and you must respond to it from the {@link +android.app.Activity#onOptionsItemSelected onOptionsItemSelected()} callback method. (For a +guide to providing search functionality, see the <a +href="{@docRoot}gudie/topics/search/index.html">Search</a> documentation.)</p> + +<p>When the activity first starts, the system populates the Action Bar and overflow menu by calling +{@link android.app.Activity#onCreateOptionsMenu onCreateOptionsMenu()}. +After you've inflated your menu in this method, you can acquire elements in an action view +(perhaps in order to attach listeners) by calling {@link android.view.Menu#findItem +findItem()} with the ID of the menu item, then {@link android.view.MenuItem#getActionView} on +the returned {@link android.view.MenuItem}. For example, the search widget from the above samples is +acquired like this:</p> + +<pre> +@Override +public boolean onCreateOptionsMenu(Menu menu) { + getMenuInflater().inflate(R.menu.options, menu); + SearchView searchView = (SearchView) menu.findItem(R.id.menu_search).getActionView(); + // Set appropriate listeners for searchView + ... + return super.onCreateOptionsMenu(menu); +} +</pre> + +<p>For more information about enabling search in the Action Bar, see the <a +href="{@docRoot}guide/topics/search/index.html">Search</a> developer guide.</p> + + + + +<h2 id="Tabs">Adding Tabs</h2> + + +<div class="figure" style="width:504px"> + <img src="{@docRoot}images/ui/actionbar-tabs.png" alt="" /> + <p class="img-caption"><strong>Figure 6.</strong> Screenshot of tabs in the +Action Bar, from the <a +href="{@docRoot}resources/samples/Honeycomb-Gallery/index.html">Honeycomb Gallery</a> sample +application.</p> +</div> + +<p>The Action Bar can display tabs that allow the user navigate between different fragments in the +activity. Each tab can include a title and/or an icon.</p> + +<p>To begin, your layout must include a {@link android.view.View} in which each {@link +android.app.Fragment} associated with a tab is displayed. Be sure the view has an ID that you +can use to reference it from your code.</p> + +<p>To add tabs to the Action Bar:</p> +<ol> + <li>Create an implementation of {@link android.app.ActionBar.TabListener} to handle the +interaction events on the Action Bar tabs. You must implement all methods: {@link +android.app.ActionBar.TabListener#onTabSelected onTabSelected()}, {@link +android.app.ActionBar.TabListener#onTabUnselected onTabUnselected()}, and {@link +android.app.ActionBar.TabListener#onTabReselected onTabReselected()}. + <p>Each callback method passes the {@link android.app.ActionBar.Tab} that received the +event and a {@link android.app.FragmentTransaction} for you to perform the fragment +transactions (add or remove fragments).</p> + <p>For example:</p> +<pre> +private class MyTabListener implements ActionBar.TabListener { + private TabContentFragment mFragment; + + // Called to create an instance of the listener when adding a new tab + public TabListener(TabContentFragment fragment) { + mFragment = fragment; + } + + @Override + public void onTabSelected(Tab tab, FragmentTransaction ft) { + ft.add(R.id.fragment_content, mFragment, null); + } + + @Override + public void onTabUnselected(Tab tab, FragmentTransaction ft) { + ft.remove(mFragment); + } + + @Override + public void onTabReselected(Tab tab, FragmentTransaction ft) { + // do nothing + } + +} +</pre> + <p>This implementation of {@link android.app.ActionBar.TabListener} adds a constructor +that saves the {@link android.app.Fragment} associated with a tab so that each callback +can add or remove that fragment.</p> + </li> + <li>Get the {@link android.app.ActionBar} for your activity by calling {@link +android.app.Activity#getActionBar} from your {@link android.app.Activity}, during {@link +android.app.Activity#onCreate onCreate()} (but be sure you do so <em>after</em> you've called +{@link android.app.Activity#setContentView setContentView()}).</li> + <li>Call {@link android.app.ActionBar#setNavigationMode(int) +setNavigationMode(NAVIGATION_MODE_TABS)} to enable tab mode for the {@link +android.app.ActionBar}.</li> + <li>Create each tab for the Action Bar: + <ol> + <li>Create a new {@link android.app.ActionBar.Tab} by calling {@link +android.app.ActionBar#newTab()} on the {@link android.app.ActionBar}.</li> + <li>Add title text and/or an icon for the tab by calling {@link +android.app.ActionBar.Tab#setText setText()} and/or {@link android.app.ActionBar.Tab#setIcon +setIcon()}. + <p class="note"><strong>Tip:</strong> These methods return the same {@link +android.app.ActionBar.Tab} instance, so you can chain the calls together.</p></li> + <li>Declare the {@link android.app.ActionBar.TabListener} to use for the tab by passing an +instance of your implementation to {@link android.app.ActionBar.Tab#setTabListener +setTabListener()}. + </ol> + </li> + <li>Add each {@link android.app.ActionBar.Tab} to the Action Bar by calling {@link +android.app.ActionBar#addTab addTab()} on the {@link android.app.ActionBar} and passing the +{@link android.app.ActionBar.Tab}.</li> +</ol> +<p>For example, the following code combines steps 2 - 5 to create two tabs and add them to +the Action Bar:</p> +<pre> +@Override +protected void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + setContentView(R.layout.main); + + // setup Action Bar for tabs + final ActionBar actionBar = getActionBar(); + actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS); + // remove the activity title to make space for tabs + actionBar.setDisplayShowTitleEnabled(false); + + // instantiate fragment for the tab + Fragment artistsFragment = new ArtistsFragment(); + // add a new tab and set its title text and tab listener + actionBar.addTab(actionBar.newTab().setText(R.string.tab_artists) + .setTabListener(new TabListener(artistsFragment))); + + Fragment albumsFragment = new AlbumsFragment(); + actionBar.addTab(actionBar.newTab().setText(R.string.tab_albums) + .setTabListener(new TabListener(albumsFragment))); +} +</pre> + +<p>All the behaviors that occur when a tab is selected must be defined by your {@link +android.app.ActionBar.TabListener} callback methods. When a tab is selected, it receives a call to +{@link android.app.ActionBar.TabListener#onTabSelected onTabSelected()} and that's where you should +add the appropriate fragment to the designated view in your layout, using {@link +android.app.FragmentTransaction#add add()} with the provided {@link +android.app.FragmentTransaction}. Likewise, when a tab is deselected (because another tab becomes +selected), you should remove that fragment from the layout, using {@link +android.app.FragmentTransaction#remove remove()}.</p> + +<p class="caution"><strong>Caution:</strong> You <strong>must not</strong> call {@link +android.app.FragmentTransaction#commit} for these transactions—the system calls it for you +and it may throw an exception if you call it yourself. You also <strong>cannot</strong> add these +fragment transactions to the back stack.</p> + +<p>If your activity is stopped, you should retain the currently selected tab with the saved state so +that when the user returns to your application, you can open the tab. When it's time to save the +state, you can query the currently selected tab with {@link +android.app.ActionBar#getSelectedNavigationIndex()}. This returns the index position of the selected +tab.</p> + +<p class="caution"><strong>Caution:</strong> It's important that you save +the state of each fragment as necessary, so when the user switches fragments with the tabs, +then returns to a previous fragment, it appears the way they left. For information about saving +the state of your fragment, see the <a +href="{@docRoot}guide/topics/fundamentals/fragments.html">Fragments</a> developer guide.</p> + + + + +<h2 id="Dropdown">Adding Drop-down Navigation</h2> + +<p>As another mode of navigation within your activity, you can provide a drop-down list in the +Action Bar. For example, the drop-down list can provide alternative modes for sorting the content in +the activity or switching the user's account.</p> + +<!-- +<div class="figure" style="width:135px"> + <img src="{@docRoot}images/ui/actionbar-dropdown.png" alt="" /> + <p class="img-caption"><strong>Figure 5.</strong> Screenshot of a drop-down navigation list in the +Action Bar.</p> +</div> +--> + +<p>Here's a quick list of steps to enable drop-down navigation:</p> + +<ol> + <li>Create a {@link android.widget.SpinnerAdapter} that provides the +list of selectable items for the drop-down and the layout to use when drawing each item in the +list.</li> + <li>Implement {@link android.app.ActionBar.OnNavigationListener} to define the behavior when the +user selects an item from the list.</li> + <li>Enable navigation mode for the Action Bar with {@link +android.app.ActionBar#setNavigationMode setNavigationMode()}. For example: +<pre> +ActionBar actionBar = getActionBar(); +actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_LIST); +</pre> + <p class="note"><strong>Note:</strong> You should perform this during your activity's {@link +android.app.Activity#onCreate +onCreate()} method.</p> + </li> + <li>Then, set the callback for the drop-down list with {@link +android.app.ActionBar#setListNavigationCallbacks setListNavigationCallbacks()}. For example: +<pre> +actionBar.setListNavigationCallbacks(mSpinnerAdapter, mNavigationCallback); +</pre> +<p>This method takes your {@link android.widget.SpinnerAdapter} and {@link +android.app.ActionBar.OnNavigationListener}. More about these next.</p> +</li> +</ol> + +<p>That's the basic setup. However, implementing the {@link android.widget.SpinnerAdapter} and +{@link android.app.ActionBar.OnNavigationListener} is where most of the work is done. There are many +ways you can implement these to define the functionality for your drop-down navigation and +implementing various types of {@link android.widget.SpinnerAdapter} is beyond the scope of this +document (you should refer to the {@link android.widget.SpinnerAdapter} class reference for more +information). However, below is a simple example for a {@link android.widget.SpinnerAdapter} and +{@link android.app.ActionBar.OnNavigationListener} to get you started (click the title to +reveal the sample).</p> + + + +<div class="toggle-content closed"> + + <h3 id="Spinner"><a href="#" onclick="return toggleContent(this)"> + <img src="{@docRoot}assets/images/triangle-closed.png" class="toggle-content-img" alt="" /> + Example SpinnerAdapter and OnNavigationListener + </a></h3> + + <div class="toggle-content-toggleme"> + +<p>{@link android.widget.SpinnerAdapter} is an adapter that provides data for a spinner widget, +such as the drop-down list in the Action Bar. {@link android.widget.SpinnerAdapter} is an interface +that you can implement, but Android includes some useful implementations that you can extend, such +as {@link android.widget.ArrayAdapter} and {@link +android.widget.SimpleCursorAdapter}. For example, here's an easy way to create a {@link +android.widget.SpinnerAdapter} by using {@link android.widget.ArrayAdapter} implementation, which +uses a string array as the data source:</p> + +<pre> +SpinnerAdapter mSpinnerAdapter = ArrayAdapter.createFromResource(this, R.array.action_list, + android.R.layout.simple_spinner_dropdown_item); +</pre> + +<p>The {@link android.widget.ArrayAdapter#createFromResource createFromResource()} method takes +three parameters: the application {@link android.content.Context}, the resource ID for the string +array, and the layout to use for each list item.</p> + +<p>A <a href="{@docRoot}guide/topics/resources/string-resource.html#StringArray">string array</a> +defined in a resource looks like this:</p> + +<pre> +<?xml version="1.0" encoding="utf-8"?> +<resources> + <string-array name="action_list"> + <item>Mercury</item> + <item>Venus</item> + <item>Earth</item> + </string-array> +</pre> +</pre> + +<p>The {@link android.widget.ArrayAdapter} returned by {@link +android.widget.ArrayAdapter#createFromResource createFromResource()} is complete and ready for you +to pass it to {@link android.app.ActionBar#setListNavigationCallbacks setListNavigationCallbacks()} +(in step 4 from above). Before you do, though, you need to create the {@link +android.app.ActionBar.OnNavigationListener OnNavigationListener}.</p> + + +<p>Your implementation of {@link android.app.ActionBar.OnNavigationListener} is where you handle +fragment changes or other modifications to your activity when the user selects an item from the +drop-down list. There's only one callback method to implement in the listener: {@link +android.app.ActionBar.OnNavigationListener#onNavigationItemSelected onNavigationItemSelected()}.</p> + +<p>The {@link +android.app.ActionBar.OnNavigationListener#onNavigationItemSelected onNavigationItemSelected()} +method receives the position of the item in the list and a unique item ID provided by the {@link +android.widget.SpinnerAdapter}.</p> + +<p>Here's an example that instantiates an anonymous implementation of {@link +android.app.ActionBar.OnNavigationListener OnNavigationListener}, which inserts a {@link +android.app.Fragment} into the +layout container identified by {@code R.id.fragment_container}:</p> + +<pre> +mOnNavigationListener = new OnNavigationListener() { + // Get the same strings provided for the drop-down's ArrayAdapter + String[] strings = getResources().getStringArray(R.array.action_list); + + @Override + public boolean onNavigationItemSelected(int position, long itemId) { + // Create new fragment from our own Fragment class + ListContentFragment newFragment = new ListContentFragment(); + FragmentTransaction ft = openFragmentTransaction(); + // Replace whatever is in the fragment container with this fragment + // and give the fragment a tag name equal to the string at the position selected + ft.replace(R.id.fragment_container, newFragment, strings[position]); + // Apply changes + ft.commit(); + return true; + } +}; +</pre> + +<p>This instance of {@link android.app.ActionBar.OnNavigationListener OnNavigationListener} is +complete and you can now call {@link android.app.ActionBar#setListNavigationCallbacks +setListNavigationCallbacks()} (in step 4), passing the {@link android.widget.ArrayAdapter} and this +{@link android.app.ActionBar.OnNavigationListener OnNavigationListener}.</p> + +<p>In this example, when the user selects an item from the drop-down list, a fragment is added to +the layout (replacing the current fragment in the {@code R.id.fragment_container} view). The +fragment added is given a tag that uniquely identifies it, which is the same string used to +identify the fragment in the drop-down list.</p> + +<p>Here's a look at the {@code ListContentFragment} class that defines each fragment in this +example:</p> + +<pre> +public class ListContentFragment extends Fragment { + private String mText; + + @Override + public void onAttach(Activity activity) { + // This is the first callback received; here we can set the text for + // the fragment as defined by the tag specified during the fragment transaction + super.onAttach(activity); + mText = getTag(); + } + + @Override + public View onCreateView(LayoutInflater inflater, ViewGroup container, + Bundle savedInstanceState) { + // This is called to define the layout for the fragment; + // we just create a TextView and set its text to be the fragment tag + TextView text = new TextView(getActivity()); + text.setText(mText); + return text; + } +} +</pre> + + </div><!-- end toggle-content-toggleme --> + +</div><!-- end toggle-content --> + + + + + +<h2 id="Style">Styling the Action Bar</h2> + +<p>The Action Bar is the heading for your application and a primary interaction point for users, +so you might want to modify some of its design in order to make it feel more integrated with your +application design. There are several ways you can do this if you wish.</p> + +<p>For simple modifications to the {@link android.app.ActionBar}, you can use the following +methods:</p> + +<dl> + <dt>{@link android.app.ActionBar#setBackgroundDrawable setBackgroundDrawable()}</dt> + <dd>Sets a drawable to use as the Action Bar's background. The drawable should be a <a +href="{@docRoot}guide/topics/graphics/2d-graphics.html#nine-patch">Nine-patch</a> image, a <a +href="{@docRoot}guide/topics/resources/drawable-resource.html#Shape">shape</a>, or a <a +href="{@docRoot}guide/topics/resources/more-resources.html#Color">solid color</a>, so the system can +resize the drawable based on the size of the Action Bar (you should <em>not</em> use a fixed-size +bitmap image).</dd> + + <dt>{@link android.app.ActionBar#setDisplayUseLogoEnabled setDisplayUseLogoEnabled()}</dt> + <dd>Enables the use of an alternative image (a "logo") in the Action Bar, instead of the default +application icon. A logo is often a wider, more detailed image that represents the application. +When this is enabled, the system uses the logo image defined for the application (or the +individual activity) in the manifest file, with the <a +href="{@docRoot}guide/topics/manifest/application-element.html#logo">{@code android:logo}</a> +attribute. The logo will be resized as necessary to fit the height of the Action Bar. (Best +practice is to design the logo at the same size as your application icon.)</dd> +</dl> + + +<p>For more complex customizations, you can use Android's <a +href="{@docRoot}guide/topics/ui/themes.html">style and theme</a> framework to restyle your Action +Bar in several ways.</p> + +<p>The Action Bar has two standard themes, "dark" and "light". The dark theme is applied with +the default holographic theme, as specified by the {@link android.R.style#Theme_Holo Theme.Holo} +theme. If you want a white background with dark text, instead, you can apply the {@link +android.R.style#Theme_Holo_Light Theme.Holo.Light} theme to the activity in the manifest file. For +example:</p> + +<pre> +<activity android:name=".ExampleActivity" + android:theme="@android:style/Theme.Holo.Light" /> +</pre> + +<p>For more control, you can override either the {@link android.R.style#Theme_Holo +Theme.Holo} or {@link android.R.style#Theme_Holo_Light Theme.Holo.Light} theme and apply custom +styles to certain aspects of the Action Bar. Some of the Action Bar properties you can customize +include the following:</p> + +<dl> + <dt>{@link android.R.styleable#Theme_actionBarTabStyle + android:actionBarTabStyle}</dt> + <dd>Style for tabs in the Action Bar.</dd> + + <dt>{@link android.R.styleable#Theme_actionBarTabBarStyle + android:actionBarTabBarStyle}</dt> + <dd>Style for the bar that appears below tabs in the Action Bar.</dd> + + <dt>{@link android.R.styleable#Theme_actionBarTabTextStyle + android:actionBarTabTextStyle}</dt> + <dd>Style for the text in the tabs.</dd> + + <dt>{@link android.R.styleable#Theme_actionDropDownStyle + android:actionDropDownStyle}</dt> + <dd>Style for the drop-down list used for the overflow menu and drop-down navigation.</dd> + + <dt>{@link android.R.styleable#Theme_actionButtonStyle + android:actionButtonStyle}</dt> + <dd>Style for the background image used for buttons in the Action Bar.</dd> + +</dl> + +<p>For example, here's a resource file that defines a custom theme for the Action Bar, based on +the standard {@link android.R.style#Theme_Holo Theme.Holo} theme:</p> + +<pre> +<?xml version="1.0" encoding="utf-8"?> +<resources> + <!-- the theme applied to the application or activity --> + <style name="CustomActionBar" parent="android:style/Theme.Holo.Light"> + <item name="android:actionBarTabTextStyle">@style/customActionBarTabTextStyle</item> + <item name="android:actionBarTabStyle">@style/customActionBarTabStyle</item> + <item name="android:actionBarTabBarStyle">@style/customActionBarTabBarStyle</item> + </style> + + <!-- style for the tab text --> + <style name="customActionBarTabTextStyle"> + <item name="android:textColor">#2966c2</item> + <item name="android:textSize">20sp</item> + <item name="android:typeface">sans</item> + </style> + + <!-- style for the tabs --> + <style name="customActionBarTabStyle"> + <item name="android:background">@drawable/actionbar_tab_bg</item> + <item name="android:paddingLeft">20dp</item> + <item name="android:paddingRight">20dp</item> + </style> + + <!-- style for the tab bar --> + <style name="customActionBarTabBarStyle"> + <item name="android:background">@drawable/actionbar_tab_bar</item> + </style> +</resources> +</pre> + +<p class="note"><strong>Note:</strong> In order for the tab background image to change, +depending on the current tab state (selected, pressed, unselected), the drawable resource used +must be a <a href="{@docRoot}guide/topics/resources/drawable-resource.html#StateList">state +list drawable</a>. Also be certain that your theme declares a parent theme, from which it +inherits all styles not explicitly declared in your theme.</p> + +<p>You can apply your custom theme to the entire application or to individual activities in your +manifest file, like this:</p> + +<pre> +<application android:theme="@style/CustomActionBar" + ... /> +</pre> + +<p>Additionally, if you want to create a custom theme for your activity that removes the Action +Bar completely, use the following style attributes:</p> + +<dl> + <dt>{@link android.R.styleable#Theme_windowActionBar + android:windowActionBar}</dt> + <dd>Set this style property {@code false} to remove the Action Bar.</dd> + + <dt>{@link android.R.styleable#Theme_windowNoTitle + android:windowNoTitle}</dt> + <dd>Set this style property {@code true} to also remove the traditional title bar.</dd> +</dl> + +<p>For more information about using themes in your application, read <a +href="{@docRoot}guide/topics/ui/themes.html">Applying Styles and Themes</a>.</p> + + + + diff --git a/docs/html/guide/topics/ui/declaring-layout.jd b/docs/html/guide/topics/ui/declaring-layout.jd index f95a89b..c348767 100644 --- a/docs/html/guide/topics/ui/declaring-layout.jd +++ b/docs/html/guide/topics/ui/declaring-layout.jd @@ -47,11 +47,11 @@ application can create View and ViewGroup objects (and manipulate their properti Plugin for Eclipse</a> offers a layout preview of your XML — with the XML file opened, select the <strong>Layout</strong> tab.</li> <li>You should also try the - <a href="{@docRoot}guide/developing/tools/hierarchy-viewer.html">Hierarchy Viewer</a> tool, + <a href="{@docRoot}guide/developing/debugging/debugging-ui.html#hierarchyViewer">Hierarchy Viewer</a> tool, for debugging layouts — it reveals layout property values, draws wireframes with padding/margin indicators, and full rendered views while you debug on the emulator or device.</li> - <li>The <a href="{@docRoot}guide/developing/tools/layoutopt.html">layoutopt</a> tool lets + <li>The <a href="{@docRoot}guide/developing/debugging/debugging-ui.html#layoutopt">layoutopt</a> tool lets you quickly analyze your layouts and hierarchies for inefficiencies or other problems.</li> </div> </div> @@ -119,7 +119,7 @@ for your Activity like so:</p> <pre> public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); - setContentView.(R.layout.main_layout); + setContentView(R.layout.main_layout); } </pre> @@ -190,10 +190,12 @@ layout parameters for the View that are appropriate for the ViewGroup in which i <p>Every ViewGroup class implements a nested class that extends {@link android.view.ViewGroup.LayoutParams}. This subclass contains property types that define the size and position for each child view, as -appropriate for the view group. As you can see in the figure below, the parent +appropriate for the view group. As you can see in figure 1, the parent view group defines layout parameters for each child view (including the child view group).</p> <img src="{@docRoot}images/layoutparams.png" alt="" height="300" align="center"/> +<p class="img-caption"><strong>Figure 1.</strong> Visualization of a view hierarchy with layout +parameters associated with each view.</p> <p>Note that every LayoutParams subclass has its own syntax for setting values. Each child element must define LayoutParams that are appropriate for its parent, diff --git a/docs/html/guide/topics/ui/dialogs.jd b/docs/html/guide/topics/ui/dialogs.jd index 1a997f9..d50e1cb 100644 --- a/docs/html/guide/topics/ui/dialogs.jd +++ b/docs/html/guide/topics/ui/dialogs.jd @@ -22,20 +22,32 @@ parent.link=index.html </li> <li><a href="#CustomDialog">Creating a Custom Dialog</a></li> </ol> - + <h2>Key classes</h2> <ol> <li>{@link android.app.Dialog}</li> + <li>{@link android.app.AlertDialog}</li> + <li>{@link android.app.DialogFragment}</li> + </ol> + + <h2>Related tutorials</h2> + <ol> + <li><a href="{@docRoot}resources/tutorials/views/hello-datepicker.html">Hello +DatePicker</a></li> + <li><a href="{@docRoot}resources/tutorials/views/hello-timepicker.html">Hello +TimePicker</a></li> </ol> </div> </div> <p>A dialog is usually a small window that appears in front of the current Activity. -The underlying Activity loses focus and the dialog accepts all user interaction. -Dialogs are normally used -for notifications and short activities that directly relate to the application in progress.</p> +The underlying Activity loses focus and the dialog accepts all user interaction. Dialogs are +normally used for notifications that should interupt the user and to perform short tasks that +directly relate to the application in progress (such as a progress bar or a login prompt).</p> -<p>The Android API supports the following types of {@link android.app.Dialog} objects:</p> +<p>The {@link android.app.Dialog} class is the base class for creating dialogs. However, you +typically should not instantiate a {@link android.app.Dialog} directly. Instead, you should use one +of the following subclasses:</p> <dl> <dt>{@link android.app.AlertDialog}</dt> <dd>A dialog that can manage zero, one, two, or three buttons, and/or a list of @@ -473,18 +485,25 @@ public class NotificationTest extends Activity { progressDialog = new ProgressDialog(NotificationTest.this); progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL); progressDialog.setMessage("Loading..."); - progressThread = new ProgressThread(handler); - progressThread.start(); return progressDialog; default: return null; } } + @Override + protected void onPrepareDialog(int id, Dialog dialog) { + switch(id) { + case PROGRESS_DIALOG: + progressDialog.setProgress(0); + progressThread = new ProgressThread(handler); + progressThread.start(); + } + // Define the Handler that receives messages from the thread and update the progress final Handler handler = new Handler() { public void handleMessage(Message msg) { - int total = msg.getData().getInt("total"); + int total = msg.arg1; progressDialog.setProgress(total); if (total >= 100){ dismissDialog(PROGRESS_DIALOG); @@ -515,9 +534,7 @@ public class NotificationTest extends Activity { Log.e("ERROR", "Thread Interrupted"); } Message msg = mHandler.obtainMessage(); - Bundle b = new Bundle(); - b.putInt("total", total); - msg.setData(b); + msg.arg1 = total; mHandler.sendMessage(msg); total++; } diff --git a/docs/html/guide/topics/ui/menus.jd b/docs/html/guide/topics/ui/menus.jd index 42790b6..d1c0ff8 100644 --- a/docs/html/guide/topics/ui/menus.jd +++ b/docs/html/guide/topics/ui/menus.jd @@ -36,6 +36,7 @@ parent.link=index.html <h2>See also</h2> <ol> + <li><a href="{@docRoot}guide/topics/ui/actionbar.html">Using the Action Bar</a></li> <li><a href="{@docRoot}guide/topics/resources/menu-resource.html">Menu Resource</a></li> </ol> </div> @@ -48,20 +49,9 @@ for you to provide application menus in your application.</p> <p>Android provides three types of application menus:</p> <dl> <dt><strong>Options Menu</strong></dt> - <dd>The primary menu for an Activity, which appears when the user presses - the device MENU key. Within the Options Menu are two groups: - <dl style="margin-top:1em"> - <dt><em>Icon Menu</em></dt> - <dd>The menu items visible at the bottom of the screen - at the press of the MENU key. It supports a maximum of six menu items. - These are the only menu items that support icons and the only menu items that <em>do not</em> support - checkboxes or radio buttons.</dd> - <dt><em>Expanded Menu</em></dt> - <dd>The vertical list of menu items exposed by the "More" menu item in the Icon Menu. - When the Icon Menu is full, the expanded menu is comprised of the sixth - menu item and the rest.</dd> - </dl> - </dd> + <dd>The primary collection of menu items for an Activity that is associated with the device MENU +key. To provide instant access to select menu items, you can place some items in the <a +href="{@docRoot}guide/topics/ui/actionbar.html">Action Bar</a>, if available.</dd> <dt><strong>Context Menu</strong></dt> <dd>A floating list of menu items that appears when the user performs a long-press on a View. </dd> @@ -74,7 +64,7 @@ Menu or a context menu. A submenu item cannot support a nested submenu. </dd> <h2 id="xml">Defining Menus</h2> -<p>Instead of instantiating {@link android.view.Menu} objects in your application code, you should +<p>Instead of instantiating a {@link android.view.Menu} in your application code, you should define a menu and all its items in an XML <a href="{@docRoot}guide/topics/resources/menu-resource.html">menu resource</a>, then inflate the menu resource (load it as a programmable object) in your application code. Defining your menus in XML is @@ -104,9 +94,9 @@ href="#groups">Menu groups</a>.</dd> <item android:id="@+id/new_game" android:icon="@drawable/ic_new_game" android:title="@string/new_game" /> - <item android:id="@+id/quit" - android:icon="@drawable/ic_quit" - android:title="@string/quit" /> + <item android:id="@+id/help" + android:icon="@drawable/ic_help" + android:title="@string/help" /> </menu> </pre> @@ -161,36 +151,64 @@ creating an option menu is discussed more in the next section.)</p> </div> -<p>The Options Menu is where you should include basic application functions -and necessary navigation items (for example, a button -to open application settings). The user -can open the Options Menu with the device MENU key. -Figure 1 shows a screenshot of an Options Menu.</p> +<p>The Options Menu is where you should include basic application functions and necessary navigation +items (for example, a button to open the application settings). Items in the Options Menu are +accessible in two distinct ways: in the Action Bar and in the menu revealed by the MENU +key.</p> + +<p>The Action Bar is an optional widget that appears at the top of the activity in place of the +title bar. It can display several menu items that you choose from the Options Menu, but items in +the Action Bar display only an icon (no title text). Users can reveal the other menu items in the +Options Menu with the MENU key.</p> -<p>When opened, the first visible portion of the Options Menu is called the Icon Menu. It -holds the first six menu items. -If you add more than six items to the Options Menu, Android places the sixth item and those after it -into the Expanded Menu, which the user can open with the "More" menu item.</p> +<p>If you include the Action Bar in your activity, the menu items that are not placed in the Action +Bar can appear in two different styles:</p> +<dl> + <dt>Action Bar Menu</dt> + <dd>If the device has an extra-large screen ({@code xlarge}), then all items in the Options Menu +that are not placed in the Action Bar are placed into a drop-down list at the right side of the +Action Bar, with icons and title text. The user can reveal the drop-down list by pressing the +drop-down icon in the Action Bar or the MENU key.</dd> + <dt>Standard Options Menu</dt> + <dd>If the device <em>does not</em> have an extra-large screen, then all items in the Options +Menu that are not placed in the Action Bar are placed into the Standard Options Menu at the bottom +of the activity. The user can reveal the standard Options Menu by pressing the MENU key. + <p>The first visible portion of the Standard Options Menu is called the Icon Menu. +It holds the first six menu items (excluding any added to the Action Bar), with icons and title +text. If there are more than six items, Android adds a "More" item as the sixth menu item and places +the remaining items into the Expanded Menu, which the user can open by selecting "More". The +Expanded Menu displays menu items only by their title text (no icon)</p> + </dd> +</dl> <p>When the user opens the Options Menu for the first time, Android calls your Activity's {@link android.app.Activity#onCreateOptionsMenu(Menu) onCreateOptionsMenu()} method. Override this method in your Activity and populate the {@link android.view.Menu} that is passed into the method. Populate the {@link android.view.Menu} by inflating a menu resource as described in <a -href="#Inflating">Inflating a Menu Resource</a>. (You can -also populate the menu in code, using {@link android.view.Menu#add(int,int,int,int) -add()} to add menu items.)</p> +href="#Inflating">Inflating a Menu Resource</a>. For example:</p> -<p>When the user selects a menu item from the Options Menu, the system calls your Activity's +<pre> +@Override +public boolean onCreateOptionsMenu(Menu menu) { + MenuInflater inflater = getMenuInflater(); + inflater.inflate(R.menu.game_menu, menu); + return true; +} +</pre> + +<p>(You can also populate the menu in code, using {@link android.view.Menu#add(int,int,int,int) +add()} to add items to the {@link android.view.Menu}.)</p> + +<p>When the user selects a menu item from the Options Menu (including items selected from the +Action Bar), the system calls your Activity's {@link android.app.Activity#onOptionsItemSelected(MenuItem) onOptionsItemSelected()} method. This method passes the {@link android.view.MenuItem} that the user selected. You can identify the menu item by calling {@link android.view.MenuItem#getItemId()}, which returns the unique ID for the menu item (defined by the {@code android:id} attribute in the menu resource or with an integer passed to the {@link android.view.Menu#add(int,int,int,int) add()} method). You can match this ID -against known menu items and perform the appropriate action.</p> - -<p>For example:</p> +against known menu items and perform the appropriate action. For example:</p> <pre> @Override @@ -200,8 +218,8 @@ public boolean onOptionsItemSelected(MenuItem item) { case R.id.new_game: newGame(); return true; - case R.id.quit: - quit(); + case R.id.help: + showHelp(); return true; default: return super.onOptionsItemSelected(item); @@ -224,8 +242,8 @@ an Activity that implements nothing except the {@link android.app.Activity#onCre onCreateOptionsMenu()} and {@link android.app.Activity#onOptionsItemSelected(MenuItem) onOptionsItemSelected()} methods. Then extend this class for each Activity that should share the same Options Menu. This way, you have to manage only one set of code for handling menu -actions and each decendent class inherits the menu behaviors.<br/><br/> -If you want to add menu items to one of your decendent activities, +actions and each descendant class inherits the menu behaviors.<br/><br/> +If you want to add menu items to one of your descendant activities, override {@link android.app.Activity#onCreateOptionsMenu(Menu) onCreateOptionsMenu()} in that Activity. Call {@code super.onCreateOptionsMenu(menu)} so the original menu items are created, then add new menu items with {@link @@ -542,7 +560,7 @@ hardware keyboard. Shortcuts cannot be added to items in a Context Menu.</p> <h3 id="intents">Intents for menu items</h3> <p>Sometimes you'll want a menu item to launch an Activity using an Intent (whether it's an -Actvitity in your application or another application). When you know the Intent you want to use and +Activity in your application or another application). When you know the Intent you want to use and have a specific menu item that should initiate the Intent, you can execute the Intent with {@link android.app.Activity#startActivity(Intent) startActivity()} during the appropriate on-item-selected callback method (such as the {@link android.app.Activity#onOptionsItemSelected(MenuItem) diff --git a/docs/html/guide/tutorials/hello-world.jd b/docs/html/guide/tutorials/hello-world.jd index 6e315b2..11e6497 100644 --- a/docs/html/guide/tutorials/hello-world.jd +++ b/docs/html/guide/tutorials/hello-world.jd @@ -23,9 +23,11 @@ It's particularly easy if you're using Eclipse as your IDE, because we've provid great plugin that handles your project creation and management to greatly speed-up your development cycles.</p> -<p>If you're not using Eclipse, that's okay. Familiarize yourself with -<a href="{@docRoot}guide/developing/other-ide.html">Developing in Other IDEs</a>. -You can then return to this tutorial and ignore anything about Eclipse.</p> +<p>If you are not using Eclipse, the tools provided by the Android SDK are accessible +on the command line, so you can choose your IDE or text editor. +For more information about developing with the Android SDK tools, see +the <a href="{@docRoot}guide/developing/index.html">Overview</a> +section for developing on Android.</p> <p>Before you start, you should already have the very latest SDK installed, and if you're using Eclipse, you should have installed the ADT plugin as well. If you have not installed these, see @@ -562,5 +564,6 @@ android create project \ <p>This creates the required folders and files for the project at the location defined by the <em>path</em>.</p> - <p>For more information on how to use the SDK tools to create and build projects, please read -<a href="{@docRoot}guide/developing/other-ide.html">Developing in Other IDEs</a>.</p> + <p>For more information on how to use the SDK tools to create and build projects on the command line, read +<a href="{@docRoot}guide/developing/projects/index.html">Creating and Managing Projects on the Command Line</a> and +<a href="{@docRoot}guide/developing/building/building-cmdline.html">Building and Running Apps on the Command Line</a>.</p> diff --git a/docs/html/guide/tutorials/notepad/notepad-ex2.jd b/docs/html/guide/tutorials/notepad/notepad-ex2.jd index a945a62..854731f 100644 --- a/docs/html/guide/tutorials/notepad/notepad-ex2.jd +++ b/docs/html/guide/tutorials/notepad/notepad-ex2.jd @@ -87,8 +87,8 @@ Open the Notepadv2 class.</p> menu callback used for the options menu. Here, we add just one line, which will add a menu item to delete a note. Call <code>menu.add()</code> like so: <pre> -public boolean onCreateContextMenu(Menu menu, View v - ContextMenuInfo menuInfo) { +public void onCreateContextMenu(Menu menu, View v, + ContextMenu.ContextMenuInfo menuInfo) { super.onCreateContextMenu(menu, v, menuInfo); menu.add(0, DELETE_ID, 0, R.string.menu_delete); }</pre> diff --git a/docs/html/guide/tutorials/notepad/notepad-extra-credit.jd b/docs/html/guide/tutorials/notepad/notepad-extra-credit.jd index 0d59b56..34f7063 100644 --- a/docs/html/guide/tutorials/notepad/notepad-extra-credit.jd +++ b/docs/html/guide/tutorials/notepad/notepad-extra-credit.jd @@ -65,6 +65,6 @@ when.</p> <p>The Android Eclipse plugin not only offers excellent debugging support for your application development, but also superb profiling support. You can also -try using <a href="{@docRoot}guide/developing/tools/traceview.html">Traceview</a> to profile your application. If your application is running too slow, this can help you +try using <a href="{@docRoot}guide/developing/debugging/debugging-tracing.html">Traceview</a> to profile your application. If your application is running too slow, this can help you find the bottlenecks and fix them.</p> diff --git a/docs/html/guide/tutorials/views/hello-webview.jd b/docs/html/guide/tutorials/views/hello-webview.jd index c4388ea..a927b04 100644 --- a/docs/html/guide/tutorials/views/hello-webview.jd +++ b/docs/html/guide/tutorials/views/hello-webview.jd @@ -12,8 +12,8 @@ we'll create a simple Activity that can view web pages.</p> <pre> <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" - android:layout_width="wrap_content" - android:layout_height="wrap_content" + android:layout_width="fill_parent" + android:layout_height="fill_parent" android:orientation="vertical"> <WebView @@ -69,7 +69,7 @@ private class HelloWebViewClient extends WebViewClient { <li>Now, in the <code>onCreate()</code> method, set an instance of the <code>HelloWebViewClient</code> as our WebViewClient: - <pre>webview.setWebViewClient(new WebViewClientDemo());</pre> + <pre>webview.setWebViewClient(new HelloWebViewClient());</pre> <p>This line should immediately follow the initialization of our WebView object.</p> <p>What we've done is create a WebViewClient that will load any URL selected in our diff --git a/docs/html/guide/webapps/debugging.jd b/docs/html/guide/webapps/debugging.jd index ee4b723..c0dce48 100644 --- a/docs/html/guide/webapps/debugging.jd +++ b/docs/html/guide/webapps/debugging.jd @@ -18,7 +18,7 @@ messages</li> <h2>See also</h2> <ol> - <li><a href="{@docRoot}guide/developing/debug-tasks.html">Debugging Tasks</a></li> + <li><a href="{@docRoot}guide/developing/debugging/index.html">Debugging</a></li> </ol> </div> @@ -46,8 +46,8 @@ those written using JavaScript {@code console} APIs.</p> <strong>Device > Run logcat</strong>. When using the <a href="{@docRoot}sdk/eclipse-adt.html">ADT plugin for Eclipse</a>, you can also view logcat messages by opening the Logcat view, available from <strong>Window > Show View > Other > Android > Logcat</strong>.</p> - <p>See <a href="{@docRoot}guide/developing/debug-tasks.html">Debugging -Tasks</a> for more information about logcat.</p> + <p>See <a href="{@docRoot}guide/developing/debugging/debugging-log.html">Debugging</a> + for more information about <codelogcat</code>.</p> </div> </div> diff --git a/docs/html/images/activity_fragment_lifecycle.png b/docs/html/images/activity_fragment_lifecycle.png Binary files differnew file mode 100644 index 0000000..156aa40 --- /dev/null +++ b/docs/html/images/activity_fragment_lifecycle.png diff --git a/docs/html/images/avd-manager.png b/docs/html/images/avd-manager.png Binary files differnew file mode 100644 index 0000000..69ce972 --- /dev/null +++ b/docs/html/images/avd-manager.png diff --git a/docs/html/images/build-simplified.png b/docs/html/images/build-simplified.png Binary files differnew file mode 100644 index 0000000..73e3452 --- /dev/null +++ b/docs/html/images/build-simplified.png diff --git a/docs/html/images/build.png b/docs/html/images/build.png Binary files differnew file mode 100644 index 0000000..bf4cf4e --- /dev/null +++ b/docs/html/images/build.png diff --git a/docs/html/images/debug-ddms.png b/docs/html/images/debug-ddms.png Binary files differnew file mode 100644 index 0000000..d92fb3c --- /dev/null +++ b/docs/html/images/debug-ddms.png diff --git a/docs/html/images/debugging.png b/docs/html/images/debugging.png Binary files differnew file mode 100644 index 0000000..fd6a41a --- /dev/null +++ b/docs/html/images/debugging.png diff --git a/docs/html/images/fragment_lifecycle.png b/docs/html/images/fragment_lifecycle.png Binary files differnew file mode 100644 index 0000000..ce9d395 --- /dev/null +++ b/docs/html/images/fragment_lifecycle.png diff --git a/docs/html/images/fundamentals/diagram_backstack.png b/docs/html/images/fundamentals/diagram_backstack.png Binary files differnew file mode 100644 index 0000000..2c6e33f --- /dev/null +++ b/docs/html/images/fundamentals/diagram_backstack.png diff --git a/docs/html/images/fundamentals/diagram_backstack_singletask_multiactivity.png b/docs/html/images/fundamentals/diagram_backstack_singletask_multiactivity.png Binary files differnew file mode 100644 index 0000000..d6a21d7 --- /dev/null +++ b/docs/html/images/fundamentals/diagram_backstack_singletask_multiactivity.png diff --git a/docs/html/images/fundamentals/diagram_multiple_instances.png b/docs/html/images/fundamentals/diagram_multiple_instances.png Binary files differnew file mode 100644 index 0000000..380e7788 --- /dev/null +++ b/docs/html/images/fundamentals/diagram_multiple_instances.png diff --git a/docs/html/images/fundamentals/diagram_multitasking.png b/docs/html/images/fundamentals/diagram_multitasking.png Binary files differnew file mode 100644 index 0000000..b8c7b45 --- /dev/null +++ b/docs/html/images/fundamentals/diagram_multitasking.png diff --git a/docs/html/images/fundamentals/fragments.png b/docs/html/images/fundamentals/fragments.png Binary files differnew file mode 100644 index 0000000..b3b7b23 --- /dev/null +++ b/docs/html/images/fundamentals/fragments.png diff --git a/docs/html/images/fundamentals/restore_instance.png b/docs/html/images/fundamentals/restore_instance.png Binary files differnew file mode 100644 index 0000000..fa428a7 --- /dev/null +++ b/docs/html/images/fundamentals/restore_instance.png diff --git a/docs/html/images/fundamentals/service_binding_tree_lifecycle.png b/docs/html/images/fundamentals/service_binding_tree_lifecycle.png Binary files differnew file mode 100644 index 0000000..46d2df5 --- /dev/null +++ b/docs/html/images/fundamentals/service_binding_tree_lifecycle.png diff --git a/docs/html/images/preview_hc/actionbar.png b/docs/html/images/preview_hc/actionbar.png Binary files differnew file mode 100644 index 0000000..31df2b2 --- /dev/null +++ b/docs/html/images/preview_hc/actionbar.png diff --git a/docs/html/images/preview_hc/fragments_layout.png b/docs/html/images/preview_hc/fragments_layout.png Binary files differnew file mode 100644 index 0000000..91c8929 --- /dev/null +++ b/docs/html/images/preview_hc/fragments_layout.png diff --git a/docs/html/images/service_lifecycle.png b/docs/html/images/service_lifecycle.png Binary files differindex 0748db2..f9602f8 100644 --- a/docs/html/images/service_lifecycle.png +++ b/docs/html/images/service_lifecycle.png diff --git a/docs/html/images/ui/actionbar-actionview.png b/docs/html/images/ui/actionbar-actionview.png Binary files differnew file mode 100644 index 0000000..cc18f9b --- /dev/null +++ b/docs/html/images/ui/actionbar-actionview.png diff --git a/docs/html/images/ui/actionbar-item-withtext.png b/docs/html/images/ui/actionbar-item-withtext.png Binary files differnew file mode 100644 index 0000000..61742d3 --- /dev/null +++ b/docs/html/images/ui/actionbar-item-withtext.png diff --git a/docs/html/images/ui/actionbar-logo.png b/docs/html/images/ui/actionbar-logo.png Binary files differnew file mode 100644 index 0000000..df914bc --- /dev/null +++ b/docs/html/images/ui/actionbar-logo.png diff --git a/docs/html/images/ui/actionbar-tabs.png b/docs/html/images/ui/actionbar-tabs.png Binary files differnew file mode 100644 index 0000000..9d36db6 --- /dev/null +++ b/docs/html/images/ui/actionbar-tabs.png diff --git a/docs/html/images/ui/actionbar.png b/docs/html/images/ui/actionbar.png Binary files differnew file mode 100644 index 0000000..dcd8449 --- /dev/null +++ b/docs/html/images/ui/actionbar.png diff --git a/docs/html/offline.jd b/docs/html/offline.jd index fe70d50..1064a99 100644 --- a/docs/html/offline.jd +++ b/docs/html/offline.jd @@ -2,48 +2,59 @@ home=true page.title=Welcome @jd:body +<style type="text/css"> +#qv h2 { + font-size:1.5em; + font-weight:bold; + margin:12px 0 .5em 0; + padding:5px; + color:#7BB026; + border:none; +} +#qv ul li { + padding: 0 5px 1em 0; +} +</style> <div id="mainBodyFluid"> <h1>Welcome to the Android SDK!</h1> -<img src="{@docRoot}assets/images/home/sdk-large.png" style="float:right; margin:-2em 3em 3em;" /> - -<h3>If you've downloaded the Android SDK for the first time...</h3> +<div id="qv-wrapper"> +<div id="qv"> + <h2>Get Started</h2> + <ul> + <li>Create a <a href="{@docRoot}resources/tutorials/hello-world.html">Hello World</a> +application</li> + <li>Read <a href="{@docRoot}resources/browser.html?tag=sample">Sample Code</a>, +especially <a href="{@docRoot}resources/samples/ApiDemos/index.html">API Demos</a></li> + <li>Read the <a href="{@docRoot}guide/topics/fundamentals/index.html">Application +Fundamentals</a></li> + <li>Read the <a href="{@docRoot}guide/developing/index.html">Overview</a> for using the SDK +tools</li> + </ul> +</div> +</div> -<p>Follow the online guide to -<a href="{@docRoot}sdk/installing.html">Installing -the Android SDK</a>, which will help you setup your development environment -(including the Android Development Tools plugin for Eclipse) -so you can start developing Android apps.</p> +<h3>If you've downloaded the Android SDK for the first time</h3> -<p>Once your environment is setup, look at the -<a href="{@docRoot}sdk/installing.html#NextSteps">Next -Steps</a> for some suggestions on how to begin learning about Android.</p> +<p>Follow the guide to <a href="{@docRoot}sdk/installing.html">Installing the Android SDK</a>, which +will help you setup your development environment.</p> -<h3>If you've just installed new SDK components using the <em>SDK and AVD Manager</em>...</h3> +<h3>If you've installed new SDK components using the SDK and AVD Manager</h3> <p>There's no additional setup.</p> -<p>Newly installed Android platforms are automatically saved in the -<code><em><sdk_dir>/</em>platforms/</code> directory of your existing SDK; -new add-ons are saved in the <code><em><sdk_dir>/</em>add-ons/</code> -directory; and new documentation is saved in the existing -<code><em><sdk_dir>/</em>docs/</code> directory (old docs are replaced).</p> - +<p>New Android platforms are saved in the <code><sdk>/platforms/</code> directory of +your existing SDK and new add-ons are saved in the <code><sdk>/add-ons/</code> directory.</p> -<hr style="margin:2em 0;" /> -<p>Note that you are currently viewing a local, offline version of the -Android developer documentation. The offline documentation offers almost all the same -content and features as the online documentation. Because some features -such as search and videos are network-based, not everything will work if you -are not connected to the Internet.</p> +<div class="note"> +<p><strong>Note:</strong> You are currently viewing the offline version of the Android developer +documentation. Because some features such as search and videos are network-based, not everything +will work if you are not connected to the Internet. Additionally, the online version may contain +more recently updated documents.</p> -<p>For the most current documentation and a fully-functional experience, please visit:</p> -<p style="margin-left:2em;"> -<a href="http://developer.android.com">http://developer.android.com</a></strong>. +<p>For the latest documentation, please visit +<b><a href="http://developer.android.com">developer.android.com</a></b>. </p> - - - </div> diff --git a/docs/html/resources/articles/backward-compatibility.jd b/docs/html/resources/articles/backward-compatibility.jd index 4b1a34c..ad64dfc 100644 --- a/docs/html/resources/articles/backward-compatibility.jd +++ b/docs/html/resources/articles/backward-compatibility.jd @@ -245,6 +245,6 @@ emulator that uses an older version of the platform. The Android SDK allows you to do this easily by creating "Android Virtual Devices" with different API levels. Once you create the AVDs, you can test your application with old and new versions of the system, perhaps running them side-by-side to see the -differences. More information about emulator AVDs can be found <a -href="{@docRoot}guide/developing/tools/avd.html">in the AVD documentation</a> and +differences. More information about emulator AVDs can be found in <a +href="{@docRoot}guide/developing/devices/index.html">Creating and Managing Virtual Devices</a> and from <code>emulator -help-virtual-device</code>.</p>
\ No newline at end of file diff --git a/docs/html/resources/articles/layout-tricks-merge.jd b/docs/html/resources/articles/layout-tricks-merge.jd index 00e0479..95409e4 100644 --- a/docs/html/resources/articles/layout-tricks-merge.jd +++ b/docs/html/resources/articles/layout-tricks-merge.jd @@ -44,7 +44,7 @@ used to stack a {@link android.widget.TextView} on top of an <div style="text-align: center;"><img src="images/merge1.jpg" alt="A FrameLayout is used to overlay a title on top of an image"></div> <p>Things get more interesting when you inspect the result with <a -href="{@docRoot}guide/developing/tools/hierarchy-viewer.html">HierarchyViewer</a>. +href="{@docRoot}guide/developing/debugging/debugging-ui.html#hierarchyViewer">HierarchyViewer</a>. If you look closely at the resulting tree, you will notice that the <code>FrameLayout</code> defined in our XML file (highlighted in blue below) is the sole child of another <code>FrameLayout</code>:</p> diff --git a/docs/html/resources/browser.jd b/docs/html/resources/browser.jd new file mode 100644 index 0000000..8a08769 --- /dev/null +++ b/docs/html/resources/browser.jd @@ -0,0 +1,49 @@ +page.title=Technical Resources +@jd:body + +<style type="text/css"> + {@literal @import} "{@docRoot}assets/android-developer-resource-browser.css"; +</style> + +<script type="text/javascript" src="{@docRoot}assets/android-developer-resource-browser.js"></script> +<script type="text/javascript" src="{@docRoot}assets/microtemplate.js"></script> + +<div> + <p style="display: none; float: right">Filter: <input id="resource-browser-keyword-filter"/></p> + <p id="resource-browser-search-params">Showing all technical resources:</p> +</div> + +<noscript> + <p class="note"><strong>Error:</strong> + You must have JavaScript enabled to view this page. Resources are also + available offline in the SDK. + </p> +</noscript> + +<div id="resource-browser-results"> + <div class="no-results">No results.</div> +</div> + +<script type="text/html" id="tmpl_resource_browser_result"> +<div class="result"> + <h3> + <% if ('external' in tagsHash) { %><strong>External: </strong> <% } %> + <a href="<%= path %>"><%= title.en %></a> + <% if ('new' in tagsHash) { %><span class="new">new!</span> <% } %> + </h3> + <p class="resource-meta"><% + var __g = ['', '']; + if ('article' in tagsHash) { + __g = ['Article', 'about']; + } else if ('tutorial' in tagsHash) { + __g = ['Tutorial', 'on']; + } else if ('sample' in tagsHash) { + __g = ['Sample', 'for']; + } else if ('video' in tagsHash) { + __g = ['Video', 'about']; + } + %> + <%= __g[0] %><% if (topicsHtml) { %> <%= __g[1] %><% } %> <%= topicsHtml %></p> + <p><%= description.en %></p> +</div> +</script> diff --git a/docs/html/resources/faq/commontasks.jd b/docs/html/resources/faq/commontasks.jd index 1173725..807df08 100644 --- a/docs/html/resources/faq/commontasks.jd +++ b/docs/html/resources/faq/commontasks.jd @@ -97,7 +97,7 @@ want to look at the sample code included with the Android SDK, in the the device, are described below. The list of files you'll need for your application are described in <a href="#filelist">List of Files for an Android Application</a>. </li> - <li><strong><a href="{@docRoot}guide/developing/other-ide.html#buildingwithant">Build and install your + <li><strong><a href="{@docRoot}guide/developing/building/building-cmdline.html">Build and install your package</a>.</strong> The Android SDK has some nice tools for generating projects and debugging code. </li> </ol> diff --git a/docs/html/resources/faq/troubleshooting.jd b/docs/html/resources/faq/troubleshooting.jd index f3252b0..05a7dda 100644 --- a/docs/html/resources/faq/troubleshooting.jd +++ b/docs/html/resources/faq/troubleshooting.jd @@ -5,7 +5,8 @@ parent.link=index.html <p>Here are some tips and tricks for common Android errors. Don't forget to use the - ddms logcat capability to get a deeper view when errors occur. See <a href="{@docRoot}guide/developing/debug-tasks.html">Debugging</a> for more debugging tips. </p> + ddms logcat capability to get a deeper view when errors occur. + See the <a href="{@docRoot}guide/developing/debugging/index.html">Debugging</a> documentation for more information.</p> <ul> <li><a href="#installeclipsecomponents">ADT Installation Error: "requires plug-in org.eclipse.wst.sse.ui".</a></li> <li><a href="#nodevice">ADB reports "no device" when an emulator is running</a></li> @@ -282,9 +283,10 @@ missing import packages, then save each file.</li> <p>If you get an error message such as "Could not load /sdcard/gestures. Make sure you have a mounted SD card," be sure that your target AVD has an -SD card. To create an AVD that has an SD card, use the -<a href="{@docRoot}guide/developing/tools/avd.html#options"><code>-c</code> -option</a> in the <code>android create avd</code> command.</p> +SD card. To create an AVD that has an SD card, specify one when creating +an AVD with the AVD manager. See +<a href="{@docRoot}guide/developing/devices/managing-avds.html#createavd"> +Creating and Managing AVDs with AVD Manager</a> for more information.</p> <h2 id="signingcalendar">I can't compile my app because the build tools generated an expired debug certificate</h2> diff --git a/docs/html/resources/index.jd b/docs/html/resources/index.jd index 1668721..9055868 100644 --- a/docs/html/resources/index.jd +++ b/docs/html/resources/index.jd @@ -1,38 +1,90 @@ page.title=Developer Resources @jd:body +<style type="text/css"> + #resource-list-table td { + border: 0; + padding: 0 24px; + width: 33%; + max-width: 250px; + border-right: 1px solid #ddd; + } + + #resource-list-table td.last { + border-right: 0; + padding-right: 0; + } +</style> + <p> -This section provides technical articles, tutorials, sample code, and other +This section provides articles, tutorials, sample code, and other information to help you quickly implement the features you want in your -application. +application. To return to this page later, just click the "Resources" +tab while any Resources page is loaded. </p> -<dl> -<dt><b>Technical Articles</b></dt> -<dd>Focused discussions about Android development subjects, including -optimizations, tips, interesting implementations, -and so on. Most of the articles provide "how-to" instructions for adding -features or functionality to your app. The articles are drawn from posts to the -Android Developers Blog. -</dd> - -<dt><b>Tutorials</b></dt> -<dd>Step-by-step instructions demonstrating how to build an Android application -that has the specific features you want. </dd> - -<dt><b>Sample Code</b></dt> -<dd>Fully-functioning sample applications that you can look at or build and run, -to learn about how Android works. Feel free to reuse any of the code or -techniques that you find in the samples!</dd> +<h2>Technical Resources</h2> + +<table id="resource-list-table"> +<tr> + <td> + <a href="{@docRoot}resources/browser.html?tag=sample"> + <img src="{@docRoot}assets/images/resource-big-sample.png"/> + </a> + <h3><a href="{@docRoot}resources/browser.html?tag=sample"> + Sample Code + </a></h3> + <p>Fully-functioning sample applications that you can build and run + to learn about how Android works. Feel free to reuse any of the code or + techniques in the samples.</p> + </td> + <td> + <a href="{@docRoot}resources/browser.html?tag=article"> + <img src="{@docRoot}assets/images/resource-big-article.png"/> + </a> + <h3><a href="{@docRoot}resources/browser.html?tag=article"> + Articles + </a></h3> + <p>Focused discussions about Android development subjects, including + optimizations, tips, interesting implementations, "how-tos", + and so on.</p> + </td> + <td> + <a href="{@docRoot}resources/browser.html?tag=tutorial"> + <img src="{@docRoot}assets/images/resource-big-tutorial.png"/> + </a> + <h3><a href="{@docRoot}resources/browser.html?tag=tutorial"> + Tutorials + </a></h3> + <p>Step-by-step instructions demonstrating how to build an Android application + that has the specific features you want.</p> + </td> + <!-- <td class="last"> + <a href="{@docRoot}resources/browser.html?tag=video"> + <img src="{@docRoot}assets/images/resource-big-video.png"/> + </a> + <h3><a href="{@docRoot}resources/browser.html?tag=video"> + Videos & Screencasts + </a></h3> + <p>Videos and presentation slides from developer events, along with + screencasts to walk you through common Android development + workflows.</p> + </td> --> +</tr> +</table> +<h2>Other Resources</h2> + +<dl> <dt><b>Community</b></dt> <dd>Links to the Android discussion groups and information about other ways to collaborate with other developers. </dd> +<dt><b>Device Dashboard</b></dt> +<dd>Device distribution data, grouped by various dimensions such as screen size +and Android platform version. </dd> + <dt><b>More</b></dt> <dd>Quick development tips, troubleshooting information, and frequently asked questions (FAQs). </dd> </dl> - -<p>To return to this page later, just click the "Resources" tab while any -Resources page is loaded. </p>
\ No newline at end of file diff --git a/docs/html/resources/resources-data.js b/docs/html/resources/resources-data.js new file mode 100644 index 0000000..11964da --- /dev/null +++ b/docs/html/resources/resources-data.js @@ -0,0 +1,682 @@ +var ANDROID_TAGS = { + type: { + 'article': 'Article', + 'tutorial': 'Tutorial', + 'sample': 'Sample', + 'video': 'Video', + 'library': 'Code Library' + }, + topic: { + 'accessibility': 'Accessibility', + 'accountsync': 'Accounts & Sync', + 'bestpractice': 'Best Practices', + 'communication': 'Communication', + 'compatibility': 'Compatibility', + 'data': 'Data Access', + 'drawing': 'Canvas Drawing', + 'gamedev': 'Game Development', + 'gl': 'OpenGL ES', + 'input': 'Input Methods', + 'intent': 'Intents', + 'layout': 'Layouts/Views', + 'media': 'Multimedia', + 'newfeature': 'New Features', + 'performance': 'Performance', + 'search': 'Search', + 'testing': 'Testing', + 'ui': 'User Interface', + 'web': 'Web Content' + }, + misc: { + 'external': 'External', + 'new': 'New' + } +}; + +var ANDROID_RESOURCES = [ + +////////////////////////// +/// TECHNICAL ARTICLES /// +////////////////////////// + + { + tags: ['article', 'performance', 'bestpractice'], + path: 'articles/avoiding-memory-leaks.html', + title: { + en: 'Avoiding Memory Leaks' + }, + description: { + en: 'Mobile devices often have limited memory, and memory leaks can cause your application to waste this valuable resource without your knowledge. This article provides tips to help you avoid common causes of memory leaks on the Android platform.' + } + }, + { + tags: ['article', 'compatibility'], + path: 'articles/backward-compatibility.html', + title: { + en: 'Backward Compatibility' + }, + description: { + en: 'The Android platform strives to ensure backwards compatibility. However, sometimes you want to use new features which aren\'t supported on older platforms. This article discusses strategies for selectively using these features based on availability, allowing you to keep your applications portable across a wide range of devices.' + } + }, + { + tags: ['article', 'intent'], + path: 'articles/can-i-use-this-intent.html', + title: { + en: 'Can I Use this Intent?' + }, + description: { + en: 'Android offers a very powerful and yet easy-to-use message type called an intent. You can use intents to turn applications into high-level libraries and make code modular and reusable. While it is nice to be able to make use of a loosely coupled API, there is no guarantee that the intent you send will be received by another application. This article describes a technique you can use to find out whether the system contains any application capable of responding to the intent you want to use.' + } + }, + { + tags: ['article', 'input'], + path: 'articles/creating-input-method.html', + title: { + en: 'Creating an Input Method' + }, + description: { + en: 'Input Method Editors (IMEs) provide the mechanism for entering text into text fields and other Views. Android devices come bundled with at least one IME, but users can install additional IMEs. This article covers the basics of developing an IME for the Android platform.' + } + }, + { + tags: ['article', 'drawing', 'ui'], + path: 'articles/drawable-mutations.html', + title: { + en: 'Drawable Mutations' + }, + description: { + en: 'Drawables are pluggable drawing containers that allow applications to display graphics. This article explains some common pitfalls when trying to modify the properties of multiple Drawables.' + } + }, + { + tags: ['article', 'bestpractice', 'ui'], + path: 'articles/faster-screen-orientation-change.html', + title: { + en: 'Faster Screen Orientation Change' + }, + description: { + en: 'When an Android device changes its orientation, the default behavior is to automatically restart the current activity with a new configuration. However, this can become a bottleneck in applications that access a large amount of external data. This article discusses how to gracefully handle this situation without resorting to manually processing configuration changes.' + } + }, + { + tags: ['article', 'compatibility'], + path: 'articles/future-proofing.html', + title: { + en: 'Future-Proofing Your Apps' + }, + description: { + en: 'A collection of common sense advice to help you ensure that your applications don\'t break when new versions of the Android platform are released.' + } + }, + { + tags: ['article', 'input'], + path: 'articles/gestures.html', + title: { + en: 'Gestures' + }, + description: { + en: 'Touch screens allow users to perform gestures, such as tapping, dragging, flinging, or sliding, to perform various actions. The gestures API enables your application to recognize even complicated gestures with ease. This article explains how to integrate this API into an application.' + } + }, + { + tags: ['article', 'gamedev', 'gl'], + path: 'articles/glsurfaceview.html', + title: { + en: 'Introducing GLSurfaceView' + }, + description: { + en: 'This article provides an overview of GLSurfaceView, a class that makes it easy to implement 2D or 3D OpenGL rendering inside of an Android application.' + } + }, + { + tags: ['article', 'ui', 'layout'], + path: 'articles/layout-tricks-reuse.html', + title: { + en: 'Layout Tricks: Creating Reusable UI Components' + }, + description: { + en: 'Learn how to combine multiple standard UI widgets into a single high-level component, which can be reused throughout your application.' + } + }, + { + tags: ['article', 'layout', 'ui', 'performance', 'bestpractice'], + path: 'articles/layout-tricks-efficiency.html', + title: { + en: 'Layout Tricks: Creating Efficient Layouts' + }, + description: { + en: 'Learn how to optimize application layouts as this article walks you through converting a LinearLayout into a RelativeLayout, and analyzes the resulting implications on performance.' + } + }, + { + tags: ['article', 'layout', 'ui', 'performance', 'bestpractice'], + path: 'articles/layout-tricks-stubs.html', + title: { + en: 'Layout Tricks: Using ViewStubs' + }, + description: { + en: 'Learn about using ViewStubs inside an application\'s layout in order to inflate rarely used UI elements, without the performance implications which would otherwise be caused by using the <code><include></code> tag.' + } + }, + { + tags: ['article', 'layout', 'ui', 'performance', 'bestpractice'], + path: 'articles/layout-tricks-merge.html', + title: { + en: 'Layout Tricks: Merging Layouts' + }, + description: { + en: 'Learn how to use the <code><merge></code> tag in your XML layouts in order to avoid unnecessary levels of hierarchy within an application\'s view tree.' + } + }, + { + tags: ['article', 'ui', 'performance'], + path: 'articles/listview-backgrounds.html', + title: { + en: 'ListView Backgrounds: An Optimization' + }, + description: { + en: 'ListViews are very popular widgets within the Android framework. This article describes some of the optimizations used by the ListView widget, and how to avoid some common issues that this causes when trying to use a custom background.' + } + }, + { + tags: ['article', 'ui', 'newfeature'], + path: 'articles/live-folders.html', + title: { + en: 'Live Folders' + }, + description: { + en: 'Live Folders allow users to display any source of data on their home screen without launching an application. This article discusses how to export an application\'s data in a format suitable for display inside of a live folder.' + } + }, + { + tags: ['article', 'ui', 'newfeature'], + path: 'articles/live-wallpapers.html', + title: { + en: 'Live Wallpapers' + }, + description: { + en: 'Live wallpapers are richer, animated, interactive backgrounds that users can display in their home screens. Learn how to create a live wallpaper and bundle it in an application that users can install on their devices.' + } + }, + { + tags: ['article', 'input'], + path: 'articles/on-screen-inputs.html', + title: { + en: 'Onscreen Input Methods' + }, + description: { + en: 'The Input Method Framework (IMF) allows users to take advantage of on-screen input methods, such as software keyboards. This article provides an overview of Input Method Editors (IMEs) and how applications interact with them.' + } + }, + { + tags: ['article', 'performance', 'bestpractice'], + path: 'articles/painless-threading.html', + title: { + en: 'Painless Threading' + }, + description: { + en: 'This article discusses the threading model used by Android applications and how applications can ensure best UI performance by spawning worker threads to handle long-running operations, rather than handling them in the main thread. The article also explains the API that your application can use to interact with Android UI toolkit components running on the main thread and spawn managed worker threads.' + } + }, + { + tags: ['article', 'ui', 'search'], + path: 'articles/qsb.html', + title: { + en: 'Quick Search Box' + }, + description: { + en: 'Quick Search Box (QSB) is a powerful, system-wide search framework. QSB makes it possible for users to quickly and easily find what they\'re looking for, both on their devices and on the web. This article discusses how to work with the QSB framework to add new search results for an installed application.' + } + }, + { + tags: ['article', 'ui'], + path: 'articles/touch-mode.html', + title: { + en: 'Touch Mode' + }, + description: { + en: 'This article explains the touch mode, one of the most important principles of Android\'s UI toolkit. Whenever a user interacts with a device\'s touch screen, the system enters touch mode. While simple in concept, there are important implications touch mode that are often overlooked.' + } + }, + { + tags: ['article', 'performance', 'bestpractice'], + path: 'articles/track-mem.html', + title: { + en: 'Tracking Memory Allocations' + }, + description: { + en: 'This article discusses how to use the Allocation Tracker tool to observe memory allocations and avoid performance problems that would otherwise be caused by ignoring the effect of Dalvik\'s garbage collector.' + } + }, + { + tags: ['article', 'newfeature'], + path: 'articles/ui-1.5.html', + title: { + en: 'UI Framework Changes in Android 1.5' + }, + description: { + en: 'Explore the UI changes that were introduced in Android 1.5, compared with the UI provided in Android 1.0 and 1.1.' + } + }, + { + tags: ['article', 'newfeature'], + path: 'articles/ui-1.6.html', + title: { + en: 'UI Framework Changes in Android 1.6' + }, + description: { + en: 'Explore the UI changes that were introduced in Android 1.6, compared with the UI provided in Android 1.5. In particular, this article discusses changes to RelativeLayouts and click listeners.' + } + }, + { + tags: ['article', 'ui', 'bestpractice'], + path: 'articles/timed-ui-updates.html', + title: { + en: 'Updating the UI from a Timer' + }, + description: { + en: 'Learn about how to use Handlers as a more efficient replacement for java.util.Timer on the Android platform.' + } + }, + { + tags: ['article', 'ui', 'accessibility'], + path: 'articles/tts.html', + title: { + en: 'Using Text-to-Speech' + }, + description: { + en: 'The text-to-speech API lets your application "speak" to users, in any of several languages. This article provides an overview of the TTS API and how you use to add speech capabilities to your application.' + } + }, + { + tags: ['article', 'ui', 'web'], + path: 'articles/using-webviews.html', + title: { + en: 'Using WebViews' + }, + description: { + en: 'WebViews allow an application to dynamically display HTML and execute JavaScript, without relinquishing control to a separate browser application. This article introduces the WebView classes and provides a sample application that demonstrates its use.' + } + }, + { + tags: ['article', 'ui'], + path: 'articles/wikinotes-linkify.html', + title: { + en: 'WikiNotes: Linkify your Text!' + }, + description: { + en: 'This article introduces WikiNotes for Android, part of the Apps for Android project. It covers the use of Linkify to turn ordinary text views into richer, link-oriented content that causes Android intents to fire when a link is selected.' + } + }, + { + tags: ['article', 'intent'], + path: 'articles/wikinotes-intents.html', + title: { + en: 'WikiNotes: Routing Intents' + }, + description: { + en: 'This article illustrates how an application, in this case the WikiNotes sample app, can use intents to route various types of linked text to the application that handles that type of data. For example, an app can use intents to route a linked telephone number to a dialer app and a web URL to a browser.' + } + }, + { + tags: ['article', 'ui', 'performance'], + path: 'articles/window-bg-speed.html', + title: { + en: 'Window Backgrounds & UI Speed' + }, + description: { + en: 'Some Android applications need to squeeze every bit of performance out of the UI toolkit and there are many ways to do so. In this article, you will discover how to speed up the drawing and the perceived startup time of your activities. Both of these techniques rely on a single feature, the window\'s background drawable.' + } + }, + { + tags: ['article', 'performance', 'bestpractice'], + path: 'articles/zipalign.html', + title: { + en: 'Zipalign: an Easy Optimization' + }, + description: { + en: 'The Android SDK includes a tool called zipalign that optimizes the way an application is packaged. Running zipalign against your application enables Android to interact with it more efficiently at run time and thus has the potential to make it and the overall system run faster. This article provides a high-level overview of the zipalign tool and its use.' + } + }, + +/////////////////// +/// SAMPLE CODE /// +/////////////////// + + { + tags: ['sample'], + path: 'samples/AccelerometerPlay/index.html', + title: { + en: 'Accelerometer Play' + }, + description: { + en: '' + } + }, + { + tags: ['sample'], + path: 'samples/AccessibilityService/index.html', + title: { + en: 'Accessibility Service' + }, + description: { + en: 'Illustrates an accessibility service that provides custom feedback for the Clock application which comes by default with Android devices' + } + }, + { + tags: ['sample', 'layout', 'ui'], + path: 'samples/ApiDemos/index.html', + title: { + en: 'API Demos' + }, + description: { + en: 'A variety of small applications that demonstrate an extensive collection of framework topics.' + } + }, + { + tags: ['sample', 'data', 'newfeature', 'accountsync'], + path: 'samples/BackupRestore/index.html', + title: { + en: 'Backup and Restore' + }, + description: { + en: 'Illustrates a few different approaches that an application developer can take when integrating with the Android Backup Manager using the BackupAgent API introduced in Android 2.2.' + } + }, + { + tags: ['sample', 'communication'], + path: 'samples/BluetoothChat/index.html', + title: { + en: 'Bluetooth Chat' + }, + description: { + en: 'An application for two-way text messaging over Bluetooth.' + } + }, + { + tags: ['sample', 'accountsync'], + path: 'samples/BusinessCard/index.html', + title: { + en: 'BusinessCard' + }, + description: { + en: 'An application that demonstrates how to launch the built-in contact picker from within an activity. This sample also uses reflection to ensure that the correct version of the contacts API is used, depending on which API level the application is running under.' + } + }, + { + tags: ['sample', 'accountsync'], + path: 'samples/ContactManager/index.html', + title: { + en: 'Contact Manager' + }, + description: { + en: 'An application that demonstrates how to query the system contacts provider using the <code>ContactsContract</code> API, as well as insert contacts into a specific account.' + } + }, + { + tags: ['sample', 'ui'], + path: 'samples/CubeLiveWallpaper/index.html', + title: { + en: 'Cube Live Wallpaper' + }, + description: { + en: 'An application that demonstrates how to create a live wallpaper and bundle it in an application that users can install on their devices.' + } + }, + { + tags: ['sample'], + path: 'samples/Home/index.html', + title: { + en: 'Home' + }, + description: { + en: 'A home screen replacement application.' + } + }, + { + tags: ['sample', 'new'], + path: 'samples/Honeycomb-Gallery/index.html', + title: { + en: 'Honeycomb Gallery' + }, + description: { + en: 'An image gallery application using Honeycomb-specific APIs.' + } + }, + { + tags: ['sample', 'gamedev', 'media'], + path: 'samples/JetBoy/index.html', + title: { + en: 'JetBoy' + }, + description: { + en: 'A game that demonstrates the SONiVOX JET interactive music technology, with <code><a href="/reference/android/media/JetPlayer.html">JetPlayer</a></code>.' + } + }, + { + tags: ['sample', 'gamedev', 'media'], + path: 'samples/LunarLander/index.html', + title: { + en: 'Lunar Lander' + }, + description: { + en: 'A classic Lunar Lander game.' + } + }, + { + tags: ['sample', 'ui', 'bestpractice', 'layout'], + path: 'samples/MultiResolution/index.html', + title: { + en: 'Multiple Resolutions' + }, + description: { + en: 'A sample application that shows how to use resource directory qualifiers to provide different resources for different screen configurations.' + } + }, + { + tags: ['sample', 'data'], + path: 'samples/NFCDemo/index.html', + title: { + en: 'NFC Demo' + }, + description: { + en: 'An application for reading NFC Forum Type 2 Tags using the NFC APIs' + } + }, + { + tags: ['sample', 'data'], + path: 'samples/NotePad/index.html', + title: { + en: 'Note Pad' + }, + description: { + en: 'An application for saving notes. Similar (but not identical) to the <a href="/resources/tutorials/notepad/index.html">Notepad tutorial</a>.' + } + }, + { + tags: ['sample', 'accountsync'], + path: 'samples/SampleSyncAdapter/index.html', + title: { + en: 'SampleSyncAdapter' + }, + description: { + en: 'Demonstrates how an application can communicate with a cloud-based service and synchronize its data with data stored locally in a content provider. The sample uses two related parts of the Android framework — the account manager and the synchronization manager (through a sync adapter).' + } + }, + { + tags: ['sample', 'ui', 'search'], + path: 'samples/SearchableDictionary/index.html', + title: { + en: 'Searchable Dictionary v2' + }, + description: { + en: 'A sample application that demonstrates Android\'s search framework, including how to provide search suggestions for Quick Search Box.' + } + }, + { + tags: ['sample'], + path: 'samples/SipDemo/index.html', + title: { + en: 'SIP Demo' + }, + description: { + en: 'A demo application highlighting how to make internet-based calls with the SIP API.' + } + }, + { + tags: ['sample', 'layout', 'ui'], + path: 'samples/Snake/index.html', + title: { + en: 'Snake' + }, + description: { + en: 'An implementation of the classic game "Snake."' + } + }, + { + tags: ['sample', 'input'], + path: 'samples/SoftKeyboard/index.html', + title: { + en: 'Soft Keyboard' + }, + description: { + en: 'An example of writing an input method for a software keyboard.' + } + }, + { + tags: ['sample', 'testing'], + path: 'samples/Spinner/index.html', + title: { + en: 'Spinner' + }, + description: { + en: 'A simple application that serves as an application under test for the SpinnerTest example.' + } + }, + { + tags: ['sample', 'testing'], + path: 'samples/SpinnerTest/index.html', + title: { + en: 'SpinnerTest' + }, + description: { + en: 'The test application for the Activity Testing tutorial. It tests the Spinner example application.' + } + }, + { + tags: ['sample', 'newfeature'], + path: 'samples/TicTacToeLib/index.html', + title: { + en: 'TicTacToeLib' + }, + description: { + en: 'An example of an Android library project, a type of project that lets you store and manage shared code and resources in one place, then make them available to your other Android applications.' + } + }, + { + tags: ['sample', 'newfeature',], + path: 'samples/TicTacToeMain/index.html', + title: { + en: 'TicTacToeMain' + }, + description: { + en: 'Demonstrates how an application can make use of shared code and resources stored in an Android library project.' + } + }, + { + tags: ['sample', 'ui'], + path: 'samples/Wiktionary/index.html', + title: { + en: 'Wiktionary' + }, + description: { + en: 'An example of creating interactive widgets for display on the Android home screen.' + } + }, + { + tags: ['sample', 'ui'], + path: 'samples/WiktionarySimple/index.html', + title: { + en: 'Wiktionary (Simplified)' + }, + description: { + en: 'A simple Android home screen widgets example.' + } + }, + { + tags: ['sample', 'layout'], + path: 'samples/XmlAdapters/index.html', + title: { + en: 'XML Adapters' + }, + description: { + en: 'Binding data to views using XML Adapters examples.' + } + }, + +///////////////// +/// TUTORIALS /// +///////////////// + + { + tags: ['tutorial'], + path: 'tutorials/hello-world.html', + title: { + en: 'Hello World' + }, + description: { + en: 'Beginning basic application development with the Android SDK.' + } + }, + { + tags: ['tutorial', 'ui', 'layout'], + path: 'tutorials/views/index.html', + title: { + en: 'Hello Views' + }, + description: { + en: 'A walk-through of the various types of layouts and views available in the Android SDK.' + } + }, + { + tags: ['tutorial', 'ui', 'bestpractice'], + path: 'tutorials/localization/index.html', + title: { + en: 'Hello Localization' + }, + description: { + en: 'The basics of localizing your applications for multiple languages and locales.' + } + }, + { + tags: ['tutorial', 'data'], + path: 'tutorials/notepad/index.html', + title: { + en: 'Notepad Tutorial' + }, + description: { + en: 'A multi-part tutorial discussing intermediate-level concepts such as data access.' + } + }, + { + tags: ['tutorial', 'testing'], + path: 'tutorials/testing/helloandroid_test.html', + title: { + en: 'Hello Testing' + }, + description: { + en: 'A basic introduction to the Android testing framework.' + } + }, + { + tags: ['tutorial', 'testing'], + path: 'tutorials/testing/activity_test.html', + title: { + en: 'Activity Testing' + }, + description: { + en: 'A more advanced demonstration of the Android testing framework and tools.' + } + } +]; diff --git a/docs/html/resources/resources_toc.cs b/docs/html/resources/resources_toc.cs index a273737..a2580a6 100644 --- a/docs/html/resources/resources_toc.cs +++ b/docs/html/resources/resources_toc.cs @@ -1,5 +1,56 @@ <ul> <li> + <h2><span class="en">Technical Resources</span> + </h2> + <ul> + <li class="toggle-list"> + <div><a href="<?cs var:toroot ?>resources/browser.html?tag=sample"> + <span class="en">Sample Code</span> + <span class="de" style="display:none">Beispielcode</span> + <span class="es" style="display:none">Código de ejemplo</span> + <span class="fr" style="display:none">Exemple de code</span> + <span class="it" style="display:none">Codice di esempio</span> + <span class="ja" style="display:none">サンプル コード</span> + <span class="zh-CN" style="display:none"></span> + <span class="zh-TW" style="display:none"></span> + </a></div> + <ul id="devdoc-nav-sample-list"> + <li><a href="<?cs var:toroot ?>resources/samples/get.html"> + <span class="en">Getting the Samples</span> + </a></li> + </ul> + </li> + <li class="toggle-list"> + <div><a href="<?cs var:toroot ?>resources/browser.html?tag=article"> + <span class="en">Articles</span> + </a></div> + <ul id="devdoc-nav-article-list"> + </ul> + </li> + <li class="toggle-list"> + <div><a href="<?cs var:toroot ?>resources/browser.html?tag=tutorial"> + <span class="en">Tutorials</span> + <span class="de" style="display:none">Lernprogramme</span> + <span class="es" style="display:none">Tutoriales</span> + <span class="fr" style="display:none">Didacticiels</span> + <span class="it" style="display:none">Esercitazioni</span> + <span class="ja" style="display:none">チュートリアル</span> + <span class="zh-CN" style="display:none"></span> + <span class="zh-TW" style="display:none"></span> + </a></div> + <ul id="devdoc-nav-tutorial-list"> + </ul> + </li> + <li class="toggle-list"> + <div><a href="<?cs var:toroot ?>resources/topics.html"> + <span class="en">Topics</span> + </a></div> + <ul id="devdoc-nav-topic-list"> + </ul> + </li> + </ul> + </li> + <li> <h2><span class="en">Community</span> <span style="display:none" class="de"></span> <span style="display:none" class="es">Comunidad</span> @@ -36,252 +87,7 @@ ?> <li> - <h2><span class="en">Technical Articles</span> - </h2> - <ul> - <li class="toggle-list"> - <div><a href="<?cs var:toroot ?>resources/articles/index.html"> - <span class="en">List of Articles</span> - </a></div> - <ul> - <li><a href="<?cs var:toroot ?>resources/articles/avoiding-memory-leaks.html"> - <span class="en">Avoiding Memory Leaks</span> - </a></li> - <li><a href="<?cs var:toroot ?>resources/articles/backward-compatibility.html"> - <span class="en">Backward Compatibility</span> - </a></li> - <li><a href="<?cs var:toroot ?>resources/articles/can-i-use-this-intent.html"> - <span class="en">Can I Use this Intent?</span> - </a></li> - <li><a href="<?cs var:toroot ?>resources/articles/creating-input-method.html"> - <span class="en">Creating an Input Method</span> - </a></li> - <li><a href="<?cs var:toroot ?>resources/articles/drawable-mutations.html"> - <span class="en">Drawable Mutations</span> - </a></li> - <li><a href="<?cs var:toroot ?>resources/articles/faster-screen-orientation-change.html"> - <span class="en">Faster Screen Orientation Change</span> - </a></li> - <li><a href="<?cs var:toroot ?>resources/articles/future-proofing.html"> - <span class="en">Future-Proofing Your Apps</span> - </a></li> - <li><a href="<?cs var:toroot ?>resources/articles/gestures.html"> - <span class="en">Gestures</span> - </a></li> - <li><a href="<?cs var:toroot ?>resources/articles/glsurfaceview.html"> - <span class="en">Introducing GLSurfaceView</span> - </a></li> - <li><a href="<?cs var:toroot ?>resources/articles/layout-tricks-reuse.html"> - <span class="en">Layout Tricks: Reusing </span> - </a></li> - <li><a href="<?cs var:toroot ?>resources/articles/layout-tricks-efficiency.html"> - <span class="en">Layout Tricks: Efficiency</span> - </a></li> - <li><a href="<?cs var:toroot ?>resources/articles/layout-tricks-stubs.html"> - <span class="en">Layout Tricks: ViewStubs </span> - </a></li> - <li><a href="<?cs var:toroot ?>resources/articles/layout-tricks-merge.html"> - <span class="en">Layout Tricks: Merging </span> - </a></li> - <li><a href="<?cs var:toroot ?>resources/articles/listview-backgrounds.html"> - <span class="en">ListView Backgrounds</span> - </a></li> - <li><a href="<?cs var:toroot ?>resources/articles/live-folders.html"> - <span class="en">Live Folders</span> - </a></li> - <li><a href="<?cs var:toroot ?>resources/articles/live-wallpapers.html"> - <span class="en">Live Wallpapers</span> - </a></li> - <li><a href="<?cs var:toroot ?>resources/articles/on-screen-inputs.html"> - <span class="en">Onscreen Input Methods</span> - </a></li> - <li><a href="<?cs var:toroot ?>resources/articles/painless-threading.html"> - <span class="en">Painless Threading</span> - </a></li> - <li><a href="<?cs var:toroot ?>resources/articles/qsb.html"> - <span class="en">Quick Search Box</span> - </a></li> - <li><a href="<?cs var:toroot ?>resources/articles/speech-input.html"> - <span class="en">Speech Input</span> - </a></li> - <li><a href="<?cs var:toroot ?>resources/articles/touch-mode.html"> - <span class="en">Touch Mode</span> - </a></li> - <li><a href="<?cs var:toroot ?>resources/articles/track-mem.html"> - <span class="en">Tracking Memory Allocations</span> - </a></li> - <li><a href="<?cs var:toroot ?>resources/articles/ui-1.5.html"> - <span class="en">UI Framework Changes in Android 1.5</span> - </a></li> - <li><a href="<?cs var:toroot ?>resources/articles/ui-1.6.html"> - <span class="en">UI Framework Changes in Android 1.6</span> - </a></li> - <li><a href="<?cs var:toroot ?>resources/articles/timed-ui-updates.html"> - <span class="en">Updating the UI from a Timer</span> - </a></li> - <li><a href="<?cs var:toroot ?>resources/articles/tts.html"> - <span class="en">Using Text-to-Speech</span> - </a></li> - <li><a href="<?cs var:toroot ?>resources/articles/contacts.html"> - <span class="en">Using the Contacts API</span> - </a></li> - <li><a href="<?cs var:toroot ?>resources/articles/using-webviews.html"> - <span class="en">Using WebViews</span> - </a></li> - <li><a href="<?cs var:toroot ?>resources/articles/wikinotes-linkify.html"> - <span class="en">WikiNotes: Linkify your Text!</span> - </a></li> - <li><a href="<?cs var:toroot ?>resources/articles/wikinotes-intents.html"> - <span class="en">WikiNotes: Routing Intents</span> - </a></li> - <li><a href="<?cs var:toroot ?>resources/articles/window-bg-speed.html"> - <span class="en">Window Backgrounds & UI Speed</span> - </a></li> - <li><a href="<?cs var:toroot ?>resources/articles/zipalign.html"> - <span class="en">Zipalign: An Easy Optimization</span> - </a></li> - </ul> - </li> - </ul> - </li> - - <li> - <h2><span class="en">Tutorials</span> - <span class="de" style="display:none">Lernprogramme</span> - <span class="es" style="display:none">Tutoriales</span> - <span class="fr" style="display:none">Didacticiels</span> - <span class="it" style="display:none">Esercitazioni</span> - <span class="ja" style="display:none">チュートリアル</span> - <span class="zh-CN" style="display:none"></span> - <span class="zh-TW" style="display:none"></span> - </h2> - <ul> - <li><a href="<?cs var:toroot ?>resources/tutorials/hello-world.html"> - <span class="en">Hello World</span> - </a></li> - <li><a href="<?cs var:toroot ?>resources/tutorials/views/index.html"> - <span class="en">Hello Views</span> - </a></li> - <li><a href="<?cs var:toroot ?>resources/tutorials/localization/index.html"> - <span class="en">Hello Localization</span> - </a></li> - <li><a href="<?cs var:toroot ?>resources/tutorials/testing/helloandroid_test.html"> - <span class="en">Hello Testing</span></a> - </li> - <li><a href="<?cs var:toroot ?>resources/tutorials/notepad/index.html"> - <span class="en">Notepad Tutorial</span> - </a></li> - <li><a href="<?cs var:toroot ?>resources/tutorials/testing/activity_test.html"> - <span class="en">Activity Testing</span></a> - </li> - </ul> - </li> - - - <li> - <h2><span class="en">Sample Code</span> - <span class="de" style="display:none">Beispielcode</span> - <span class="es" style="display:none">Código de ejemplo</span> - <span class="fr" style="display:none">Exemple de code</span> - <span class="it" style="display:none">Codice di esempio</span> - <span class="ja" style="display:none">サンプル コード</span> - <span class="zh-CN" style="display:none"></span> - <span class="zh-TW" style="display:none"></span> - </h2> - <ul> - <li><a href="<?cs var:toroot ?>resources/samples/get.html"> - <span class="en">Getting the Samples</span> - </a></li> - <li class="toggle-list"> - <div><a href="<?cs var:toroot ?>resources/samples/index.html"> - <span class="en">List of Samples</span> - </a></div> - <ul> - <li><a href="<?cs var:toroot ?>resources/samples/AccelerometerPlay/index.html"> - <span class="en">Accelerometer Play</span> - </a> <span class="new">new!</span></li> - <li><a href="<?cs var:toroot ?>resources/samples/AccessibilityService/index.html"> - <span class="en">Accessibility Service</span> - </a> <span class="new">new!</span></li> - <li><a href="<?cs var:toroot ?>resources/samples/ApiDemos/index.html"> - <span class="en">API Demos</span> - </a></li> - <li><a href="<?cs var:toroot ?>resources/samples/BackupRestore/index.html"> - <span class="en">Backup and Restore</span> - </a></li> - <li><a href="<?cs var:toroot ?>resources/samples/BluetoothChat/index.html"> - <span class="en">Bluetooth Chat</span> - </a></li> - <li><a href="<?cs var:toroot ?>resources/samples/BusinessCard/index.html"> - <span class="en">Business Card</span> - </a></li> - <li><a href="<?cs var:toroot ?>resources/samples/ContactManager/index.html"> - <span class="en">Contact Manager</span> - </a></li> - <li><a href="<?cs var:toroot ?>resources/samples/Home/index.html"> - <span class="en">Home</span> - </a></li> - <li><a href="<?cs var:toroot ?>resources/samples/JetBoy/index.html"> - <span class="en">JetBoy</span> - </a></li> - <li><a href="<?cs var:toroot ?>resources/samples/CubeLiveWallpaper/index.html"> - <span class="en">Live Wallpaper</span> - </a></li> - <li><a href="<?cs var:toroot ?>resources/samples/LunarLander/index.html"> - <span class="en">Lunar Lander</span> - </a></li> - <li><a href="<?cs var:toroot ?>resources/samples/MultiResolution/index.html"> - <span class="en">Multiple Resolutions</span> - </a></li> - <li><a href="<?cs var:toroot ?>resources/samples/NFCDemo/index.html"> - <span class="en">NFCDemo</span> - </a> <span class="new">new!</span></li> - <li><a href="<?cs var:toroot ?>resources/samples/NotePad/index.html"> - <span class="en">Note Pad</span> - </a></li> - <li><a href="<?cs var:toroot ?>resources/samples/SampleSyncAdapter/index.html"> - <span class="en">Sample Sync Adapter</span> - </a></li> - <li><a href="<?cs var:toroot ?>resources/samples/SearchableDictionary/index.html"> - <span class="en">Searchable Dictionary v2</span> - </a></li> - <li><a href="<?cs var:toroot ?>resources/samples/SipDemo/index.html"> - <span class="en">SIP Demo</span> - </a> <span class="new">new!</span></li> - <li><a href="<?cs var:toroot ?>resources/samples/Snake/index.html"> - <span class="en">Snake</span> - </a></li> - <li><a href="<?cs var:toroot ?>resources/samples/SoftKeyboard/index.html"> - <span class="en">Soft Keyboard</span> - </a></li> - <li><a href="<?cs var:toroot ?>resources/samples/Spinner/index.html"> - <span class="en">Spinner</span> - </a></li> - <li><a href="<?cs var:toroot ?>resources/samples/SpinnerTest/index.html"> - <span class="en">SpinnerTest</span> - </a></li> - <li><a href="<?cs var:toroot ?>resources/samples/TicTacToeLib/index.html"> - <span class="en">TicTacToeLib</span> - </a></li> - <li><a href="<?cs var:toroot ?>resources/samples/TicTacToeMain/index.html"> - <span class="en">TicTacToeMain</span> - </a></li> - <li><a href="<?cs var:toroot ?>resources/samples/Wiktionary/index.html"> - <span class="en">Wiktionary</span> - </a></li> - <li><a href="<?cs var:toroot ?>resources/samples/WiktionarySimple/index.html"> - <span class="en">Wiktionary (Simplified)</span> - </a></li> - </ul> - </li> - </ul> - </li> - - - - <li> - <h2><span class="en">More</span> - </h2> + <h2><span class="en">More</span></h2> <ul> <li><a href="<?cs var:toroot ?>resources/faq/commontasks.html"> <span class="en">Common Tasks </span> @@ -307,8 +113,6 @@ </li> </ul> </li> - - </ul> <script type="text/javascript"> diff --git a/docs/html/resources/samples/images/XmlPhotosAdapter.png b/docs/html/resources/samples/images/XmlPhotosAdapter.png Binary files differnew file mode 100644 index 0000000..c018d54 --- /dev/null +++ b/docs/html/resources/samples/images/XmlPhotosAdapter.png diff --git a/docs/html/resources/samples/images/XmlRssReader.png b/docs/html/resources/samples/images/XmlRssReader.png Binary files differnew file mode 100644 index 0000000..00f841b --- /dev/null +++ b/docs/html/resources/samples/images/XmlRssReader.png diff --git a/docs/html/resources/samples/images/hcgallery.png b/docs/html/resources/samples/images/hcgallery.png Binary files differnew file mode 100644 index 0000000..9a80fd7 --- /dev/null +++ b/docs/html/resources/samples/images/hcgallery.png diff --git a/docs/html/resources/samples/images/sample_notepadtest_junit.png b/docs/html/resources/samples/images/sample_notepadtest_junit.png Binary files differnew file mode 100644 index 0000000..4cda54e --- /dev/null +++ b/docs/html/resources/samples/images/sample_notepadtest_junit.png diff --git a/docs/html/resources/samples/index.jd b/docs/html/resources/samples/index.jd index 0572d00..beecd67 100644 --- a/docs/html/resources/samples/index.jd +++ b/docs/html/resources/samples/index.jd @@ -65,9 +65,6 @@ href="{@docRoot}resources/samples/get.html">Getting the Samples</a>.</p> <dd>A sample application that shows how to use resource directory qualifiers to provide different resources for different screen configurations.</dd> - <dt><a href="NFCDemo/index.html">NFCDemo</a></dt> - <dd>An application for reading NFC Forum Type 2 Tags using platform NFC apis.</a>.</dd> - <dt><a href="NotePad/index.html">Note Pad</a></dt> <dd>An application for saving notes. Similar (but not identical) to the <a href="{@docRoot}resources/tutorials/notepad/index.html">Notepad tutorial</a>.</dd> diff --git a/docs/html/resources/topics.jd b/docs/html/resources/topics.jd new file mode 100644 index 0000000..b5960ff --- /dev/null +++ b/docs/html/resources/topics.jd @@ -0,0 +1,72 @@ +page.title=Technical Resource Topics +@jd:body + +<style type="text/css"> + #resource-topic-table td { + border: 0; + padding: 0; + margin: 0; + padding-left: 1em; + width: 18em; + } + + #resource-topic-table ul { + padding: 0; + margin: 0; + } + + #resource-topic-table li { + list-style: none; + margin: 0; + padding: 0; + } +</style> + +<p> +You can browse the list of technical resources by topic by clicking on the +links below. Over time, as more topics are added, they will be added to the +list below. +</p> + +<noscript> + <p class="note"><strong>Error:</strong> + You must have JavaScript enabled to view this page. Resources are also + available offline in the SDK. + </p> +</noscript> + +<table id="resource-topic-table"> + <tr></tr> +</table> + +<script type="text/javascript"> +<!-- +(function() { + var topics = []; + for (var topic in ANDROID_TAGS['topic']) { + topics.push({name:topic,title:ANDROID_TAGS['topic'][topic]}); + } + topics.sort(function(x,y){ return (x.title < y.title) ? -1 : 1; }); + var topicParent = null; + for (var i = 0; i < topics.length; i++) { + if (topicParent == null || i % 10 == 0) { + // create a new column + topicParent = $('ul', $('<td><ul>').appendTo('#resource-topic-table tr')); + } + + topicParent.append( + $('<li>').append( + $('<h3>').append( + $('<a>') + .attr('href', toRoot + "resources/browser.html?tag=" + topics[i].name) + .append($('<span>') + .addClass('en') + .html(topics[i].title) + ) + ) + ) + ); + } +})(); +//--> +</script>
\ No newline at end of file diff --git a/docs/html/resources/tutorials/notepad/notepad-ex2.jd b/docs/html/resources/tutorials/notepad/notepad-ex2.jd index 289b5fe..499b796 100644 --- a/docs/html/resources/tutorials/notepad/notepad-ex2.jd +++ b/docs/html/resources/tutorials/notepad/notepad-ex2.jd @@ -87,8 +87,8 @@ Open the Notepadv2 class.</p> menu callback used for the options menu. Here, we add just one line, which will add a menu item to delete a note. Call <code>menu.add()</code> like so: <pre> -public boolean onCreateContextMenu(Menu menu, View v - ContextMenuInfo menuInfo) { +public void onCreateContextMenu(Menu menu, View v, + ContextMenu.ContextMenuInfo menuInfo) { super.onCreateContextMenu(menu, v, menuInfo); menu.add(0, DELETE_ID, 0, R.string.menu_delete); }</pre> diff --git a/docs/html/resources/tutorials/testing/activity_test.jd b/docs/html/resources/tutorials/testing/activity_test.jd index ec878d2..afb9e3c 100644 --- a/docs/html/resources/tutorials/testing/activity_test.jd +++ b/docs/html/resources/tutorials/testing/activity_test.jd @@ -239,7 +239,8 @@ page.title=Activity Testing <p> In this tutorial, you will use the Android emulator to run applications. The emulator needs an Android Virtual Device (AVD) with an API level equal to or higher than the one you set for the projects in the previous step. - To find out how to check this and create the right AVD if necessary, see <a href="{@docRoot}guide/developing/eclipse-adt.html#AVD">Creating an AVD</a>. + To find out how to check this and create the right AVD if necessary, + see <a href="{@docRoot}guide/developing/devices/managing-avds.html">Creating an AVD</a>. </p> <p> As a test of the AVD and emulator, run the SpinnerActivity application in Eclipse with ADT. When it starts, @@ -1237,7 +1238,7 @@ import android.widget.SpinnerAdapter; also use this tool to run the test application from the command line. </li> <li> - <a href="{@docRoot}guide/developing/tools/othertools.html#android">android</a> - Manages projects and test projects. This tool also manages AVDs and Android platforms. + <a href="{@docRoot}guide/developing/tools/android.html">android</a> - Manages projects and test projects. This tool also manages AVDs and Android platforms. </li> </ul> <p> diff --git a/docs/html/resources/tutorials/views/hello-mapview.jd b/docs/html/resources/tutorials/views/hello-mapview.jd index 9ea635c..836d22c 100644 --- a/docs/html/resources/tutorials/views/hello-mapview.jd +++ b/docs/html/resources/tutorials/views/hello-mapview.jd @@ -17,13 +17,13 @@ Components</a>.</p> <p>After installing the Google APIs add-on in your SDK, set your project properties to use the build target called "Google APIs by Google Inc.". See the instructions for setting a build -target in <a href="{@docRoot}guide/developing/eclipse-adt.html">Developing in -Eclipse with ADT</a> or <a -href="{@docRoot}guide/developing/other-ide.html">Developing in Other IDEs</a>, -as appropriate for your environment. </p> +target in <a href="{@docRoot}guide/developing/projects/projects-eclipse.html#CreatingAProject"> +Creating and Managing Projects in Eclipse</a> or <a +href="{@docRoot}guide/developing/projects/projects-cmdline.html#CreatingAProject"> +Creating and Managing Projects on the Command Line</a>, as appropriate for your environment.</p> <p>You will also need to set up a new AVD that uses the same Google APIs deployment target. See <a -href="{@docRoot}guide/developing/tools/avd.html">Android Virtual Devices</a> for +href="{@docRoot}guide/developing/devices/index.html">Creating and Managing Virtual Devices</a> for more information.</p> <p>For reference material, see the <a @@ -127,7 +127,7 @@ android.app.Activity#onCreate(Bundle) onCreate()} method:</p> </pre> </li> <li>That's all there is to it. Run the application. (Remember, you must have an <a -href="{@docRoot}guide/developing/tools/avd.html">AVD</a> configured to use the Google APIs +href="{@docRoot}guide/developing/devices/index.html">AVD</a> configured to use the Google APIs target, or be using a development device that includes the Maps library.)</li> </ol> diff --git a/docs/html/resources/webinars/date.js b/docs/html/resources/webinars/date.js deleted file mode 100644 index 5768aa7..0000000 --- a/docs/html/resources/webinars/date.js +++ /dev/null @@ -1,119 +0,0 @@ -// Copyright 2009 Google Inc. All Rights Reserved. - -/** - * @fileoverview Utility functions for formating date. - */ - -/** - * Formats start date and end date in JSON format to string of format: - "09/09/2010 20:00 PM to 22:00 PM PST" - * @param {object} start date in JSON format. - * @param {object} end date in JSON format. - * @param {string} formatted date string. - */ -function formatDate(start,end) { - var s_ampm = null; - var e_ampm = null; - - var toStr = function (num) { - if (num <= 12) { - return "" + num; - } else { - return "" + (num - 12); - } - }; - - var getMonthName = function (num) { - switch(num) { - case 1: - return 'January'; - case 2: - return 'February'; - case 3: - return 'March'; - case 4: - return 'April'; - case 5: - return 'May'; - case 6: - return 'June'; - case 7: - return 'July'; - case 8: - return 'August'; - case 9: - return 'September'; - case 10: - return 'October'; - case 11: - return 'November'; - case 12: - return 'December'; - } - } - - var regex = /(^\d{4})-(\d{2})-(\d{2})\s{1}(\d{2}):(\d{2}):(\d{2}$)/; - var s_match = regex.exec(start.toString()); - - if( s_match == null) { - return ''; - } - var yy = s_match[1]; - - var mm = parseInt(s_match[2], 10 /** base 10 **/); - var dd = s_match[3]; - - var s_hh = parseInt(s_match[4], 10 /** base 10 **/); - - if (s_hh > 12) { - s_ampm = "PM"; - } else { - s_ampm = "AM"; - } - s_hh = toStr(s_hh); - var s_mi = s_match[5]; - - - var str = getMonthName(mm) + " " + dd + ", " + yy ; - str += " " + s_hh + ":" + s_mi; - str += " " + s_ampm; - - regex = /(^\d{4})-(\d{2})-(\d{2})\s{1}(\d{2}):(\d{2}):(\d{2}$)/; - var e_match = regex.exec(end.toString()); - if( e_match == null) { - return str + ' PST'; - } - var e_hh = parseInt(e_match[4], 10 /** base 10 **/); - if (e_hh > 12) { - e_ampm = "PM"; - } else { - e_ampm = "AM"; - } - e_hh = toStr(e_hh); - var e_mi = e_match[5]; - - str += " to " + e_hh + ":" + e_mi; - str += " " + e_ampm; - str += " PST"; - return str; - -} - - -function formatDateUtf(date) { - var regex = /(^\d{4})-(\d{2})-(\d{2})\s{1}(\d{2}):(\d{2}):(\d{2}$)/; - var match = regex.exec(date.toString()); - var yy = match[1]; - var mm = match[2]; - var dd = match[3]; - var hh = parseInt(match[4], 10) + 8; // +8 to convert from PST to GMT - var mi = match[5] + "00"; // add seconds - - if (hh >= 24) { // If the GMT adjustment put us into the next day, - dd++; // increment the day and - hh -= 24; // set the hour back to real hours - } - hh = hh < 10 ? "0" + hh : hh; // form a double digit number for single digit hours - - return yy + mm + dd + 'T' + hh + mi + 'Z'; -} diff --git a/docs/html/resources/webinars/webinar-upcoming.jd b/docs/html/resources/webinars/webinar-upcoming.jd deleted file mode 100644 index 34879ec..0000000 --- a/docs/html/resources/webinars/webinar-upcoming.jd +++ /dev/null @@ -1,64 +0,0 @@ -page.title=Upcoming Schedule -@jd:body - -<script type="text/javascript"> - -/** -/* Draw all webinars from feed into a 'webinars' div - * @param data The feed data returned from the webinars request - */ -function renderWebinar(data) { - - var entries = data.webinars || []; - - var resultsDiv = $('#resource-browser-results'); - var code = []; - - // Loop through each entry (each webinar) and add it to the 'webinars' list - for (var i = 0; i < entries.length; i++) { - var entry = entries[i]; - - var title = entry.title; - var description = entry.description; - var url = entry.url; - var start = entry.start; - var end = entry.end; - - code.push('<div>'); - code.push('<h3>' + title + '</h3>'); - code.push('<p><i>' + formatDate(start, end) + '</i>'); - code.push('<br/><a href="https://www.google.com/calendar/event?action=TEMPLATE&hl=en&text=' + title + - '&dates=' + formatDateUtf(start) + '/' + formatDateUtf(end) + - '&details=' + description + ' Go to: http://developer.android.com/resources/webinars/webinar-watch.html' + - '&location=developer.android.com' + - '&sprop=name:Android Developers' + - '&sprop=website:developer.android.com' + - '" target="_blank">Add this to my calendar</a></p>'); - code.push('<p>' + description + '</p>'); - code.push('</div>'); - } - - var html = code.join('\n'); - resultsDiv.html(html); -} - -/* Request the webinar feeds from webinarhosting server */ -function showWebinars() { - var script = "<script type='text/javascript' src='/resources/webinars/date.js'><\/script>"; - $("body").append(script); - $.getJSON( - 'http://android-webinars.appspot.com/feeds/api/upcomingwebinars?callback=?', - function(json){renderWebinar(json);}); -} -// Initialization actions -showWebinars(); // load webinars - -</script> - -<p>This page provides a schedule of upcoming webinars. - When a webinar occurs, you can watch it live and participate in an ICQ session that's coupled - with the presentation, by following the live link at - <a href="{@docRoot}resources/webinars/webinar-watch.html">Watch a Webinar</a>.</p> - -<div id="resource-browser-results"> - </div> diff --git a/docs/html/resources/webinars/webinar-watch.jd b/docs/html/resources/webinars/webinar-watch.jd deleted file mode 100644 index 81c2bec..0000000 --- a/docs/html/resources/webinars/webinar-watch.jd +++ /dev/null @@ -1,111 +0,0 @@ -page.title=Watch a Webinar -@jd:body - -<script type="text/javascript"> - -/** - * Draw all webinars from feed into a 'live_webinar' div - * @param data The feed data returned from the live webinars request - */ -function renderLiveWebinar(data) { - - var entries = data.webinars || []; - - var resultsDiv = $('#live_webinar'); - var code = []; - - // Loop through each entry (each webinar) and add it to the 'webinars' list - for (var i = 0; i < entries.length; i++) { - var entry = entries[i]; - - var title = entry.title; - var description = entry.description; - var url = entry.url; - var start = entry.start; - var end = entry.end; - code.push('<div >'); - code.push('<h3><b>Live!</b> <a href="' + url + '" target="_blank" onClick=_gaq.push(["_trackEvent", "Live Webinar", "' + title + '"]);>' + title + '</a></h3>'); - code.push('<p ><i>' + formatDate(start, end) + '</i>'); - code.push('<p>' + description); - code.push('</div>'); - } - if (entries.length == 0) { - code.push('<div >'); - code.push('<p class="note">There is currently no live webinar. Check the schedule for <a href="/resources/webinars/webinar-upcoming.html">Upcoming Webinars</a>.'); - code.push('</div>'); - } - var html = code.join('\n'); - resultsDiv.html(html); -} - -/* Request the webinar feeds from webinarhosting server */ -function showLiveWebinars() { - var script = "<script type='text/javascript' src='/resources/webinars/date.js'><\/script>"; - $("body").append(script); - $.getJSON( - 'http://android-webinars.appspot.com/feeds/api/livewebinar?callback=?', - function(json){renderLiveWebinar(json);}); -} -// Initialization actions -showLiveWebinars(); // load webinars - -/** - * Draw all past webinars from feed into a 'webinars' div - * @param data The feed data returned from the webinars request - */ -function renderPastWebinar(data) { - - var entries = data.webinars || []; - - var resultsDiv = $('#past_webinars'); - var code = []; - code.push('<h2> Past Webinars </h2>'); - - // Loop through each entry (each webinar) and add it to the 'webinars' list - for (var i = 0; i < entries.length; i++) { - var entry = entries[i]; - - var title = entry.title; - var description = entry.description; - var url = entry.url; - var start = entry.start; - var end = entry.end; - code.push('<div >'); - code.push('<h3><a href="' + url + '" target="_blank" onClick=_gaq.push(["_trackEvent", "Past Webinars", "' + title + '"]);>' + title + '</a></h3>'); - code.push('<p><i>' + formatDate(start, end) + '</i>'); - code.push('<p>' + description); - code.push('</div>'); - } - if (entries.length == 0) { - code.push('<div >'); - code.push('<p>There are no past webinars.'); - code.push('</div>'); - } - var html = code.join('\n'); - resultsDiv.html(html); -} - -/* Request the past webinar feeds from webinarhosting server */ -function showPastWebinars() { - var script = "<script type='text/javascript' src='/resources/webinars/date.js'><\/script>"; - $("body").append(script); - $.getJSON( - 'http://android-webinars.appspot.com/feeds/api/pastwebinars?callback=?', - function(json){renderPastWebinar(json);}); -} -// Initialization actions -showPastWebinars(); // load webinars - -</script> - -<p>Webinars are web-based seminars that provide online training for a wide range of Android - developer topics. When a new webinar takes place, you can watch live and chat with the presenter - and other participants in an IRC session that's coupled with the presentation. The IRC session -is held on the <em>#android-dev</em> channel at <em>irc.freenode.net</em>.</p> -<p style="margin-bottom:2em">When available, live webinars appear at the top of this page. If there's no live webinar, you - can watch one of the previous webinars from the list below.</p> - -<div id="live_webinar"> - </div> -<div id="past_webinars"> - </div> diff --git a/docs/html/sdk/1.6_r1/upgrading.jd b/docs/html/sdk/1.6_r1/upgrading.jd index 49535c9..ebe6a95 100644 --- a/docs/html/sdk/1.6_r1/upgrading.jd +++ b/docs/html/sdk/1.6_r1/upgrading.jd @@ -1,5 +1,6 @@ page.title=Upgrading the SDK sdk.version=1.6 +sdk.preview=0 @jd:body diff --git a/docs/html/sdk/RELEASENOTES.jd b/docs/html/sdk/RELEASENOTES.jd index a94eba7..bf091e9 100644 --- a/docs/html/sdk/RELEASENOTES.jd +++ b/docs/html/sdk/RELEASENOTES.jd @@ -64,7 +64,7 @@ changes include: </p> skins. </li> <li>Android SDK and AVD Manager, a graphical UI to let you manage your SDK and AVD environments more easily. The tool lets you create and manage -your <a href="{@docRoot}guide/developing/tools/avd.html">Android Virtual +your <a href="{@docRoot}guide/developing/devices/managing-avds.html">Android Virtual Devices</a> and download new SDK packages (such as platform versions and add-ons) into your environment.</li> <li>Improved support for test packages in New Project Wizard</li> @@ -222,7 +222,7 @@ skins, including: </p> density for each skin, to create any combination of resolution/density (WVGA with medium density, for instance). To do so, use the <code>android</code> tool command line to create a new AVD that uses a custom hardware configuration. See -<a href="{@docRoot}guide/developing/tools/avd.html#createavd">Creating an +<a href="{@docRoot}guide/developing/devices/managing-avds.html#createavd">Creating an AVD</a> for more information.</p> <h3>Other Notes and Resolved Issues</h3> @@ -330,7 +330,7 @@ changes include: </p> Android 1.5). The tools are updated to let you deploy your application on any platform in the SDK, which helps you ensure forward-compatibility and, if applicable, backward-compatibility.</li> - <li>Introduces <a href="{@docRoot}guide/developing/tools/avd.html">Android + <li>Introduces <a href="{@docRoot}guide/developing/devices/managing-avds.html">Android Virtual Devices</a> — (AVD) configurations of options that you run in the emulator to better model actual devices. Each AVD gets its own dedicated storage area, making it much easier to work with multiple emulators @@ -407,7 +407,7 @@ that can run in the emulator. available to use.</p> <p>For more information about AVDs, see <a -href="{@docRoot}guide/developing/tools/avd.html">Android Virtual Devices</a> +href="{@docRoot}guide/developing/devices/index.html">Creating and Managing Virtual Devices</a> <h3>Other Notes</h3> @@ -585,8 +585,7 @@ these USB drivers that you can install, to let you develop on the device:</p> <p>The USB driver files are located in the <code><SDK>/usb_driver</code> directory. For details and installation instructions, see <a -href="{@docRoot}guide/developing/device.html#setting-up">Setting Up a -Device for Development</a>.</p> +href="{@docRoot}guide/developing/device.html#setting-up">Connecting Hardware Devices</a>.</p> </p> <h3>Resolved Issues, Changes</h3> diff --git a/docs/html/sdk/android-2.3.jd b/docs/html/sdk/android-2.3.jd index bdf4968..734d97b 100644 --- a/docs/html/sdk/android-2.3.jd +++ b/docs/html/sdk/android-2.3.jd @@ -468,7 +468,7 @@ in {@link android.app.ActivityManager.RunningAppProcessInfo}. The value indicates that a specific process is running something that is considered to be actively perceptible to the user. An example would be an application performing background music playback.</li> -<li>The {@link android.app.Activity#setPersistent(boolean)} method to mark an +<li>The Activity.setPersistent(boolean) method to mark an Activity as persistent is now deprecated and the implementation is a no-op.</li> </ul> </li> diff --git a/docs/html/sdk/android-3.0-highlights.jd b/docs/html/sdk/android-3.0-highlights.jd index 0378c35..ed49307 100644 --- a/docs/html/sdk/android-3.0-highlights.jd +++ b/docs/html/sdk/android-3.0-highlights.jd @@ -129,7 +129,7 @@ This document provides a glimpse of some of the new features and technologies, a <p style="margin-top:1em;margin-bottom:.75em;"><strong>Camera and Gallery</strong></p> -<p>The Camera application has been redesigned to take advantage of a larger screen for quick access to exposure, focus, flash, zoom, front-facing camera, and more. To let users capture scenes in new ways, it adds built-in support for time-lapse video recording. The Gallery application lets users view albums and other collections in full-screen mode, with easy access to thumbnails for other photos in the collection. </p> +<p>The Camera application has been redesigned to take advantage of a larger screen for quick access to exposure, focus, flash, zoom, front-facing camera, and more. To let users capture scenes in new ways, it adds built-in support for time-lapse video recording. Gallery application lets users view albums and other collections in full-screen mode, with easy access to thumbnails for other photos in the collection. </p> <p style="margin-top:1em;margin-bottom:.75em;"><strong>Contacts</strong></p> diff --git a/docs/html/sdk/android-3.0.jd b/docs/html/sdk/android-3.0.jd new file mode 100644 index 0000000..2c8a7f0 --- /dev/null +++ b/docs/html/sdk/android-3.0.jd @@ -0,0 +1,755 @@ +page.title=Android 3.0 Platform Preview +@jd:body + +<div id="qv-wrapper"> +<div id="qv"> + +<h2>In this document</h2> +<ol> + <li><a href="#api">API Overview</a></li> + <li><a href="#api-level">API Level</a></li> + <li><a href="#apps">Built-in Applications</a></li> + <li><a href="#locs">Locales</a></li> + <li><a href="#skins">Emulator Skins</a></li> +</ol> + +<h2>Reference</h2> +<ol> +<li><a +href="{@docRoot}sdk/api_diff/honeycomb/changes.html">API +Differences Report »</a> </li> +</ol> + +<h2>See Also</h2> +<ol> + <li><a href="{@docRoot}sdk/preview/start.html">Getting Started</a></li> +</ol> + +</div> +</div> + +<p><em>API Level:</em> <b>Honeycomb</b></p> + +<p>For developers, the Android 3.0 preview is available as a downloadable component for the +Android SDK.</p> + +<p class="note"><strong>Note:</strong> Read the <a +href="{@docRoot}sdk/preview/start.html">Getting Started</a> guide for important information +about setting up your development environment and limitiations of the Android 3.0 preview.</p> + + + + + + + +<h2 id="#api">API Overview</h2> + +<p>The sections below provide a technical overview of what's new for developers in Android 3.0, +including new features and changes in the framework API since the previous version.</p> + + +<h3>Fragments</h3> + +<p>A fragment is a new framework component that allows you to separate distinct elements of an +activity into self-contained modules that define their own UI and lifecycle. To create a +fragment, you must extend the {@link android.app.Fragment} class and implement several lifecycle +callback methods, similar to an {@link android.app.Activity}. You can then combine multiple +fragments in a single activity to build a multi-pane UI in which each +pane manages its own lifecycle and user inputs.</p> + +<p>You can also use a fragment without providing a UI and instead use the fragment as a worker +for the activity, such as to manage the progress of a download that occurs only while the +activity is running.</p> + +<p>Additionally:</p> + +<ul> + <li>Fragments are self-contained and can be reused in multiple activities</li> + <li>Fragments can be added, removed, replaced and animated inside the activity</li> + <li>Fragment can be added to a back stack managed by the activity, preserving the state of +fragments as they are changed and allowing the user to navigate backward through the different +states</li> + <li>By <a +href="{@docRoot}guide/topics/resources/providing-resources.html#AlternativeResources">providing +alternative layouts</a>, you can mix and match fragments, based +on the screen size and orientation</li> + <li>Fragments have direct access to their container activity and can contribute items to the +activity's Action Bar (discussed next)</li> +</ul> + +<p>To manage the fragments in your activity, you must use the {@link +android.app.FragmentManager}, which provides several APIs for interacting with fragments, such +as finding fragments in the activity and popping fragments off the back stack to restore them +after they've been removed or hidden.</p> + +<p>To perform a transaction, such as add or remove a fragment, you must create a {@link +android.app.FragmentTransaction}. You can then call methods such as {@link +android.app.FragmentTransaction#add add()} {@link android.app.FragmentTransaction#remove +remove()}, or {@link android.app.FragmentTransaction#replace replace()}. Once you've applied all +the changes you want to perform for the transaction, you must call {@link +android.app.FragmentTransaction#commit commit()} and the system applies the fragment transaction to +the activity.</p> + +<p>For more information about using fragments, read the <a +href="{@docRoot}guide/topics/fundamentals/fragments.html">Fragments</a> developer guide.</p> + + + + +<h3>Action Bar</h3> + +<p>The Action Bar is a replacement for the traditional title bar at the top of the activity window. +It includes the application logo in the left corner and provides a new interface for items in the +activity's Options Menu. Additionally, the Action Bar allows you to:</p> + +<ul> + <li>Include select menu items directly in the Action Bar—as "action +items"—for quick access to global user actions. + <p>In your XML declaration for the menu item, include the attribute, {@code +android:showAsAction} with a value of {@code "ifRoom"}. When there's enough room in the +Action Bar, the menu item appears directly in the bar. Otherwise, the item is placed in the +overflow menu, revealed by the icon on the right side of the Action Bar.</p></li> + + <li>Add interactive widgets to the Action Bar—as "action views"—such as a search box. + <p>In the XML for the menu item that should behave as an action view, include the {@code +android:actionViewLayout} attribute with a layout +resource for the action view or {@code android:actionViewClass} with the class name of the +widget. Like action items, an action view appears only when there's room for it in the Action +Bar. If there's not enough room, it is placed in the overflow menu and behaves like a regular +menu item (for example, an item can provide a {@link android.widget.SearchView} as an action +view, but when in the overflow menu, selecting the item activates the search dialog).</p></li> + + <li>Add an action to the application logo when tapped and replace it with a custom logo + <p>The application logo is automatically assigned the {@code android.R.id.home} ID, +which the system deliveres to your activity's {@link android.app.Activity#onOptionsItemSelected +onOptionsItemSelected()} callback when tapped. Simply respond to this ID in your callback +method to perform an action such as go to your application's "home" activity.</p> + <p>To replace the icon with a logo, </p></li> + + <li>Add breadcrumbs for navigating backward through fragments</li> + <li>Add built in tabs and a drop-down list for navigation</li> + <li>Customize the Action Bar themes and custom backgrounds</li> +</ul> + +<p>The Action Bar is standard for all applications that set either the <a +href="{@docRoot}guide/topics/manifest/uses-sdk-element.html#min">{@code +android:minSdkVersion}</a> or <a +href="{@docRoot}guide/topics/manifest/uses-sdk-element.html#target">{@code +android:targetSdkVersion}</a> to {@code "Honeycomb"}. (The "Honeycomb" API Level is provisional +and effective only while using the preview SDK—you must change it to the official API +Level when the final SDK becomes available—see <a +href="{@docRoot}sdk/preview/start.html">Getting Started</a> for more information.)</p> + +<p>For more information about the Action Bar, read the <a +href="{@docRoot}guide/topics/ui/actionbar.html">Action +Bar</a> developer guide.</p> + + + + +<h3>System clipboard</h3> + +<p>Applications can now copy and paste data (beyond mere text) to and from the system-wide +clipboard. Clipped data can be plain text, a URI, or an intent.</p> + +<p>By providing the system access to your data in a content provider, the user can copy complex +content (such as an image or data structure) from your application and paste it into another +application that supports that type of content.</p> + +<p>To start using the clipboard, get the global {@link android.content.ClipboardManager} object +by calling {@link android.content.Context#getSystemService getSystemService(CLIPBOARD_SERVICE)}.</p> + +<p>To create an item to attach to the clipboard ("copy"), you need to create a new {@link +android.content.ClipData} object, which holds one or more {@link android.content.ClipData.Item} +objects, each describing a single entity. To create a {@link android.content.ClipData} object with +just one {@link android.content.ClipData.Item}, you can use one of the helper methods, such as +{@link android.content.ClipData#newPlainText newPlainText()}, {@link +android.content.ClipData#newUri newUri()}, and {@link android.content.ClipData#newIntent +newIntent()}, which each return a {@link android.content.ClipData} object pre-loaded with the +appropriate {@link android.content.ClipData.Item}.</p> + +<p>To add the {@link android.content.ClipData} to the clipboard, pass it to {@link +android.content.ClipboardManager#setPrimaryClip setPrimaryClip()} for your instance of {@link +android.content.ClipboardManager}.</p> + +<p>You can then acquire ("paste") a file from the clipboard by calling {@link +android.content.ClipboardManager#getPrimaryClip()} on the {@link +android.content.ClipboardManager}. Handling the {@link android.content.ClipData} you receive can +be more complicated and you need to be sure you can actually handle the data type.</p> + +<p>For more information, see the {@link android.content.ClipData} class reference. You can also see +an example implementation of copy and paste in the <a +href="{@docRoot}resources/samples/NotePad/index.html">NotePad</a> sample application.</p> + + + + +<h3>Drag and drop</h3> + +<p>New APIs facilitate the ability for your application to implement drag and drop +functionality in the UI.</p> + +<p>To begin dragging content in your activity, call {@link android.view.View#startDrag startDrag()} +on a {@link android.view.View}, providing a {@link android.content.ClipData} object that represents +the information to drag, a {@link android.view.View.DragShadowBuilder} to facilitate the "shadow" +that the user sees while dragging, and an {@link java.lang.Object} that can share information about +the drag object with views that may receive the object.</p> + +<p>To accept a drag object (receive the "drop") in a +{@link android.view.View}, register the view with an {@link android.view.View.OnDragListener +OnDragListener} by +calling {@link android.view.View#setOnDragListener setOnDragListener()}. When a drag event occurs on +the view, the system calls {@link android.view.View.OnDragListener#onDrag onDrag()} for the {@link +android.view.View.OnDragListener OnDragListener}, which receives a {@link android.view.DragEvent} +describing the +type of event has occurred (such as "drag started", "drag ended", or "drop"). During a drag, the +system repeatedly calls {@link +android.view.View.OnDragListener#onDrag onDrag()} for the view underneath the drag, to +deliver a stream of events. The receiving view can +inquire the event type delivered to {@link android.view.View#onDragEvent onDragEvent()} by calling +{@link android.view.DragEvent#getAction getAction()} on the {@link android.view.DragEvent}.</p> + +<p>Although a drag event may carry a {@link android.content.ClipData} object, this is not related +to the system clipboard. The data being dragged is passed as a {@link +android.content.ClipData} object to {@link android.view.View#startDrag startDrag()} and the system +sends it to the receiving {@link android.view.View} in the {@link android.view.DragEvent} sent to +{@link android.view.View.OnDragListener#onDrag onDrag()}. A drag and drop operation should never +put the dragged data in the global system clipboard.</p> + + + +<h3>App widgets</h3> + +<p>Android 3.0 supports several new widget classes for more interactive app widgets, including: +{@link +android.widget.GridView}, {@link android.widget.ListView}, {@link android.widget.StackView}, {@link +android.widget.ViewFlipper}, and {@link android.widget.AdapterViewFlipper}.</p> + +<p>You can also use the new {@link android.widget.RemoteViewsService} to populate +collection views such as ({@link android.widget.GridView}, {@link android.widget.ListView}, and +{@link android.widget.StackView}).</p> + +<p>{@link android.appwidget.AppWidgetProviderInfo} also supports two new fields: {@link +android.appwidget.AppWidgetProviderInfo#autoAdvanceViewId} and {@link +android.appwidget.AppWidgetProviderInfo#previewImage}. The {@link +android.appwidget.AppWidgetProviderInfo#autoAdvanceViewId} field lets you specify the view ID of the +app widget subview, which is auto-advanced by the app widget’s host. The +{@link android.appwidget.AppWidgetProviderInfo#previewImage} field specifies a preview of what the +app widget looks like and is shown to the user from the widget picker. If this field is not +supplied, the app widget's icon is used for the preview.</p> + +<p>Android also provides a new widget preview tool ({@code WidgetPreview}), located in the SDK +tools, to take a screenshot of your app widget, which you can use when specifying the {@link +android.appwidget.AppWidgetProviderInfo#previewImage} field.</p> + + + + + +<h3>Status bar notifications</h3> + +<p>The {@link android.app.Notification} APIs have been extended to support more content-rich status +bar notifications, plus a new {@link android.app.Notification.Builder} class allows you to easily +control the notification properties.</p> +<p>New features include:</p> +<ul> + <li>Support for a large icon in the notification, using {@link +android.app.Notification.Builder#setLargeIcon setLargeIcon()}. This is usually for +social applications to show the contact photo of the person who is the source of the +notification or for media apps to show an album thumbnail.</li> + <li>Support for custom layouts in the status bar ticker, using {@link +android.app.Notification.Builder#setTicker(CharSequence,RemoteViews) setTicker()}.</li> + <li>Support for custom notification layouts to include buttons with {@link +android.app.PendingIntent}s, for more interactive notification widgets +(such as to control ongoing music in the background).</li> +</ul> + + + + +<h3>Content loaders</h3> + +<p>New framework APIs facilitate asynchronous loading of data using the {@link +android.content.Loader} class. You can use it in combination with UI components such as views and +fragments to dynamically load data from worker threads. The {@link +android.content.CursorLoader} subclass is specially designed to help do so for data queried from +a {@link android.content.ContentResolver}.</p> + + + + + +<h3>Bluetooth A2DP and headset APIs</h3> + +<p>Android now includes APIs for applications to verify the state of connected Bluetooth A2DP and +headset profile devices. For example, applications can identify when a Bluetooth headset is +connected for listening to music and notify the user as appropriate. Applications can also receive +broadcasts for vendor specific AT commands and notify the user about the state of the connected +device, such as when the connected device's battery is low.</p> + +<p>You can initialize the respective {@link android.bluetooth.BluetoothProfile} by calling {@link +android.bluetooth.BluetoothAdapter#getProfileProxy getProfileProxy()} with either the {@link +android.bluetooth.BluetoothProfile#A2DP} or {@link android.bluetooth.BluetoothProfile#HEADSET} +profile constant and a {@link android.bluetooth.BluetoothProfile.ServiceListener} to receive +callbacks when the Bluetooth client is connected or disconnected.</p> + + + + +<h3>Animation framework</h3> + +<p>An all new flexible animation framework allows you to animate arbitrary properties of any object +(View, Drawable, Fragment, Object, or anything else). It allows you to define many aspects of an +animation, such as:</p> +<ul> + <li>Duration</li> + <li>Repeat amount and behavior</li> + <li>Type of time interpolation</li> + <li>Animator sets to play animations together, sequentially, or after specified delays</li> + <li>Frame refresh delay</li> +</ul> + + <p>You can define these animation aspects, and others, for an object's int, float, and hexadecimal +color values, by default. To animate any other type of value, you tell the system how to calculate +the values for that given type, by implementing the {@link android.animation.TypeEvaluator} +interface.</p> + +<p>There are two animators you can use to animate values of a property: {@link +android.animation.ValueAnimator} and {@link android.animation.ObjectAnimator}. The {@link +android.animation.ValueAnimator} computes the animation values, but is not aware of the specific +object or property that is animated as a result. It simply performs the calculations, and you must +listen for the updates and process the data with your own logic. The {@link +android.animation.ObjectAnimator} is a subclass of {@link android.animation.ValueAnimator} and +allows you to set the object and property to animate, and it handles all animation work. +That is, you give the {@link android.animation.ObjectAnimator} the object to animate, the +property of the object to change over time, and a set of values to apply to the property over +time in order to animate it, then start the animation.</p> + +<p>Additionally, the {@link android.animation.LayoutTransition} class enables automatic transition +animations for changes you make to your activity layout. To enable transitions for part of the +layout, create a {@link android.animation.LayoutTransition} object and set it on +any {@link android.view.ViewGroup} by calling {@link +android.view.ViewGroup#setLayoutTransition setLayoutTransition()}. This causes default +animations to run whenever items are added to or removed from the group. To specify custom +animations, call {@link android.animation.LayoutTransition#setAnimator setAnimator()} on the {@link +android.animation.LayoutTransition} and provide a custom {@link android.animation.Animator}, +such as a {@link android.animation.ValueAnimator} or {@link android.animation.ObjectAnimator} +discussed above.</p> + +<p>For more information, see the <a +href="{@docRoot}guide/topics/graphics/animation.html">Animation</a> developer guide.</p> + + + + +<h3>Extended UI framework</h3> + +<ul> + + <li><b>Multiple-choice selection for ListView and GridView</b> + +<p>New {@link android.widget.AbsListView#CHOICE_MODE_MULTIPLE_MODAL} mode for {@link +android.widget.AbsListView#setChoiceMode setChoiceMode()} allows for selecting multiple items +from a {@link android.widget.ListView} and {@link android.widget.GridView}.</p> + +<p>To enable multiple-choice selection, call {@link +android.widget.AbsListView#setChoiceMode setChoiceMode(CHOICE_MODE_MULTIPLE_MODAL)} and register a +{@link android.widget.AbsListView.MultiChoiceModeListener MultiChoiceModeListener} with {@link +android.widget.AbsListView#setMultiChoiceModeListener setMultiChoiceModeListener()}.</p> + +<p>When the user performs a long-press on an item, the Action Bar switches to the Multi-choice +Action Mode. The system notifies the {@link android.widget.AbsListView.MultiChoiceModeListener +MultiChoiceModeListener} when items are selected by calling {@link +android.widget.AbsListView.MultiChoiceModeListener#onItemCheckedStateChanged +onItemCheckedStateChanged()}.</p> + +<p>For an example of multiple-choice selection, see the <a +href="{@docRoot}resources/samples/ApiDemos/src/com/example/android/apis/view/List15.html">List15. +java</a> +class in the API Demos sample application.</p> + </li> + + + <li><b>New APIs to transform views</b> + + <p>New APIs allow you to easily apply 2D and 3D transformations to {@link +android.view.View}s in your activity layout, using a set of object properties that define the view's +layout position, orientation, transparency and more.</p> + <p>New methods to set properties include: {@link android.view.View#setAlpha setAlpha()}, {@link +android.view.View#setBottom setBottom()}, {@link android.view.View#setLeft setLeft()}, {@link +android.view.View#setRight setRight()}, {@link android.view.View#setBottom setBottom()}, {@link +android.view.View#setPivotX setPivotX()}, {@link android.view.View#setPivotY setPivotY()}, {@link +android.view.View#setRotationX setRotationX()}, {@link android.view.View#setRotationY +setRotationY()}, {@link android.view.View#setScaleX setScaleX()}, {@link android.view.View#setScaleY +setScaleY()}, {@link android.view.View#setAlpha setAlpha()}, and others.</p> + + <p>Some methods also have a corresponding XML attribute that you can specify in your layout +file. Available attributes include: {@code translationX}, {@code translationY}, {@code rotation}, +{@code rotationX}, {@code rotationY}, {@code scaleX}, {@code scaleY}, {@code transformPivotX}, +{@code transformPivotY}, and {@code alpha}.</p> + + <p>Using some of these new properties in combination with the new animation framework (discussed +previously), you can easily create some fancy animations to your views. For example, to rotate a +view on its y-axis, supply {@link android.animation.ObjectAnimator} with the {@link +android.view.View}, the "rotationY" property, and the values to use:</p> +<pre> +ObjectAnimator animator = ObjectAnimator.ofFloat(myView, "rotationY", 0, 360); +animator.setDuration(2000); +animator.start(); +</pre> + </li> + + + <li><b>New holographic themes</b> + + <p>The standard system widgets and overall look have been redesigned for use on larger screens +such as tablets and incorporate the new "holographic" UI theme. The system applies these styles +using the standard <a href="{@docRoot}guide/topics/ui/themes.html">style and theme</a> system. +Any application that targets the Android 3.0 platform inherits the holographic theme by default. +However, if your application also applies its own styles, then it will override the holographic +theme, unless you update your styles to inherit the holographic theme.</p> + +<p>To apply the holographic theme to individual activities or to inherit them in your own theme +definitions, use one of several new {@link android.R.style#Theme_Holo Theme.Holo} +themes.</p> + </li> + + + <li><b>New widgets</b> + + <ul> + <li>{@link android.widget.AdapterViewAnimator} + <p>Base class for an {@link android.widget.AdapterView} that performs animations when switching + between its views.</p></li> + + <li>{@link android.widget.AdapterViewFlipper} + <p>Simple {@link android.widget.ViewAnimator} that animates between two or more views that have + been added to it. Only one child is shown at a time. If requested, it can automatically flip + between + each child at a regular interval.</p></li> + + <li>{@link android.widget.CalendarView} + <p>Allows users to select dates from a calendar and you can configure the range of dates + available. A user can select a date by tapping on it and can scroll and fling + the calendar to a desired date.</p></li> + + <li>{@link android.widget.ListPopupWindow} + <p>Anchors itself to a host view and displays a list of choices, such as for a list of + suggestions when typing into an {@link android.widget.EditText} view.</p></li> + + <li>{@link android.widget.NumberPicker} + <p>Enables the user to select a number from a predefined range. The widget presents an + input field and up and down buttons for selecting a number. Touching the input field shows a + scroll wheel that allows the user to scroll through values or touch again to directly edit the + current value. It also allows you to map from positions to strings, so that + the corresponding string is displayed instead of the position index.</p></li> + + <li>{@link android.widget.PopupMenu} + <p>Displays a {@link android.view.Menu} in a modal popup window that's anchored to a view. The + popup + appears below the anchor view if there is room, or above it if there is not. If the IME (soft + keyboard) is visible, the popup does not overlap it until it is touched.</p></li> + + <li>{@link android.widget.SearchView} + <p>Provides a search box that works in conjunction with a search provider (in the same manner as + the traditional <a href="{@docRoot}guide/topics/search/search-dialog.html">search dialog</a>). +It + also displays recent query suggestions or custom suggestions as configured by the search + provider. This widget is particularly useful for offering search in the Action Bar.</p></li> + + <li>{@link android.widget.StackView} + <p>A view that displays its children in a 3D stack and allows users to discretely swipe through + the + children.</p></li> + + </ul> + </li> + +</ul> + + + + +<!-- +<h3>WebKit</h3> +<h3>JSON (utilities)</h3> + --> + + +<h3>Graphics</h3> + +<ul> + <li><b>Hardware accelerated 2D graphics</b> + +<p>You can now enable the OpenGL renderer for your application by setting {@code +android:hardwareAccelerated="true"} in your manifest element's <a +href="{@docRoot}guide/topics/manifest/application-element.html">{@code <application>}</a> +element or for individual <a +href="{@docRoot}guide/topics/manifest/activity-element.html">{@code <activity>}</a> +elements.</p> + +<p>This flag helps applications by making them draw faster. This results in smoother animations, +smoother scrolling, and overall better performance and response to user interaction.</p></li> + + + <li><b>View support for hardware and software layers</b> + + <p>By default, a {@link android.view.View} has no layer specified. You can specify that the +view be backed by either a hardware or software layer, specified by values {@link +android.view.View#LAYER_TYPE_HARDWARE} and {@link android.view.View#LAYER_TYPE_SOFTWARE}, using +{@link android.view.View#setLayerType setLayerType()} or the <a +href="{@docRoot}reference/android/view/View.html#attr_android:layerType">{@code layerType}</a> +attribute.</p> + <p>A hardware layer is backed by a hardware specific texture (generally Frame Buffer Objects or +FBO on OpenGL hardware) and causes the view to be rendered using Android's hardware rendering +pipeline, but only if hardware acceleration is turned on for the view hierarchy. When hardware +acceleration is turned off, hardware layers behave exactly as software layers.</p> + <p>A software layer is backed by a bitmap and causes the view to be rendered using Android's +software rendering pipeline, even if hardware acceleration is enabled. Software layers should be +avoided when the affected view tree updates often. Every update will require to re-render the +software layer, which can potentially be slow.</p> + <p>For more information, see the {@link android.view.View#LAYER_TYPE_HARDWARE} and {@link +android.view.View#LAYER_TYPE_SOFTWARE} documentation.</p> + </li> + + + <li><b>Renderscript 3D graphics engine</b> + +<p>Renderscript is a runtime 3D framework that provides both an API for building 3D scenes as well +as a special, platform-independent shader language for maximum performance. Using Renderscript, you +can accelerate graphics operations and data processing. Renderscript is an ideal way to create +high-performance 3D effects for applications, wallpapers, carousels, and more.</p></li> +</ul> + + + + +<h3>Media</h3> + + +<ul> + + <li><b>Time lapse video</b> + +<p>Camcorder APIs now support the ability to record time lapse video. The {@link +android.media.MediaRecorder#setCaptureRate setCaptureRate()} sets the rate at which frames +should be captured.</p></li> + + <li><b>Texture support for image streams</b> + +<p>New {@link android.graphics.SurfaceTexture} allows you to capture an image stream as an OpenGL ES +texture. By calling {@link android.hardware.Camera#setPreviewTexture setPreviewTexture()} for your +{@link android.hardware.Camera} instance, you can specify the {@link +android.graphics.SurfaceTexture} upon which to draw video playback or preview frames from the +camera.</p></li> + + <li><b>HTTP Live streaming</b> + +<p>Applications can now pass an M3U playlist URL to the media framework to begin an HTTP Live +streaming session. The media framework supports most of the HTTP Live streaming specification, +including adaptive bit rate.</p></li> + + <li><b>EXIF data</b> + +<p>The {@link android.media.ExifInterface} includes new fields for photo aperture, ISO, and exposure +time.</p></li> + + <li><b>Camcorder profiles</b> + +<p>New {@link android.media.CamcorderProfile#hasProfile hasProfile()} method and several video +quality profiles (such as {@link android.media.CamcorderProfile#QUALITY_1080P}, {@link +android.media.CamcorderProfile#QUALITY_720P}, {@link +android.media.CamcorderProfile#QUALITY_CIF}, and others) allow you to determine camcorder +quality options.</p></li> + + <li><b>Digital media file transfer</b> + +<p>The platform includes built-in support for Media/Picture Transfer Protocol (MTP/PTP) over USB, +which lets users easily transfer any type of media files between devices and to a host computer. +Developers can build on this support, creating applications that let users create or manage rich +media files that they may want to transfer or share across devices. </p></li> + + <li><b>Digital rights management (DRM)</b> + +<p>New extensible digital rights management (DRM) framework for checking and enforcing digital +rights. It's implemented in two architectural layers:</p> +<ul> + <li>A DRM framework API, which is exposed to applications and runs through the Dalvik VM for +standard applications.</li> + <li>A native code DRM manager that implements the framework API and exposes an interface for DRM +plug-ins to handle rights management and decryption for various DRM schemes.</li> +</ul> + +<p>For application developers, the framework offers an abstract, unified API that simplifies the +management of protected content. The API hides the complexity of DRM operations and allows a +consistent operation mode for both protected and unprotected content, and across a variety of DRM +schemes.</p> + +<p>For device manufacturers, content owners, and Internet digital media providers the DRM +framework?s plugin API provides a means of adding support for a DRM scheme of choice into the +Android system, for secure enforcement of content protection.</p> + +<p>The preview release does not provide any native DRM plug-ins for checking and enforcing digital +rights. However, device manufacturers may ship DRM plug-ins with their devices.</p> + +<p>You can find all of the DRM APIs in the {@link android.drm} package.</p></li> + +</ul> + + + + + + + + +<h2 id="api-level">API Level</h2> + +<p>The Android 3.0 platform delivers an updated version of +the framework API. Because this is a preview of the Android 3.0 API, it uses a provisional API +level of "Honeycomb", instead of an integer identifier, which will be provided when the final SDK +is made available and all APIs are final.</p> + +<p>To use APIs introduced in Android 3.0 in your application, you need compile the application +against the Android library that is provided in the Android 3.0 preview SDK platform and you must +declare this API Level in your manifest as <code>android:minSdkVersion="Honeycomb"</code>, in the +<code><uses-sdk></code> element in the application's manifest.</p> + +<p>For more information about using this provisional API Level and setting up your environment +to use the preview SDK, please see the <a href="{@docRoot}sdk/preview/start.html">Getting +Started</a> document.</p> + + + + +<h2 id="apps">Built-in Applications</h2> + +<p>The system image included in the downloadable platform provides these +built-in applications:</p> + +<table style="border:0;padding-bottom:0;margin-bottom:0;"> +<tr> +<td style="border:0;padding-bottom:0;margin-bottom:0;"> +<ul> +<li>Browser</li> +<li>Calculator</li> +<li>Camera</li> +<li>Clock</li> +<li>Contacts</li> +<li>Custom Locale</li> +<li>Dev Tools</li> +<li>Downloads</li> +<li>Email</li> +</ul> +</td> +<td style="border:0;padding-bottom:0;margin-bottom:0;padding-left:5em;"> +<ul> +<li>Gallery</li> +<li>Music</li> +<li>Search</li> +<li>Settings</li> +<li>Spare Parts (developer app)</li> +<li>Speech Recorder</li> +</ul> +</td> +</tr> +</table> + + +<h2 id="locs" style="margin-top:.75em;">Locales</h2> + +<p>The system image included in the downloadable SDK platform provides a variety of +built-in locales. In some cases, region-specific strings are available for the +locales. In other cases, a default version of the language is used. The +languages that are available in the Android 3.0 system +image are listed below (with <em>language</em>_<em>country/region</em> locale +descriptor).</p> + +<table style="border:0;padding-bottom:0;margin-bottom:0;"> +<tr> +<td style="border:0;padding-bottom:0;margin-bottom:0;"> +<ul> +<li>Arabic, Egypt (ar_EG)</li> +<li>Arabic, Israel (ar_IL)</li> +<li>Bulgarian, Bulgaria (bg_BG)</li> +<li>Catalan, Spain (ca_ES)</li> +<li>Czech, Czech Republic (cs_CZ)</li> +<li>Danish, Denmark(da_DK)</li> +<li>German, Austria (de_AT)</li> +<li>German, Switzerland (de_CH)</li> +<li>German, Germany (de_DE)</li> +<li>German, Liechtenstein (de_LI)</li> +<li>Greek, Greece (el_GR)</li> +<li>English, Australia (en_AU)</li> +<li>English, Canada (en_CA)</li> +<li>English, Britain (en_GB)</li> +<li>English, Ireland (en_IE)</li> +<li>English, India (en_IN)</li> +<li>English, New Zealand (en_NZ)</li> +<li>English, Singapore(en_SG)</li> +<li>English, US (en_US)</li> +<li>English, Zimbabwe (en_ZA)</li> +<li>Spanish (es_ES)</li> +<li>Spanish, US (es_US)</li> +<li>Finnish, Finland (fi_FI)</li> +<li>French, Belgium (fr_BE)</li> +<li>French, Canada (fr_CA)</li> +<li>French, Switzerland (fr_CH)</li> +<li>French, France (fr_FR)</li> +<li>Hebrew, Israel (he_IL)</li> +<li>Hindi, India (hi_IN)</li> +</ul> +</td> +<td style="border:0;padding-bottom:0;margin-bottom:0;padding-left:5em;"> +<li>Croatian, Croatia (hr_HR)</li> +<li>Hungarian, Hungary (hu_HU)</li> +<li>Indonesian, Indonesia (id_ID)</li> +<li>Italian, Switzerland (it_CH)</li> +<li>Italian, Italy (it_IT)</li> +<li>Japanese (ja_JP)</li> +<li>Korean (ko_KR)</li> +<li>Lithuanian, Lithuania (lt_LT)</li> +<li>Latvian, Latvia (lv_LV)</li> +<li>Norwegian bokmål, Norway (nb_NO)</li> +<li>Dutch, Belgium (nl_BE)</li> +<li>Dutch, Netherlands (nl_NL)</li> +<li>Polish (pl_PL)</li> +<li>Portuguese, Brazil (pt_BR)</li> +<li>Portuguese, Portugal (pt_PT)</li> +<li>Romanian, Romania (ro_RO)</li> +<li>Russian (ru_RU)</li></li> +<li>Slovak, Slovakia (sk_SK)</li> +<li>Slovenian, Slovenia (sl_SI)</li> +<li>Serbian (sr_RS)</li> +<li>Swedish, Sweden (sv_SE)</li> +<li>Thai, Thailand (th_TH)</li> +<li>Tagalog, Philippines (tl_PH)</li> +<li>Turkish, Turkey (tr_TR)</li> +<li>Ukrainian, Ukraine (uk_UA)</li> +<li>Vietnamese, Vietnam (vi_VN)</li> +<li>Chinese, PRC (zh_CN)</li> +<li>Chinese, Taiwan (zh_TW)</li> +</td> +</tr> +</table> + +<p class="note"><strong>Note:</strong> The Android platform may support more +locales than are included in the SDK system image. All of the supported locales +are available in the <a href="http://source.android.com/">Android Open Source +Project</a>.</p> + +<h2 id="skins">Emulator Skins</h2> + +<p>The downloadable platform includes the following emulator skin:</p> + +<ul> + <li> + WXGA (1280x800, medium density, xlarge screen) + </li> +</ul> + +<p>For more information about how to develop an application that displays +and functions properly on all Android-powered devices, see <a +href="{@docRoot}guide/practices/screens_support.html">Supporting Multiple +Screens</a>.</p>
\ No newline at end of file diff --git a/docs/html/sdk/eclipse-adt.jd b/docs/html/sdk/eclipse-adt.jd index 78d2ccd..0bb830c 100644 --- a/docs/html/sdk/eclipse-adt.jd +++ b/docs/html/sdk/eclipse-adt.jd @@ -333,7 +333,7 @@ called <code>src/</code>. There is now support for any number of source folders, with no name restriction. They can even be in subfolder such as <code>src/java</code>. If you are already working with library projects created in ADT 0.9.7, see <a -href="{@docRoot}guide/developing/eclipse-adt.html#libraryMigrating">Migrating +href="{@docRoot}guide/developing/projects/index.html#libraryMigrating">Migrating library projects to ADT 0.9.8</a> for important information about moving to the new ADT environment.</li> <li>Adds support for library projects that depend on other library @@ -371,8 +371,7 @@ code and resources in a separate development project. You can then reference the library project from other Android projects and, at build time, the tools compile the shared code and resources as part of the dependent applications. More information about this feature is available in the <a -href="{@docRoot}guide/developing/eclipse-adt.html#libraryProject">Developing -in Eclipse with ADT</a> document. </p> +href="{@docRoot}guide/developing/projects/index.html#LibraryProjects">Creating and Managing Projects</a> document. </p> <p>If you are not developing in Eclipse, <a href="tools-notes.html">SDK Tools r6</a> provides the equivalent library project support through the Ant build system.</p> diff --git a/docs/html/sdk/index.jd b/docs/html/sdk/index.jd index bfcd14e..499b31f 100644 --- a/docs/html/sdk/index.jd +++ b/docs/html/sdk/index.jd @@ -19,6 +19,7 @@ sdk.linux_checksum=9fefac5ff85d329836439f6e77a78cae @jd:body +<div class="non-preview"> <p>Here's an overview of the steps you must follow to set up the Android SDK:</p> <ol> @@ -32,3 +33,4 @@ installer for help with the initial setup.)</li> <p>To get started, download the appropriate package from the table above, then read the guide to <a href="installing.html">Installing the SDK</a>.</p> +</div> diff --git a/docs/html/sdk/installing.jd b/docs/html/sdk/installing.jd index 7344bef..53d5515 100644 --- a/docs/html/sdk/installing.jd +++ b/docs/html/sdk/installing.jd @@ -147,8 +147,9 @@ last step in setting up your Android SDK.</p> <p>If you prefer to work in a different IDE, you do not need to install Eclipse or ADT, instead, you can directly use the SDK tools to build and -debug your application. The developer guide has more information about <a -href="{@docRoot}guide/developing/other-ide.html">Developing in Other IDEs</a>.</p> +debug your application. The <a href="{@docRoot}guide/developing/index.html">Overview</a> +section of the developer guide outlines the major steps that you need to complete +when developing in Eclipse or other IDEs.</p> @@ -546,9 +547,9 @@ first step in getting started with Android development. </p> <li>Get an overview of the <a href="{@docRoot}guide/developing/tools/index.html">development tools</a> that are available to you</li> - <li>Read how to develop <a - href="{@docRoot}guide/developing/eclipse-adt.html">in Eclipse/ADT</a> or - <a href="{@docRoot}guide/developing/other-ide.html">in other IDEs</a> + <li>Read the <a + href="{@docRoot}guide/developing/index.html">Overview</a> + for how to develop an Android application. </li> <li>Read <a href="{@docRoot}guide/developing/device.html">Developing on a Device</a> to set up an Android-powered device to run and test your application.</li> diff --git a/docs/html/sdk/ndk/index.jd b/docs/html/sdk/ndk/index.jd index 2f53305..2c3fd6a 100644 --- a/docs/html/sdk/ndk/index.jd +++ b/docs/html/sdk/ndk/index.jd @@ -1,16 +1,16 @@ ndk=true -ndk.win_download=android-ndk-r5b-windows.zip -ndk.win_bytes=61299831 -ndk.win_checksum=87745ada305ab639399161ab4faf684c +ndk.win_download=android-ndk-r5-windows.zip +ndk.win_bytes=62217450 +ndk.win_checksum=59cbb02d91d74e9c5c7278d94c989e80 -ndk.mac_download=android-ndk-r5b-darwin-x86.tar.bz2 +ndk.mac_download=android-ndk-r5-darwin-x86.tar.bz2 ndk.mac_bytes=50210863 -ndk.mac_checksum=019a14622a377b3727ec789af6707037 +ndk.mac_checksum=9dee8e4cb529a5619e9b8d1707478c32 -ndk.linux_download=android-ndk-r5b-linux-x86.tar.bz2 -ndk.linux_bytes=44138539 -ndk.linux_checksum=4c0045ddc2bfd657be9d5177d0e0b7e7 +ndk.linux_download=android-ndk-r5-linux-x86.tar.bz2 +ndk.linux_bytes=44362746 +ndk.linux_checksum=49d5c35ec02bafc074842542c58b7eb3 page.title=Android NDK @jd:body diff --git a/docs/html/sdk/ndk/overview.jd b/docs/html/sdk/ndk/overview.jd index 56b9201..2562a25 100644 --- a/docs/html/sdk/ndk/overview.jd +++ b/docs/html/sdk/ndk/overview.jd @@ -275,16 +275,19 @@ page.title=What is the NDK? <li>If you are developing in Eclipse with ADT, use the New Project Wizard to create a new Android project for each sample, using the "Import from Existing Source" option and importing the source from <code><ndk>/apps/<app_name>/project/</code>. Then, set up an AVD, - if necessary, and build/run the application in the emulator. For more information about - creating a new Android project in Eclipse, see <a href= - "{@docRoot}guide/developing/eclipse-adt.html">Developing in Eclipse</a>.</li> + if necessary, and build/run the application in the emulator.</li> <li>If you are developing with Ant, use the <code>android</code> tool to create the build file for each of the sample projects at <code><ndk>/apps/<app_name>/project/</code>. Then set up an AVD, if necessary, build your project in the usual way, and run it in the - emulator. For more information, see <a href= - "{@docRoot}guide/developing/other-ide.html">Developing in Other IDEs</a>.</li> + emulator.</li> + </ul> + + <p>For more information about developing with the Android SDK tools and what + you need to do to create, build, and run your applications, see + the <a href="{@docRoot}guide/developing/index.html">Overview</a> + section for developing on Android.</p> <h4 id="hello-jni">Exploring the hello-jni Sample</h4> diff --git a/docs/html/sdk/preview/features.jd b/docs/html/sdk/preview/features.jd index 81b4ff6..cd0dea1 100644 --- a/docs/html/sdk/preview/features.jd +++ b/docs/html/sdk/preview/features.jd @@ -1,4 +1,186 @@ -sdk.redirect=true - +page.title=Introduction to Honeycomb @jd:body +<p>Welcome to the Honeycomb preview SDK. Honeycomb is the next major release of the Android +platform and is optimized for tablet devices. This document provides an introduction to the new +platform features and APIs available in Honeycomb.</p> + + +<h2>Fragments</h2> + +<div class="figure" style="width:400px"> + <img src="{@docRoot}images/preview_hc/fragments_layout.png" alt="" /> + <p class="img-caption"><strong>Fragment Layout.</strong> An activity with two +fragments: one with a list view, on the left, and one that displays selected content on the +right. This demo is available in the samples package.</p> +</div> + + +<p>A new framework component that allows you to separate distinct elements of an activity into +self-contained modules that define their own UI and lifecycle—defining what may be +considered "sub-activities".</p> +<ul> + <li>Multiple fragments can be combined in a single activity to build a multi-pane UI in which +each pane manages its own lifecycle and user inputs</li> + <li>Fragments are self-contained and can be reused in multiple activities</li> + <li>Fragments can be added, removed, replaced and animated inside the activity</li> + <li>Fragment can be added to a back stack managed by the activity, preserving the state of +fragments as they are changed and allowing the user to navigate backward through the different +states</li> + <li>By <a +href="{@docRoot}guide/topics/resources/providing-resources.html#AlternativeResources">providing +alternative resources</a>, you can mix and match fragments, based +on the screen size and orientation</li> + <li>Fragments have direct access to their container activity and can contribute items to the +activity's Options Menu</li> +</ul> + +<p>For more information, see the <a +href="{@docRoot}guide/topics/fragments/index.html">Fragments</a> developer guide.</p> + + +<h2>Action Bar</h2> + +<p>A replacement for the traditional title bar, which provides users quick access to global +actions and different navigation modes.</p> +<ul> + <li>Provides quick access to items from the Options Menu ("action items") and interactive +widgets ("action views")</li> + <li>Includes the application logo in the left corner, which can perform actions when tapped +and can be replaced with a custom logo</li> + <li>Provides breadcumbs for navigating backward through fragments</li> + <li>Offers built in navigation modes, including tabs and a drop-down list</li> + <li>Can be customized with themes and custom backgrounds</li> + <li>And more</li> +</ul> + +<img src="{@docRoot}images/preview_hc/actionbar.png" alt="" /> +<p class="img-caption"><strong>Action Bar.</strong> An action bar with a custom logo, +tabs, and Options Menu. This demo is available in the samples package.</p> + +<p>For more information, see the <a +href="{@docRoot}guide/topics/ui/actionbar.html">Action Bar</a> developer guide.</p> + + +<h2>System Clipboard</h2> + +<p>Applications can copy and paste data (beyond mere text) to and from the system-wide +clipboard.</p> + +<ul> + <li>Clipped data can be plain text, a URI, or an intent</li> + <li>The new {@link android.content.ClipData} class represents a complex data type for the +clipboard</li> + <li>The new {@link android.content.ClipboardManager} class allows apps to add {@link +android.content.ClipData} to the clipboard (copy) and read {@link +android.content.ClipData} from the clipboard (paste)</li> + <li>The {@link android.content.ContentProvider} class has been extended to generate byte +streams based on data types added to the clipboard and point to data hosted in a +content provider</li> +</ul> + +<p>See {@link android.content.ClipData} and {@link android.content.ClipboardManager} +for more information. You can also see an example implementation of copy/paste in an updated +version of the NotePad application (available in the samples package).</p> + + +<h2>Drag and Drop</h2> + +<p>New APIs to perform drag and drop operations, leveraging the system clipboard APIs to +transport data.</p> + +<ul> + <li>Any {@link android.view.View} can be used for a drag and drop event and a thumbnail of that +view is generated and used during the drag</li> + <li>{@link android.view.ViewGroup}s that can receive the object are notified during hover and drop +events</li> + <li>The new {@link android.view.DragEvent} class describes a drag event relating to a view, +including the item's current coordinates, the type of action (whether the drag has entered the +view, exited the view, started, dropped, etc.), and provides access to the {@link +android.content.ClipData} being carried</li> + <li>The new {@link android.view.View.OnDragListener} interface defines a callback that views +can register in order to be notified of drag events being dispatched to the view; view's can +register a drag listener with {@link android.view.View#setOnDragListener setOnDragListener()}</li> +</ul> + +<p>See {@link android.view.DragEvent} and {@link android.view.View.OnDragListener} for more +information.</p> + + +<h2>New Animations</h2> + +<p>An all new animation framework.</p> + +<ul> + <li>A flexible animation system that allows you to animate the properties of any object (View, +Drawable, Fragment, Object, anything)</li> +</ul> + +<p>See the {@link android.animation} package.</p> + + +<h2>Extended App Widgets</h2> + +<p>App widgets can now be more interactive and accept finger gestures.</p> + +<ul> + <li>The complete list of supported widgets for an app widget is now: {@link +android.widget.AnalogClock}, {@link android.widget.Button}, {@link android.widget.Chronometer}, +{@link android.widget.ImageButton}, {@link android.widget.ImageView}, {@link +android.widget.ProgressBar}, {@link android.widget.TextView}, {@link +android.widget.ViewFlipper}, {@link android.widget.AdapterViewFlipper}, {@link +android.widget.StackView}, {@link android.widget.ListView}, and {@link +android.widget.GridView}.</li> +</ul> + + +<h2>Extended Status Bar Notifications</h2> + +<p>The {@link android.app.Notification} class has been extended to support more content-rich +status bar notifications when on xlarge screens.</p> + +<ul> + <li>New {@link android.app.Notification.Builder} class helps you easily create new {@link +android.app.Notification} objects</li> + <li>Support for a title in the status bar ticker (in addition to the normal ticker text)</li> + <li>Support for a large "sender" icon in the notification—a second icon intended for +social applications to show the contact photo of the person who is the source of the +notification</li> + <li>Support for custom layouts in the status bar ticker</li> + <li>Support for buttons in the expanded notification that deliver custom intents +(such as to control ongoing music in the background)</li> +</ul> + + +<h2>Plus Android 2.3</h2> + +<p>Honeycomb includes all platform changes introduced for Android 2.3.</p> + +<p>To take full advantage of Honeycomb, you should also be aware of the new features +and APIs introduced for Android 2.3. To learn more, read the <a +href="{@docRoot}sdk/android-2.3.html">Android 2.3 release notes</a>.</p> + +<!-- +<div class="special"> +<p>To set up your preview SDK and start developing apps for Honeycomb, see the <a +href="{@docRoot}sdk/preview/installing.html">Getting Started</a> guide.</p> +</div> +--> + + + + + + + + + + + + + + + + + + diff --git a/docs/html/sdk/preview/installing.jd b/docs/html/sdk/preview/installing.jd index 1e6b26b..c835c49 100644 --- a/docs/html/sdk/preview/installing.jd +++ b/docs/html/sdk/preview/installing.jd @@ -1,5 +1,62 @@ -sdk.redirect=true - +page.title=Getting Started with Honeycomb @jd:body +<p>First, you need to set up your development environment with the new SDK Tools and preview +platform:</p> + +<ol> + <li>Unpack the SDK Tools r8 package you've received. + <p>If you have an existing Android SDK directory, simply replace your existing {@code +tools/} directory with the one from the new package and add the {@code platform-tools/} +directory along side it (at the root of the SDK directory).</p></li> + <li>Unpack the platform package ({@code android-Froyo}) and place it in your SDK's {@code +platforms/} directory.</li> + <li>If you're using Eclipse, also update your Eclipse plugin using the provided archive file. + <ol> + <li>Select <strong>Help > Install new software</strong>.</li> + <li>Click <strong>Add</strong>.</li> + <li>Click <strong>Archive</strong>.</li> + <li>Locate and select the archive file. Click <strong>OK</strong>. + <p>Developer Tools now appear in the Available Software window and you can proceed +to install the plugin.</p> + </li> + </ol> + </li> +</ol> + +<p class="note"><strong>Note:</strong> Beginning with SDK Tools r8 (the version you've received), +the {@code adb} tool is now located in the {@code <sdk>/platform-tools/} directory (instead +of in {@code <sdk>/tools/}). Be sure to update your {@code PATH} environment variable and any +build/debugging scripts you have.</p> + + + +<h2 id="Setup">Set Up Your AVD and Application</h2> + +<p>With your SDK now set up, follow these steps to start developing an application for +Honeycomb.</p> + +<ol> + + <li>Create a new AVD targeted to "Android Froyo (Preview)" and with a custom skin resolution of +1280 x 800.</li> + + <li>Set the build target of your application to "Android Froyo (Preview)".</li> + <li>Set your manifest file's {@code <uses-sdk>} element to use {@code +android:minSdkVersion="Froyo"}. For example: +<pre> +<manifest> + <uses-sdk android:minSdkVersion="Froyo" /> + ... +</manifest> +</pre> +<p>"Froyo" is a provisional API Level for the Honeycomb release, used only during the preview +period. When the APIs are +finalized and the SDK is released publicly, you must update this with the appropriate API Level +integer.</p> +<p class="note"><strong>Note:</strong> By providing your {@code <uses-sdk>} element in the +manifest file <em>before</em> the {@code <application>} element, your application will +automatically apply the new Holographic theme.</p> +</li> +</ol> diff --git a/docs/html/sdk/preview/start.jd b/docs/html/sdk/preview/start.jd new file mode 100644 index 0000000..3bf70b3 --- /dev/null +++ b/docs/html/sdk/preview/start.jd @@ -0,0 +1,294 @@ +page.title=Getting Started with the Android 3.0 Preview +@jd:body + +<p>Welcome to Android 3.0!</p> + +<p>Android 3.0 is the next major release of the Android platform and is optimized for larger screen +devices, particularly tablets. We're offering a preview SDK so you can get a head-start developing +applications for it or simply test and optimize your existing application for upcoming devices.</p> + +<p><strong>Be aware that:</strong></p> +<ul> + <li>The APIs in the preview SDK are <strong>not final</strong>. Some APIs may change in behavior +or availability when the final SDK is made available.</li> + <li>You <strong>cannot</strong> publish an application that's built against the preview +SDK—you can only run an application built against the preview SDK on the Android +emulator.</li> + <li>The documentation on <a href="http://developer.android.com">developer.android.com</a> +does <strong>not</strong> include the Android 3.0 documentation—to read the API reference and +developer guides for Android 3.0, you must install the Android 3.0 preview documentation from +the AVD and SDK Manager.</li> +</ul> + + + +<h3>How do I start?</h3> + +<ol> + <li><a href="#Setup">Set up the preview SDK</a></li> + <li>Then choose your app adventure: + <ol type="a"> + <li><a href="#Optimize">Optimize Your App for Tablets and Similar Devices</a> + <p>When you have an existing application and you want to maintain compatibility with +older versions of Android.</p> + </li> + <li><a href="#Upgrade">Upgrade or Develop a New App for Tablets and Similar Devices</a> + <p>When you want to upgrade your application to use APIs introduced in Android 3.0 or + create a new application targeted to tablets and similar devices.</p></li> + </ol> + </li> +</ol> + +<h3>Code samples</h3> +<p>Many of the new features and APIs that are described in the <a href="{@docRoot}sdk/android-3.0.html#api"> +Android 3.0 Platform Preview</a> also have accompanying samples that help you understand how to use them. +To get the samples, download them from the SDK repository using the Android SDK Manager. After download +the samples are located in <code><sdk_root>/samples/android-Honeycomb</code>. The list of links +below helps you find samples for the features you are interested in:</p> +<ul> + <li><a href="{@docRoot}resources/samples/Honeycomb-Gallery/index.html">Honeycomb Gallery</a> - + A demo application highlighting how to use some of the new APIs in Honeycomb, including fragments, the action bar, + drag and drop, transition animations, and a stack widget.</li> + <li><a href="{@docRoot}resources/samples/ApiDemos/src/com/example/android/apis/app/index.html#Fragment">Fragments</a> + <li><a href="{@docRoot}resources/samples/ApiDemos/src/com/example/android/apis/app/ActionBarMechanics.html">Action Bar</a></li> + <li><a href="{@docRoot}resources/samples/ApiDemos/src/com/example/android/apis/content/ClipboardSample.html">Clipboard</a></li> + <li><a href="{@docRoot}resources/samples/ApiDemos/src/com/example/android/apis/view/DragAndDropDemo.html">Drag and Drop</a></li> + <li><a href="{@docRoot}resources/samples/ApiDemos/src/com/example/android/apis/view/List15.html"> + Multiple-choice selection for ListView and GridView</a></li> + <li><a href="{@docRoot}resources/samples/ApiDemos/src/com/example/android/apis/app/LoaderThrottle.html">Content Loaders</a></li> + <li><a href="{@docRoot}resources/samples/ApiDemos/src/com/example/android/apis/animation/index.html">Property Animation</a></li> + <li><a href="{@docRoot}resources/samples/ApiDemos/src/com/example/android/apis/view/SearchViewActionBar.html">Search View Widget</a></li> + <li><a href="{@docRoot}resources/samples/ApiDemos/src/com/example/android/apis/view/PopupMenu1.html">Popup Menu Widget</a></li> +</ul> + + +<h2 id="Setup">Set Up the Preview SDK</h2> + +<p>To start using the Android 3.0 preview SDK, set up your existing Android SDK with the new +platform:</p> +<p>(If you don't have an existing SDK, <a href="{@docRoot}sdk/index.html">download it +now</a>.)</p> +<ol> + <li><a href="{@docRoot}sdk/adding-components.html#launching">Launch the Android SDK and AVD +Manager</a> and install the following: + <ul> + <li>SDK Platform Android 3.0 Preview</li> + <li>Android SDK Tools, revision 9</li> + <li>Documentation for Android 'Honeycomb' Preview</li> + <li>Samples for SDK API Honeycomb Preview</li> + </ul> + </li> + <li><a href="{@docRoot}guide/developing/other-ide.html#AVD">Create an AVD</a> for tablets: set +the target to "Android 3.0 (Preview)" and the skin to "WXGA".</li> +</ol> + + +<h3>About emulator performance</h3> + +<p>Because the Android emulator must simulate the ARM instruction set architecture on your +computer and the WXGA screen is significantly larger than what the emulator +normally handles, emulator performance is much slower than usual.</p> + +<p>In particular, initializing the emulator can be slow and can take several +minutes, depending on your hardware. When the emulator is booting there is +limited user feedback, so please be patient and continue waiting until you see +the home screen appear. </p> + +<p>Note that you do not need to do a full boot of your emulator each time you +rebuild your application — typically you only need to boot at the start of +a session. See the Tips section below for information about using Snapshots to +cut startup time after first initialization. </p> + +<p>We're working hard to resolve the performance issues and it will improve in future releases. +Unfortunately, the emulator will perform slowly during your trial with the preview SDK. For the time +being, the emulator is still best way to evaluate your application's appearance and functionality on +Android 3.0.</p> + +<p class="note"><strong>Tip:</strong> To improve the startup time for the emulator, enable +snapshots for the AVD when you create it with the SDK and AVD Manager (there's a checkbox in +the GUI). Then, start the AVD from the manager and check <b>Launch from snapshot</b> and <b>Save to +snapshot</b>. This way, when you close the emulator, a snapshot of the AVD state is saved and +used to quickly relaunch the AVD next time. However, when you choose to save a snapshot, the +emulator will be slow to close, so you might want to enable <b>Save to +snapshot</b> only for the first time you launch the AVD.</p> + + +<h3>Known issues</h3> + +<p>The following known issues occur for Android 3.0 AVDs that are loaded in the emulator:</p> + <ul> + <li>You cannot take screenshots of an emulator screen. The Device Screen + Capture window displays <strong>Screen not available</strong>.</li> + <li>The emulator cannot receive incoming SMS messages.</li> + <li>GPS emulation is currently not supported.</li> + <li>When rotating the emulator screen by pressing Ctrl-F11, the screen turns green momentarily, +then displays the normal interface.</li> + <li>In some circumstances, the emulator displays a rotated portrait screen while in landscape +mode. To view the screen correctly, rotate the emulator to portrait mode by pressing Ctrl-F11 or +turn off the auto-rotate setting in <strong>Settings > Screen > Auto-rotate screen</strong>.</li> + <li>The Dev Tools application sometimes crashes when trying to use the Package Browser +feature.</li> + <li>On Ubuntu 10.04 64-bit machines, you cannot create an AVD that has an SD card.</li> + </ul> + + + +<h2 id="Optimize">Optimize Your Application for Tablets and Similar Devices</h2> + +<p>If you've already developed an application for Android, there are a few things you can do +to optimize it for a tablet-style experience, without changing the minimum platform version required +(you don't need to change the manifest {@code minSdkVersion}).</p> + +<p class="note"><strong>Note:</strong> All Android applications are forward-compatible, so +there's nothing you <em>have to</em> do—if your application is a good citizen of the Android +APIs, your app should work fine on devices running Android 3.0. However, in order to provide users +a better experience when running your app on an Android 3.0 tablet or similar-size device, we +recommend that you update your application to adapt to the new system theme and optimize your +application for larger screens.</p> + +<p>Here's what you can do to optimize your application for tablets running Android +3.0:</p> + +<ol> + <li><b>Test your current application on Android 3.0</b> + <ol> + <li>Build your application as-is and install it on your WXGA AVD (created above).</li> + <li>Perform your usual tests to be sure everything works and looks as expected.</li> + </ol> + </li> + + <li><b>Apply the new "holographic" theme to your application</b> + <ol> + <li>Open your manifest file and update the <a +href="{@docRoot}guide/topics/manifest/uses-sdk-element.html">{@code <uses-sdk>}</a> element to +set {@code android:targetSdkVersion} to {@code "Honeycomb"}. For example: +<pre> +<manifest ... > + <uses-sdk android:minSdkVersion="4" + android:targetSdkVersion="Honeycomb" /> + <application ... > + ... + <application> +</manifest> +</pre> + <p class="note"><strong>Note:</strong> The API Level value "Honeycomb" is a provisional API +Level that is valid only while testing against the preview SDK. You +<strong>should not</strong> publish your application using this API Level. When the final version of +the Android 3.0 SDK is made available, you must change this value to the real API Level that will be +specified for Android 3.0. For more information, read about <a +href="{@docRoot}guide/appendix/api-levels.html">Android API Levels</a>.</p> + <p>By targeting the Android 3.0 platform, the system automatically applies the Holographic theme +to each of your activities, when running on an Android 3.0 device.</p> + </li> + <li>Continue to build against your application's {@code minSdkVersion}, but install it +on the Android 3.0 AVD. Perform more testing on your application to be sure that your user interface +works well with the Holographic theme. + <p class="note"><strong>Note:</strong> If you've applied themes to your activities already, +they will override the Holographic theme that the system applies when you set the {@code +android:targetSdkVersion} to {@code "Honeycomb"}. +Once the Android 3.0 APIs are finalized and an official API Level is assigned, you can use +the <a href="{@docRoot}guide/topics/resources/providing-resources.html#VersionQualifier">system +version qualifier</a> to provide an alternative theme that's based on the Holographic theme when +your application is running on Android 3.0.</p> + </ol> + </li> + + <li><b>Supply alternative layout resources for xlarge screens</b> + <p>As discussed in the guide to <a +href="{@docRoot}guide/practices/screens_support.html">Supporting Multiple Screens</a>, Android +2.3 and above support the <code>xlarge</code> resource qualifier, which you should use to supply +alternative layouts for extra large screens.</p> + <p>By providing alternative layouts for some of your activities when running on extra large +screens, you can improve the user experience of your application on a tablet without using any +new APIs.</p> + <p>For example, here are some things to consider when creating a new layout for tables:</p> + <ul> + <li>Landscape layout: The "normal" orientation for tablets is usually landscape (wide), so +you should be sure that your activities offer an appropriate layout for such a wide viewing +area.</li> + <li>Button position: Consider whether the position of the most common buttons in your UI are +easily accessible while holding a tablet with two hands.</li> + </ul> + </li> +</ol> + + <p>In general, always be sure that your application follows the <a +href="{@docRoot}guide/practices/screens_support.html#screen-independence">Best Practices +for Screen Independence</a>.</p> + + +<h2 id="Upgrade">Upgrade or Develop a New App for Tablets and Similar Devices</h2> + +<p>If you want to develop something truly for tablet-type devices running Android 3.0, then you need +to use new APIs available in Android 3.0. This section introduces some of the new features that you +should use.</p> + +<p>The first thing to do when you create a project with the Android 3.0 preview is set the <a +href="{@docRoot}guide/topics/manifest/uses-sdk-element.html">{@code <uses-sdk>}</a> element to +use {@code "Honeycomb"} for the {@code android:minSdkVersion}. For example:</p> + +<pre> +<manifest ... > + <uses-sdk android:minSdkVersion="Honeycomb" /> + <application ... > + ... + <application> +</manifest> +</pre> + +<p class="note"><strong>Note:</strong> The API Level value "Honeycomb" is a provisional API +Level that is valid only while building and testing against the preview SDK. You +<strong>cannot</strong> publish your application using this API Level. When the final version of the +Android 3.0 SDK is made available, you must change this value to the real API Level that is +specified for Android 3.0. For more information, read about <a +href="{@docRoot}guide/appendix/api-levels.html">Android API Levels</a>.</p> + +<p>Be sure that the <a href="{@docRoot}guide/topics/manifest/uses-sdk-element.html">{@code +<uses-sdk>}</a> element appears <strong>before</strong> the <a +href="{@docRoot}guide/topics/manifest/application-element.html">{@code <application>}</a> +element.</p> + +<p>By targeting the Android 3.0 platform (and declaring it before <a +href="{@docRoot}guide/topics/manifest/application-element.html">{@code <application>}</a>), +the system automatically applies the new Holographic theme to each of your +activities.</p> + + + +<h3>Publishing your app for tablet-type devices only</h3> + +<p>Additionally, you should decide whether your application is for <em>only</em> tablet devices +(specifically, <em>xlarge</em> devices) or for devices of all sizes that may run Android 3.0.</p> + +<p>If your application is <em>only</em> for tablets (<em>xlarge</em> screens; not for mobile +devices/phones), then you should include the <a +href="{@docRoot}guide/topics/manifest/supports-screens-element.html">{@code +<supports-screens>}</a> element in your manifest with all sizes except for xlarge declared +false. For example:</p> + +<pre> +<manifest ... > + <uses-sdk android:minSdkVersion="Honeycomb" /> + <supports-screens android:smallScreens="false" + android:normalScreens="false" + android:largeScreens="false" + android:xlargeScreens="true" /> + <application ... > + ... + <application> +</manifest> +</pre> + +<p>With this declaration, you indicate that your application does not support any screen size except +extra large. External services such as Android Market may use this to filter your application +from devices that do not have an extra large screen.</p> + +<p>Otherwise, if you want your application to be available to both small devices (phones) and large +devices (tablets), do <em>not</em> include the <a +href="{@docRoot}guide/topics/manifest/supports-screens-element.html">{@code +<supports-screens>}</a> element.</p> + +<div class="special"> +<p>To learn more about some of the new APIs, +see the <a href="{@docRoot}sdk/android-3.0.html">Android 3.0 Platform Preview</a> document.</p> +</div> diff --git a/docs/html/sdk/sdk_toc.cs b/docs/html/sdk/sdk_toc.cs index 3358cf0..9b67fee 100644 --- a/docs/html/sdk/sdk_toc.cs +++ b/docs/html/sdk/sdk_toc.cs @@ -35,6 +35,21 @@ </a></li> </ul> + </li> + <?cs /if ?><?cs + if:sdk.preview ?> + <li><h2>Android 3.0 Preview SDK</h2> + <ul> + <li><a href="<?cs var:toroot ?>sdk/preview/start.html">Getting Started</a> <span class="new">new!</span></li> + <li class="toggle-list"> + <div><a href="<?cs var:toroot ?>sdk/android-3.0.html"> + <span class="en">Android 3.0 Platform</span></a> <span class="new">new!</span></div> + <ul> + <li><a href="<?cs var:toroot ?>sdk/api_diff/honeycomb/changes.html">API Differences Report +»</a></li> + </ul> + </li> + </ul> </li><?cs /if ?> <?cs diff --git a/docs/html/sdk/tools-notes.jd b/docs/html/sdk/tools-notes.jd index d188bc5..97ca8ab 100644 --- a/docs/html/sdk/tools-notes.jd +++ b/docs/html/sdk/tools-notes.jd @@ -241,9 +241,8 @@ code and resources in a separate development project. You can then reference the library project from other Android projects and, at build time, the tools compile the shared code and resources as part of the dependent applications. More information about this feature is available in the <a -href="{@docRoot}guide/developing/other-ide.html#libraryProject">Developing -in Other IDEs</a> document.</p> -<p>If you are developing in Eclipse, <a href="eclipse-adt.html">ADT 0.9.7</a> +href="{@docRoot}guide/developing/projects/index.html#LibraryProjects">Creating and Managing Projects</a> document.</p> +<p>If you are developing in Eclipse, <a href="eclipse-adt.html">ADT</a> provides the equivalent library project support.</p> </dd> </dl> |