M7350v1_en_gpl

This commit is contained in:
T
2024-09-09 08:52:07 +00:00
commit f9cc65cfda
65988 changed files with 26357421 additions and 0 deletions

View File

@@ -0,0 +1,9 @@
<html>
<head>
<meta http-equiv="refresh" content="0;url=documentation.html">
</head>
<body>
<a href="documentation.html">click here if you are not redirected</a>
</body>
</html>

View File

@@ -0,0 +1,8 @@
<html>
<head>
<meta http-equiv="refresh" content="0;url=framework/index.html">
</head>
<body>
<a href="framework/index.html">click here if you are not redirected</a>
</body>
</html>

View File

@@ -0,0 +1,8 @@
<html>
<head>
<meta http-equiv="refresh" content="0;url=docs/offline.html">
</head>
<body>
<a href="docs/offline.html">click here if you are not redirected</a>
</body>
</html>

View File

@@ -0,0 +1,8 @@
<html>
<head>
<meta http-equiv="refresh" content="0;url=../../samples/">
</head>
<body>
<a href="../../samples/">click here if you are not redirected</a>
</body>
</html>

38
base/docs/html/app.yaml Normal file
View File

@@ -0,0 +1,38 @@
application: androidappdocs-staging
version: 1
runtime: python
api_version: 1
# This file defines two mutually exclusive
# hander blocks:
# - a handler for use on a local dev_appserver
# during development or non-production doc build
# - a handler for use on a production gae
# instance. This handler requires that the
# docs files in the app have been compressed
# with divide_and_compress.py and that main.py
# and gae_shell/ are present.
#
# Only one of the handler blocks should be
# uncommented at any given time. By default,
# the development handler is exposed.
handlers:
# DEVELOPMENT HANDLER
# (this handler block *must* be commented
# out before pushing to a production server)
- url: /
static_dir: /
# PRODUCTION GAE HANDLER
#- url: /gae_shell/static
# static_dir: gae_shell/static
# expiration: 1d
#
#- url: /gae_shell/.*
# script: /gae_shell/shell.py
# login: admin
#
#- url: .*
# script: main.py

View File

@@ -0,0 +1,127 @@
community=true
page.title=Community
@jd:body
<div id="mainBodyFluid">
<h1>Community</h1>
<p>Welcome to the Android developers community! We're glad you're here and invite you to participate in these discussions. Before posting, please read the <a href="http://source.android.com/discuss/android-discussion-groups-charter">Groups Charter</a> that covers the community guidelines.</p>
<p class="note"><strong>Note:</strong> If you are seeking discussion about Android source code (not application development),
then please refer to the <a href="http://source.android.com/discuss">Open Source Project Mailing lists</a>.</p>
<p style="margin-bottom:.5em"><strong>Contents</strong></p>
<ol class="toc">
<li><a href="#BeforeYouPost">Before you post</a></li>
<li><a href="#ApplicationDeveloperLists">Application developer mailing lists</a></li>
<li><a href="#UsingEmail">Using email with the mailing lists</a></li>
<li><a href="#UsingIRC">Using IRC</a></li>
</ol>
<h2 id="BeforeYouPost">Before you post</h2>
<p>Before writing a post, please try the following:</p>
<ol>
<li><a href="{@docRoot}guide/appendix/faq/index.html">Read the FAQs</a> The most common questions about developing Android applications are addressed in this frequently updated list.</li>
<li><strong>Type in keywords of your questions in the main Android site's search bar</strong> (such as the one above). This search encompasses all previous discussions, across all groups, as well as the full contents of the site, documentation, and blogs. Chances are good that somebody has run into the same issue before.</li>
<li><b>Search the mailing list archives</b> to see whether your questions have already been discussed.
</li>
</ol>
<p>If you can't find your answer, then we encourage you to address the community.
As you write your post, please do the following:
<ol>
<li><b>Read
the <a href="http://sites.google.com/a/android.com/opensource/discuss/android-discussion-groups-charter">mailing list charter</a></b> that covers the community guidelines.
</li>
<li><b>Select the most appropriate mailing list for your question</b>. There are several different lists for
developers, described below.</li>
<li>
<b>Be very clear</b> about your question
in the subject -- it helps everyone, both those trying to answer your
question as well as those who may be looking for information in the
future.</li>
<li><b>Give plenty of details</b> in your post to
help others understand your problem. Code or log snippets, as well as
pointers to screenshots, may also be helpful. For a great guide to
phrasing your questions, read <a href="http://www.catb.org/%7Eesr/faqs/smart-questions.html">How To Ask Questions The Smart Way</a>.
</li>
</ol>
<h3 id="ApplicationDeveloperLists">Application developer mailing lists</h3>
<ul>
<li><b>Android beginners</b> - You're new to Android application development. You want to figure out how to get started with the Android SDK and the basic Android APIs? Start here. This list is open to any discussion around beginner-type questions for developers using the SDK; this is a great way to get up and running with your new application on the Android platform. Ask about getting your development environment set up, get help with the first steps of Android development (your first User Interface, your first permission, your first file on the Android filesystem, your first app on the Android Market...). Be sure to check the archives first before asking new questions. Please avoid advanced subjects, which belong on android-developers, and user questions, which will get a better reception on android-discuss.
<ul>
<li>Subscribe using Google Groups:&nbsp;<a href="http://groups.google.com/group/android-beginners">android-beginners</a></li>
<li>Subscribe via email:&nbsp;<a href="mailto:android-beginners-subscribe@googlegroups.com">android-beginners-subscribe@googlegroups.com</a></li>
</ul>
</li>
<li><b>Android developers</b> - You're now an experienced Android application developer. You've grasped the basics of Android app development, you're comfortable using the SDK, now you want to move to advanced topics. Get help here with troubleshooting applications, advice on implementation, and strategies for improving your application's performance and user experience. This is the not the right place to discuss user issues (use android-discuss for that) or beginner questions with the Android SDK (use android-beginners for that).
<ul>
<li>Subscribe using Google Groups:&nbsp;<a href="http://groups.google.com/group/android-developers">android-developers</a></li>
<li>Subscribe via email:&nbsp;<a href="mailto:android-developers-subscribe@googlegroups.com">android-developers-subscribe@googlegroups.com</a></li>
</ul>
</li>
<li><b>Android discuss</b> - The "water cooler" of Android discussion. You can discuss just about anything Android-related here, ideas for the Android platform, announcements about your applications, discussions about Android devices, community resources... As long as your discussion is related to Android, it's on-topic here. However, if you have a discussion here that could belong on another list, you are probably not reaching all of your target audience here and may want to consider shifting to a more targeted list.
<ul>
<li>Subscribe using Google Groups:&nbsp;<a href="http://groups.google.com/group/android-discuss">android-discuss</a></li>
<li>Subscribe via email:&nbsp;<a href="mailto:android-discuss-subscribe@googlegroups.com">android-discuss-subscribe@googlegroups.com</a></li>
</ul>
</li>
<li><b>Android ndk</b> - A place for discussing the Android NDK and topics related to using native code in Android applications.
<ul>
<li>Subscribe using Google Groups:&nbsp;<a href="http://groups.google.com/group/android-ndk">android-ndk</a></li>
<li>Subscribe via email:&nbsp;<a href="mailto:android-ndk-subscribe@googlegroups.com">android-ndk-subscribe@googlegroups.com</a></li>
</ul>
</li>
<li><b>Android security discuss</b> - A place for open discussion on secure development, emerging security concerns, and best practices for and by android developers. Please don't disclose vulnerabilities directly on this list, you'd be putting all Android users at risk.
<ul>
<li>Subscribe using Google Groups:&nbsp;<a href="http://groups.google.com/group/android-security-discuss">android-security-discuss</a></li>
<li>Subscribe via email:&nbsp;<a href="mailto:android-security-discuss@googlegroups.com">android-security-discuss@googlegroups.com</a></li>
</ul>
</li>
<li><b>Android security announce</b> - A low-volume group for security-related announcements by the Android Security Team.
<ul>
<li>Subscribe using Google Groups:&nbsp;<a href="http://groups.google.com/group/android-security-announce">android-security-announce</a></li>
<li>Subscribe via email:&nbsp;<a href="mailto:android-security-announce-subscribe@googlegroups.com">android-security-announce-subscribe@googlegroups.com</a></li>
</ul>
</li>
<li><b>Android Market Help Forum</b> - A web-based discussion forum where you can ask questions or report issues relating to Android Market.
<ul>
<li>URL:&nbsp;<a href="http://www.google.com/support/forum/p/Android+Market?hl=en">http://www.google.com/support/forum/p/Android+Market?hl=en</a></li>
</ul>
</li>
</ul>
<h2 id="UsingEmail">Using email with the mailing lists</h2>
<p>Instead of using the <a href="http://groups.google.com/">Google Groups</a> site, you can use your email client of choice to participate in the mailing lists.</p>
<p>To subscribe to a group without using the Google Groups site, use the link under "subscribe via email" in the lists above.</p>
<p>To set up how you receive mailing list postings by email:</p>
<ol><li>Sign into the group via the Google Groups site. For example, for the android-framework group you would visit <a href="http://groups.google.com/group/android-framework">http://groups.google.com/group/android-framework</a>.</li>
<li>Click "Edit
my membership" on the right side.</li>
<li>Under "How do
you want to read this group?" select one of the email options. </li>
</ol>
<h2 id="UsingIRC">Using IRC</h2>
<p>The Android community is using the #android channel on the irc.freenode.net server.
</p>
</div>

BIN
base/docs/html/favicon.ico Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.1 KiB

View File

@@ -0,0 +1 @@
google-site-verification: googlef295f8c7d59b0d29.html

View File

@@ -0,0 +1,357 @@
page.title=Android API Levels
@jd:body
<div id="qv-wrapper">
<div id="qv">
<h2>In this document</h2>
<ol>
<li><a href="#intro">What is API Level?</a></li>
<li><a href="#uses">Uses of API Level in Android</a></li>
<li><a href="#considerations">Development Considerations</a>
<ol>
<li><a href="#fc">Application forward compatibility</a></li>
<li><a href="#bc">Application backward compatibility</a></li>
<li><a href="#platform">Selecting a platform version and API Level</a></li>
<li><a href="#apilevel">Declaring a minimum API Level</a></li>
<li><a href="#testing">Testing against higher API Levels</a></li>
</ol>
</li>
<li><a href="#provisional">Using a Provisional API Level</a></li>
<li><a href="#filtering">Filtering the Documentation</a></li>
</ol>
<h2>See also</h2>
<ol>
<li><a href="{@docRoot}guide/topics/manifest/uses-sdk-element.html">&lt;uses-sdk&gt;</a> manifest element</li>
</ol>
</div>
</div>
<p>As you develop your application on Android, it's useful to understand the
platform's general approach to API change management. It's also important to
understand the API Level identifier and the role it plays in ensuring your
application's compatibility with devices on which it may be installed. </p>
<p>The sections below provide information about API Level and how it affects
your applications. </p>
<p>For information about how to use the "Filter by API Level" control
available in the API reference documentation, see
<a href="#filtering">Filtering the documentation</a> at the
end of this document. </p>
<h2 id="intro">What is API Level?</h2>
<p>API Level is an integer value that uniquely identifies the framework API
revision offered by a version of the Android platform.</p>
<p>The Android platform provides a framework API that applications can use to
interact with the underlying Android system. The framework API consists of:</p>
<ul>
<li>A core set of packages and classes</li>
<li>A set of XML elements and attributes for declaring a manifest file</li>
<li>A set of XML elements and attributes for declaring and accessing resources</li>
<li>A set of Intents</li>
<li>A set of permissions that applications can request, as well as permission
enforcements included in the system</li>
</ul>
<p>Each successive version of the Android platform can include updates to the
Android application framework API that it delivers. </p>
<p>Updates to the framework API are designed so that the new API remains
compatible with earlier versions of the API. That is, most changes in the API
are additive and introduce new or replacement functionality. As parts of the API
are upgraded, the older replaced parts are deprecated but are not removed, so
that existing applications can still use them. In a very small number of cases,
parts of the API may be modified or removed, although typically such changes are
only needed to ensure API robustness and application or system security. All
other API parts from earlier revisions are carried forward without
modification.</p>
<p>The framework API that an Android platform delivers is specified using an
integer identifier called "API Level". Each Android platform version supports
exactly one API Level, although support is implicit for all earlier API Levels
(down to API Level 1). The initial release of the Android platform provided
API Level 1 and subsequent releases have incremented the API Level.</p>
<p>The following table specifies the API Level supported by each version of the
Android platform.</p>
<table>
<tr><th>Platform Version</th><th>API Level</th></tr>
<tr><td>Android 2.3.3</td><td>10</td></tr>
<tr><td>Android 2.3</td><td>9</td></tr>
<tr><td>Android 2.2</td><td>8</td></tr>
<tr><td>Android 2.1</td><td>7</td></tr>
<tr><td>Android 2.0.1</td><td>6</td></tr>
<tr><td>Android 2.0</td><td>5</td></tr>
<tr><td>Android 1.6</td><td>4</td></tr>
<tr><td>Android 1.5</td><td>3</td></tr>
<tr><td>Android 1.1</td><td>2</td></tr>
<tr><td>Android 1.0</td><td>1</td></tr>
</table>
<h2 id="uses">Uses of API Level in Android</h2>
<p>The API Level identifier serves a key role in ensuring the best possible
experience for users and application developers:
<ul>
<li>It lets the Android platform describe the maximum framework API revision
that it supports</li>
<li>It lets applications describe the framework API revision that they
require</li>
<li>It lets the system negotiate the installation of applications on the user's
device, such that version-incompatible applications are not installed.</li>
</ul>
<p>Each Android platform version stores its API Level identifier internally, in
the Android system itself. </p>
<p>Applications can use a manifest element provided by the framework API &mdash;
<code>&lt;uses-sdk&gt;</code> &mdash; to describe the minimum and maximum API
Levels under which they are able to run, as well as the preferred API Level that
they are designed to support. The element offers three key attributes:</p>
<ul>
<li><code>android:minSdkVersion</code> &mdash; Specifies the minimum API Level
on which the application is able to run. The default value is "1".</li>
<li><code>android:targetSdkVersion</code> &mdash; Specifies the API Level
on which the application is designed to run. In some cases, this allows the
application to use manifest elements or behaviors defined in the target
API Level, rather than being restricted to using only those defined
for the minimum API Level.</li>
<li><code>android:maxSdkVersion</code> &mdash; Specifies the maximum API Level
on which the application is able to run. <strong>Important:</strong> Please read the <a
href="{@docRoot}guide/topics/manifest/uses-sdk-element.html"><code>&lt;uses-sdk&gt;</code></a>
documentation before using this attribute. </li>
</ul>
<p>For example, to specify the minimum system API Level that an application
requires in order to run, the application would include in its manifest a
<code>&lt;uses-sdk&gt;</code> element with a <code>android:minSdkVersion</code>
attribute. The value of <code>android:minSdkVersion</code> would be the integer
corresponding to the API Level of the earliest version of the Android platform
under which the application can run. </p>
<p>When the user attempts to install an application, or when revalidating an
appplication after a system update, the Android system first checks the
<code>&lt;uses-sdk&gt;</code> attributes in the application's manifest and
compares the values against its own internal API Level. The system allows the
installation to begin only if these conditions are met:</p>
<ul>
<li>If a <code>android:minSdkVersion</code> attribute is declared, its value
must be less than or equal to the system's API Level integer. If not declared,
the system assumes that the application requires API Level 1. </li>
<li>If a <code>android:maxSdkVersion</code> attribute is declared, its value
must be equal to or greater than the system's API Level integer.
If not declared, the system assumes that the application
has no maximum API Level. Please read the <a
href="{@docRoot}guide/topics/manifest/uses-sdk-element.html"><code>&lt;uses-sdk&gt;</code></a>
documentation for more information about how the system handles this attribute.</li>
</ul>
<p>When declared in an application's manifest, a <code>&lt;uses-sdk&gt;</code>
element might look like this: </p>
<pre>&lt;manifest&gt;
&lt;uses-sdk android:minSdkVersion="5" /&gt;
...
&lt;/manifest&gt;</pre>
<p>The principal reason that an application would declare an API Level in
<code>android:minSdkVersion</code> is to tell the Android system that it is
using APIs that were <em>introduced</em> in the API Level specified. If the
application were to be somehow installed on a platform with a lower API Level,
then it would crash at run-time when it tried to access APIs that don't exist.
The system prevents such an outcome by not allowing the application to be
installed if the lowest API Level it requires is higher than that of the
platform version on the target device.</p>
<p>For example, the {@link android.appwidget} package was introduced with API
Level 3. If an application uses that API, it must declare a
<code>android:minSdkVersion</code> attribute with a value of "3". The
application will then be installable on platforms such as Android 1.5 (API Level
3) and Android 1.6 (API Level 4), but not on the Android 1.1 (API Level 2) and
Android 1.0 platforms (API Level 1).</p>
<p>For more information about how to specify an application's API Level
requirements, see the <a
href="{@docRoot}guide/topics/manifest/uses-sdk-element.html"><code>&lt;uses-sdk&gt;</code></a>
section of the manifest file documentation.</p>
<h2 id="considerations">Development Considerations</h2>
<p>The sections below provide information related to API level that you should
consider when developing your application.</p>
<h3 id="fc">Application forward compatibility</h3>
<p>Android applications are generally forward-compatible with new versions of
the Android platform.</p>
<p>Because almost all changes to the framework API are additive, an Android
application developed using any given version of the API (as specified by its
API Level) is forward-compatible with later versions of the Android platform and
higher API levels. The application should be able to run on all later versions
of the Android platform, except in isolated cases where the application uses a
part of the API that is later removed for some reason. </p>
<p>Forward compatibility is important because many Android-powered devices
receive over-the-air (OTA) system updates. The user may install your
application and use it successfully, then later receive an OTA update to a new
version of the Android platform. Once the update is installed, your application
will run in a new run-time version of the environment, but one that has the API
and system capabilities that your application depends on. </p>
<p>In some cases, changes <em>below</em> the API, such those in the underlying
system itself, may affect your application when it is run in the new
environment. For that reason it's important for you, as the application
developer, to understand how the application will look and behave in each system
environment. To help you test your application on various versions of the Android
platform, the Android SDK includes multiple platforms that you can download.
Each platform includes a compatible system image that you can run in an AVD, to
test your application. </p>
<h3 id="bc">Application backward compatibility</h3>
<p>Android applications are not necessarily backward compatible with versions of
the Android platform older than the version against which they were compiled.
</p>
<p>Each new version of the Android platform can include new framework APIs, such
as those that give applications access to new platform capabilities or replace
existing API parts. The new APIs are accessible to applications when running on
the new platform and, as mentioned above, also when running on later versions of
the platform, as specified by API Level. Conversely, because earlier versions of
the platform do not include the new APIs, applications that use the new APIs are
unable to run on those platforms.</p>
<p>Although it's unlikely that an Android-powered device would be downgraded to
a previous version of the platform, it's important to realize that there are
likely to be many devices in the field that run earlier versions of the
platform. Even among devices that receive OTA updates, some might lag and
might not receive an update for a significant amount of time. </p>
<h3 id="platform">Selecting a platform version and API Level</h3>
<p>When you are developing your application, you will need to choose
the platform version against which you will compile the application. In
general, you should compile your application against the lowest possible
version of the platform that your application can support.
<p>You can determine the lowest possible platform version by compiling the
application against successively lower build targets. After you determine the
lowest version, you should create an AVD using the corresponding platform
version (and API Level) and fully test your application. Make sure to declare a
<code>android:minSdkVersion</code> attribute in the application's manifest and
set its value to the API Level of the platform version. </p>
<h3 id="apilevel">Declaring a minimum API Level</h3>
<p>If you build an application that uses APIs or system features introduced in
the latest platform version, you should set the
<code>android:minSdkVersion</code> attribute to the API Level of the latest
platform version. This ensures that users will only be able to install your
application if their devices are running a compatible version of the Android
platform. In turn, this ensures that your application can function properly on
their devices. </p>
<p>If your application uses APIs introduced in the latest platform version but
does <em>not</em> declare a <code>android:minSdkVersion</code> attribute, then
it will run properly on devices running the latest version of the platform, but
<em>not</em> on devices running earlier versions of the platform. In the latter
case, the application will crash at runtime when it tries to use APIs that don't
exist on the earlier versions.</p>
<h3 id="testing">Testing against higher API Levels</h3>
<p>After compiling your application, you should make sure to test it on the
platform specified in the application's <code>android:minSdkVersion</code>
attribute. To do so, create an AVD that uses the platform version required by
your application. Additionally, to ensure forward-compatibility, you should run
and test the application on all platforms that use a higher API Level than that
used by your application. </p>
<p>The Android SDK includes multiple platform versions that you can use,
including the latest version, and provides an updater tool that you can use to
download other platform versions as necessary. </p>
<p>To access the updater, use the <code>android</code> command-line tool,
located in the &lt;sdk&gt;/tools directory. You can launch the Updater by using
the <code>android</code> command without specifying any options. You can
also simply double-click the android.bat (Windows) or android (OS X/Linux) file.
In ADT, you can also access the updater by selecting
<strong>Window</strong>&nbsp;>&nbsp;<strong>Android SDK and AVD
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
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
you begin developing on the platform although the APIs may not be final, the
platform's API Level integer will not be specified. You must instead use the
platform's <em>provisional API Level</em> in your application manifest, in order
to build applications against the platform. A provisional API Level is not an
integer, but a string matching the codename of the unreleased platform version.
The provisional API Level will be specified in the release notes for the Early
Look SDK release notes and is case-sensitive.</p>
<p>The use of a provisional API Level is designed to protect developers and
device users from inadvertently publishing or installing applications based on
the Early Look framework API, which may not run properly on actual devices
running the final system image.</p>
<p>The provisional API Level will only be valid while using the Early Look SDK
and can only be used to run applications in the emulator. An application using
the provisional API Level can never be installed on an Android device. At the
final release of the platform, you must replace any instances of the provisional
API Level in your application manifest with the final platform's actual API
Level integer.</p>
<h2 id="filtering">Filtering the Reference Documentation by API Level</h2>
<p>Reference documentation pages on the Android Developers site offer a "Filter
by API Level" control in the top-right area of each page. You can use the
control to show documentation only for parts of the API that are actually
accessible to your application, based on the API Level that it specifies in
the <code>android:minSdkVersion</code> attribute of its manifest file. </p>
<p>To use filtering, select the checkbox to enable filtering, just below the
page search box. Then set the "Filter by API Level" control to the same API
Level as specified by your application. Notice that APIs introduced in a later
API Level are then grayed out and their content is masked, since they would not
be accessible to your application. </p>
<p>Filtering by API Level in the documentation does not provide a view
of what is new or introduced in each API Level &mdash; it simply provides a way
to view the entire API associated with a given API Level, while excluding API
elements introduced in later API Levels.</p>
<p>If you decide that you don't want to filter the API documentation, just
disable the feature using the checkbox. By default, API Level filtering is
disabled, so that you can view the full framework API, regardless of API Level.
</p>
<p>Also note that the reference documentation for individual API elements
specifies the API Level at which each element was introduced. The API Level
for packages and classes is specified as "Since &lt;api level&gt;" at the
top-right corner of the content area on each documentation page. The API Level
for class members is specified in their detailed description headers,
at the right margin. </p>

View File

@@ -0,0 +1,106 @@
page.title=Reference of Available Intents
@jd:body
<p>This document describes the default applications and settings that Google provides
in their standard Android implementation. </p>
<h3>Intents handled by Google Android applications<a name="googleintents" id="googleintents"></a></h3>
<p> Android ships with Activities that handle the following Intent URI/Action pairs. </p>
<table width="100%" border="1">
<tr>
<th scope="col">Scheme</th>
<th scope="col">Action<br />
android.intent.action.<em>value</em></th>
<th scope="col">Description</th>
</tr>
<tr>
<td>http://<em>web_address</em><br />
https://<em>web_address</em></td>
<td>VIEW</td>
<td>Open a browser window to the URL specified. </td>
</tr>
<tr>
<td>&quot;&quot; (empty string) <br />
http://<em>web_address</em><br />
https://<em>web_address</em></td>
<td>WEB_SEARCH</td>
<td>Opens the file at the location on the device in the browser. </td>
</tr>
<tr>
<td height="103">tel: <em>phone_number</em></td>
<td>CALL</td>
<td><p>Calls the entered phone number. Valid telephone numbers as defined
in <a href="http://tools.ietf.org/html/rfc3966">the IETF RFC 3966</a> are
accepted. Valid examples include the following:</p>
<ul>
<li>tel:2125551212 </li>
<li>tel:
(212) 555 1212</li>
</ul>
<p>The dialer is good at normalizing some kinds of schemes: for example
telephone numbers, so the schema described isn't strictly required
in the {@link android.net.Uri#parse(java.lang.String)
Uri(URI string)} factory. However, if you have not tried a
schema or are unsure whether it can be handled, use the {@link
android.net.Uri#fromParts(java.lang.String, java.lang.String,
java.lang.String) Uri.fromParts(scheme, ssp, fragment)} factory
instead.</p>
<p><strong><em>Note:</em></strong>&nbsp;&nbsp;&nbsp;This requires your
application to request the following permission in your manifest: <code>&lt;uses-permission
id=&quot;android.permission.CALL_PHONE&quot; /&gt;</code></p></td>
</tr>
<tr>
<td><p>tel:<em>phone_number</em><br />
voicemail:</p> </td>
<td>DIAL</td>
<td><p>Dials (but does not actually initiate the call) the number given
(or the stored voicemail on the phone). Telephone number normalization
described for CALL applies to DIAL as well. </p> </td>
</tr>
<tr>
<td>geo:<em>latitude</em>,<em>longitude</em><br />
geo:<em>latitude</em>,<em>longitude</em>?z=<em>zoom</em><br />
geo:0,0?q=<em>my+street+address</em><br />
geo:0,0?q=<em>business+near+city</em><br />
</td>
<td>VIEW</td>
<td>Opens the Maps application to the given location or query. The Geo URI scheme
(not fully supported) is <a href="http://tools.ietf.org/html/draft-mayrhofer-geo-uri-00">currently under
development</a>.<p>
The <em>z</em> field specifies the zoom level. A zoom level of 1 shows the whole Earth, centered at the
given <em>lat</em>,<em>lng</em>. A zoom level of 2 shows a quarter of the Earth, and so on. The highest
zoom level is 23. A larger zoom level will be clamped to 23.
</td>
</tr>
<tr>
<td>google.streetview:cbll=<em>lat</em>,<em>lng</em>&amp;cbp=1,<em>yaw</em>,,<em>pitch</em>,<em>zoom</em>&amp;mz=<em>mapZoom</em>
</td>
<td>VIEW</td>
<td>Opens the Street View application to the given location. The URI scheme is
based on the syntax used for Street View panorama information in Google Maps URLs.<p>
The cbll field is required. The cbp and mz fields are optional.<p>
<table border="1">
<tr><th>Parameter</th><th>Description</th></tr>
<tr><td>lat</td><td>latitude</td></tr>
<tr><td>lng</td><td>longitude</td></tr>
<tr><td>yaw</td><td>Panorama center-of-view in degrees clockwise from North.<br />
<b>Note:</b> The two commas after the yaw parameter are required. They are present
for backwards-compatibility reasons.</td></tr>
<tr><td>pitch</td><td>Panorama center-of-view in degrees from
-90 (look straight up) to 90 (look straight down.)</td></tr>
<tr><td>zoom</td><td>Panorama zoom. 1.0 = normal zoom, 2.0 = zoomed in 2x, 3.0 = zoomed in 4x, and so on.<br />
A zoom of 1.0 is 90 degree horizontal FOV for a nominal
landscape mode 4 x 3 aspect ratio display.
Android phones in portrait mode will adjust the zoom so that
the vertical FOV is approximately the same as the landscape vertical
FOV. This means that the horizontal FOV of an Android phone in portrait
mode is much narrower than in landscape mode. This is done to minimize
the fisheye lens effect that would be present if a 90 degree horizontal
FOV was used in portrait mode.</td></tr>
<tr><td>mapZoom</td><td>The map zoom of the map location associated with this panorama. This value is passed on to the
Maps activity when the Street View "Go to Maps" menu item is chosen. It corresponds to the <em>z</em> parameter in
the geo: intent.</td></tr>
</table>
</td>
</tr>
</table>
<p></p>

View File

@@ -0,0 +1,819 @@
page.title=Common Tasks and How to Do Them in Android
parent.title=FAQs, Tips, and How-to
parent.link=index.html
@jd:body
<ul>
<li><a href="#neweclipseandroidproject">Creating an Android Application using
the Eclipse plugin</a></li>
<li><a href="#newandroidprojectnoeclipse">Creating an Android Application without
the Eclipse plugin</a></li>
<li><a href="#addexternallibrary">Adding an External Library (.jar) using Eclipse</a></li>
<li><a href="#implementcallbacks">Implementing Activity callbacks</a> (Android
calls your activity at various key moments in its life cycle. You must know
how to handle each of these to draw your screen, initialize class members,
and acquire data.)</li>
<li><a href="#opennewscreen">Opening a new screen</a></li>
<li><a href="#listening">Listening for button clicks </a></li>
<li><a href="#configurewindowproperties">Configuring general window properties </a></li>
<li><a href="#localhostalias">Referring to localhost from the emulated environment</a></li>
<li><a href="#appstate">Storing and retrieving state</a></li>
<li><a href="{@docRoot}guide/topics/data/data-storage.html#preferences">Storing and retrieving preferences</a></li>
<li><a href="#storingandretrieving">Storing and retrieving larger or more complex
persistent data</a> (files and data) </li>
<li><a href="#playback">Playing audio, video, still, or other media files</a></li>
<li><a href="#broadcastreceivers">Listening for and broadcasting global messages
and setting alarms</a></li>
<li><a href="#alerts">Displaying alerts </a></li>
<li><a href="#progressbar">Displaying a progress bar</a> </li>
<li><a href="#addmenuitems">Adding items to the screen menu</a> </li>
<li><a href="#webpage">Display a web page</a> </li>
<li><a href="#binding">Binding to data</a></li>
<li><a href="#handle">Getting a Handle to a Screen Element</a></li>
<li><a href="#captureimages">Capture images from the phone camera </a></li>
<li><a href="#threading">Handling expensive operations in the UI thread</a></li>
<li><a href="#selectingtext">Selecting, highlighting, or styling portions of
text</a></li>
<li><a href="#querymap">Utilizing attributes in a Map query</a></li>
<li><a href="#filelist">List of files for an Android application</a></li>
<li><a href="#logging">Print messages to a log file</a></li>
</ul>
<p>The ApiDemos sample application includes many, many examples of common
tasks and UI features. See the code inside
<code>&lt;sdk&gt;samples/ApiDemos</code> and the other sample applications
under the <code>samples/</code> folder in the SDK.</p>
<h2 id="neweclipseandroidproject">Creating an Android Application using the Eclipse Plugin</h2>
<p>Using the Android Eclipse plugin is the fastest and easiest way
to start creating a new Android application. The plugin automatically generates
the correct project structure for your application, and keeps the resources
compiled for you automatically.</p>
<p>It is still a good idea to know what is going on though. Take a look at <a
href="{@docRoot}guide/topics/fundamentals.html">Application Fundamentals</a>
to understand the basics of how an Android application works.</p>
<p>You should also take a look at the ApiDemos application and the other sample
applications included in the SDK, in the <code>&lt;sdk&gt;/samples/</code>
folder in the SDK.</p>
<p>Finally, a great way to started with Android development in Eclipse is to
follow both the <a href="{@docRoot}resources/tutorials/hello-world.html">Hello,
World</a> and <a
href="{@docRoot}resources/tutorials/notepad/index.html">Notepad</a> code
tutorials. In particular, the start of the Hello Android tutorial is an
excellent introduction to creating a new Android application in Eclipse.</p>
<h2 id="newandroidprojectnoeclipse">Creating an Android Application without the Eclipse Plugin</h2>
<p>This topic describes the manual steps in creating an Android application.
Before reading this, you should read <a
href="{@docRoot}guide/topics/fundamentals.html">Application Fundamentals</a>
to understand the basics of how an Android application works. You might also
want to look at the sample code included with the Android SDK, in the
<code>&lt;sdk&gt;/samples/</code> directory. </p>
<p>Here is a list of the basic steps in building an application.</p>
<ol>
<li><strong>Create your required resource files</strong> &nbsp;&nbsp;This includes
the AndroidManifest.xml global description file, string files that your application
needs, and layout files describing your user interface. A full list of optional
and required files and syntax details for each is given in <a href="#filelist">File
List for an Android Application</a>. </li>
<li><strong>Design your user interface</strong> &nbsp;&nbsp;See <a
href="{@docRoot}guide/topics/ui/index.html">User Interface</a> for
details on elements of the Android screen. </li>
<li><strong>Implement your Activity </strong>(this page)<strong>&nbsp;&nbsp; </strong> You
will create one class/file for each screen in your application. Screens will
inherit from an {@link android.app android.app} class, typically {@link android.app.Activity
android.app.Activity} for basic screens, {@link android.app.ListActivity
android.app.ListActivity} for list screens, or {@link android.app.Dialog
android.app.Dialog} for dialog boxes. You will implement the required callbacks
that let you draw your screen, query data, and commit changes, and also perform
any required tasks such as opening additional screens or reading data from
the device. Common tasks, such as opening a new screen or reading data from
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
package</a>.</strong> The Android SDK has some nice tools for generating
projects and debugging code. </li>
</ol>
<h2 id="addexternallibrary">Adding an External Library (.jar) using Eclipse</h2>
<p>
You can use a third party JAR in your application by adding it to your Eclipse project as follows:
</p>
<ol>
<li>
In the <strong>Package Explorer</strong> panel, right-click on your project and select <strong>Properties</strong>.
<li>
Select <strong>Java Build Path</strong>, then the tab <strong>Libraries</strong>.
<li>
Press the <strong>Add External JARs...</strong> button and select the JAR file.
</ol>
<p>
Alternatively, if you want to include third party JARs with your package, create a new directory for them within your project and select <strong>Add Library...</strong> instead.</p>
<p>
It is not necessary to put external JARs in the assets folder.
</p>
<a name="implementcallbacks" id="implementcallbacks"></a>
<h2>Implementing Activity Callbacks</h2>
<p>Android calls a number of callbacks to let you draw your screen, store data before
pausing, and refresh data after closing. You must implement at least some of
these methods. See <a href="{@docRoot}guide/topics/fundamentals.html#lcycles">Lifecycles</a>
discussion in Application Fundamentals to learn when and in what order these methods
are called. Here are some of the standard types of screen classes that Android provides:</p>
<ul>
<li>{@link android.app.Activity android.app.Activity} - This is a standard screen,
with no specialization.</li>
<li>{@link android.app.ListActivity android.app.ListActivity} - This is a screen
that is used to display a list of something. It hosts a ListView object,
and exposes methods to let you identify the selected item, receive callbacks
when the selected item changes, and perform other list-related actions. </li>
<li>{@link android.app.Dialog android.app.Dialog} - This is a small, popup dialog-style
window that isn't intended to remain in the history stack. (It is not resizeable
or moveable by the user.)</li>
</ul>
<a name="opennewscreen" id="opennewscreen"></a><h2>Opening a New Screen</h2>
<p>Your Activity will often need to open another Activity screen as it progresses.
This new screen can be part of the same application or part of another application,
the new screen can be floating or full screen, it can return a result, and you
can decide whether to close this screen and remove it from the history stack
when you are done with it, or to keep the screen open in history. These next
sections describe all these options. </p>
<h3>Floating or full?<a name="floatingorfull" id="floatingorfull"></a></h3>
<p>When you open a new screen you can decide whether to make it transparent or floating,
or full-screen. The choice of new screen affects the event sequence of events
in the old screen (if the new screen obscures the old screen, a different
series of events is called in the old screen). See <a
href="{@docRoot}guide/topics/fundamentals.html#lcycles">Lifecycles</a> discussion
in Application Fundamentals for details. </p>
<p>Transparent or floating windows are implemented in three
standard ways: </p>
<ul>
<li>Create an {@link android.app.Dialog app.Dialog} class </li>
<li>Create an {@link android.app.AlertDialog app.AlertDialog} class </li>
<li>Set the {@link android.R.style#Theme_Dialog} <em>theme</em> attribute to <code>&#064;android:style/Theme.Dialog</code>
in your AndroidManifest.xml file. For example:
<pre>&lt;activity class=&quot;AddRssItem&quot; android:label=&quot;Add an item&quot; android:theme=&quot;&#064;android:style/Theme.Dialog&quot;/&gt;
</pre></li>
</ul>
<p>Calling startActivity() or startActivityForResult() will open a new screen in whatever
way it defines itself (if it uses a floating theme it will be floating,
otherwise it will be full screen). </p>
<h3>Opening a Screen </h3>
<p>When you want to open a new screen, you can either explicitly specify the activity
class to open, or you can let the operating system decide which screen to open,
based upon the data and various parameters you pass in. A screen is opened by
calling {@link android.app.Activity#startActivity(android.content.Intent) startActivity}
and passing in an {@link android.content.Intent Intent} object, which specifies
the criteria for the handling screen. To specify a specific screen, call Intent.setClass
or setClassName with the exact activity class to open. Otherwise, set a variety
of values and data, and let Android decide which screen is appropriate to open.
Android will find one or zero Activities that match the specified requirements;
it will never open multiple activities for a single request. More information
on Intents and how Android resolves them to a specific class is given in the
{@link android.content.Intent Intent} topic. </p>
<a name="intentexamples" id="intentexamples"></a><h3>Some Intent examples </h3>
<p>The following snippet loads the com.android.samples.Animation1 class, and
passes it some arbitrary data.:</p>
<pre>Intent myIntent = new Intent();
myIntent.setClassName(&quot;com.android.samples&quot;, &quot;com.android.samples.Animation1&quot;);
myIntent.putExtra(&quot;com.android.samples.SpecialValue&quot;, &quot;Hello, Joe!&quot;); // key/value pair, where key needs current package prefix.
startActivity(myIntent); </pre>
<p>The next snippet requests that a Web page be opened by specifying the VIEW action,
and a URI data string starting with &quot;http://&quot; schema:</p>
<pre>Intent myIntent = new Intent(Intent.VIEW_ACTION, Uri.parse(&quot;http://www.google.com&quot;));</pre>
<p>Here is the intent filter from the AndroidManifest.xml file for com.android.browser:</p>
<pre>&lt;intent-filter&gt;
&lt;action android:name=&quot;android.intent.action.VIEW&quot; /&gt;
&lt;category android:name=&quot;android.intent.category.DEFAULT&quot; /&gt;
&lt;scheme android:name=&quot;http&quot; /&gt;
&lt;scheme android:name=&quot;https&quot; /&gt;
&lt;scheme android:name=&quot;file&quot; /&gt;
&lt;/intent-filter&gt; </pre>
<p>Android defines a number of standard values, for instance the action constants
defined by {@link android.content.Intent}. You can define custom values, but
both the caller and handler must use them. See the &lt;intent-filter&gt;
tag description in <a href="{@docRoot}guide/topics/manifest/manifest-intro.html">The AndroidManifest.xml
File</a> for more information on the manifest syntax for the handling
application. </p>
<a name="returningaresult" id="returningaresult"></a><h3>Returning a Result from a Screen</h3>
<p>A window can return a result after it closes. This result will be passed back
into the calling Activity's {@link android.app.Activity#onActivityResult(int,int,android.content.Intent)
onActivityResult()} method, which can supply an Intent containing arbitrary data, along with
the request code passed to startActivityForResult(). Note that you must call the {@link
android.app.Activity#startActivityForResult(android.content.Intent,int) startActivityForResult()}
method that accepts a request code parameter to get this callback. The following
code demonstrates opening a new screen and retrieving a result. </p>
<pre>// Open the new screen.
public void onClick(View v){
// Start the activity whose result we want to retrieve. The
// result will come back with request code GET_CODE.
Intent intent = new Intent(this, com.example.app.ChooseYourBoxer.class);
startActivityForResult(intent, CHOOSE_FIGHTER);
}
// Listen for results.
protected void onActivityResult(int requestCode, int resultCode, Intent data){
// See which child activity is calling us back.
switch (resultCode) {
case CHOOSE_FIGHTER:
// This is the standard resultCode that is sent back if the
// activity crashed or didn't doesn't supply an explicit result.
if (resultCode == RESULT_CANCELED){
myMessageboxFunction("Fight cancelled");
}
else {
myFightFunction(data);
}
default:
break;
}
}
// Class SentResult
// Temporary screen to let the user choose something.
private OnClickListener mLincolnListener = new OnClickListener(){
public void onClick(View v) {
Bundle stats = new Bundle();
stats.putString("height","6\'4\"");
stats.putString("weight", "190 lbs");
stats.putString("reach", "74\"");
setResult(RESULT_OK, "Lincoln", stats);
finish();
}
};
private OnClickListener mWashingtonListener = new OnClickListener() {
public void onClick(View v){
Bundle stats = new Bundle();
stats.putString("height","6\'2\"");
stats.putString("weight", "190 lbs");
stats.putString("reach", "73\"");
setResult(RESULT_OK, "Washington", Bundle);
finish();
}
};
</pre>
<h3>Lifetime of the new screen </h3>
<p>An activity can remove itself from the history stack by calling {@link android.app.Activity#finish()
Activity.finish()} on itself, or the activity that opened the screen can call
{@link android.app.Activity#finishActivity(int) Activity.finishActivity()}
on any screens that it opens to close them. </p>
<a name="listening" id="listening"></a><h2>Listening for Button Clicks</h2>
<p>Button click and other UI event capturing are covered in <a href="{@docRoot}guide/topics/ui/ui-events.html">Handling UI Events</a> on the UI Design page.</p>
<a name="configurewindowproperties" id="configurewindowproperties"></a><h2>Configuring General Window Properties</h2>
<p>You can set a number of general window properties, such as whether to display
a title, whether the window is floating, and whether it displays an icon, by
calling methods on the {@link android.view.Window Window} member
of the underlying View object for the window. Examples include calling {@link
android.app.Activity#getWindow() getWindow().requestFeature()} (or the convenience
method {@link android.app.Activity#requestWindowFeature(int) requestWindowFeature(<em>some_feature</em>)})
to hide the title. Here is an example of hiding the title bar:</p>
<pre>//Hide the title bar
requestWindowFeature(Window.FEATURE_NO_TITLE);
</pre>
<p>A better way to achieve the same end is to specify a theme in your Android
Manifest file:</p>
<pre>&lt;application android:icon="@drawable/icon" android:theme="@android:style/Theme.NoTitleBar"&gt;
</pre>
<p>This is preferable because it tells the system not to show a title bar while
your application is starting up. With the explicit method call, your application
will have a title bar visible to the user until <code>onCreate</code> runs.</p>
<p>(Note that this can be applied to either the <code>&lt;application&gt;</code>
tag or to individual <code>&lt;activity&gt;</code> tags.)</p>
<a name="localhostalias" id="localhostalias"></a><h2>Referring to localhost from the emulated environment</h2>
<p>
If you need to refer to your host computer's <em>localhost</em>, such as when you
want the emulator client to contact a server running on the same host, use the alias
<code>10.0.2.2</code> to refer to the host computer's loopback interface.
From the emulator's perspective, localhost (<code>127.0.0.1</code>) refers to its own
loopback interface.
</p>
<a name="appstate" id="appstate"></a><h2>Storing and Retrieving State</h2>
<p>If your application is dumped from memory because of space concerns, it will lose
all user interface state information such as checkbox state and text box values
as well as class member values. Android calls {@link android.app.Activity#onSaveInstanceState(android.os.Bundle)
Activity.onSaveInstanceState} before it pauses the application. This method hands in a {@link
android.os.Bundle Bundle} that can be used to store name/value pairs that will
persist and be handed back to the application even if it is dropped from memory.
Android will pass this Bundle back to you when it calls {@link android.app.Activity#onCreate(android.os.Bundle)
onCreate()}. This Bundle only exists while the application is still in the history
stack (whether or not it has been removed from memory) and will be lost when
the application is finalized. See the topics for {@link android.app.Activity#onSaveInstanceState} and
{@link android.app.Activity#onCreate} for
examples of storing and retrieving state.</p>
<p>Read more about the lifecycle of an application in <a href="{@docRoot}guide/topics/fundamentals.html">Application Fundamentals</a>.</p>
<h3>Storing and Retrieving Larger or More Complex Persistent Data<a name="storingandretrieving" id="storingandretrieving"></a></h3>
<p>Your application can store files or complex collection objects, and reserve them
for private use by itself or other activities in the application, or it can expose
its data to all other applications on the device. See <a href="{@docRoot}guide/topics/data/data-storage.html">Storing,
Retrieving, and Exposing Data</a> to learn how to store and retrieve private data,
how to store and retrieve common data from the device, and how to expose your
private data to other applications.</p>
<a name="playback" id="playback"></a><h2>Playing Media Files</h2>
<p>Please see the document <a href="{@docRoot}guide/topics/media/index.html">Audio and Video</a> for more details.</p>
<a name="broadcastreceivers" id="broadcastreceivers"></a><h2>Listening For and Broadcasting Global Messages, and Setting Alarms</h2>
<p>You can create a listening class that can be notified or even instantiated whenever
a specific type of system message is sent.
</p>
<p>The listening classes, called broadcast receivers, extend {@link android.content.BroadcastReceiver
BroadcastReceiver}. If you want Android to instantiate the object whenever an appropriate
intent notification is sent, define the receiver with a <code>&lt;receiver&gt;</code> element
in the AndroidManifest.xml file. If the caller is expected to instantiate the
object in preparation to receive a message, this is not required. The receiver
will get a call to their {@link android.content.BroadcastReceiver#onReceive(android.content.Context,android.content.Intent)
BroadcastReceiver.onReceive()} method. A receiver can define an <code>&lt;intent-filter&gt;</code> tag
that describes the types of messages it will receive. Just as Android's IntentResolver
will look for appropriate Activity matches for a startActivity() call, it will
look for any matching Receivers (but it will send the message to all matching
receivers, not to the &quot;best&quot; match). </p>
<p>To send a notification, the caller creates an {@link android.content.Intent Intent}
object and calls {@link android.app.Activity#sendBroadcast(android.content.Intent)
Context.sendBroadcast()} with that Intent. Multiple recipients can receive
the same message. You can broadcast an Intent message to an intent receiver in
any application, not only your own. If the receiving class is not registered
using <code>&lt;receiver&gt;</code> in its manifest, you can dynamically instantiate
and register a receiver by calling {@link android.content.Context#registerReceiver(android.content.BroadcastReceiver,android.content.IntentFilter)
Context.registerReceiver()}. </p>
<p>Receivers can include intent filters to specify what kinds of intents they are
listening for. Alternatively, if you expect a single known caller to contact
a single known receiver, the receiver does not specify an intent filter, and
the caller specifies the receiver's class name in the Intent by calling {@link
android.content.Intent#setClassName(java.lang.String, java.lang.String) Intent.setClassName()}
with the recipient's class name. The recipient receives a {@link android.content.Context
Context} object that refers to its own package, not to the package of the sender.</p>
<p><em><strong>Note:</strong></em>&nbsp;&nbsp;&nbsp;If a receiver or broadcaster
enforces permissions, your application might need to request permission
to send or receive messages from that object. You can request permission by using
the &lt;uses-permission&gt; tag in the manifest. </p>
<p>Here is a code snippet of a sender and receiver. This example does not demonstrate
registering receivers dynamically. For a full code example, see the AlarmService
class in the ApiDemos project.</p>
<h3>Sending the message</h3>
<pre>// We are sending this to a specific recipient, so we will
// only specify the recipient class name.
Intent intent = new Intent(this, AlarmReceiver.class);
intent.putExtra(&quot;message&quot;,&quot;Wake up.&quot;);
sendBroadcast(intent);
</pre>
<h3>Receiving the message</h3>
<p><strong>Receiver AndroidManifest.xml </strong>(because there is no intent filter
child, this class will only receive a broadcast when the receiver class is specified
by name, as is done in this example):</p>
<pre>
&lt;receiver class=".AlarmReceiver" /&gt;</pre>
<p><strong>Receiver Java code: </strong></p>
<pre>
public class AlarmReceiver extends BroadcastReceiver{
// Display an alert that we've received a message.
&#064;Override
public void onReceive(Context context, Intent intent){
// Send a text notification to the screen.
NotificationManager nm = (NotificationManager)
context.getSystemService(Context.NOTIFICATION_SERVICE);
nm.notifyWithText(R.id.alarm,
&quot;Alarm!!!&quot;,
NotificationManager.LENGTH_SHORT,
null);
}
} </pre>
<h3>Other system messages</h3>
<p>You can listen for other system messages sent by Android as well, such as USB
connection/removal messages, SMS arrival messages, and timezone changes. See
{@link android.content.Intent} for a list of broadcast messages to listen for.
Messages are marked &quot;Broadcast Action&quot; in the documentation. </p>
<h3>Listening for phone events<a name="phoneevents" id="phoneevents"></a></h3>
<p>The {@link android.telephony android.telephony} package overview page describes how to
register to listen for phone events. </p>
<a name="alarms" id="alarms"></a><h3>Setting Alarms </h3>
<p>Android provides an {@link android.app.AlarmManager AlarmManager} service that
will let you specify an Intent to send at a designated time. This intent is typically
used to start an application at a preset time. (Note: If you want to send
a notification to a sleeping or running application, use {@link android.os.Handler
Handler} instead.)</p>
<a name="alerts" id="alerts"></a><h2>Displaying Alerts</h2>
<p>There are two major kinds of alerts that you may display to the user:
(1) Normal alerts are displayed in response to a user action, such as
trying to perform an action that is not allowed. (2) Out-of-band alerts,
called notifications, are
displayed as a result of something happening in the background, such as the
user receiving new e-mail.</p>
<a name="dialogsandalerts" id="dialogsandalerts"></a><h3>Normal Alerts</h3>
<p>Android provides a number of ways for you to show popup notifications to your
user as they interact with your application. </p>
<table width="100%" border="1">
<tr>
<th scope="col">Class</th>
<th scope="col">Description</th>
</tr>
<tr>
<td>{@link android.app.Dialog app.Dialog}</td>
<td>A generic floating dialog box with a layout that you design. </td>
</tr>
<tr>
<td><p>{@link android.app.AlertDialog app.AlertDialog}</p></td>
<td>A popup alert dialog with two buttons (typically OK and Cancel) that
take callback handlers. See the section after this table for more details. </td>
</tr>
<tr>
<td>{@link android.app.ProgressDialog ProgressDialog} </td>
<td>A dialog box used to indicate progress of an operation with a known progress
value or an indeterminate length (setProgress(bool)). See <strong>Views</strong> &gt; <strong>Progress Bar</strong> in
ApiDemos for examples. </td>
</tr>
<tr>
<td>Activity</td>
<td>By setting the theme of an activity to
{@link android.R.style#Theme_Dialog
android:theme=&quot;&#064;android:style/Theme.Dialog&quot;},
your activity will take on
the appearance of a normal dialog, floating on top of whatever was
underneath it. You usually set the theme through the
{@link android.R.attr#theme android:theme} attribute in your AndroidManifest.xml.
The advantage of this
over Dialog and AlertDialog is that Application has a much better managed
life cycle than dialogs: if a dialog goes to the background and is killed,
you cannot recapture state, whereas Application exposes a {@link android.os.Bundle
Bundle} of saved values in <code>onCreate()</code> to help you maintain state.</td>
</tr>
</table>
<h3>AlertDialog</h3>
<p>This is a basic warning dialog box that lets you configure a message, button text,
and callback. You can create one by calling using the {@link
android.app.AlertDialog.Builder} class, as shown here. </p>
<pre>private Handler mHandler = new Handler() {
public void handleMessage(Message msg) {
switch (msg.what) {
case ACCEPT_CALL:
answer(msg.obj);
break;
case BOUNCE_TO_VOICEMAIL:
voicemail(msg.obj);
break;
}
}
};
private void IncomingMotherInLawCall(Connection c) {
String Text;
// &quot;Answer&quot; callback.
Message acceptMsg = Message.obtain();
acceptMsg.target = mHandler;
acceptMsg.what = ACCEPT_CALL;
acceptMsg.obj = c.getCall();
// &quot;Cancel&quot; callback.
final Message rejectMsg = Message.obtain();
rejectMsg.target = mHandler;
rejectMsg.what = BOUNCE_TO_VOICEMAIL;
rejectMsg.obj = c.getCall();
new AlertDialog.Builder(this)
.setMessage("Phyllis is calling")
.setPositiveButton("Answer", acceptMsg)
.setOnCancelListener(new OnCancelListener() {
public void onCancel(DialogInterface dialog) {
rejectMsg.sendToTarget();
}});
.show();
} </pre>
<h3>Notifications</h3>
<p>Out-of-band alerts should always be displayed using the
{@link android.app.NotificationManager}, which allows you to tell the user
about something they may be interested in without disrupting what they are
currently doing. A notification can be anything from a brief pop-up box
informing the user of the new information, through displaying a persistent
icon in the status bar, to vibrating, playing sounds, or flashing lights to
get the user's attention. In all cases, the user must explicitly shift their
focus to the notification before they can interact with it.</p>
<p>The following code demonstrates using NotificationManager to display a basic text
popup when a new SMS message arrives in a listening service, and provides the
current message count. You can see several more examples in the ApiDemos application,
under app/ (named <em>notification</em>*.java).</p>
<pre>static void setNewMessageIndicator(Context context, int messageCount){
// Get the static global NotificationManager object.
NotificationManager nm = NotificationManager.getDefault();</p>
// If we're being called because a new message has been received,
// then display an icon and a count. Otherwise, delete the persistent
// message.
if (messageCount &gt; 0) {
nm.notifyWithText(myApp.NOTIFICATION_GUID, // ID for this notification.
messageCount + &quot; new message&quot; + messageCount &gt; 1 ? &quot;s&quot;:&quot;&quot;, // Text to display.
NotificationManager.LENGTH_SHORT); // Show it for a short time only.
}
}</pre>
<p>To display a notification in the status bar and have it launch an intent when
the user selects it (such as the new text message notification does), call {@link
android.app.NotificationManager#notify(int, android.app.Notification) NotificationManager.notify()},
and pass in vibration patterns, status bar icons, or Intents to associate with
the notification. </p>
<a name="progressbar" id="progressbar"></a><h2>Displaying a Progress Bar</h2>
<p>An activity can display a progress bar to notify the user that something is happening.
To display a progress bar in a screen, call {@link android.app.Activity#requestWindowFeature(int)
Activity.requestWindowFeature(Window.FEATURE_PROGRESS)}. To set the value
of the progress bar, call {@link android.view.Window#setFeatureInt(int,int)
Activity.getWindow().setFeatureInt(Window.FEATURE_PROGRESS, <em>level</em>)}.
Progress bar values are from 0 to 9,999, or set the value to 10,000 to make the
progress bar invisible. </p>
<p>You can also use the {@link android.app.ProgressDialog ProgressDialog} class,
which enables a dialog box with an embedded progress bar to send a &quot;I'm working
on it&quot; notification to the user. </p>
<a name="addmenuitems" id="addmenuitems"></a><h2>Adding Items to the Screen Menu</h2>
<p>See <a href="{@docRoot}guide/topics/ui/menus.html">Creating Menus</a>.</p>
<a name="webpage" id="webpage"></a><h2>Display a Web Page</h2>
<p>Use the {@link android.webkit.WebView webkit.WebView} object. </p>
<a name="binding" id="binding"></a><h2>Binding to Data</h2>
<p>You can bind a ListView to a set of underlying data by using a shim class called
{@link android.widget.ListAdapter ListAdapter} (or a subclass). ListAdapter subclasses
bind to a variety of data sources, and expose a common set of methods such as
getItem() and getView(), and uses them to pick View items to display in its list.
You can extend ListAdapter and override getView() to create your own custom list
items. There are essentially only two steps you need to perform to bind to data: </p>
<ol>
<li>Create a ListAdapter object and specify its data source</li>
<li>Give the ListAdapter to your ListView object.</li>
</ol>
<p>That's it!</p>
<p>Here's an example of binding a ListActivity screen to the results from a cursor
query. (Note that the setListAdapter() method shown is a convenience method that
gets the page's ListView object and calls setAdapter() on it.)</p>
<pre>// Run a query and get a Cursor pointing to the results.
Cursor c = People.query(this.getContentResolver(), null);
startManagingCursor(c);
// Create the ListAdapter. A SimpleCursorAdapter lets you specify two interesting things:
// an XML template for your list item, and
// The column to map to a specific item, by ID, in your template.
ListAdapter adapter = new SimpleCursorAdapter(this,
android.R.layout.simple_list_item_1, // Use a template that displays a text view
c, // Give the cursor to the list adapter
new String[] {People.NAME} , // Map the NAME column in the people database to...
new String[] {"text1"}); // The "text1" view defined in the XML template
setListAdapter(adapter);</pre>
<p>See view/List4 in the ApiDemos project for an example of extending ListAdapter
for a new data type. </p>
<a name="handle"></a>
<h2>Getting a Handle to a Screen Element</h2>
<p>You can get a handle to a screen element by calling {@link
android.app.Activity#findViewById(int) Activity.findViewById}. You can then use
the handle to set or retrieve any values exposed by the object. </p>
<a name="captureimages" id="captureimages"></a><h2>Capture Images from the Phone Camera</h2>
<p>You can hook into the device's camera onto your own Canvas object by using the
{@link android.hardware.Camera Camera} class. See that class's documentation,
and the ApiDemos project's Camera Preview application (Graphics/Camera Preview)
for example code. </p>
<a name="threading" id="threading"></a><h2>Handling Expensive Operations in the UI Thread</h2>
<p>Avoid performing long-running operations (such as network I/O) directly in the UI thread &mdash;
the main thread of an application where the UI is run &mdash; or your application may be blocked
and become unresponsive. Here is a brief summary of the recommended approach for handling expensive operations:</p>
<ol>
<li>Create a Handler object in your UI thread</li>
<li>Spawn off worker threads to perform any required expensive operations</li>
<li>Post results from a worker thread back to the UI thread's handler either through a Runnable or a {@link android.os.Message}</li>
<li>Update the views on the UI thread as needed</li>
</ol>
<p>The following outline illustrates a typical implementation:</p>
<pre>
public class MyActivity extends Activity {
[ . . . ]
// Need handler for callbacks to the UI thread
final Handler mHandler = new Handler();
// Create runnable for posting
final Runnable mUpdateResults = new Runnable() {
public void run() {
updateResultsInUi();
}
};
&#64;Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
[ . . . ]
}
protected void startLongRunningOperation() {
// Fire off a thread to do some work that we shouldn't do directly in the UI thread
Thread t = new Thread() {
public void run() {
mResults = doSomethingExpensive();
mHandler.post(mUpdateResults);
}
};
t.start();
}
private void updateResultsInUi() {
// Back in the UI thread -- update our UI elements based on the data in mResults
[ . . . ]
}
}
</pre>
<p>For further discussions on this topic, see
<a href="{@docRoot}guide/practices/design/responsiveness.html">Designing for Responsiveness</a>
and the {@link android.os.Handler} documentation.</p>
<a name="selectingtext" id="selectingtext"></a><h2>Selecting, Highlighting, or Styling Portions of Text</h2>
<p>You can highlight or style the formatting of strings or substrings of text in
a TextView object. There are two ways to do this:</p>
<ul>
<li>If you use a <a href="{@docRoot}guide/topics/resources/available-resources.html#stringresources">string resource</a>,
you can add some simple styling, such as bold or italic using HTML notation.
The currently supported tags are: <code>B</code> (bold),
<code>I</code> (italic), <code>U</code> (underline),
<code>TT</code> (monospace), <code>BIG</code>, <code>SMALL</code>,
<code>SUP</code> (superscript), <code>SUB</code> (subscript),
and <code>STRIKE</code> (strikethrough).
So, for example, in res/values/strings.xml you could declare this:<br />
<code>&lt;resource&gt;<br />
&nbsp;&nbsp;&nbsp;&nbsp;&lt;string&nbsp;id=&quot;@+id/styled_welcome_message&quot;&gt;We
are &lt;b&gt;&lt;i&gt;so&lt;/i&gt;&lt;/b&gt; glad to see you.&lt;/string&gt;<br />
&lt;/resources&gt;</code></li>
<li>To style text on the fly, or to add highlighting or more complex styling,
you must use the Spannable object as described next. </li>
</ul>
<p>To style text on the fly, you must make sure the TextView is using {@link android.text.Spannable}
storage for the text (this will always be true if the TextView is an EditText),
retrieve its text with {@link android.widget.TextView#getText}, and call {@link
android.text.Spannable#setSpan}, passing in a new style class from the {@link
android.text.style} package and the selection range. </p>
<p>The following code snippet demonstrates creating a string with a highlighted section,
italic section, and bold section, and adding it to an EditText object. </p>
<pre>// Get our EditText object.
EditText vw = (EditText)findViewById(R.id.text);
// Set the EditText's text.
vw.setText("Italic, highlighted, bold.");
// If this were just a TextView, we could do:
// vw.setText("Italic, highlighted, bold.", TextView.BufferType.SPANNABLE);
// to force it to use Spannable storage so styles can be attached.
// Or we could specify that in the XML.
// Get the EditText's internal text storage
Spannable str = vw.getText();
// Create our span sections, and assign a format to each.
str.setSpan(new StyleSpan(android.graphics.Typeface.ITALIC), 0, 7, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
str.setSpan(new BackgroundColorSpan(0xFFFFFF00), 8, 19, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
str.setSpan(new StyleSpan(android.graphics.Typeface.BOLD), 21, str.length() - 1, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
</pre>
<a name="querymap" id="querymap"></a><h2>Utilizing attributes in a Map query</h2>
<p>
When using a search intent to ask the Maps activity to search for something, the Maps activity responds to the following attributes in the optional context bundle:
</p>
<pre>
float "centerLatitude" default 0.0f
float "centerLongitude" default 0.0f
float "latitudeSpan" default 0.0f
float "longitudeSpan" default 0.0f
int "zoomLevel" default 10
</pre>
<p>
This context information is used to center the search result in a particular area, and is equivalent to adjusting the Map activity to the described location and zoom level before issuing the query.
</p>
<p>
If the latitudeSpan, longitudeSpan, and zoomLevel attributes are not consistent, then it is undefined which one takes precedence.
</p>
<a name="filelist" id="filelist"></a><h2>List of Files for an Android Application</h2>
<p>The following list describes the structure and files of an Android application.
Many of these files can be built for you (or stubbed out) by the android tool
shipped in the tools/ menu of the SDK. </p>
<table width="100%" border="0">
<tr>
<td width="28%" valign="top">MyApp/<br /></td>
<td width="72%" valign="top">&nbsp;</td>
</tr>
<tr>
<td valign="top">&nbsp;&nbsp;&nbsp;&nbsp;AndroidManifest.xml</td>
<td valign="top">(<em>required</em>) Advertises the screens that this application provides,
where they can be launched (from the main program menu or elsewhere),
any content providers it implements and what kind of data they handle,
where the implementation classes are, and other application-wide
information. Syntax details for this file are described in <a href="{@docRoot}guide/topics/manifest/manifest-intro.html">The AndroidManifest.xml File</a>.</td>
</tr>
<tr>
<td valign="top">&nbsp;&nbsp;&nbsp;&nbsp;src/<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;/<em>myPackagePath</em>/.../<em>MyClass</em>.java</td>
<td valign="top">(<em>required</em>) This folder holds all the source code files for your
application, inside the appropriate package subfolders. </td>
</tr>
<tr>
<td valign="top">&nbsp;&nbsp;&nbsp;&nbsp;res/</td>
<td valign="top">(<em>required</em>) This folder holds all the <em>resources</em> for
your application. Resources are external data files or description files
that are compiled into your code at build time. Files in different folders
are compiled differently, so you must put the proper resource into the
proper folder. (See <a href="{@docRoot}guide/topics/resources/resources-i18n.html">Resources</a> for details.)</td>
</tr>
<tr>
<td valign="top">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;anim/<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<em>animation1</em>.xml<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<em>...</em></td>
<td valign="top">(<em>optional</em>) Holds any animation XML description files that the
application uses. The format of these files is described in <a href="{@docRoot}guide/topics/resources/resources-i18n.html">Resources</a>. </td>
</tr>
<tr>
<td valign="top">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;drawable/<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<em>some_picture</em>.png<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<em>some_stretchable</em>.9.png<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<em>some_background</em>.xml<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;...</td>
<td valign="top">(<em>optional</em>) Zero or more files that will be compiled to {@link
android.graphics.drawable android.graphics.drawable} resources. Files
can be image files (png, gif, or other) or XML files describing other
graphics such as bitmaps, stretchable bitmaps, or gradients. Supported
bitmap file formats are PNG (preferred), JPG, and GIF (discouraged),
as well as the custom 9-patch stretchable bitmap format. These formats
are described in <a href="{@docRoot}guide/topics/resources/resources-i18n.html">Resources</a>. </td>
</tr>
<tr>
<td valign="top">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;layout/<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<em>screen_1_layout</em>.xml<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;...<br /></td>
<td valign="top">(<em>optional</em>) Holds all the XML files describing screens or parts
of screens. Although you could create a screen in Java, defining them
in XML files is typically easier. A layout file is similar in concept
to an HTML file that describes the screen layout and components. See <a href="{@docRoot}guide/topics/ui/index.html">User Interface</a> for more information about designing screens, and <a href="{@docRoot}guide/topics/resources/available-resources.html#layoutresources">Available Resource Types</a> for the syntax of these files.</td>
</tr>
<tr>
<td valign="top">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;values/<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;arrays<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &nbsp;classes.xml<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;colors.xml<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;dimens.xml<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; strings.xml<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;styles.xml<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;values.xml<br /></td>
<td valign="top"><p>(<em>optional</em>) XML files describing additional resources
such as strings, colors, and styles. The naming, quantity, and number
of these files are not enforced--any XML file is compiled, but these
are the standard names given to these files. However, the syntax
of these files is prescribed by Android, and described in <a href="{@docRoot}guide/topics/resources/resources-i18n.html">Resources</a>. </p>
</td>
</tr>
<tr>
<td valign="top">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;xml/</td>
<td valign="top">(<em>optional</em>) XML files that can be read at run time on the device. </td>
</tr>
<tr>
<td valign="top">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;raw/</td>
<td valign="top">(<em>optional</em>) Any files to be copied directly to the device. </td>
</tr>
</table>
<a name="logging" ></a>
<h2>Print Messages to a Log File</h2>
<p>To write log messages from your application:</p>
<ol><li>Import <code>android.util.Log</code>.</li>
<li>Use <code>Log.v()</code>, <code>Log.d()</code>, <code>Log.i()</code>,
<code>Log.w()</code>, or <code>Log.e()</code> to log messages.
(See the {@link android.util.Log} class.)<br/> E.g.,
<code>Log.e(this.toString(), "error: " + err.toString())</code></li>
<li>Launch <a href="{@docRoot}guide/developing/tools/ddms.html">DDMS</a> from a terminal
by executing <code>ddms</code> in your Android SDK <code>/tools</code> path.</li>
<li>Run your application in the Android emulator.</li>
<li>From the DDMS application, select the emulator
(e.g., "emulator-5554") and click <b>Device > Run logcat...</b>
to view all the log data.</li>
</ol>
<p class="note"><strong>Note:</strong> If you are running Eclipse and
encounter a warning about the VM debug port when opening DDMS, you can ignore it
if you're only interested in logs. However, if you want to further inspect and
control your processes from DDMS, then you should close Eclipse before launching DDMS so that
it may use the VM debugging port.</p>

View File

@@ -0,0 +1,197 @@
page.title=Android Application Framework FAQ
parent.title=FAQs, Tips, and How-to
parent.link=index.html
@jd:body
<ul>
<li><a href="#1">Do all the Activities and Services of an
application run in a single process?</a></li>
<li><a href="#2">Do all Activities run in the main thread of
an application process?</a></li>
<li><a href="#3">How do I pass complicated data structures
from one Activity/Service to another?</a></li>
<li><a href="#4">How can I check if an Activity is already
running before starting it?</a></li>
<li><a href="#5">If an Activity starts a remote service, is
there any way for the Service to pass a message back to the Activity?</a></li>
<li><a href="#6">How to avoid getting the Application not
responding dialog?</a></li>
<li><a href="#7">How does an application know if a package is
added or removed?</a></li>
</ul>
<a name="1" id="1"></a>
<h2>Do all the Activities and Services of an application run in a
single process?</h2>
<p>All Activities and Services in an application run in a single process by
default. If needed, you can declare an <code>android:process</code> attribute
in your manifest file, to explicitly place a component (Activity/Service) in
another process.</p>
<a name="2" id="2"></a>
<h2>Do all Activities run in the main thread of an application
process?</h2>
<p>By default, all of the application code in a single process runs
in the main UI thread. This is the same thread
that also handles UI events. The only exception is the code that handles
IPC calls coming in from other processes. The system maintains a
separate pool of transaction threads in each process to dispatch all
incoming IPC calls. The developer should create separate threads for any
long-running code, to avoid blocking the main UI thread.</p>
<a name="3" id="3"></a>
<h2>How do I pass data between Activities/Services within a single
application?</h2>
<p>It depends on the type of data that you want to share:</p>
<h3>Primitive Data Types</h3>
<p>To share primitive data between Activities/Services in an
application, use Intent.putExtras(). For passing primitive data that
needs to persist use the
<a href="{@docRoot}guide/topics/data/data-storage.html#preferences">
Preferences</a> storage mechanism.</p>
<h3>Non-Persistent Objects</h3>
<p>For sharing complex non-persistent user-defined objects for short
duration, the following approaches are recommended:
</p>
<h4>The android.app.Application class</h4>
<p>The android.app.Application is a base class for those who need to
maintain global application state. It can be accessed via
getApplication() from any Activity or Service. It has a couple of
life-cycle methods and will be instantiated by Android automatically if
your register it in AndroidManifest.xml.</p>
<h4>A public static field/method</h4>
<p>An alternate way to make data accessible across Activities/Services is to use <em>public static</em>
fields and/or methods. You can access these static fields from any other
class in your application. To share an object, the activity which creates your object sets a
static field to point to this object and any other activity that wants to use
this object just accesses this static field.</p>
<h4>A HashMap of WeakReferences to Objects</h4>
<p>You can also use a HashMap of WeakReferences to Objects with Long
keys. When an activity wants to pass an object to another activity, it
simply puts the object in the map and sends the key (which is a unique
Long based on a counter or time stamp) to the recipient activity via
intent extras. The recipient activity retrieves the object using this
key.</p>
<h4>A Singleton class</h4>
<p>There are advantages to using a static Singleton, such as you can
refer to them without casting getApplication() to an
application-specific class, or going to the trouble of hanging an
interface on all your Application subclasses so that your various
modules can refer to that interface instead. </p>
<p>But, the life cycle of a static is not well under your control; so
to abide by the life-cycle model, the application class should initiate and
tear down these static objects in the onCreate() and onTerminate() methods
of the Application Class</p>
</p>
<h3>Persistent Objects</h3>
<p>Even while an application appears to continue running, the system
may choose to kill its process and restart it later. If you have data
that you need to persist from one activity invocation to the next, you
need to represent that data as state that gets saved by an activity when
it is informed that it might go away.</p>
<p>For sharing complex persistent user-defined objects, the
following approaches are recommended:
<ul>
<li>Application Preferences</li>
<li>Files</li>
<li>contentProviders</li>
<li>SQLite DB</li>
</ul>
</p>
<p>If the shared data needs to be retained across points where the application
process can be killed, then place that data in persistent storage like
Application Preferences, SQLite DB, Files or ContentProviders. Please refer to
the <a href="{@docRoot}guide/topics/data/data-storage.html">Data Storage</a>
for further details on how to use these components.</p>
<a name="4" id="4"></a>
<h2>How can I check if an Activity is already running before starting
it?</h2>
<p>The general mechanism to start a new activity if its not running&mdash;
or to bring the activity stack to the front if is already running in the
background&mdash; is the to use the NEW_TASK_LAUNCH flag in the startActivity()
call.</p>
<a name="5" id="5"></a>
<h2>If an Activity starts a remote service, is there any way for the
Service to pass a message back to the Activity?</h2>
<p>The remote service can define a callback interface and register it with the
clients to callback into the clients. The
{@link android.os.RemoteCallbackList RemoteCallbackList} class provides methods to
register and unregister clients with the service, and send and receive
messages.</p>
<p>The sample code for remote service callbacks is given in <a
href="{@docRoot}guide/samples/ApiDemos/src/com/example/android/apis/app/RemoteService.html">ApiDemos/RemoteService</a></p>
<a name="6" id="6"></a>
<h2>How to avoid getting the Application not responding dialog?</h2>
<p>Please read the <a href="{@docRoot}guide/practices/design/responsiveness.html">Designing for Responsiveness</a>
document.</p>
<a name="7" id="7"></a>
<h2>How does an application know if a package is added or removed?
</h2>
<p>Whenever a package is added, an intent with PACKAGE_ADDED action
is broadcast by the system. Similarly when a package is removed, an
intent with PACKAGE_REMOVED action is broadcast. To receive these
intents, you should write something like this:
<pre>
&lt;receiver android:name ="com.android.samples.app.PackageReceiver"&gt;
&lt;intent-filter&gt;
&lt;action android:name="android.intent.action.PACKAGE_ADDED"/&gt;
&lt;action android:name="android.intent.action.PACKAGE_REMOVED"/&gt;
&lt;data android:scheme="package" /&gt;
&lt;/intent-filter&gt;
&lt;/receiver&gt;
</pre>
<br>
Here PackageReceiver is a BroadcastReceiver class.Its onReceive()
method is invoked, every time an application package is installed or
removed.
</p>

View File

@@ -0,0 +1,15 @@
page.title=FAQs, Tips, and How-to
@jd:body
<dl>
<dt><a href="commontasks.html">Common Development Tasks and How To Do Them</a></dt>
<dd>Quick and to the point &mdash; how-to's for a variety of development tasks you are likely to use.</dd>
<dt><a href="framework.html">Application Framework FAQ</a></dt>
<dd>Common questions about the Android Application Framework.</dd>
<dt><a href="troubleshooting.html">Troubleshooting Tips</a></dt>
<dd>Answers to help you troubleshoot common problems.</dd>
<dt><a href="licensingandoss.html">Open Source Licensing FAQ</a></dt>
<dd>Common topics around licensing and Android Open Source</dd>
<dt><a href="security.html">Android Security FAQ</a></dt>
<dd>Answers to common questions about Android security.</dd>
</dl>

View File

@@ -0,0 +1,19 @@
page.title=Android Open Source Licensing FAQ
parent.title=FAQs, Tips, and How-to
parent.link=index.html
@jd:body
<ul>
<li><a href="#mirror">Where can I find the open source components of Android?</a></li>
<li><a href="#timeline">When will we see more code released under open source licenses?</a></li>
<li><a href="#apache2">Why are you releasing the code under the Apache License instead of GPLv2?</a></li>
</ul>
<a name="mirror" id="mirror"></a><h2>Where can I find the open source components of Android?</h2>
<p>The source code for the full Android stack is available from the <a href="http://source.android.com">Android Open Source Project </a> site.
<p>Other mirrored GPL and LGPL'd components are available at <a href="http://code.google.com/p/android/downloads/list"><code>http://code.google.com/p/android/downloads/list</code></a>.</p>
<p>Notices for other licenses can be found within the SDK.</p>
<a name="apache2" id="apache2"></a><h2>Why are you releasing the code under the Apache License instead of GPLv2?</h2>
<p>One of the best explanations for the reasoning behind releasing code under Apache2 can be found in a <a href="http://arstechnica.com/news.ars/post/20071106-why-google-chose-the-apache-software-license-over-gplv2.html">ArsTechnica article</a> by Ryan Paul.</p>

View File

@@ -0,0 +1,156 @@
page.title=Android Security FAQ
parent.title=FAQs, Tips, and How-to
parent.link=index.html
@jd:body
<ul>
<li><a href="#secure">Is Android Secure?</a></li>
<li><a href="#issue">I think I found a security flaw. How do I report
it?</a></li>
<li><a href="#informed">How can I stay informed of Android security
announcements?</a></li>
<li><a href="#use">How do I securely use my Android phone?</a></li>
<li><a href="#malware">I think I found malicious software being distributed
for Android. How can I help?</a></li>
<li><a href="#fixes">How will Android-powered devices receive security fixes?</a>
</li>
<li><a href="#directfix">Can I get a fix directly from the Android Platform
Project?</a></li>
</ul>
<a name="secure" id="secure"></a><h2>Is Android secure?</h2>
<p>The security and privacy of our users' data is of primary importance to the
Android Open Source Project. We are dedicated to building and maintaining one
of the most secure mobile platforms available while still fulfilling our goal
of opening the mobile device space to innovation and competition.</p>
<p>The Android Platform provides a rich <a
href="http://code.google.com/android/devel/security.html">security model</a>
that allows developers to request the capabilities, or access, needed by their
application and to define new capabilities that other applications can request.
The Android user can choose to grant or deny an application's request for
certain capabilities on the handset.</p>
<p>We have made great efforts to secure the Android platform, but it is
inevitable that security bugs will be found in any system of this complexity.
Therefore, the Android team works hard to find new bugs internally and responds
quickly and professionally to vulnerability reports from external researchers.
</p>
<a name="issue" id="issue"></a><h2>I think I found a security flaw. How do I
report it?</h2>
<p>You can reach the Android security team at <a
href="mailto:security@android.com">security@android.com</a>. If you like, you
can protect your message using our <a
href="http://code.google.com/android/security_at_android_dot_com.txt">PGP
key</a>.</p>
<p>We appreciate researchers practicing responsible disclosure by emailing us
with a detailed summary of the issue and keeping the issue confidential while
users are at risk. In return, we will make sure to keep the researcher informed
of our progress in issuing a fix and will properly credit the reporter(s) when
we announce the patch. We will always move swiftly to mitigate or fix an
externally-reported flaw and will publicly announce the fix once patches are
available to users.</p>
<a name="informed" id="informed"></a><h2>How can I stay informed of Android
security announcements?</h2>
<p>An important part of sustainably securing a platform, such as, Android is
keeping the user and security community informed of bugs and fixes. We will
publicly announce security bugs when the fixes are available via postings to
the <a
href="http://groups.google.com/group/android-security-announce">android-security-announce</a>
group on Google Groups. You can subscribe to this group as you would a mailing
list and view the archives here.</p>
<p>For more general discussion of Android platform security, or how to use
security features in your Android application, please subscribe to <a
href="http://groups.google.com/group/android-security-discuss">android-security-discuss</a>.
</p>
<a name="use" id="use"></a><h2>How do I securely use my Android phone?</h2>
<p>As an open platform, Android allows users to load software from any
developer onto a device. As with a home PC, the user must be
aware of who is providing the software they are downloading and must decide
whether they want to grant the application the capabilities it requests.
This decision can be informed by the user's judgment of the software
developer's trustworthiness, and where the software came from.</p>
<p>Despite the security protections in Android, it is important
for users to only download and install software from developers they trust.
More details on how Android users can make smart security decisions will be
released when consumer devices become available.</p>
<a name="malware" id="malware"></a><h2>I think I found malicious software being
distributed for Android. How can I help?</h2>
<p>Like any other open platform, it will be possible for unethical developers
to create malicious software, known as <a
href="http://en.wikipedia.org/wiki/Malware">malware</a>, for Android. If you
think somebody is trying to spread malware, please let us know at <a
href="mailto:security@android.com">security@android.com</a>. Please include as
much detail about the application as possible, with the location it is
being distributed from and why you suspect it of being malicious software.</p>
<p>The term <i>malicious software</i> is subjective, and we cannot make an
exhaustive definition. Some examples of what the Android Security Team believes
to be malicious software is any application that:
<ul>
<li>drains the device's battery very quickly;</li>
<li>shows the user unsolicited messages (especially messages urging the
user to buy something);</li>
<li>resists (or attempts to resist) the user's effort to uninstall it;</li>
<li>attempts to automatically spread itself to other devices;</li>
<li>hides its files and/or processes;</li>
<li>discloses the user's private information to a third party, without the
user's knowledge and consent;</li>
<li>destroys the user's data (or the device itself) without the user's
knowledge and consent;</li>
<li>impersonates the user (such as by sending email or buying things from a
web store) without the user's knowledge and consent; or</li>
<li>otherwise degrades the user's experience with the device.</li>
</ul>
</p>
<a name="fixes" id="fixes"></a><h2>How will Android-powered devices receive security
fixes?</h2>
<p>The manufacturer of each device is responsible for distributing software
upgrades for it, including security fixes. Many devices will update themselves
automatically with software downloaded "over the air", while some devices
require the user to upgrade them manually.</p>
<p>When Android-powered devices are publicly available, this FAQ will provide links how
Open Handset Alliance members release updates.</p>
<a name="directfix" id="directfix"></a><h2>Can I get a fix directly from the
Android Platform Project?</h2>
<p>Android is a mobile platform that will be released as open source and
available for free use by anybody. This means that there will be many
Android-based products available to consumers, and most of them will be created
without the knowledge or participation of the Android Open Source Project. Like
the maintainers of other open source projects, we cannot build and release
patches for the entire ecosystem of products using Android. Instead, we will
work diligently to find and fix flaws as quickly as possible and to distribute
those fixes to the manufacturers of the products.</p>
<p>In addition, We will add security fixes to the open source distribution of
Android and publicly announce the changes on <a
href="http://groups.google.com/group/android-security-announce">android-security-announce</a>.
</p>
<p>If you are making an Android-powered device and would like to know how you can
properly support your customers by keeping abreast of software updates, please
contact us at <a
href="mailto:info@openhandsetalliance.com">info@openhandsetalliance.com</a>.</p>

View File

@@ -0,0 +1,335 @@
page.title=Troubleshooting
parent.title=FAQs, Tips, and How-to
parent.link=index.html
@jd:body
<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>
<ul>
<li><a href="#installeclipsecomponents">ADT Installation Error: "requires plug-in org.eclipse.wst.sse.ui".</a></li>
<li><a href="#nodevice">ADB reports &quot;no device&quot; when an emulator is running</a></li>
<li><a href="#noapp">My new application/activity isn't showing up in the device application
list </a></li>
<li><a href="#noupdate">I updated my app, but the updates don't seem to be showing up on
the device</a></li>
<li><a href="#layout_wilih">I'm getting a &quot;Binary XML file line #2: You must supply a layout_wilih
attribute&quot; error when I start an application</a></li>
<li><a href="#permission">My request to (<em>make a call, catch an incoming SMS, receive
a notification, send an intent to an Android application</em>) is being
ignored</a></li>
<li><a href="#build">Help! My project won't build in Eclipse</a></li>
<li><a href="#eclipse">Eclipse isn't talking to the emulator</a></li>
<li><a href="#majorminor">When I go to preferences in Eclipse and select "Android", I get the following error message: Unsupported major.minor version 49.0.</a></li>
<li><a href="#apidemosreinstall">I can't install ApiDemos apps in my IDE because of a signing error</a></li>
<li><a href="#gesturebuilderinstall">I can't install the GestureBuilder sample
app in the emulator</a></li>
<li><a href="#signingcalendar">I can't compile my app because the build tools generated an expired debug certificate</a></li>
<li><a href="#manifestfiles">Unable to view manifest files from within Eclipse</a></li>
</ul>
<a name="installeclipsecomponents" id="installeclipsecomponents"></a><h2>ADT Installation Error: "requires plug-in org.eclipse.wst.sse.ui".</h2>
<p>
The "Android Editors" feature of the ADT Plugin requires specific Eclipse components, such as WST. If you
encounter this error message during ADT installation, you need to install the
required Eclipse components and then try the ADT installation again. Follow the steps below to install the required components for the
Android Editors feature, based on the version of Eclipse that you are using.</p>
<table style="font-size:100%">
<tr><th>Eclipse 3.3 (Europa)</th><th>Eclipse 3.4 (Ganymede)</th></tr>
<tr>
<td width="50%">
<ol>
<li>From the dialog where you select the <strong>Update sites to visit</strong>, select the checkboxes for both the
ADT site, and the Callisto/Europa/Ganymede Discovery Site (you may want to
check <strong>Automatically select mirrors</strong> at the bottom).</li>
<li>Click <strong>Finish</strong>.</li>
<li>In the <strong>Next</strong> dialog, select the Android Plugins.</li>
<li>Now, expand the tree item of the discovery site. It seems that if you
don't do it, it doesn't load the content of the discovery site.</li>
<li>On the right, click <strong>Select required</strong>. This will select all the components
that are required to install the Android plugin (wst, emf, etc...).</li>
<li>Click <strong>Next</strong>, accept the agreement, click <strong>Install All</strong>, and restart Eclipse.</li>
</ol>
</td>
<td>
<ol>
<li>Select <strong>Help</strong> &gt; <strong>Software Updates...</strong></li>
<li>Select the <strong>Installed Software</strong> tab.</li>
<li>Click <strong>Update...</strong></li>
<li>If an update for ADT is available, select it and click <strong>Finish</strong>.</li>
</ol>
</td>
</tr>
</table>
</p>
<a name="nodevice"></a><h2>ADB reports &quot;no device&quot; when an emulator is running</h2>
<p>Try restarting adb by stopping it (<code>adb
kill-server</code>) then any other adb command to restart it.</p>
<a name="noapp"></a><h2>My new application/activity isn't showing up in the
applications list </h2>
<ul>
<li>You often must restart your device or emulator before a new activity shows
up in the applications list. This is particularly true when it is a completely
new application with a new AndroidManifest.xml file.</li>
<li>If this is for a new activity in an existing AndroidManifest.xml file, did
you include an <code>&lt;activity&gt;</code> tag for your app (or a <code>&lt;service&gt;</code> tag
for a service, or a <code>&lt;receiver&gt;</code> tag for a receiver, etc.)? </li>
<li>Make sure that your AndroidManifest.xml file is valid. Errors in attribute
values, such as the <em>value </em> attribute in <code>&lt;action <em>value</em>=&quot;<em>&lt;something&gt;</em>&quot;&gt;</code>
will often not be caught by compilers, but will prevent your application
from being displayed because the intent filter will not be matched. Extra
spaces or other characters can often sneak into these strings.</li>
<li>Did you send your .apk file to the device (<a href="{@docRoot}guide/developing/tools/adb.html#move">adb install</a>)?</li>
<li>Run logcat on your device (<code>adb logcat</code>)
and then install your .apk file. Check the logcat output to see whether the
application is being installed and recognized properly. Here's sample output
from a successful installation:
<pre>I/FileObserver( 414): *** onEvent wfd: 3 mask: 8 path: MyRSSReader.apk
D/PackageManager( 414): Scanning package: /data/app/MyRSSReader.apk
D/PackageManager( 414): Adding package com.example.codelab.rssexample
D/PackageManager( 414): Registered content provider: my_rss_item, className = com.example.codelab.rssexample.RssContentProvider, isSyncable = false
D/PackageManager( 414): Providers: com.example.codelab.rssexample.RssContentProvider
D/PackageManager( 414): Activities: com.example.codelab.rssexample.MyRssReader com.example.codelab.rssexample.MyRssReader2 </pre>
</li>
<li>If logcat shows that the package manager is having problems loading the manifest
file, force your manifest to be recompiled by adding a space in the file and
compiling it.</li>
</ul>
<a name="noupdate"></a><h2>I updated my app, but the updates don't seem to be showing up on the device</h2>
<p>Did you remember to send your .apk file to the device (<a href="{@docRoot}guide/developing/tools/adb.html#move">adb
install</a>)?</p>
<a name="layout_wilih"></a><h2>I'm getting a &quot;Binary XML file line #2: You must supply a layout_wilih
attribute&quot; error
when I start an application (but I declare a layout_wilih attribute <em>right
there!!!</em>)</h2>
<ul>
<li>Make sure that the SDK you are building with is the same version as the Android
OS that you are running on. </li>
<li>Make sure that you're calling setContentView() early in your onCreate() method.
Calling other methods, such as setListAdapter() before calling setContentView()
can sometimes create odd errors when Android tries to access screen elements
that haven't been set before.</li>
</ul>
<a name="permission"></a><h2>My request to (<em>make a call, catch an incoming SMS,
receive a notification, send an intent to an Android application</em>) is being
ignored</h2>
<p>You might not have permission (or might not have requested permission) to
call this activity or receive this intent. Many standard Android activities,
such as making a call, have a permission assigned to it to prevent arbitrary
applications from sending or receiving requests. See <a
href="{@docRoot}guide/topics/security/security.html">Security and
Permissions</a> for more information on permissions, and
{@link android.Manifest.permission Manifest.permission} for a list of
standard permissions supported by the Android platform.
</p>
<a name="build"></a><h2>Help! My project won't build in Eclipse</h2>
<p>If your project doesn't build, you may notice symptoms such as new
resources added in the <code>res/</code> sub-folders not showing up in the R class,
the emulator not being started, not being able to run the application, or even seeming to run an old version of the application.</p>
<p>To troubleshoot these types of problems, first try:</p>
<ol>
<li>Switch to the DDMS view in Eclipse (if you don't already have it open):
<ol type="a">
<li>From the menu select <code>Window &gt; Open Perspective &gt; Other</code></li>
<li>Select DDMS from the list and hit OK</li>
</ol>
</li>
<li>In the Devices panel (top right panel by default), click on the down triangle
to bring up the panel menu</li>
<li>Select <code>Reset ADB</code> from the menu, and then try running the
application again</li>
</ol>
<p>If the above still doesn't work, you can try these steps:</p>
<ol>
<li>
Check the console and problems tabs at the bottom of the Eclipse UI
</li>
<li>
If there are problems listed in either place, they should give you a clue
what is wrong
</li>
<li>
If you aren't sure if the problems are fresh or stale, clear the console
with a right click &gt; Clear, then clean the project
</li>
<li>
To clean the project (a good idea with any kind of build error), select
Project &gt; Clean from the eclipse main menu, then select the project you
are working on (or clean all)
</li>
</ol>
<a name="eclipse"></a><h2>Eclipse isn't talking to the emulator</h2>
<p>When communication doesn't seem to be happening between Eclipse and the emulator, symptoms can include: nothing happening when you press run, the emulator hanging waiting
for a debugger to connect, or errors that Eclipse reports about not being able
to find the emulator or shell. By far the most common symptom is that when you press run, the emulator starts (or
is already running), but the application doesn't start.</p>
<p>
You may find any of these steps will fix the problem and with practice you
probably can figure out which one you need to do for your particular issue, but
to start with, the safest option is to run through all of them in order:</p>
<ol>
<li>
Quit the emulator if it is running
</li>
<li>
Check that any emulator processes are killed (sometimes they can hang, use ps on unix or mac, or task manager in the process view on
windows).
</li>
<li>
Quit Eclipse
</li>
<li>
From the command line, type:
<pre>adb kill-server </pre>
</li>
<li>
Start Eclipse and try again
</li>
</ol>
<a name="majorminor"></a><h2>When I go to preferences in Eclipse and select "Android", I get the following error message: Unsupported major.minor version 49.0.</h2>
<p>This error is displayed if you are using an older version of the JDK. Please make sure you are using JDK version 5 or 6.</p>
<h2 id="apidemosreinstall">I can't install ApiDemos apps in my IDE because of a signing error</a></h2>
<p>The Android system requires that all applications be signed, as described in
<a href="{@docRoot}guide/publishing/app-signing.html">Signing Your Applications</a>. The ApiDemos
applications included with the SDK are preinstalled on the emulator and for that reason have been
compiled and signed with a private key.</p>
If you want to modify or run one of the ApiDemos apps from Eclipse/ADT or other IDE, you can do so
so only after you uninstall the <em>preinstalled</em> version of the app from the emulator. If
you try to run an ApiDemos app from your IDE without removing the preinstalled version first,
you will get errors similar to these: </p>
<pre>[2008-08-13 15:14:15 - ApiDemos] Re-installation failed due to different application signatures.
[2008-08-13 15:14:15 - ApiDemos] You must perform a full uninstall of the application. WARNING: ...This will remove the application data!
[2008-08-13 15:14:15 - ApiDemos] Please execute 'adb uninstall com.android.samples' in a shell.</pre>
<p>The error occurs because, in this case, you are attempting to install another copy of ApiDemos
onto the emulator, a copy that is signed with a different certificate. (The Android IDE tools will
have signed the app with a debug certificate, where the existing version was already signed with
a private certificate.) The system does not allow this type of reinstallation. </p>
<p>To resolve the issue, you need to fully uninstall the preinstalled and then reinstall it using
the adb tool. Here's how to do that:</p>
<ol>
<li>In a terminal, change to the tools directory of the SDK.</li>
<li>If no emulator instance is running, start an emulator using using the command <code>emulator &</code>.</li>
<li>Uninstall the preinstalled app using the command <code>adb uninstall com.android.samples</code>.</li>
<li>Reinstall the app using the command <code>adb install &lt;path to the ApiDemos.apk&gt;</code>. If you are
working in Eclipse/ADT, you can just compile and run the app in the normal way. </li>
</ol>
<p>Note that if multiple emulator instances are running, you need to direct your uninstall/install
commands to the emulator instance that you are targeting. To do that you can add the
<code>-s &lt;serialNumber&gt;</code> to the command, for example: </p>
<pre>adb -s emulator-5556 install</pre>
<p>For more information about adb, see the <a href="{@docRoot}guide/developing/tools/adb.html">Android Debug Bridge</a>
documentation.</p>
<h2 id="gesturebuilderinstall">I can't install the GestureBuilder sample
app in the emulator</a></h2>
<p>This is similar to the ApiDemos problem described above, except that
you cannot fix it by uninstalling GestureBuilder from the emulator. The
GestureBuilder app cannot be uninstalled because it is currently installed
within the system files themselves.</p>
<p><strong>Symptoms</strong></p>
<ul><li><p>You cannot run GestureBuilder in the emulator:</p>
<pre>[2009-12-10 14:57:19 - GestureBuilderActivity]Re-installation failed due to different application signatures.
[2009-12-10 14:57:19 - GestureBuilderActivity]You must perform a full uninstall of the application. WARNING: This will remove the application data!
[2009-12-10 14:57:19 - GestureBuilderActivity]Please execute 'adb uninstall com.android.gesture.builder' in a shell.</pre>
</li>
<li><p>Running <code>adb uninstall com.android.gesture.builder</code> fails:</p>
<pre>$ adb uninstall com.android.gesture.builder
Failure</pre>
</li></ul>
<p>For now, the work-around is to change the sample's package name
so that the system can install it as a new app rather than as a
replacement for the existing GestureBuilder app. To change the
package name, open the manifest file and modify the package attribute
of the manifest element. Next, update imports and other references to
the package name, rebuild the app, and run it in an AVD.</p>
<p>For example, here's how you could do this in Eclipse:</p>
<ol>
<li>Right-click on the package name
(<code>src/com.android.gesture.builder</code>).</li>
<li>Select <strong>Refactor &gt; Rename</strong> and change the name, for example to
<code>com.android.gestureNEW.builder</code>. </li>
<li>Open the manifest file. Inside the <code>&lt;manifest&gt;</code>
tag, change the package name to
<code>com.android.gestureNEW.builder</code>.</li>
<li>Open each of the two Activity files and do Ctrl-Shift-O to add
missing import packages, then save each file.</li>
<li>Run the GestureBuilder application on the emulator.</li>
</ol>
<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>
<h2 id="signingcalendar">I can't compile my app because the build tools generated an expired debug certificate</h2>
<p>If your development machine uses a locale that has a non-Gregorian calendar, you may encounter problems when first trying to compile and run your application. Specifically, you may find that the Android build tools won't compile your application because the debug key is expired. </p>
<p>The problem occurs because the Keytool utility &mdash; included in the JDK and used by the Android build tools &mdash; fails to properly handle non-Gregorian locales and may create validity dates that are in the past. That is, it may generate a debug key that is already expired, which results in the compile error.</p>
<p>If you encounter this problem, follow these steps to work around it: </p>
<ol>
<li>First, delete the debug keystore/key already generated by the Android build tools. Specifically, delete the <code>debug.keystore</code> file. On Linux/Mac OSX, the file is stored in <code>~/.android</code>. On Windows XP, the file is stored in <code>
C:\Documents and Settings\&lt;user&gt;\.android</code>. On Windows Vista, the file is stored in <code>
C:\Users\&lt;user&gt;\.android</code></li>
<li>Next, you can either
<ul>
<li>Temporarily change your development machine's locale (date and time) to one that uses a Gregorian calendar, for example, United States. Once the locale is changed, use the Android build tools to compile and install your app. The build tools will regenerate a new keystore and debug key with valid dates. Once the new debug key is generated, you can reset your development machine to the original locale. </li>
<li>Alternatively, if you do not want to change your machine's locale settings, you can generate the keystore/key on any machine using the Gregorian calendar, then copy the <code>debug.keystore</code> file from that computer to the proper location on your development machine. </li>
</ul>
</li>
</ol>
<p>This problem has been verified on Windows and may apply to other platforms. </p>
<p>For general information about signing Android applications, see
<a href="{@docRoot}guide/publishing/app-signing.html">Signing Your Applications</a>. </p>
<h2 id="manifestfiles">Unable to view manifest files from within
Eclipse</a></h2>
<p>When you try to open an application's manifest file from within
Eclipse, you might get an error such as this one:</p>
<pre>An error has occurred. See error log for more details.
org.eclipse.wst.sse.ui.StructuredTextEditor.isBlockSelectionModeEnabled()Z</pre>
<p>Try reverting to the 3.0 version of the Eclipse XML Editors and
Tools. If this does not work, remove the 3.1 version of the tool. To do
this in Eclipse 3.4:</p>
<ol>
<li>Select <strong>Help > Software Updates...</strong></li>
<li>Select the <strong>Installed Software</strong> tab.</li>
<li>Select <strong>Eclipse XML Editors and Tools</strong>.</li>
<li>Click <strong>Uninstall</strong>.</li>
<li>Click <strong>Finish</strong>.</li>
</ol>
<p>When you restart Eclipse, you should be able to view the manifest
files. </p>

View File

@@ -0,0 +1,115 @@
page.title=Intents List: Invoking Google Applications on Android Devices
@jd:body
<div class="sidebox-wrapper">
<div class="sidebox">
For more information about intents, see the <a
href="{@docRoot}guide/topics/intents/intents-filters.html">Intents and Intent Filters</a>.
</div>
</div>
<p>The table below lists the intents that your application can send, to invoke Google applications on Android devices in certain ways. For each action/uri pair, the table describes how the receiving Google application handles the intent. </p>
<p>Note that this list is not comprehensive.</p>
<table>
<tr>
<th scope="col">Target Application</th>
<th scope="col">Intent URI</th>
<th scope="col">Intent Action</th>
<th scope="col">Result</th>
</tr>
<tr>
<td rowspan="2">Browser</td>
<td>http://<em>web_address</em><br />
https://<em>web_address</em></td>
<td>VIEW</td>
<td>Open a browser window to the URL specified. </td>
</tr>
<tr>
<td>&quot;&quot; (empty string) <br />
http://<em>web_address</em><br />
https://<em>web_address</em></td>
<td>WEB_SEARCH</td>
<td>Opens the file at the location on the device in the browser. </td>
</tr>
<tr>
<td rowspan="2">Dialer</td>
<td height="103">tel: <em>phone_number</em></td>
<td>CALL</td>
<td><p>Calls the entered phone number. Valid telephone numbers as defined
in <a href="http://tools.ietf.org/html/rfc3966">the IETF RFC 3966</a> are
accepted. Valid examples include the following:</p>
<ul>
<li>tel:2125551212 </li>
<li>tel:
(212) 555 1212</li>
</ul>
<p>The dialer is good at normalizing some kinds of schemes: for example
telephone numbers, so the schema described isn't strictly required
in the {@link android.net.Uri#parse(java.lang.String)
Uri(URI string)} factory. However, if you have not tried a
schema or are unsure whether it can be handled, use the {@link
android.net.Uri#fromParts(java.lang.String, java.lang.String,
java.lang.String) Uri.fromParts(scheme, ssp, fragment)} factory
instead.</p>
<p><strong><em>Note:</em></strong>&nbsp;&nbsp;&nbsp;This requires your
application to request the following permission in your manifest: <code>&lt;uses-permission
id=&quot;android.permission.CALL_PHONE&quot; /&gt;</code></p></td>
</tr>
<tr>
<td><p>tel:<em>phone_number</em><br />
voicemail:</p> </td>
<td>DIAL</td>
<td><p>Dials (but does not actually initiate the call) the number given
(or the stored voicemail on the phone). Telephone number normalization
described for CALL applies to DIAL as well. </p> </td>
</tr>
<tr>
<td>Google Maps</td>
<td>geo:<em>latitude</em>,<em>longitude</em><br />
geo:<em>latitude</em>,<em>longitude</em>?z=<em>zoom</em><br />
geo:0,0?q=<em>my+street+address</em><br />
geo:0,0?q=<em>business+near+city</em><br />
</td>
<td>VIEW</td>
<td>Opens the Maps application to the given location or query. The Geo URI scheme
(not fully supported) is <a href="http://tools.ietf.org/html/draft-mayrhofer-geo-uri-00">currently under
development</a>.<p>
The <em>z</em> field specifies the zoom level. A zoom level of 1 shows the whole Earth, centered at the
given <em>lat</em>,<em>lng</em>. A zoom level of 2 shows a quarter of the Earth, and so on. The highest
zoom level is 23. A larger zoom level will be clamped to 23.
</td>
</tr>
<tr>
<td>Google Streetview</td>
<td>google.streetview:cbll=<em>lat</em>,<em>lng</em>&amp;cbp=1,<em>yaw</em>,,<em>pitch</em>,<em>zoom</em>&amp;mz=<em>mapZoom</em>
</td>
<td>VIEW</td>
<td>Opens the Street View application to the given location. The URI scheme is
based on the syntax used for Street View panorama information in Google Maps URLs.<p>
The cbll field is required. The cbp and mz fields are optional.<p>
<table border:none>
<tr><td><em>lat</em></td><td>latitude</td></tr>
<tr><td><em>lng</em></td><td>longitude</td></tr>
<tr><td><em>yaw</em></td><td>Panorama center-of-view in degrees clockwise from North.<br />
<b>Note:</b> The two commas after the yaw parameter are required. They are present
for backwards-compatibility reasons.</td></tr>
<tr><td><em>pitch</em></td><td>Panorama center-of-view in degrees from
-90 (look straight up) to 90 (look straight down.)</td></tr>
<tr><td><em>zoom</em></td><td>Panorama zoom. 1.0 = normal zoom, 2.0 = zoomed in 2x, 3.0 = zoomed in 4x, and so on.<br />
A zoom of 1.0 is 90 degree horizontal FOV for a nominal landscape mode 4
x 3 aspect ratio display Android phones in portrait mode will adjust the zoom so
that the vertical FOV is approximately the same as the landscape vertical FOV.
This means that the horizontal FOV of an Android phone in portrait mode is much
narrower than in landscape mode. This is done to minimize the fisheye lens
effect that would be present if a 90 degree horizontal FOV was used in portrait
mode.</td></tr>
<tr><td><em>mapZoom</em></td><td>The map zoom of the map location associated with this panorama. This value is passed on to the
Maps activity when the Street View "Go to Maps" menu item is chosen. It corresponds to the <em>z</em> parameter in
the geo: intent.</td></tr>
</table>
</td>
</tr>
</table>
<p></p>

View File

@@ -0,0 +1,293 @@
page.title=Glossary
@jd:body
<p>The list below defines some of the basic terminology of the Android platform. </p>
<dl>
<dt id="apk">.apk file</dt> <dd>Android application package file. Each
Android application is compiled and packaged in a single file that
includes all of the application's code (.dex files), resources, assets,
and manifest file. The application package file can have any name but
<em>must</em> use the <code>.apk</code> extension. For example:
<code>myExampleAppname.apk</code>. For convenience, an application package
file is often referred to as an ".apk".
<p>Related: <a href="#application">Application</a>.</p>
</dd>
<dt id="dex">.dex file </dt>
<dd>Compiled Android application code file.
<p>Android programs are compiled into .dex (Dalvik Executable) files, which
are in turn zipped into a single .apk file on the device. .dex files can
be created by automatically translating compiled applications written in
the Java programming language.</dd>
<dt id="action">Action</dt>
<dd>A description of something that an Intent sender wants done. An action is
a string value assigned to an Intent. Action strings can be defined by Android
or by a third-party developer. For example, android.intent.action.VIEW
for a Web URL, or com.example.rumbler.SHAKE_PHONE for a custom application
to vibrate the phone.
<p>Related: <a href="#intent">Intent</a>.</p>
</dd>
<dt id="activity">Activity</dt>
<dd>A single screen in an application, with supporting Java code, derived
from the {@link android.app.Activity} class. Most commonly, an activity is
visibly represented by a full screen window that can receive and handle UI
events and perform complex tasks, because of the Window it uses to render
its window. Though an Activity is typically full screen, it can also be
floating or transparent.</dd>
<dt id="adb">adb</dt>
<dd>Android Debug Bridge, a command-line debugging application included with the
SDK. It provides tools to browse the device, copy tools on the device, and
forward ports for debugging. If you are developing in Eclipse using the
ADT Plugin, adb is integrated into your development environment. See
<a href="{@docRoot}guide/developing/tools/adb.html">Android Debug Bridge</a>
for more information. </dd>
<dt id="application">Application</dt>
<dd>From a component perspective, an Android application consists of one
or more activities, services, listeners, and intent receivers. From a
source file perspective, an Android application consists of code,
resources, assets, and a single manifest. During compilation, these files
are packaged in a single file called an application package file (.apk).
<p>Related: <a href="#apk">.apk</a>, <a href="#activity">Activity</a></p></dd>
<dt id="canvas">Canvas</dt>
<dd>A drawing surface that handles compositing of the actual bits against
a Bitmap or Surface object. It has methods for standard computer drawing
of bitmaps, lines, circles, rectangles, text, and so on, and is bound to a
Bitmap or Surface. Canvas is the simplest, easiest way to draw 2D objects
on the screen. However, it does not support hardware acceleration, as
OpenGL ES does. The base class is {@link android.graphics.Canvas}.
<p>Related: <a href="#drawable">Drawable</a>, <a href="#opengles">OpenGL
ES</a>.</p></dd>
<dt id="contentprovider">Content Provider</dt>
<dd>A data-abstraction layer that you can use to safely expose your
application's data to other applications. A content provider is built on
the {@link android.content.ContentProvider} class, which handles content
query strings of a specific format to return data in a specific format.
See <a href="{@docRoot}guide/topics/providers/content-providers.html">
Content Providers</a> topic for more information.
<p>Related: <a href="#uri">URI Usage in Android</a></p></dd>
<dt id="dalvik">Dalvik</dt>
<dd>The Android platform's virtual machine. The Dalvik VM is an
interpreter-only virtual machine that executes files in the Dalvik
Executable (.dex) format, a format that is optimized for efficient storage
and memory-mappable execution. The virtual machine is register-based, and
it can run classes compiled by a Java language compiler that have been
transformed into its native format using the included &quot;dx&quot; tool.
The VM runs on top of Posix-compliant operating systems, which it relies
on for underlying functionality (such as threading and low level memory
management). The Dalvik core class library is intended to provide a
familiar development base for those used to programming with Java Standard
Edition, but it is geared specifically to the needs of a small mobile
device.</dd>
<dt id="ddms">DDMS</dt>
<dd>Dalvik Debug Monitor Service, a GUI debugging application included
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>
<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
simple action (such as button choice) and perhaps return a value. A dialog
is not intended to persist in the history stack, contain complex layout,
or perform complex actions. Android provides a default simple dialog for
you with optional buttons, though you can define your own dialog layout.
The base class for dialogs is {@link android.app.Dialog Dialog}.
<p>Related: <a href="#activity">Activity</a>.</p></dd>
<dt id="drawable">Drawable</dt>
<dd>A compiled visual resource that can be used as a background, title, or
other part of the screen. A drawable is typically loaded into another UI
element, for example as a background image. A drawable is not able to
receive events, but does assign various other properties such as "state"
and scheduling, to enable subclasses such as animation objects or image
libraries. Many drawable objects are loaded from drawable resource files
&mdash; xml or bitmap files that describe the image. Drawable resources
are compiled into subclasses of {@link android.graphics.drawable}. For
more information about drawables and other resources, see <a
href="{@docRoot}guide/topics/resources/resources-i18n.html">Resources</a>.
<p>Related: <a href="#resources">Resources</a>, <a href="#canvas">Canvas
</a></p></dd>
<dt id="intent">Intent</dt>
<dd>An message object that you can use to launch or communicate with other
applications/activities asynchronously. An Intent object is an instance of
{@link android.content.Intent}. It includes several criteria fields that you can
supply, to determine what application/activity receives the Intent and
what the receiver does when handling the Intent. Available criteria include
include the desired action, a category, a data string, the MIME type of
the data, a handling class, and others. An application sends
an Intent to the Android system, rather than sending it directly to
another application/activity. The application can send the Intent to a
single target application or it can send it as a broadcast, which can in
turn be handled by multiple applications sequentially. The Android system
is responsible for resolving the best-available receiver for each Intent,
based on the criteria supplied in the Intent and the Intent Filters
defined by other applications. For more information, see <a
href="{@docRoot}guide/topics/intents/intents-filters.html">Intents and
Intent Filters</a>.
<p>Related: <a href="#intentfilter">Intent Filter</a>, <a
href="#broadcastreceiver">Broadcast Receiver</a>.</p></dd>
<dt id="intentfilter">Intent Filter</dt>
<dd>A filter object that an application declares in its manifest file, to
tell the system what types of Intents each of its components is willing to
accept and with what criteria. Through an intent filter, an application
can express interest in specific data types, Intent actions, URI formats,
and so on. When resolving an Intent, the system evaluates all of the
available intent filters in all applications and passes the Intent to the
application/activity that best matches the Intent and criteria. For more
information, see <a
href="{@docRoot}guide/topics/intents/intents-filters.html">Intents and
Intent Filters</a>.
<p>Related: <a href="#intent">Intent</a>, <a
href="#broadcastreceiver">Broadcast Receiver</a>.</p></dd>
<dt id="broadcastreceiver">Broadcast Receiver </dt>
<dd>An application class that listens for Intents that are broadcast,
rather than being sent to a single target application/activity. The system
delivers a broadcast Intent to all interested broadcast receivers, which
handle the Intent sequentially.
<p>Related: <a href="#intent">Intent</a>, <a href="#intentfilter">Intent
Filter</a>.</p> </dd>
<dt id="layoutresource">Layout Resource</dt>
<dd>An XML file that describes the layout of an Activity screen.
<p>Related: <a href="#resources">Resources</a></p></dd>
<dt id="manifest">Manifest File</dt>
<dd>An XML file that each application must define, to describe the
application's package name, version, components (activities, intent
filters, services), imported libraries, and describes the various
activities, and so on. See <a
href="{@docRoot}guide/topics/manifest/manifest-intro.html">The
AndroidManifest.xml File</a> for complete information.</dd>
<dt id="ninepatch">Nine-patch / 9-patch / Ninepatch image</dt>
<dd>A resizeable bitmap resource that can be used for backgrounds or other
images on the device. See <a
href="{@docRoot}guide/topics/resources/available-resources.html#ninepatch">
Nine-Patch Stretchable Image</a> for more information.
<p>Related: <a href="#resources">Resources</a>.</p></dd>
<dt id="opengles">OpenGL ES</dt>
<dd> Android provides OpenGL ES libraries that you can use for fast,
complex 3D images. It is harder to use than a Canvas object, but
better for 3D objects. The {@link android.opengl} and
{@link javax.microedition.khronos.opengles} packages expose
OpenGL ES functionality.
<p>Related: <a href="#canvas">Canvas</a>, <a href="#surface">Surface</a></p></dd>
<dt id="resources">Resources</dt>
<dd>Nonprogrammatic application components that are external to the
compiled application code, but which can be loaded from application code
using a well-known reference format. Android supports a variety of
resource types, but a typical application's resources would consist of UI
strings, UI layout components, graphics or other media files, and so on.
An application uses resources to efficiently support localization and
varied device profiles and states. For example, an application would
include a separate set of resources for each supported local or device
type, and it could include layout resources that are specific to the
current screen orientation (landscape or portrait). For more information
about resources, see <a
href="{@docRoot}guide/topics/resources/index.html"> Resources and
Assets</a>. The resources of an application are always stored in the
<code>res/*</code> subfolders of the project. </dd>
<dt id="service">Service</dt>
<dd>An object of class {@link android.app.Service} that runs in the
background (without any UI presence) to perform various persistent
actions, such as playing music or monitoring network activity.
<p>Related: <a href="#activity">Activity</a></p></dd>
<dt id="surface">Surface</dt>
<dd>An object of type {@link android.view.Surface} representing a block of
memory that gets composited to the screen. A Surface holds a Canvas object
for drawing, and provides various helper methods to draw layers and resize
the surface. You should not use this class directly; use
{@link android.view.SurfaceView} instead.
<p>Related: <a href="#canvas">Canvas</a></p></dd>
<dt id="surfaceview">SurfaceView</dt>
<dd>A View object that wraps a Surface for drawing, and exposes methods to
specify its size and format dynamically. A SurfaceView provides a way to
draw independently of the UI thread for resource-intensive operations
(such as games or camera previews), but it uses extra memory as a result.
SurfaceView supports both Canvas and OpenGL ES graphics. The base class is
{@link android.view.SurfaceView}.
<p>Related: <a href="#canvas">Surface</a></p></dd>
<dt id="theme">Theme</dt>
<dd>A set of properties (text size, background color, and so on) bundled
together to define various default display settings. Android provides a
few standard themes, listed in {@link android.R.style} (starting with
&quot;Theme_&quot;). </dd>
<dt id="uri">URIs in Android</dt>
<dd>Android uses URI strings as the basis for requesting data in a content
provider (such as to retrieve a list of contacts) and for requesting
actions in an Intent (such as opening a Web page in a browser). The URI
scheme and format is specialized according to the type of use, and an
application can handle specific URI schemes and strings in any way it
wants. Some URI schemes are reserved by system components. For example,
requests for data from a content provider must use the
<code>content://</code>. In an Intent, a URI using an <code>http://</code>
scheme will be handled by the browser. </dd>
<dt id="view">View</dt>
<dd>An object that draws to a rectangular area on the screen and handles
click, keystroke, and other interaction events. A View is a base class for
most layout components of an Activity or Dialog screen (text boxes,
windows, and so on). It receives calls from its parent object (see
viewgroup, below)to draw itself, and informs its parent object about where
and how big it would like to be (which may or may not be respected by the
parent). For more information, see {@link android.view.View}.
<p>Related: <a href="#viewgroup">Viewgroup</a>, <a href="#widget">Widget
</a></p></dd>
<dt id="viewgroup">Viewgroup</dt>
<dd> A container object that groups a set of child Views. The viewgroup is
responsible for deciding where child views are positioned and how large
they can be, as well as for calling each to draw itself when appropriate.
Some viewgroups are invisible and are for layout only, while others have
an intrinsic UI (for instance, a scrolling list box). Viewgroups are all
in the {@link android.widget widget} package, but extend
{@link android.view.ViewGroup ViewGroup}.
<p>Related: <a href="#view">View</a></p></dd>
<dt id="widget">Widget</dt>
<dd>One of a set of fully implemented View subclasses that render form
elements and other UI components, such as a text box or popup menu.
Because a widget is fully implemented, it handles measuring and drawing
itself and responding to screen events. Widgets are all in the
{@link android.widget} package. </dd>
<!--
<dt id="panel">Panel</dt>
<dd> A panel is a concept not backed by a specific class. It is a View of
some sort that is tied in closely to a parent window, but can handle
clicks and perform simple functions related to its parent. A panel floats
in front of its parent, and is positioned relative to it. A common example
of a panel (implemented by Android) is the options menu available to every
screen. At present, there are no specific classes or methods for creating
a panel &mdash; it's more of a general idea. </dd>
-->
<dt id="panel">Window</dt>
<dd>In an Android application, an object derived from the abstract class
{@link android.view.Window} that specifies the elements of a generic
window, such as the look and feel (title bar text, location and content of
menus, and so on). Dialog and Activity use an implementation of this class
to render a window. You do not need to implement this class or use windows
in your application. </dd>
</dl>

View File

@@ -0,0 +1,13 @@
page.title=Appendix
@jd:body
<dl>
<dt><a href="media-formats.html">Supported Android Media Formats</a></dt>
<dd>A list of media codecs included in the Android platform.</dd>
<dt><a href="g-app-intents.html">Intents List: Invoking Google Applications on Android Devices</a></dt>
<dd>Intents you can send to invoke Google applications on Android devices.</dd>
<dt><a href="faq/index.html">FAQs, Tips, and How-to</a></dt>
<dd>How to get things done in Android.</dd>
<dt><a href="glossary.html">Glossary</a></dt>
<dd>Glossary of Android terminology.</dd>
</dl>

View File

@@ -0,0 +1,201 @@
page.title=App Install Location
@jd:body
<div id="qv-wrapper">
<div id="qv">
<h2>Quickview</h2>
<ul>
<li>You can allow your application to install on the device's external storage.</li>
<li>Some types of applications should <strong>not</strong> allow installation on the external
storage.</li>
<li>Installing on the external storage is ideal for large applications that are not tightly
integrated with the system (most commonly, games).</li>
</ul>
<h2>In this document</h2>
<ol>
<li><a href="#Compatiblity">Backward Compatibility</a></li>
<li><a href="#ShouldNot">Applications That Should NOT Install on External Storage</a></li>
<li><a href="#Should">Applications That Should Install on External Storage</a></li>
</ol>
<h2>See also</h2>
<ol>
<li><code><a href="{@docRoot}guide/topics/manifest/manifest-element.html">
&lt;manifest&gt;</a></code></li>
</ol>
</div>
</div>
<p>Beginning with API Level 8, you can allow your application to be installed on the
external storage (for example, the device's SD card). This is an optional feature you can declare
for your application with the <a
href="{@docRoot}guide/topics/manifest/manifest-element.html#install">{@code
android:installLocation}</a> manifest attribute. If you do
<em>not</em> declare this attribute, your application will be installed on the internal storage
only and it cannot be moved to the external storage.</p>
<p>To allow the system to install your application on the external storage, modify your
manifest file to include the <a
href="{@docRoot}guide/topics/manifest/manifest-element.html#install">{@code
android:installLocation}</a> attribute in the <code><a
href="{@docRoot}guide/topics/manifest/manifest-element.html">&lt;manifest&gt;</a></code> element,
with a value of either "{@code preferExternal}" or "{@code auto}". For example:</p>
<pre>
&lt;manifest xmlns:android="http://schemas.android.com/apk/res/android"
android:installLocation="preferExternal"
... &gt;
</pre>
<p>If you declare "{@code preferExternal}", you request that your application be installed on the
external storage, but the system does not guarantee that your application will be installed on
the external storage. If the external storage is full, the system will install it on the internal
storage. The user can also move your application between the two locations.</p>
<p>If you declare "{@code auto}", you indicate that your application may be installed on the
external storage, but you don't have a preference of install location. The system will
decide where to install your application based on several factors. The user can also move your
application between the two locations.</p>
<p>When your application is installed on the external storage:</p>
<ul>
<li>There is no effect on the application performance so long
as the external storage is mounted on the device.</li>
<li>The {@code .apk} file is saved on the external storage, but all private user data,
databases, optimized {@code .dex} files, and extracted native code are saved on the
internal device memory.</li>
<li>The unique container in which your application is stored is encrypted with a randomly
generated key that can be decrypted only by the device that originally installed it. Thus, an
application installed on an SD card works for only one device.</li>
<li>The user can move your application to the internal storage through the system settings.</li>
</ul>
<p class="warning"><strong>Warning:</strong> When the user enables USB mass storage to share files
with a computer or unmounts the SD card via the system settings, the external storage is unmounted
from the device and all applications running on the external storage are immediately killed.</p>
<h2 id="Compatiblity">Backward Compatibility</h2>
<p>The ability for your application to install on the external storage is a feature available only
on devices running API Level 8 (Android 2.2) or greater. Existing applications that were built prior
to API Level 8 will always install on the internal storage and cannot be moved to the external
storage (even on devices with API Level 8). However, if your application is designed to support an
API Level <em>lower than</em> 8, you can choose to support this feature for devices with API Level 8
or greater and still be compatible with devices using an API Level lower than 8.</p>
<p>To allow installation on external storage and remain compatible with versions lower than API
Level 8:</p>
<ol>
<li>Include the {@code android:installLocation} attribute with a value of "{@code auto}" or
"{@code preferExternal}" in the <code><a
href="{@docRoot}guide/topics/manifest/uses-sdk-element.html">&lt;manifest&gt;</a></code>
element.</li>
<li>Leave your {@code android:minSdkVersion} attribute as is (something <em>less
than</em> "8") and be certain that your application code uses only APIs compatible with that
level.</li>
<li>In order to compile your application, change your build target to API Level 8. This is
necessary because older Android libraries don't understand the {@code android:installLocation}
attribute and will not compile your application when it's present.</li>
</ol>
<p>When your application is installed on a device with an API Level lower than 8, the {@code
android:installLocation} attribute is ignored and the application is installed on the internal
storage.</p>
<p class="caution"><strong>Caution:</strong> Although XML markup such as this will be ignored by
older platforms, you must be careful not to use programming APIs introduced in API Level 8
while your {@code minSdkVersion} is less than "8", unless you perform the work necessary to
provide backward compatibility in your code. For information about building
backward compatibility in your application code, see the <a
href="{@docRoot}resources/articles/backward-compatibility.html">Backward Compatibility</a>
article.</p>
<h2 id="ShouldNot">Applications That Should NOT Install on External Storage</h2>
<p>When the user enables USB mass storage to share files with their computer (or otherwise
unmounts or removes the external storage), any application
installed on the external storage and currently running is killed. The system effectively becomes
unaware of the application until mass storage is disabled and the external storage is
remounted on the device. Besides killing the application and making it unavailable to the user,
this can break some types of applications in a more serious way. In order for your application to
consistently behave as expected, you <strong>should not</strong> allow your application to be
installed on the external storage if it uses any of the following features, due to the cited
consequences when the external storage is unmounted:</p>
<dl>
<dt>Services</dt>
<dd>Your running {@link android.app.Service} will be killed and will not be restarted when
external storage is remounted. You can, however, register for the {@link
android.content.Intent#ACTION_EXTERNAL_APPLICATIONS_AVAILABLE} broadcast Intent, which will notify
your application when applications installed on external storage have become available to the
system again. At which time, you can restart your Service.</dd>
<dt>Alarm Services</dt>
<dd>Your alarms registered with {@link android.app.AlarmManager} will be cancelled. You must
manually re-register any alarms when external storage is remounted.</dd>
<dt>Input Method Engines</dt>
<dd>Your <a href="{@docRoot}resources/articles/on-screen-inputs.html">IME</a> will be
replaced by the default IME. When external storage is remounted, the user can open system settings
to enable your IME again.</dd>
<dt>Live Wallpapers</dt>
<dd>Your running <a href="{@docRoot}resources/articles/live-wallpapers.html">Live Wallpaper</a>
will be replaced by the default Live Wallpaper. When external storage is remounted, the user can
select your Live Wallpaper again.</dd>
<dt>Live Folders</dt>
<dd>Your <a href="{@docRoot}resources/articles/live-folders.html">Live Folder</a> will be
removed from the home screen. When external storage is remounted, the user can add your Live Folder
to the home screen again.</dd>
<dt>App Widgets</dt>
<dd>Your <a href="{@docRoot}guide/topics/appwidgets/index.html">App Widget</a> will be removed
from the home screen. When external storage is remounted, your App Widget will <em>not</em> be
available for the user to select until the system resets the home application (usually not until a
system reboot).</dd>
<dt>Account Managers</dt>
<dd>Your accounts created with {@link android.accounts.AccountManager} will disappear until
external storage is remounted.</dd>
<dt>Sync Adapters</dt>
<dd>Your {@link android.content.AbstractThreadedSyncAdapter} and all its sync functionality will
not work until external storage is remounted.</dd>
<dt>Device Administrators</dt>
<dd>Your {@link android.app.admin.DeviceAdminReceiver} and all its admin capabilities will
be disabled, which can have unforeseeable consequences for the device functionality, which may
persist after external storage is remounted.</dd>
<dt>Broadcast Receivers listening for "boot completed"</dt>
<dd>The system delivers the {@link android.content.Intent#ACTION_BOOT_COMPLETED} broadcast
before the external storage is mounted to the device. If your application is installed on the
external storage, it can never receive this broadcast.</dd>
</dl>
<p>If your application uses any of the features listed above, you <strong>should not</strong> allow
your application to install on external storage. By default, the system <em>will not</em> allow your
application to install on the external storage, so you don't need to worry about your existing
applications. However, if you're certain that your application should never be installed on the
external storage, then you should make this clear by declaring <a
href="{@docRoot}guide/topics/manifest/manifest-element.html#install">{@code
android:installLocation}</a> with a value of "{@code internalOnly}". Though this does not
change the default behavior, it explicitly states that your application should only be installed
on the internal storage and serves as a reminder to you and other developers that this decision has
been made.</p>
<h2 id="Should">Applications That Should Install on External Storage</h2>
<p>In simple terms, anything that does not use the features listed in the previous section
are safe when installed on external storage. Large games are more commonly the types of
applications that should allow installation on external storage, because games don't typically
provide additional services when innactive. When external storage becomes unavailable and a game
process is killed, there should be no visible effect when the storage becomes available again and
the user restarts the game (assuming that the game properly saved its state during the normal
<a href="{@docRoot}guide/topics/fundamentals.html#lcycles">Activity lifecycle</a>).</p>
<p>If your application requires several megabytes for the APK file, you should
carefully consider whether to enable the application to install on the external storage so that
users can preserve space on their internal storage.</p>

View File

@@ -0,0 +1,353 @@
page.title=Market Filters
@jd:body
<div id="qv-wrapper">
<div id="qv">
<h2>Quickview</h2>
<ul> <li>Android Market applies filters to that let you control whether your app is shown to a
user who is browing or searching for apps.</li>
<li>Filtering is determined by elements in an app's manifest file,
aspects of the device being used, and other factors.</li> </ul>
<h2>In this document</h2>
<ol> <li><a href="#how-filters-work">How Filters Work in Android Market</a></li>
<li><a href="#manifest-filters">Filtering based on Manifest File Elements</a></li>
<li><a href="#other-filters">Other Filters</a></li>
</ol>
<h2>See also</h2>
<ol>
<li><a
href="{@docRoot}guide/practices/compatibility.html">Compatibility</a></li>
<li style="margin-top:2px;"><code><a
href="{@docRoot}guide/topics/manifest/supports-screens-element.html">&lt;supports-screens&gt;</a></code></li>
<li><code><a
href="{@docRoot}guide/topics/manifest/uses-configuration-element.html">&lt;uses-configuration&gt;</a></code></li>
<li><code><a
href="{@docRoot}guide/topics/manifest/uses-feature-element.html">&lt;uses-feature&gt;</a></code></li>
<li><code><a
href="{@docRoot}guide/topics/manifest/uses-library-element.html">&lt;uses-library&gt;</a></code></li>
<li><code><a
href="{@docRoot}guide/topics/manifest/uses-permission-element.html">&lt;uses-permission&gt;</a></code></li>
<li><code><a
href="{@docRoot}guide/topics/manifest/uses-sdk-element.html">&lt;uses-sdk&gt;</code></a></li>
</ol>
<div id="qv-extra"> <img id="rule" src="{@docRoot}assets/images/grad-rule-qv.png">
<div id="qv-sub-rule"> <img src="{@docRoot}assets/images/icon_market.jpg"
style="float:left;margin:0;padding:0;"> <p style="color:#669999;">Interested in
publishing your app on Android Market?</p> <a id="publish-link"
href="http://market.android.com/publish">Go to Android Market &raquo;</a> </div>
</div>
</div> </div>
<p>When a user searches or browses in Android Market, the results are filtered, and
some applications might not be visible. For example, if an application requires a
trackball (as specified in the manifest file), then Android Market will not show
the app on any device that does not have a trackball.</p> <p>The manifest file and
the device's hardware and features are only part of how applications are filtered
&#8212; filtering also depends on the country and carrier, the presence or absence
of a SIM card, and other factors. </p>
<p>Changes to the Android Market filters are independent of changes
to the Android platform itself. This document will be updated periodically to reflect
any changes that occur. </p>
<h2 id="how-filters-work">How Filters Work in Android Market</h2>
<p>Android Market uses the filter restrictions described below to determine
whether to show your application to a user who is browsing or searching for
applications on a given device. When determining whether to display your app,
Market checks the device's hardware and software capabilities, as well as it's
carrier, location, and other characteristics. It then compares those against the
restrictions and dependencies expressed by the application itself, in its
manifest, <code>.apk</code>, and publishing details. If the application is
compatible with the device according to the filter rules, Market displays the
application to the user. Otherwise, Market hides your application from search
results and category browsing. </p>
<p> You can use the filters described below to control whether Market shows or
hides your application to users. You can request any combination of the
available filters for your app &#8212; for example, you could set a
<code>minSdkVersion</code> requirement of <code>"4"</code> and set
<code>smallScreens="false"</code> in the app, then when uploading the app to
Market you could target European countries (carriers) only. Android Market's
filters would prevent the application from being visible on any device that did
not match all three of these requirements. </p>
<p>A filtered app is not visible within Market, even if a user specifically requests
the app by clicking a deep link that points directly to the app's ID within Market.
All filtering restrictions are associated with an application's version and can
change between versions. For example:</p>
<ul>
<li>If you publish a new version of your app with stricter restrictions, the app
will not be visible to users for whom it is filtered, even if those users were
able see the previous version.</li>
<li>If a user has installed your application and you publish an upgrade that
makes the app invisible to the user, the user will not see that an upgrade is
available. </li>
</ul>
<h2 id="manifest-filters">Filtering based on Manifest Elements</h2>
<p>Most Market filters are triggered by elements within an application's
manifest file, <a
href="{@docRoot}guide/topics/manifest/manifest-intro.html">AndroidManifest.xml</a>,
although not everything in the manifest file can trigger filtering. The
table below lists the manifest elements that you can use to trigger Android
Market filtering, and explains how the filtering works.</p>
<p class="table-caption"><strong>Table 1.</strong> Manifest elements that
trigger filtering on Market.</p>
<table>
<tr>
<th>Manifest Element</th>
<th>Filter Name</th>
<th>How It Works</th>
</tr>
<tr>
<td valign="top" style="white-space:nowrap;"><code><a href="{@docRoot}guide/topics/manifest/supports-screens-element.html">&lt;supports-screens&gt;</a></code>
<!-- ##api level 4## --></td>
<td valign="top">Screen Size</td>
<td valign="top">
<p>An application indicates the screen sizes that it is capable of supporting by
setting attributes of the <code>&lt;supports-screens&gt;</code> element. When
the application is published, Market uses those attributes to determine whether
to show the application to users, based on the screen sizes of their
devices. </p>
<p>As a general rule, Market assumes that the platform on the device can adapt
smaller layouts to larger screens, but cannot adapt larger layouts to smaller
screens. Thus, if an application declares support for "normal" screen size only,
Market makes the application available to both normal- and large-screen devices,
but filters the application so that it is not available to small-screen
devices.</p>
<p>If an application does not declare attributes for
<code>&lt;supports-screens&gt;</code>, Market uses the default values for those
attributes, which vary by API Level. Specifically: </p>
<ul>
<li><p>In API level 3, the <code>&lt;supports-screens&gt;</code> element itself
is undefined and no attributes are available. In this case, Market assumes that
the application is designed for normal-size screens and shows the application to
devices that have normal or large screens. </p>
<p>This behavior is especially significant for applications that set their
<code><a
href="{@docRoot}guide/topics/manifest/uses-sdk-element.html">android:
minSdkVersion</a></code> to 3 or lower, since Market will filter them from
small-screen devices by default. Such applications can enable support for
small-screen devices by adding a <code>android:targetSdkVersion="4"</code>
attribute to the <code>&lt;uses-sdk&gt;</code> element in their manifest
files. For more information, see <a
href="{@docRoot}guide/practices/screens_support.html#strategies">Strategies for
Legacy Applications</a>.</p></li>
<li>In API Level 4, the defaults for all of the attributes is
<code>"true"</code>. If an application does not declare a
<code>&lt;supports-screens&gt;</code> element, Market assumes that the
application is designed for all screen sizes and does not filter it from any
devices. If the application does not declare one of the attributes, Market uses
the default value of <code>"true"</code> and does not filter the app for devices
of corresponding screen size.</li>
</ul>
<p><strong>Example 1</strong><br />
The manifest declares <code>&lt;uses-sdk android:minSdkVersion="3"&gt;</code>
and does not does not include a <code>&lt;supports-screens&gt;</code> element.
<strong>Result</strong>: Android Market will not show the app to a user of a
small-screen device, but will show it to users of normal and large-screen
devices, users, unless other filters apply. </p>
<p><strong>Example 2<br />
</strong>The manifest declares <code>&lt;uses-sdk android:minSdkVersion="3"
android:targetSdkVersion="4"&gt;</code> and does not include a
<code>&lt;supports-screens&gt;</code> element.
<strong>Result</strong>: Android Market will show the app to users on all
devices, unless other filters apply. </p>
<p><strong>Example 3<br />
</strong>The manifest declares <code>&lt;uses-sdk android:minSdkVersion="4"&gt;</code>
and does not include a <code>&lt;supports-screens&gt;</code> element.
<strong>Result</strong>: Android Market will show the app to all users,
unless other filters apply. </p>
<p>For more information on how to declare support for screen sizes in your
application, see <code><a
href="{@docRoot}guide/topics/manifest/supports-screens-element.html">&lt;supports-screens&gt;</a></code>
and <a href="{@docRoot}guide/practices/screens_support.html">Supporting Multiple
Screens</a>.</p>
</td>
</tr>
<tr>
<td valign="top" style="white-space:nowrap;"><code><a href="{@docRoot}guide/topics/manifest/uses-configuration-element.html">&lt;uses-configuration&gt;</a></code>
<!-- ##api level 3## --></td>
<td valign="top">Device
Configuration: <br />
keyboard, navigation, touch screen</td>
<td valign="top"><p>An application can
request certain hardware features, and Android Market will show the app only on devices that have the required hardware.</p>
<p><strong>Example 1<br />
</strong>The manifest includes <code>&lt;uses-configuration android:reqFiveWayNav=&quot;true&quot; /&gt;</code>, and a user is searching for apps on a device that does not have a five-way navigational control. <strong>Result</strong>: Android Market will not show the app to the user. </p>
<p><strong>Example 2<br />
</strong>The manifest does not include a <code>&lt;uses-configuration&gt;</code> element. <strong>Result</strong>: Android Market will show the app to all users, unless other filters apply.</p>
<p>For more details, see <a
href="{@docRoot}guide/topics/manifest/uses-configuration-element.html"><code>&lt;uses-configuration&gt;</code></a>.</p></td>
</tr>
<tr>
<td rowspan="2" valign="top" style="white-space:nowrap;"><code><a
href="{@docRoot}guide/topics/manifest/uses-feature-element.html">&lt;uses-feature&gt;</a>
</code>
<!-- ##api level 4## --></td>
<td valign="top">Device Features<br />
(<code>name</code>)</td>
<td valign="top"><p>An application can require certain device features to be
present on the device. This functionality was introduced in Android 2.0 (API
Level 5).</p>
<p><strong>Example 1<br />
</strong>The manifest includes <code>&lt;uses-feature
android:name=&quot;android.hardware.sensor.light&quot; /&gt;</code>, and a user
is searching for apps on a device that does not have a light sensor.
<strong>Result</strong>: Android Market will not show the app to the user. </p>
<p><strong>Example 2<br />
</strong>The manifest does not include a <code>&lt;uses-feature&gt;</code>
element. <strong>Result</strong>: Android Market will show the app to all users,
unless other filters apply.</p>
<p>For complete information, see <code><a
href="{@docRoot}guide/topics/manifest/uses-feature-element.html">&lt;uses-feature&gt;</a>
</code>.</p>
<p><em>Filtering based on implied features:</em> In some cases, Android
Market interprets permissions requested through
<code>&lt;uses-permission&gt;</code> elements as feature requirements equivalent
to those declared in <code>&lt;uses-feature&gt;</code> elements. See <a
href="#uses-permission-filtering"><code>&lt;uses-permission&gt;</code></a>,
below.</p>
</td>
</tr>
<tr>
<td valign="top">OpenGL-ES
Version<br />
(<code>openGlEsVersion</code>)</td>
<td valign="top"><p>An application can require that the device support a specific
OpenGL-ES version using the <code>&lt;uses-feature
android:openGlEsVersion=&quot;int&quot;&gt;</code> attribute.</p>
<p><strong>Example 1<br />
</strong>An app
requests multiple OpenGL-ES versions by specifying <code>openGlEsVersion</code> multiple times in the
manifest. <strong>Result</strong>: Market assumes that the app requires the highest of the indicated versions.</p>
<p><strong>Example 2<br />
</strong>An app
requests OpenGL-ES version 1.1, and a user is searching for apps on a device that supports OpenGL-ES version 2.0. <strong>Result</strong>: Android Market will show the app to the user, unless other filters apply. If a
device reports that it supports OpenGL-ES version <em>X</em>, Market assumes that it
also supports any version earlier than <em>X</em>.
</p>
<p><strong>Example 3<br />
</strong>A user is searching for apps on a device that does not
report an OpenGL-ES version (for example, a device running Android 1.5 or earlier). <strong>Result</strong>: Android Market assumes that the device
supports only OpenGL-ES 1.0. Market will only show the user apps that do not specify <code>openGlEsVersion</code>, or apps that do not specify an OpenGL-ES version higher than 1.0. </p>
<p><strong>Example 4<br />
</strong>The manifest does not specify <code>openGlEsVersion</code>. <strong>Result</strong>: Android Market will show the app to all users, unless other filters apply. </p>
<p>For more details, see <a
href="{@docRoot}guide/topics/manifest/uses-feature-element.html"><code>&lt;uses-feature&gt;</code></a>.</p></td>
</tr>
<tr>
<td valign="top" style="white-space:nowrap;"><code><a href="{@docRoot}guide/topics/manifest/uses-library-element.html">&lt;uses-library&gt;</a></code></td>
<td valign="top">Software Libraries</td>
<td valign="top"><p>An application can require specific
shared libraries to be present on the device. </p>
<p><strong>Example 1<br />
</strong>An app requires the <code>com.google.android.maps</code> library, and a user is searching for apps on a device that does not have the <code>com.google.android.maps</code> library. <strong>Result</strong>: Android Market will not show the app to the user. </p>
<p><strong>Example 2</strong><br />
The manifest does not include a <code>&lt;uses-library&gt;</code> element. <strong>Result</strong>: Android Market will show the app to all users, unless other filters apply.</p>
<p>For more details, see <a
href="{@docRoot}guide/topics/manifest/uses-library-element.html"><code>&lt;uses-library&gt;</code></a>.</p></td>
</tr>
<tr id="uses-permission-filtering">
<td valign="top" style="white-space:nowrap;"><code><a href="{@docRoot}guide/topics/manifest/uses-permission-element.html">&lt;uses-permission&gt;</a></code></td>
<td valign="top">&nbsp;</td>
<td valign="top">Strictly, Android Market does not filter based on
<code>&lt;uses-permission&gt;</code> elements. However, it does read the
elements to determine whether the application has hardware feature requirements
that may not have been properly declared in <code>&lt;uses-feature&gt;</code>
elements. For example, if an application requests the <code>CAMERA</code>
permission but does not declare a <code>&lt;uses-feature&gt;</code> element for
<code>android.hardware.camera</code>, Android Market considers that the
application requires a camera and should not be shown to users whose devices do
not offer a camera.</p>
<p>In general, if an application requests hardware-related permissions,
Android Market assumes that the application requires the underlying hardware
features, even though there might be no corresponding to
<code>&lt;uses-feature&gt;</code> declarations. Android Market then sets up
filtering based on the features implied by the <code>&lt;uses-feature&gt;</code>
declarations.</p>
<p>For a list of permissions that imply hardware features, see
the documentation for the <a
href="{@docRoot}guide/topics/manifest/uses-feature-element.html#permissions-features"><code>&lt;uses-feature&gt;</code></a>
element.</p>
</td>
</tr>
<tr>
<td rowspan="2" valign="top" style="white-space:nowrap;"><code><a href="{@docRoot}guide/topics/manifest/uses-sdk-element.html">&lt;uses-sdk&gt;</a></code></td>
<td valign="top">Minimum Framework Version (<code>minSdkVersion</code>)</td>
<td valign="top"><p>An application can require a minimum API level. </p>
<p><strong>Example 1</strong><br />
The manifest includes <code>&lt;uses-sdk
android:minSdkVersion=&quot;3&quot;&gt;</code>, and the app uses APIs that were introduced in API Level 3. A user is searching for apps on a device that has API Level 2. <strong>Result</strong>: Android Market will not show the app to the user. </p>
<p><strong>Example 2</strong><br />
The manifest does not include <code>minSdkVersion</code>, and the app uses APIs that were introduced in API Level 3. A user is searching for apps on a device that has API Level 2. <strong>Result</strong>: Android Market assumes that <code>minSdkVersion</code> is &quot;1&quot; and that the app is compatible with all versions of Android. Market shows the app to the user and allows the user to download the app. The app crashes at runtime. </p>
<p>Because you want to avoid this second scenario, we recommend that you always declare a <code>minSdkVersion</code>. For details, see <a
href="{@docRoot}guide/topics/manifest/uses-sdk-element.html#min"><code>android:minSdkVersion</code></a>.</p></td>
</tr>
<tr>
<td valign="top">Maximum Framework Version (<code>maxSdkVersion</code>)</td>
<td valign="top"><p><em>Deprecated.</em> Android
2.1 and later do not check or enforce the <code>maxSdkVersion</code> attribute, and
the SDK will not compile if <code>maxSdkVersion</code> is set in an app's manifest. For devices already
compiled with <code>maxSdkVersion</code>, Market will respect it and use it for
filtering.</p>
<p> Declaring <code>maxSdkVersion</code> is <em>not</em> recommended. For details, see <a
href="{@docRoot}guide/topics/manifest/uses-sdk-element.html#max"><code>android:maxSdkVersion</code></a>.</p></td>
</tr>
</table>
<h2 id="other-filters">Other Filters</h2>
<p>Android Market uses other application characteristics to determine whether to show or hide an application for a particular user on a given device, as described in the table below. </p>
<p class="table-caption"><strong>Table 2.</strong> Application and publishing characteristics that affect filtering on Market.</p>
<table> <tr>
<th>Filter Name</th> <th>How It Works</th> </tr>
<tr>
<td valign="top">Publishing Status</td> <td valign="top"><p>Only published applications will appear in
searches and browsing within Android Market.</p> <p>Even if an app is unpublished, it can
be installed if users can see it in their Downloads area among their purchased,
installed, or recently uninstalled apps.</p> <p>If an application has been
suspended, users will not be able to reinstall or update it, even if it appears in their Downloads.</p> </td></tr>
<tr>
<td valign="top">Priced
Status</td> <td valign="top"><p>Not all users can see paid apps. To show paid apps, a device
must have a SIM card and be running Android 1.1 or later, and it must be in a
country (as determined by SIM carrier) in which paid apps are available.</p></td>
</tr> <tr>
<td valign="top">Country / Carrier Targeting</td> <td valign="top"> <p>When you upload your app to
the Android Market, you can select specific countries to target. The app will only
be visible to the countries (carriers) that you select, as follows:</p>
<ul><li><p>A device's country is determined based on the carrier, if a carrier is
available. If no carrier can be determined, the Market application tries to
determine the country based on IP.</p></li> <li><p>Carrier is determined based on
the device's SIM (for GSM devices), not the current roaming carrier.</p></li></ul>
</td> </tr> <tr>
<td valign="top">Native Platform</td> <td valign="top"><p>An application that includes native
libraries that target a specific platform (ARM EABI v7, for example) will only be
visible on devices that support that platform. For details about the NDK and using
native libraries, see <a href="{@docRoot}sdk/ndk/index.html#overview">What is the
Android NDK?</a></p> </tr> <tr>
<td valign="top">Forward-Locked Applications</td> <td valign="top"><p>To
forward lock an application, set copy protection to "On" when you upload the
application to Market. Market will not show copy-protected applications on
developer devices or unreleased devices.</p></td> </tr> </table>

View File

@@ -0,0 +1,158 @@
page.title=Android Supported Media Formats
@jd:body
<p>The <a href="#core">Core Media Formats</a> table below describes the media format support built into the Android platform. Note that any given mobile device may provide support for additional formats or file types not listed in the table. </p>
<p>As an application developer, you are free to make use of any media codec that is available on any Android-powered device, including those provided by the Android platform and those that are device-specific.</p>
<h2 id="core">Core Media Formats</h2>
<table>
<tbody>
<tr>
<th>Type</th>
<th>Format</th>
<th>Encoder</th>
<th>Decoder</th>
<th>Details</th>
<th>File Type(s) Supported</th>
</tr>
<tr>
<td rowspan="9">Audio</td>
<td>AAC LC/LTP</td>
<td style="text-align: center;">X</td>
<td style="text-align: center;">X</td>
<td rowspan="3">Mono/Stereo content in any combination of standard bit rates up to 160 kbps and sampling rates from 8 to 48kHz</td>
<td rowspan="3">3GPP (.3gp) and MPEG-4 (.mp4, .m4a). No support for raw AAC (.aac)</td>
</tr>
<tr>
<td>HE-AACv1 (AAC+)</td>
<td>&nbsp;</td>
<td style="text-align: center;">X</td>
</tr>
<tr>
<td>HE-AACv2 (enhanced AAC+)</td>
<td>&nbsp;</td>
<td style="text-align: center;">X</td>
</tr>
<tr>
<td>AMR-NB</td>
<td style="text-align: center;">X</td>
<td style="text-align: center;">X</td>
<td>4.75 to 12.2 kbps sampled @ 8kHz</td>
<td>3GPP (.3gp)
</td>
</tr>
<tr>
<td>AMR-WB</td>
<td style="text-align: center;">X</td>
<td style="text-align: center;">X</td>
<td>9 rates from 6.60 kbit/s to 23.85 kbit/s sampled @ 16kHz</td>
<td>3GPP (.3gp)</td>
</tr>
<tr>
<td>MP3</td>
<td>&nbsp;</td>
<td style="text-align: center;">X</td>
<td>Mono/Stereo 8-320Kbps constant (CBR) or variable bit-rate (VBR)
</td>
<td>MP3 (.mp3)</td>
</tr>
<tr>
<td>MIDI</td>
<td>&nbsp;</td>
<td style="text-align: center;">X</td>
<td>MIDI Type 0 and 1. DLS Version 1 and 2. XMF and Mobile XMF. Support for ringtone formats RTTTL/RTX, OTA, and iMelody </td>
<td>Type 0 and 1 (.mid, .xmf, .mxmf). Also RTTTL/RTX (.rtttl, .rtx), OTA (.ota), and iMelody (.imy)</td>
</tr>
<tr>
<td>Ogg Vorbis</td>
<td>&nbsp;</td>
<td style="text-align: center;">X</td>
<td>&nbsp;</td>
<td>Ogg (.ogg)</td>
</tr>
<tr>
<td>PCM/WAVE</td>
<td>&nbsp;</td>
<td style="text-align: center;">X</td>
<td>8- and 16-bit linear PCM (rates up to limit of hardware)</td>
<td>WAVE (.wav)</td>
</tr>
<tr>
<td rowspan="4">Image</td>
<td>JPEG</td>
<td style="text-align: center;">X</td>
<td style="text-align: center;">X</td>
<td>Base+progressive</td>
<td>JPEG (.jpg)</td>
</tr>
<tr>
<td>GIF</td>
<td>&nbsp;</td>
<td style="text-align: center;">X</td>
<td>&nbsp;</td>
<td>GIF (.gif)</td>
</tr>
<tr>
<td>PNG</td>
<td style="text-align: center;">X</td>
<td style="text-align: center;">X</td>
<td>&nbsp;</td>
<td>PNG (.png)</td>
</tr>
<tr>
<td>BMP</td>
<td>&nbsp;</td>
<td style="text-align: center;">X</td>
<td>&nbsp;</td>
<td>BMP (.bmp)</td>
</tr>
<tr>
<td rowspan="3">Video</td>
<td>H.263</td>
<td style="text-align: center;">X</td>
<td style="text-align: center;">X</td>
<td>&nbsp;</td>
<td>3GPP (.3gp) and MPEG-4 (.mp4)</td>
</tr>
<tr>
<td>H.264 AVC</td>
<td style="text-align: center;"></td>
<td style="text-align: center;">X</td>
<td>&nbsp;</td>
<td>3GPP (.3gp) and MPEG-4 (.mp4)</td>
</tr>
<tr>
<td>MPEG-4 SP</td>
<td>&nbsp;</td>
<td style="text-align: center;">X</td>
<td>&nbsp;</td>
<td>3GPP (.3gp)</td>
</tr>
</tbody></table>

View File

@@ -0,0 +1,261 @@
page.title=Application Model
@jd:body
<h1>Android Application Model: Applications, Tasks, Processes, and Threads</h1>
<p>In most operating systems, there is a strong 1-to-1 correlation between
the executable image (such as the .exe on Windows) that an application lives in,
the process it runs in, and the icon and application the user interacts with.
In Android these associations are much more fluid, and it is important to
understand how the various pieces can be put together.</p>
<p>Because of the flexible nature of Android applications, there is some
basic terminology that needs to be understood when implementing the
various pieces of an application:</p>
<ul>
<li><p>An <strong>android package</strong> (or <strong>.apk</strong> for short)
is the file containing an application's code and its resources. This is the
file that an application is distributed in and downloaded by the user when
installing that application on their device.</p></li>
<li><p>A <strong>task</strong> is generally what the user perceives as
an "application" that can be launched: usually a task has an icon in the
home screen through which it is accessed, and it is available as a top-level
item that can be brought to the foreground in front of other
tasks.</p></li>
<li><p>A <strong>process</strong> is a low-level kernel process in which
an application's code is running. Normally all of the code in a
.apk is run in one, dedicated process for that .apk; however, the
{@link android.R.styleable#AndroidManifestApplication_process process} tag
can be used to modify where that code is run, either for
{@link android.R.styleable#AndroidManifestApplication the entire .apk}
or for individual
{@link android.R.styleable#AndroidManifestActivity activity},
{@link android.R.styleable#AndroidManifestReceiver receiver},
{@link android.R.styleable#AndroidManifestService service}, or
{@link android.R.styleable#AndroidManifestProvider provider}, components.</p></li>
</ul>
<h2 id="Tasks">Tasks</h2>
<p>A key point here is: <em>when the user sees as an "application," what
they are actually dealing with is a task</em>. If you just create a .apk
with a number of activities, one of which is a top-level entry point (via
an {@link android.R.styleable#AndroidManifestIntentFilter intent-filter} for
the action <code>android.intent.action.MAIN</code> and
category <code>android.intent.category.LAUNCHER</code>), then there will indeed
be one task created for your .apk, and any activities you start from there
will also run as part of that task.</p>
<p>A task, then, from the user's perspective your application; and from the
application developer's perspective it is one or more activities the user
has traversed through in that task and not yet closed, or an activity stack.
A new task is created by
starting an activity Intent with the {@link android.content.Intent#FLAG_ACTIVITY_NEW_TASK
Intent.FLAG_ACTIVITY_NEW_TASK} flag; this Intent will be used as the root Intent of
the task, defining what task it is. Any activity started without this flag
will run in the same task as the activity that is starting it (unless that
activity has requested a special launch mode, as discussed later). Tasks can
be re-ordered: if you use FLAG_ACTIVITY_NEW_TASK but there is already a task
running for that Intent, the current task's activity stack will be brought
to the foreground instead of starting a new task.</p>
<p>FLAG_ACTIVITY_NEW_TASK must only be used with care: using it says that,
from the user's perspective, a new application starts at this point. If this
is not the behavior you desire, you should not be creating a new task. In
addition, you should only use the new task flag if it is possible for the user
to navigate from home back to where they are and launch the same Intent as a
new task. Otherwise, if the user presses HOME instead of BACK from the task
you have launched, your task and its activities will be ordered behind the
home screen without a way to return to them.</p>
<h3>Task Affinities</h3>
<p>In some cases Android needs to know which task an activity belongs to even when
it is not being launched in to a specific task. This is accomplished through
task affinities, which provide a unique static name for the task that one or more
activities are intended to run in. The default task affinity for an activity
is the name of the .apk package name the activity is implemented in. This
provides the normally expected behavior, where all of the activities in a
particular .apk are part of a single application to the user.</p>
<p>When starting a new activity without the
{@link android.content.Intent#FLAG_ACTIVITY_NEW_TASK
Intent.FLAG_ACTIVITY_NEW_TASK} flag, task affinities have no impact on the
task the new activity will run in: it will always run in the task of the
activity that is starting it. However, if the NEW_TASK flag is being used,
then the affinity will be used to determine if a task already exists with
the same affinity. If so, that task will be brought to the front and the
new activity launched at the top of that task.</p>
<p>This behavior is most useful for situations where you must use the
NEW_TASK flag, in particular launching activities from status bar notifications
or home screen shortcuts. The result is that, when the user launches your
application this way, its current task state will be brought to the foreground,
and the activity they now want to look at placed on top of it.</p>
<p>You can assign your own task affinities in your manifest's
{@link android.R.styleable#AndroidManifestApplication application} tag for
all activities in the .apk, or the
{@link android.R.styleable#AndroidManifestActivity activity} tag of
individual activities. Some examples of how this can be used are:</p>
<ul>
<li>If your .apk contains multiple top-level applications that the user can
launch, then you will probably want to assign different affinities to each
of the activities that the users sees for your .apk. A good convention for
coming up with distinct names is to append your .apk's package name with
a colon separated string. For example, the "com.android.contacts" .apk
may have the affinities "com.android.contacts:Dialer" and
"com.android.contacts:ContactsList".</ul>
<li>If you are replacing a notification, shortcut, or other such "inner"
activity of an application that can be launched from outside of it, you may
need to explicitly set the taskAffinity of your replacement activity to be
the same as the application you are replacing. For example, if you are
replacing the contacts details view (which the user can make and invoke
shortcuts to), you would want to set the taskAffinity to
"com.android.contacts".</li>
</ul>
<h3>Launch Modes and Launch Flags</h3>
<p>The main way you control how activities interact with tasks is through
the activity's
{@link android.R.styleable#AndroidManifestActivity_launchMode launchMode}
attribute and the {@link android.content.Intent#setFlags flags} associated
with an Intent. These two parameters can work together in various ways
to control the outcome of the activity launch, as described in their
associated documentation. Here we will look at some common use cases and
combinations of these parameters.</p>
<p>The most common launch mode you will use (besides the default
<code>standard</code> mode) is <code>singleTop</code>. This does not have
an impact on tasks; it just avoids starting the same activity multiple times
on the top of a stack.
<p>The <code>singleTask</code> launch mode has a major
impact on tasks: it causes the activity to always be started in
a new task (or its existing task to be brought to the foreground). Using
this mode requires a lot of care in how you interact with the rest of the
system, as it impacts every path in to the activity. It should only be used
with activities that are front doors to the application (that is, which
support the MAIN action and LAUNCHER category).</p>
<p>The <code>singleInstance</code> launch mode is even more specialized, and
should only be used in applications that are implemented entirely as one
activity.</p>
<p>A situation you will often run in to is when another entity (such as the
{@link android.app.SearchManager} or {@link android.app.NotificationManager})
starts one of your activities. In this case, the
{@link android.content.Intent#FLAG_ACTIVITY_NEW_TASK
Intent.FLAG_ACTIVITY_NEW_TASK} flag must be used, because the activity is
being started outside of a task (and the application/task may not even
exist). As described previously, the standard behavior in this situation
is to bring to the foreground the current task matching the new activity's
affinity and start the new activity at the top of it. There are, however,
other types of behavior that you can implement.</p>
<p>One common approach is to also use the
{@link android.content.Intent#FLAG_ACTIVITY_CLEAR_TOP
Intent.FLAG_ACTIVITY_CLEAR_TOP} flag in conjunction with NEW_TASK. By doing so,
if your task is already running, then it will be brought to the foreground,
all of the activities on its stack cleared except the root activity, and the
root activity's {@link android.app.Activity#onNewIntent} called with the
Intent being started. Note that the activity often also use the <code>singleTop</code>
or <code>singleTask</code> launch mode when using this approach, so that
the current instance is given the new intent instead of requiring that it
be destroyed and a new instance started.</p>
<p>Another approach you can take is to set the notification activity's
<code>android:taskAffinity</code> to the empty string "" (indicating no affinity)
and setting the
<code>{@link android.R.styleable#AndroidManifestActivity_noHistory
android:noHistory}</code> and
<code>{@link android.R.styleable#AndroidManifestActivity_excludeFromRecents
android:excludeFromRecents}</code> attributes.
This approach is useful if you would like the notification
to take the user to a separate activity describing it, rather than return
to the application's task. By specifying these attributes, the activity will
be finished whether the user leaves it with BACK or HOME and it will not
show up in the recent tasks list; if the <code>noHistory</code> attribute
isn't specified, pressing HOME will result in the activity and its task
remaining in the system, possibly with no way to return to it.</p>
<p>Be sure to read the documentation on the
{@link android.R.styleable#AndroidManifestActivity_launchMode launchMode attribute}
and the {@link android.content.Intent#setFlags Intent flags} for the details
on these options.</p>
<h2 id="Processes">Processes</h2>
<p>In Android, processes are entirely an implementation detail of applications
and not something the user is normally aware of. Their main uses are simply:</p>
<ul>
<li> Improving stability or security by putting untrusted or unstable code
into another process.
<li> Reducing overhead by running the code of multiple .apks in the same
process.
<li> Helping the system manage resources by putting heavy-weight code in
a separate process that can be killed independently of other parts of the
application.
</ul>
<p>As described previously, the
{@link android.R.styleable#AndroidManifestApplication_process process} attribute
is used to control the process that particular application components run in.
Note that this attribute can not be used to violate security of the system: if
two .apks that are not sharing the same user ID try to run in the same process,
this will not be allowed and different distinct processes will be created for
each of them.</p>
<p>See the <a href="{@docRoot}devel/security.html">security</a> document for
more information on these security restrictions.</p>
<h2 id="Threads">Threads</h2>
<p>Every process has one or more threads running in it. In most situations, Android
avoids creating additional threads in a process, keeping an application
single-threaded unless it creates its own threads. An important repercussion
of this is that all calls to {@link android.app.Activity},
{@link android.content.BroadcastReceiver}, and {@link android.app.Service}
instances are made only from the main thread of the process they are running in.</p>
<p>Note that a new thread is <strong>not</strong> created for each
Activity, BroadcastReceiver, Service, or ContentProvider instance:
these application components are instantiated in the desired process (all in the
same process unless otherwise specified), in the main thread of that process.
This means that none of these components (including services) should perform
long or blocking operations (such as networking calls or computation loops)
when called by the system, since this will block
all other components in the process. You can use the standard library
{@link java.lang.Thread} class or Android's {@link android.os.HandlerThread}
convenience class to perform long operations on another thread.</p>
<p>There are a few important exceptions to this threading rule:</p>
<ul>
<li><p>Calls on to an {@link android.os.IBinder} or interface implemented on
an IBinder are dispatched from the thread calling them or a thread pool in the
local process if coming from another process, <em>not</em>
from the main thread of their process. In particular, calls on to the IBinder
of a {@link android.app.Service} will be called this way. (Though
calls to methods on Service itself are done from the main thread.)
This means that <em>implementations of IBinder interfaces must always be
written in a thread-safe way, since they can be called from any number of
arbitrary threads at the same time</em>.</p></li>
<li><p>Calls to the main methods of {@link android.content.ContentProvider}
are dispatched from the calling thread or main thread as with IBinder. The
specific methods are documented in the ContentProvider class.
This means that <em>implementations of these methods must always be
written in a thread-safe way, since they can be called from any number of
arbitrary threads at the same time</em>.</p></li>
<li><p>Calls on {@link android.view.View} and its subclasses are made from the
thread that the view's window is running in. Normally this will be the main
thread of the process, however if you create a thread and show a window from
there then the window's view hierarchy will be called from that thread.</p></li>
</ul>

View File

@@ -0,0 +1,76 @@
page.title=Building Blocks
@jd:body
<h1>Android Building Blocks</h1>
<p>You can think of an Android application as a collection of components, of
various kinds. These components are for the most part quite loosely coupled,
to the degree where you can accurately describe them as a federation of
components rather than a single cohesive application.</p>
<p>Generally, these components all run in the same system process. It's
possible (and quite common) to create multiple threads within that process,
and it's also possible to create completely separate child processes if you
need to. Such cases are pretty uncommon though, because Android tries very
hard to make processes transparent to your code.</p>
<p>These are the most important parts of the Android APIs:</p>
<dl>
<dt><a href="{@docRoot}devel/bblocks-manifest.html">AndroidManifest.xml</a></dt>
<dd>The AndroidManifest.xml file is the control file that tells the system
what to do with all the top-level components (specifically activities,
services, intent receivers, and content providers described below)
you've created. For instance, this is the
"glue" that actually specifies which Intents your Activities receive.</dd>
<dt>{@link android.app.Activity Activities}</dt>
<dd>An Activity is, fundamentally, an object that has a life cycle. An
Activity is a chunk of code that does some work; if necessary, that work
can include displaying a UI to the user. It doesn't have to, though - some
Activities never display UIs. Typically, you'll designate one of your
application's Activities as the entry point to your application. </dd>
<dt>{@link android.view.View Views}</dt>
<dd>A View is an object that knows how to draw itself to the screen.
Android user interfaces are comprised of trees of Views. If you want to
perform some custom graphical technique (as you might if you're writing a
game, or building some unusual new user interface widget) then you'd
create a View.</dd>
<dt>{@link android.content.Intent Intents}</dt>
<dd>An Intent is a simple message object that represents an "intention" to
do something. For example, if your application wants to display a web
page, it expresses its "Intent" to view the URI by creating an Intent
instance and handing it off to the system. The system locates some other
piece of code (in this case, the Browser) that knows how to handle that
Intent, and runs it. Intents can also be used to broadcast interesting
events (such as a notification) system-wide.</dd>
<dt>{@link android.app.Service Services}</dt>
<dd>A Service is a body of code that runs in the background. It can run in
its own process, or in the context of another application's process,
depending on its needs. Other components "bind" to a Service and invoke
methods on it via remote procedure calls. An example of a Service is a
media player; even when the user quits the media-selection UI, she
probably still intends for her music to keep playing. A Service keeps the
music going even when the UI has completed.</dd>
<dt>{@link android.app.NotificationManager Notifications}</dt>
<dd>A Notification is a small icon that appears in the status bar. Users
can interact with this icon to receive information. The most well-known
notifications are SMS messages, call history, and voicemail, but
applications can create their own. Notifications are the
strongly-preferred mechanism for alerting the user of something that needs
their attention.</dd>
<dt>{@link android.content.ContentProvider ContentProviders}</dt>
<dd>A ContentProvider is a data storehouse that provides access to data on
the device; the classic example is the ContentProvider that's used to
access the user's list of contacts. Your application can access data that
other applications have exposed via a ContentProvider, and you can also
define your own ContentProviders to expose data of your own.</dd>
</dl>

View File

@@ -0,0 +1,92 @@
page.title=Getting Started
@jd:body
<h1>Getting Started with Android</h1>
<p>To get started with Android, please read the following sections first:</p>
<dl>
<dt><a href="{@docRoot}intro/installing.html">Installing the SDK and
Plugin</a></dt>
<dd>How to install the Android SDK and Eclipse plugin.</dd>
<dt><a href="{@docRoot}intro/develop-and-debug.html">Developing and Debugging</a></dt>
<dd>An introduction to developing and debugging Android applications in Eclipse,
plus information on using other IDEs.</dd>
<dt><a href="{@docRoot}intro/hello-android.html">Hello Android</a></dt>
<dd>Writing your first Android Application, the ever popular Hello World,
Android style.</dd>
<dt><a href="{@docRoot}intro/anatomy.html">Anatomy of an App</a></dt>
<dd>A guide to the structure and architecture of an Android
Application. This guide will help you understand the pieces that make up
an Android app.</dd>
<dt><a href="{@docRoot}intro/tutorial.html">Notepad Tutorial</a></dt>
<dd>This tutorial document will lead you through
constructing a real Android Application: A notepad which can create, edit
and delete notes, and covers many of the basic concepts with practical
examples.</dd>
<dt><a href="{@docRoot}intro/tools.html">Development Tools</a></dt>
<dd>The
command line tools included with the SDK, what they do, and how to use
them.</dd>
<dt><a href="{@docRoot}intro/appmodel.html">Application Model</a></dt>
<dd>A guide to Applications, Tasks, Processes, and Threads.
These are the elements that define the way your application is run by the
system and presented to the user.</dd>
<dt><a href="{@docRoot}intro/lifecycle.html">Application Life Cycle</a></dt>
<dd>The important life-cycle details for
Applications and the Activities running inside of them.</dd>
</dl>
<h2>Other Introductory Material</h2>
<p>After reading the sections above, the following Getting Started information is also very useful:</p>
<h3>Core Packages</h3>
<p> These are the basic packages that make up the Android SDK for writing
applications. The packages are organized as layers, listed here from
lowest-level to highest.</p>
<dl>
<dt>{@link android.util}</dt>
<dd>contains various low-level utility classes, such
as specialized container classes, XML utilities, etc.</dd>
<dt>{@link android.os}</dt>
<dd> provides basic operating system services, message
passing, and inter-process communication.</dd>
<dt>{@link android.graphics}</dt><dd>is the core rendering package.</dd>
<dt>{@link android.text}, {@link android.text.method}, {@link
android.text.style}, and {@link android.text.util} </dt>
<dd>supply a rich set of
text processing tools, supporting rich text, input methods, etc.</dd>
<dt>{@link android.database}</dt>
<dd>contains low-level APIs for working with
databases.</dd>
<dt>{@link android.content}</dt>
<dd>provides various services for accessing data
on the device: applications installed on the device and their associated
resources, and content providers for persistent dynamic data.</dd>
<dt>{@link android.view}</dt>
<dd>is the core user-interface framework.</dd>
<dt>{@link android.widget}</dt>
<dd>supplies standard user interface elements
(lists, buttons, layout managers, etc) built from the view package.</dd>
<dt>{@link android.app}</dt>
<dd>provides the high-level application model,
implemented using Activities.</dd>
</dl>
<h3>Other Notable Packages</h3>
<p> These packages provide additional domain-specific features of the Android
platform. They are not necessary for basic application development.</p>
<dl>
<dt>{@link android.provider}</dt>
<dd>contains definitions for various standard
content providers included with the platform.</dd>
<dt>{@link android.telephony}</dt>
<dd>provides APIs for interacting with the
device's phone stack.</dd>
<dt>{@link android.webkit}</dt>
<dd>includes various APIs for working with
web-based content.</dd>
</dl>

View File

@@ -0,0 +1,8 @@
<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>

View File

@@ -0,0 +1,141 @@
page.title=What is Android?
@jd:body
<p>Android is a software stack for mobile devices that includes an operating
system, middleware and key applications. The <a
href="http://developer.android.com/sdk/index.html">Android SDK</a>
provides the tools and APIs necessary to begin developing applications on the
Android platform using the Java programming language.</p>
<h2>Features</h2>
<ul>
<li><strong>Application framework</strong> enabling reuse and replacement
of components</li>
<li><strong>Dalvik virtual machine</strong> optimized for mobile
devices</li>
<li><strong>Integrated browser</strong> based on the open source <a
href="http://webkit.org/">WebKit</a> engine </li>
<li><strong>Optimized graphics</strong> powered by a custom 2D graphics library; 3D
graphics based on the OpenGL ES 1.0 specification (hardware acceleration
optional)</li>
<li><strong>SQLite</strong> for structured data storage</li>
<li><strong>Media support</strong> for common audio, video, and still
image formats (MPEG4, H.264, MP3, AAC, AMR, JPG, PNG,
GIF)</li>
<li><strong>GSM Telephony</strong> (hardware dependent)</li>
<li><strong>Bluetooth, EDGE, 3G, and WiFi</strong> (hardware dependent)</li>
<li><strong>Camera, GPS, compass, and accelerometer</strong> (hardware dependent)</li>
<li><strong>Rich development environment</strong> including a device
emulator, tools for debugging, memory and performance profiling, and a plugin for the Eclipse IDE</li>
</ul>
<a name="os_architecture" id="os_architecture"></a>
<h2>Android Architecture</h2>
<p>The following diagram shows the major components of the Android operating
system. Each section is described in more detail below.</p>
<p><img src="{@docRoot}images/system-architecture.jpg" alt="Android System Architecture" width="713" height="512"></p>
<a name="applications" id="applications"></a>
<h2>Applications</h2>
<p>Android will ship with a set of core applications including an email
client, SMS program, calendar, maps, browser, contacts, and
others. All applications are written using the Java programming language.</p>
<a name="application_framework" id="application_framework"></a>
<h2>Application Framework</h2>
<p>By providing an open development platform, Android
offers developers the ability to build extremely rich and innovative
applications. Developers are free to take advantage of the
device hardware, access location information, run background services, set alarms,
add notifications to the status bar, and much, much more. </p>
<p>Developers have full access to the same framework APIs used by the core
applications. The application architecture is designed to simplify the reuse
of components; any application can publish its capabilities and any other
application may then make use of those capabilities (subject to security
constraints enforced by the framework). This same mechanism allows components
to be replaced by the user.</p>
<p>Underlying all applications is a set of services and systems, including:
<ul>
<li>A rich and extensible set of <a
href="{@docRoot}resources/tutorials/views/index.html">Views</a> that can be used to
build an application, including lists, grids, text boxes, buttons, and even
an embeddable web browser</li>
<li><a href="{@docRoot}guide/topics/providers/content-providers.html">Content
Providers</a> that enable applications to access data from other
applications (such as Contacts), or to share their own data</li> <li>A <a
href="{@docRoot}guide/topics/resources/resources-i18n.html">Resource
Manager</a>, providing access to non-code resources such as localized
strings, graphics, and layout files</li>
<li>A {@link android.app.NotificationManager Notification Manager} that enables
all applications to display custom alerts in the status bar</li>
<li>An {@link android.app.Activity Activity Manager} that manages the
lifecycle of applications and provides a common navigation backstack</li>
</ul>
<p>For more details and a walkthrough of an application, see the <a
href="{@docRoot}resources/tutorials/notepad/index.html">Notepad Tutorial</a>.</p>
<a name="libraries" id="libraries"></a>
<h2>Libraries</h2>
<p>Android includes a set of C/C++ libraries used by various components of the
Android system. These capabilities are exposed to developers through the
Android application framework. Some of the core libraries are listed below:</p>
<ul>
<li><strong>System C library</strong> - a BSD-derived implementation of
the standard C system library (libc), tuned for embedded Linux-based
devices</li>
<li><strong>Media Libraries</strong> - based on PacketVideo's OpenCORE;
the libraries support playback and recording of many popular audio and video
formats, as well as static image files, including MPEG4, H.264, MP3, AAC,
AMR, JPG, and PNG</li>
<li><strong>Surface Manager</strong> - manages access to the display
subsystem and seamlessly composites 2D and 3D graphic layers from multiple
applications</li>
<li><strong>LibWebCore</strong> - a modern web browser engine which
powers both the Android browser and an embeddable web view</li>
<li><strong>SGL</strong> - the underlying 2D graphics
engine</li>
<li><strong>3D libraries</strong> - an implementation based on
OpenGL ES 1.0 APIs; the libraries use either hardware 3D acceleration
(where available) or the included, highly optimized 3D software
rasterizer</li>
<li><strong>FreeType</strong> - bitmap and vector font rendering</li>
<li><strong>SQLite</strong> - a powerful and lightweight relational
database engine available to all applications</li>
</ul>
<a name="runtime" id="runtime"></a>
<h2>Android Runtime</h2>
<p>Android includes a set of core libraries that provides most of
the functionality available in the core libraries of the Java programming
language.</p>
<p>Every Android application runs in its own process, with its own instance of
the Dalvik virtual machine. Dalvik has been written so that a device can run
multiple VMs efficiently. The Dalvik VM executes files in the Dalvik
Executable (.dex) format which is optimized for minimal memory
footprint. The VM is register-based, and runs classes
compiled by a Java language compiler that have been transformed into the .dex
format by the included &quot;dx&quot; tool.</p>
<p>The Dalvik VM relies on the Linux kernel for underlying functionality such
as threading and low-level memory management.</p>
<a name="kernel" id="kernel"></a>
<h2>Linux Kernel</h2>
<p>Android relies on Linux version 2.6 for core system services such as
security, memory management, process management, network stack, and driver
model. The kernel also acts as an abstraction layer between the hardware and
the rest of the software stack.</p>

View File

@@ -0,0 +1,232 @@
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() &mdash; get item number " + position);
</pre>
<p>The logcat will then output something like:</p>
<pre class="no-pretty-print">
I/MyActivity( 1557): MyClass.getView() &mdash; 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).&nbsp; 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 &quot;ps&quot; to find the process you
want, and then &quot;kill -3 &quot;. 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 &quot;Dump
radio state&quot;.</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 &quot;Wait for debugger&quot; 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 &quot;Wait for debugger&quot;
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>

View File

@@ -0,0 +1,175 @@
page.title=Developing on a Device
@jd:body
<div id="qv-wrapper">
<div id="qv">
<h2>In this document</h2>
<ol>
<li><a href="#setting-up">Setting up a Device for Development</a>
<ol>
<li><a href="#VendorIds">USB Vendor IDs</a></li>
</ol>
</li>
</ol>
<h2>See also</h2>
<ol>
<li><a href="{@docRoot}sdk/win-usb.html">Google USB Driver</a></li>
<li><a href="{@docRoot}sdk/oem-usb.html">OEM USB Drivers</a></li>
<li><a
href="{@docRoot}guide/developing/eclipse-adt.html">Developing in Eclipse, with ADT</a></li>
<li><a
href="{@docRoot}guide/developing/other-ide.html">Developing in other IDEs</a></li>
</ol>
</div>
</div>
<p>When building a mobile application, it's important that you always test your application on a
real device before releasing it to users. This page describes how to set up your development
environment and Android-powered device for testing and debugging on the device.</p>
<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
you don't yet have a device, check with the service providers in your area to determine which
Android-powered devices are available.</p>
<p>If you want a SIM-unlocked phone, then you might consider either an Android Dev Phone or the
Google Nexus S. These are SIM-unlocked so that you can use them on any GSM network using a SIM
card. The Android Dev Phones also feature an unlocked bootloader so you can install custom system
images (great for developing and installing custom versions of the Android platform). To find a
a place you can purchase the Nexus S, visit <a
href="http://www.google.com/phone/detail/nexus-s">google.com/phone</a>. To purchase an Android
Dev Phone, see the <a href="http://market.android.com/publish">Android Market</a> site
(requires a developer account).</p>
<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
on configurations that are not equivalent to those of your real device. Although the emulator
does not allow you to test every device feature (such as the accelerometer), it does
allow you to verify that your application functions properly on different versions of the Android
platform, in different screen sizes and orientations, and more.</p>
<h2 id="setting-up">Setting up a Device for Development</h2>
<p>With an Android-powered device, you can develop and debug your Android applications just as you
would on the emulator. Before you can start, there are just a few things to do:</p>
<ol>
<li>Declare your application as "debuggable" in your Android Manifest.
<p>In Eclipse, you can do this from the <b>Application</b> tab when viewing the Manifest
(on the right side, set <b>Debuggable</b> to <em>true</em>). Otherwise, in the <code>AndroidManifest.xml</code>
file, add <code>android:debuggable="true"</code> to the <code>&lt;application></code> element.</p>
</li>
<li>Turn on "USB Debugging" on your device.
<p>On the device, go to the home screen, press <b>MENU</b>, select <b>Applications</b> > <b>Development</b>,
then enable <b>USB debugging</b>.</p>
</li>
<li>Setup your system to detect your device.
<ul>
<li>If you're developing on Windows, you need to install a USB driver
for adb. If you're using an Android Developer Phone (ADP), Nexus One, or Nexus S,
see the <a href="{@docRoot}sdk/win-usb.html">Google Windows USB
Driver</a>. Otherwise, you can find a link to the appropriate OEM driver in the
<a href="{@docRoot}sdk/oem-usb.html">OEM USB Drivers</a> document.</li>
<li>If you're developing on Mac OS X, it just works. Skip this step.</li>
<li>If you're developing on Ubuntu Linux, you need to add a rules file
that contains a USB configuration for each type of device you want to use for
development. Each device manufacturer uses a different vendor ID. The
example rules files below show how to add an entry for a single vendor ID
(the HTC vendor ID). In order to support more devices, you will need additional
lines of the same format that provide a different value for the
<code>SYSFS{idVendor}</code> property. For other IDs, see the table of <a
href="#VendorIds">USB Vendor IDs</a>, below.
<ol>
<li>Log in as root and create this file:
<code>/etc/udev/rules.d/51-android.rules</code>.
<p>For Gusty/Hardy, edit the file to read:<br/>
<code>SUBSYSTEM=="usb", SYSFS{idVendor}=="0bb4",
MODE="0666"</code></p>
<p>For Dapper, edit the file to read:<br/>
<code>SUBSYSTEM=="usb_device", SYSFS{idVendor}=="0bb4",
MODE="0666"</code></p>
</li>
<li>Now execute:<br/>
<code>chmod a+r /etc/udev/rules.d/51-android.rules</code>
</li>
</ol>
</li>
</ul>
</li>
</ol>
<p>You can verify that your device is connected by executing <code>adb devices</code> from your
SDK {@code platform-tools/} directory. If connected, you'll see the device name listed as a
"device."</p>
<p>If using Eclipse, run or debug as usual. You will be presented
with a <b>Device Chooser</b> dialog that lists the available emulator(s) and connected device(s).
Select the device upon which you want to install and run the application.</p>
<p>If using the <a href="{@docRoot}guide/developing/tools/adb.html">Android Debug Bridge</a> (adb),
you can issue commands with the <code>-d</code> flag to target your
connected device.</p>
<h3 id="VendorIds">USB Vendor IDs</h3>
<p>This table provides a reference to the vendor IDs needed in order to add
USB device support on Linux. The USB Vendor ID is the value given to the
<code>SYSFS{idVendor}</code> property in the rules file, as described in step 3, above.</p>
<table>
<tr>
<th>Manufacturer</th><th>USB Vendor ID</th></tr>
<tr>
<td>Acer</td>
<td><code>0502</code></td></tr>
<tr>
<td>Dell</td>
<td><code>413c</code></td></tr>
<tr>
<td>Foxconn</td>
<td><code>0489</code></td></tr>
<tr>
<td>Garmin-Asus</td>
<td><code>091E</code></td></tr>
<tr>
<td>HTC</td>
<td><code>0bb4</code></td></tr>
<tr>
<td>Huawei</td>
<td><code>12d1</code></td></tr>
<tr>
<td>Kyocera</td>
<td><code>0482</code></td></tr>
<tr>
<td>LG</td>
<td><code>1004</code></td></tr>
<tr>
<td>Motorola</td>
<td><code>22b8</code></td></tr>
<tr>
<td>Nvidia</td>
<td><code>0955</code></td></tr>
<tr>
<td>Pantech</td>
<td><code>10A9</code></td></tr>
<tr>
<td>Samsung</td>
<td><code>04e8</code></td></tr>
<tr>
<td>Sharp</td>
<td><code>04dd</code></td></tr>
<tr>
<td>Sony Ericsson</td>
<td><code>0fce</code></td></tr>
<tr>
<td>ZTE</td>
<td><code>19D2</code></td></tr>
</table>

View File

@@ -0,0 +1,860 @@
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> &gt; <strong>New</strong> &gt; <strong>Project</strong>.</li>
<li>Select <strong>Android</strong> &gt; <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 &mdash; 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">&lt;uses-sdk&gt;</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>&lt;Android Version&gt;</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 &mdash; 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> &gt; <strong>Run</strong> (or
<strong>Run</strong> &gt; <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> &gt; <strong>Run</strong> (or
<strong>Run</strong> &gt; <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> &gt;
<strong>Open Run Dialog</strong> (or <strong>Open Debug Dialog</strong>)
</li>
<li>In Eclipse 3.4 (Ganymede), select <strong>Run </strong>&gt;
<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>&lt;manifest&gt;
...
&lt;application&gt;
...
&lt;activity android:name="GameActivity" /&gt;
...
&lt;/application&gt;
&lt;/manifest&gt;</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>&lt;activity&gt;</code>,
<code>&lt;service&gt;</code>, <code>&lt;receiver&gt;</code>,
<code>&lt;provider&gt;</code>, and so on, as well as
<code>&lt;permission&gt;</code>, <code>&lt;uses-library&gt;</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>&lt;manifest&gt;
...
&lt;application&gt;
...
&lt;activity android:name="com.example.android.tictactoe.library.GameActivity" /&gt;
...
&lt;/application&gt;
&lt;/manifest&gt;</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>&lt;uses-library&gt;</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 &mdash; or lower than &mdash; 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
projects 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 &lt;<em>library-name</em>&gt;_&lt;<em>folder-name</em>&gt; 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> &mdash; 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> &gt;
<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 &quot;zip&quot;, 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> &gt; <strong>Show
View</strong> &gt; <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(&quot;.zip&quot;)</code></td>
<td><code>(boolean) true</code></td>
</tr>
<tr>
<td><code>zip.endsWith(&quot;.jar&quot;)</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 &quot;scrapbook&quot;.</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>
-->

View File

@@ -0,0 +1,8 @@
<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>

View File

@@ -0,0 +1,937 @@
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>&lt;target_ID&gt;</em> \
--name <em>&lt;your_project_name&gt;</em> \
--path <em>path/to/your/project</em> \
--activity <em>&lt;your_activity_name&gt;</em> \
--package <em>&lt;your_package_namespace&gt;</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>&lt;path_to_your_project&gt;</em>/src/<em>&lt;your_package_namespace_path&gt;</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) &mdash; located in the SDK <code>platform-tools/</code> directory &mdash; 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>&lt;project_name&gt;</em> --target <em>&lt;target_ID&gt;</em>
--path <em>&lt;path_to_your_project&gt;</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&mdash;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
&mdash; <em>debug mode</em> &mdash; and one for building your final package for release &mdash;
<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\&lt;jdkdir&gt;</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>&lt;your_project_name&gt;</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>&lt;your_project_name&gt;</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>&lt;your_project_name&gt;</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>&lt;path_to_your_bin&gt;</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>&lt;sdk&gt;/tools/</code> directory
and use this command:</p>
<pre class="no-pretty-print" style="color:black">
android create lib-project --name <em>&lt;your_project_name&gt;</em> \
--target <em>&lt;target_ID&gt;</em> \
--path <em>path/to/your/project</em> \
--package <em>&lt;your_library_package_namespace&gt;</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>&lt;manifest&gt;
...
&lt;application&gt;
...
&lt;activity android:name="GameActivity" /&gt;
...
&lt;/application&gt;
&lt;/manifest&gt;</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>&lt;target_ID&gt;</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>&lt;sdk&gt;/tools/</code> directory
and use this command:</p>
<pre>
android update lib-project \
--target <em>&lt;target_ID&gt;</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>&lt;activity&gt;</code>,
<code>&lt;service&gt;</code>, <code>&lt;receiver&gt;</code>,
<code>&lt;provider&gt;</code>, and so on, as well as
<code>&lt;permission&gt;</code>, <code>&lt;uses-library&gt;</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>&lt;manifest&gt;
...
&lt;application&gt;
...
&lt;activity android:name="com.example.android.tictactoe.library.GameActivity" /&gt;
...
&lt;/application&gt;
&lt;/manifest&gt;</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>&lt;uses-library&gt;</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 &mdash; or lower than &mdash; 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
projects 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>

View File

@@ -0,0 +1,36 @@
page.title=Testing Overview
@jd:body
<p>
Android includes powerful tools for setting up and running test applications.
Whether you are working in Eclipse with ADT or working from the command line, these tools
help you set up and run your tests within an emulator or the device you are targeting.
The documents listed below explain how to work with the tools in your development environment.
</p>
<p>
If you aren't yet familiar with the Android testing framework, please read the topic
<a href="{@docRoot}guide/topics/testing/testing_android.html">Testing Fundamentals</a>
before you get started.
For a step-by-step introduction to Android testing, try the <a
href="{@docRoot}resources/tutorials/testing/helloandroid_test.html">Hello, Testing</a>
tutorial, which introduces basic testing concepts and procedures.
For a more advanced tutorial, try <a
href="{@docRoot}resources/tutorials/testing/activity_test.html">Activity Testing</a>,
which guides you through a more complex testing scenario.
</p>
<dl>
<dt><a href="testing_eclipse.html">Testing in Eclipse, with ADT</a></dt>
<dd>
The ADT plugin lets you quickly set up and manage test projects directly in
the Eclipse UI. Once you have written your tests, you can build and run them and
then see the results in the Eclipse JUnit view. You can also use the SDK command-line
tools to execute your tests if needed.
</dd>
<dt><a href="testing_otheride.html">Testing in Other IDEs</a></dt>
<dd>
The SDK command-line tools provide the same capabilities as the ADT plugin. You can
use them to set up and manage test projects, build your test application,
run your tests, and see the results. You use
the <code>android</code> tool to create and manage test projects, the Ant build system
to compile them, and the <code>adb</code> tool to install and run them.
</dd>
</dl>

View File

@@ -0,0 +1,530 @@
page.title=Testing In Eclipse, with ADT
@jd:body
<div id="qv-wrapper">
<div id="qv">
<h2>In this document</h2>
<ol>
<li><a href="#CreateTestProjectEclipse">Creating a Test Project</a></li>
<li><a href="#CreateTestAppEclipse">Creating a Test Package</a></li>
<li><a href="#RunTestEclipse">Running Tests</a></li>
</ol>
</div>
</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
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>.
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.
</p>
<p>
ADT provides several features that help you set up and manage your testing environment
effectively:
</p>
<ul>
<li>
It lets you quickly create a test project and link it to the application under test.
When it creates the test project, it automatically inserts the necessary
<code>&lt;instrumentation&gt;</code> element in the test package's manifest file.
</li>
<li>
It lets you quickly import the classes of the application under test, so that your
tests can inspect them.
</li>
<li>
It lets you create run configurations for your test package and include in
them flags that are passed to the Android testing framework.
</li>
<li>
It lets you run your test package without leaving Eclipse. ADT builds both the
application under test and the test package automatically, installs them if
necessary to your device or emulator, runs the test package, and displays the
results in a separate window in Eclipse.
</li>
</ul>
<p>
If you are not developing in Eclipse or you want to learn how to create and run tests from the
command line, see
<a href="{@docRoot}guide/developing/testing/testing_otheride.html">Testing in Other IDEs</a>.
</p>
<h2 id="CreateTestProjectEclipse">Creating a Test Project</h2>
<p>
To set up a test environment for your Android application, you must first create a separate
project that holds the test code. The new project follows the directory structure
used for any Android application. It includes the same types of content and files, such as
source code, resources, a manifest file, and so forth. The test package you
create is connected to the application under test by an
<a href="{@docRoot}guide/topics/manifest/instrumentation-element.html">
<code>&lt;instrumentation&gt;</code></a> element in its manifest file.
</p>
<p>
The <em>New Android Test Project</em> dialog makes it easy for you to generate a
new test project that has the proper structure, including the
<code>&lt;instrumentation&gt;</code> element in the manifest file. You can use the New
Android Test Project dialog to generate the test project at any time. The dialog appears
just after you create a new Android main application project, but you can also run it to
create a test project for a project that you created previously.
</p>
<p>
To create a test project in Eclipse with ADT:
</p>
<ol>
<li>
In Eclipse, select <strong>File &gt; New &gt; Other</strong>. This opens the <em>Select a
Wizard</em> dialog.
</li>
<li>
In the dialog, in the <em>Wizards</em> drop-down list, find the entry for Android, then
click the toggle to the left. Select <strong>Android Test Project</strong>, then at the
bottom of the dialog click <strong>Next</strong>. The <em>New Android Test Project</em>
wizard appears.
</li>
<li>
Next to <em>Test Project Name</em>, enter a name for the project. You may use any name,
but you may want to associate the name with the project name for the application under test.
One way to do this is to take the application's project name, append the string "Test" to
it, and then use this as the test package project name.
<p>
The name becomes part of the suggested project path, but you can change this in the
next step.
</p>
</li>
<li>
In the <em>Content</em> panel, examine the suggested path to the project.
If <em>Use default location</em> is set, then the wizard will suggest a path that is
a concatenation of the workspace path and the project name you entered. For example,
if your workspace path is <code>/usr/local/workspace</code> and your project name is
<code>MyTestApp</code>, then the wizard will suggest
<code>/usr/local/workspace/MyTestApp</code>. To enter your own
choice for a path, unselect <em>Use default location</em>, then enter or browse to the
path where you want your project.
<p>
To learn more about choosing the location of test projects, please read
<a href="{@docRoot}guide/topics/testing/testing_android.html#TestProjectPaths">
Testing Fundamentals</a>.
</p>
</li>
<li>
In the Test Target panel, set An Existing Android Project, click Browse, then select your
Android application from the list. You now see that the wizard has completed the Test
Target Package, Application Name, and Package Name fields for you (the latter two are in
the Properties panel).
</li>
<li>
In the Build Target panel, select the Android SDK platform that the application under test
uses.
</li>
<li>
Click Finish to complete the wizard. If Finish is disabled, look for error messages at the
top of the wizard dialog, and then fix any problems.
</li>
</ol>
<h2 id="CreateTestAppEclipse">Creating a Test Package</h2>
<p>
Once you have created a test project, you populate it with a test package. This package does not
require an Activity, although you can define one if you wish. Although your test package can
combine Activity classes, test case classes, or ordinary classes, your main test case
should extend one of the Android test case classes or JUnit classes, because these provide the
best testing features.
</p>
<p>
Test packages do not need to have an Android GUI. When you run the package in
Eclipse with ADT, its results appear in the JUnit view. Running tests and seeing the results is
described in more detail in the section <a href="#RunTestEclipse">Running Tests</a>.
</p>
<p>
To create a test package, start with one of Android's test case classes defined in
{@link android.test android.test}. These extend the JUnit
{@link junit.framework.TestCase TestCase} class. The Android test classes for Activity objects
also provide instrumentation for testing an Activity. To learn more about test case
classes, please read the topic <a href="{@docRoot}guide/topics/testing/testing_android.html">
Testing Fundamentals</a>.
</p>
<p>
Before you create your test package, you choose the Java package identifier you want to use
for your test case classes and the Android package name you want to use. To learn more
about this, please read
<a href="{@docRoot}guide/topics/testing/testing_android.html#PackageNames">
Testing Fundamentals</a>.
</p>
<p>
To add a test case class to your project:
</p>
<ol>
<li>
In the <em>Project Explorer</em> tab, open your test project, then open the <em>src</em>
folder.
</li>
<li>
Find the Java package identifier set by the projection creation wizard. If you haven't
added classes yet, this node won't have any children, and its icon will not be filled in.
If you want to change the identifier value, right-click the identifier and select
<strong>Refactor</strong> &gt; <strong>Rename</strong>, then enter the new name.
</li>
<li>
When you are ready, right-click the Java package identifier again and select
<strong>New</strong> &gt; <strong>Class</strong>. This displays the <em>New Java Class</em>
dialog, with the <em>Source folder</em> and <em>Package</em> values already set.
</li>
<li>
In the <em>Name</em> field, enter a name for the test case class. One way to choose a
class name is to append the string "Test" to the class of the component you are testing.
For example, if you are testing the class MyAppActivity, your test case class
name would be MyAppActivityTest. Leave the modifiers set to <em>public</em>.
</li>
<li>
In the <em>Superclass</em> field, enter the name of the Android test case class you
are extending. You can also browse the available classes.
</li>
<li>
In <em>Which method stubs would you like to create?</em>, unset all the options, then
click <strong>Finish</strong>. You will set up the constructor manually.
</li>
<li>
Your new class appears in a new Java editor pane.
</li>
</ol>
<p>
You now have to ensure that the constructor is set up correctly. Create a constructor for your
class that has no arguments; this is required by JUnit. As the first statement in this
constructor, add a call to the base class' constructor. Each base test case class has its
own constructor signature. Refer to the class documentation in the documentation for
{@link android.test} for more information.
</p>
<p>
To control your test environment, you will want to override the <code>setUp()</code> and
<code>tearDown()</code> methods:
</p>
<ul>
<li>
<code>setUp()</code>: This method is invoked before any of the test methods in the class.
Use it to set up the environment for the test (the test fixture. You can use
<code>setUp()</code> to instantiate a new Intent with the action <code>ACTION_MAIN</code>.
You can then use this intent to start the Activity under test.
</li>
<li>
<code>tearDown()</code>: This method is invoked after all the test methods in the class. Use
it to do garbage collection and to reset the test fixture.
</li>
</ul>
<p>
Another useful convention is to add the method <code>testPreconditions()</code> to your test
class. Use this method to test that the application under test is initialized correctly. If this
test fails, you know that that the initial conditions were in error. When this happens, further
test results are suspect, regardless of whether or not the tests succeeded.
</p>
<p>
The Resources tab contains an
<a href="{@docRoot}resources/tutorials/testing/activity_test.html">Activity Testing</a>
tutorial with more information about creating test classes and methods.
</p>
<h2 id="RunTestEclipse">Running Tests</h2>
<div class="sidebox-wrapper">
<div class="sidebox">
<h2>Running tests from the command line</h2>
<p>
If you've created your tests in Eclipse, you can still run your tests and test
suites by using command-line tools included with the Android SDK. You may want
to do this, for example, if you have a large number of tests to run, if you
have a large test case, or if you want a fine level of control over which
tests are run at a particular time.
</p>
<p>
To run tests created in Eclipse with ADT with command-line tools, you must first
install additional files into the test project using the <code>android</code>
tool's "create test-project" option. To see how to do this, read
<a href="{@docRoot}guide/developing/testing/testing_otheride.html#CreateProject">
Testing in Other IDEs</a>.
</p>
</div>
</div>
<p>
When you run a test package in Eclipse with ADT, the output appears in the Eclipse JUnit view.
You can run the entire test package or one test case class. To do run tests, Eclipse runs the
<code>adb</code> command for running a test package, and displays the output, so there is no
difference between running tests inside Eclipse and running them from the command line.
</p>
<p>
As with any other package, to run a test package in Eclipse with ADT you must either attach a
device to your computer or use the Android emulator. If you use the emulator, you must have an
Android Virtual Device (AVD) that uses the same target as the test package.
</p>
<p>
To run a test in Eclipse, you have two choices:</p>
<ul>
<li>
Run a test just as you run an application, by selecting
<strong>Run As... &gt; Android JUnit Test</strong> from the project's context menu or
from the main menu's <strong>Run</strong> item.
</li>
<li>
Create an Eclipse run configuration for your test project. This is useful if you want
multiple test suites, each consisting of selected tests from the project. To run
a test suite, you run the test configuration.
<p>
Creating and running test configurations is described in the next section.
</p>
</li>
</ul>
<p>
To create and run a test suite using a run configuration:
</p>
<ol>
<li>
In the Package Explorer, select the test project, then from the main menu, select
<strong>Run &gt; Run Configurations...</strong>. The Run Configurations dialog appears.
</li>
<li>
In the left-hand pane, find the Android JUnit Test entry. In the right-hand pane, click the
Test tab. The Name: text box shows the name of your project. The Test class: dropdown box
shows one of the test classes in your project.
</li>
<li>
To run one test class, click Run a single test, then enter your project name in the
Project: text box and the class name in the Test class: text box.
<p>
To run all the test classes, click Run all tests in the selected project or package,
then enter the project or package name in the text box.
</p>
</li>
<li>
Now click the Target tab.
<ul>
<li>
Optional: If you are using the emulator, click Automatic, then in the Android
Virtual Device (AVD) selection table, select an existing AVD.
</li>
<li>
In the Emulator Launch Parameters pane, set the Android emulator flags you want to
use. These are documented in the topic
<a href="{@docRoot}guide/developing/tools/emulator.html#startup-options">
Android Emulator</a>.
</li>
</ul>
</li>
<li>
Click the Common tab. In the Save As pane, click Local to save this run configuration
locally, or click Shared to save it to another project.
</li>
<li>
Optional: Add the configuration to the Run toolbar and the <strong>Favorites</strong>
menu: in the Display in Favorites pane click the checkbox next to Run.
</li>
<li>
Optional: To add this configuration to the <strong>Debug</strong> menu and toolbar, click
the checkbox next to Debug.
</li>
<li>
To save your settings, click Close.<br/>
<p class="note"><strong>Note:</strong>
Although you can run the test immediately by clicking Run, you should save the test
first and then run it by selecting it from the Eclipse standard toolbar.
</p>
</li>
<li>
On the Eclipse standard toolbar, click the down arrow next to the green Run arrow. This
displays a menu of saved Run and Debug configurations.
</li>
<li>
Select the test run configuration you just created. The test starts.
</li>
</ol>
<p>
The progress of your test appears in the Console view as a series of messages. Each message is
preceded by a timestamp and the <code>.apk</code> filename to which it applies. For example,
this message appears when you run a test to the emulator, and the emulator is not yet started:
</p>
<div class="sidebox-wrapper">
<div class="sidebox">
<h2>Message Examples</h2>
<p>
The examples shown in this section come from the
<a href="{@docRoot}resources/samples/SpinnerTest/index.html">SpinnerTest</a>
sample test package, which tests the
<a href="{@docRoot}resources/samples/Spinner/index.html">Spinner</a>
sample application. This test package is also featured in the
<a href="{@docRoot}resources/tutorials/testing/activity_test.html">Activity Testing</a>
tutorial.
</p>
</div>
</div>
<pre>
[<em>yyyy-mm-dd hh:mm:ss</em> - <em>testfile</em>] Waiting for HOME ('android.process.acore') to be launched...
</pre>
<p>
In the following description of these messages, <code><em>devicename</em></code> is the name of
the device or emulator you are using to run the test, and <code><em>port</em></code> is the
port number for the device. The name and port number are in the format used by the
<code><a href="{@docRoot}guide/developing/tools/adb.html#devicestatus">adb devices</a></code>
command. Also, <code><em>testfile</em></code> is the <code>.apk</code> filename of the test
package you are running, and <em>appfile</em> is the filename of the application under test.
</p>
<ul>
<li>
If you are using an emulator and you have not yet started it, then Eclipse
first starts the emulator. When this is complete, you see
the message:
<p>
<code>HOME is up on device '<em>devicename</em>-<em>port</em>'</code>
</p>
</li>
<li>
If you have not already installed your test package, then you see
the message:
<p>
<code>Uploading <em>testfile</em> onto device '<em>devicename</em>-<em>port</em>'
</code>
</p>
<p>
then the message <code>Installing <em>testfile</em></code>.
</p>
<p>
and finally the message <code>Success!</code>
</p>
</li>
</ul>
<p>
The following lines are an example of this message sequence:
</p>
<code>
[2010-07-01 12:44:40 - MyTest] HOME is up on device 'emulator-5554'<br>
[2010-07-01 12:44:40 - MyTest] Uploading MyTest.apk onto device 'emulator-5554'<br>
[2010-07-01 12:44:40 - MyTest] Installing MyTest.apk...<br>
[2010-07-01 12:44:49 - MyTest] Success!<br>
</code>
<br>
<ul>
<li>
Next, if you have not yet installed the application under test to the device or
emulator, you see the message
<p>
<code>Project dependency found, installing: <em>appfile</em></code>
</p>
<p>
then the message <code>Uploading <em>appfile</em></code> onto device
'<em>devicename</em>-<em>port</em>'
</p>
<p>
then the message <code>Installing <em>appfile</em></code>
</p>
<p>
and finally the message <code>Success!</code>
</p>
</li>
</ul>
<p>
The following lines are an example of this message sequence:
</p>
<code>
[2010-07-01 12:44:49 - MyTest] Project dependency found, installing: MyApp<br>
[2010-07-01 12:44:49 - MyApp] Uploading MyApp.apk onto device 'emulator-5554'<br>
[2010-07-01 12:44:49 - MyApp] Installing MyApp.apk...<br>
[2010-07-01 12:44:54 - MyApp] Success!<br>
</code>
<br>
<ul>
<li>
Next, you see the message
<code>Launching instrumentation <em>instrumentation_class</em> on device
<em>devicename</em>-<em>port</em></code>
<p>
<code>instrumentation_class</code> is the fully-qualified class name of the
instrumentation test runner you have specified (usually
{@link android.test.InstrumentationTestRunner}.
</p>
</li>
<li>
Next, as {@link android.test.InstrumentationTestRunner} builds a list of tests to run,
you see the message
<p>
<code>Collecting test information</code>
</p>
<p>
followed by
</p>
<p>
<code>Sending test information to Eclipse</code>
</p>
</li>
<li>
Finally, you see the message <code>Running tests</code>, which indicates that your tests
are running. At this point, you should start seeing the test results in the JUnit view.
When the tests are finished, you see the console message <code>Test run complete</code>.
This indicates that your tests are finished.
</li>
</ul>
<p>
The following lines are an example of this message sequence:
</p>
<code>
[2010-01-01 12:45:02 - MyTest] Launching instrumentation android.test.InstrumentationTestRunner on device emulator-5554<br>
[2010-01-01 12:45:02 - MyTest] Collecting test information<br>
[2010-01-01 12:45:02 - MyTest] Sending test information to Eclipse<br>
[2010-01-01 12:45:02 - MyTest] Running tests...<br>
[2010-01-01 12:45:22 - MyTest] Test run complete<br>
</code>
<br>
<p>
The test results appear in the JUnit view. This is divided into an upper summary pane,
and a lower stack trace pane.
</p>
<p>
The upper pane contains test information. In the pane's header, you see the following
information:
</p>
<ul>
<li>
Total time elapsed for the test package (labeled Finished after <em>x</em> seconds).
</li>
<li>
Number of runs (Runs:) - the number of tests in the entire test class.
</li>
<li>
Number of errors (Errors:) - the number of program errors and exceptions encountered
during the test run.
</li>
<li>
Number of failures (Failures:) - the number of test failures encountered during the test
run. This is the number of assertion failures. A test can fail even if the program does
not encounter an error.
</li>
<li>
A progress bar. The progress bar extends from left to right as the tests run. If all the
tests succeed, the bar remains green. If a test fails, the bar turns from green to red.
</li>
</ul>
<p>
The body of the upper pane contains the details of the test run. For each test case class
that was run, you see a line with the class name. To look at the results for the individual
test methods in that class, you click the left arrow to expand the line. You now see a
line for each test method in the class, and to its right the time it took to run.
If you double-click the method name, Eclipse opens the test class source in an editor view
pane and moves the focus to the first line of the test method.
</p>
<p>
The results of a successful test are shown in figure 1.
</p>
<a href="{@docRoot}images/testing/eclipse_test_results.png">
<img src="{@docRoot}images/testing/eclipse_test_results.png"
alt="Messages for a successful test" height="327px" id="TestResults"/>
</a>
<p class="img-caption">
<strong>Figure 1.</strong> Messages for a successful test.
</p>
<p>
The lower pane is for stack traces. If you highlight a failed test in the upper pane, the
lower pane contains a stack trace for the test. If a line corresponds to a point in your
test code, you can double-click it to display the code in an editor view pane, with the
line highlighted. For a successful test, the lower pane is empty.
</p>
<p>The results of a failed test are shown in figure 2.</p>
<a href="{@docRoot}images/testing/eclipse_test_run_failure.png">
<img src="{@docRoot}images/testing/eclipse_test_run_failure.png"
alt="" height="372px" id="TestRun"/>
</a>
<p class="img-caption">
<strong>Figure 2.</strong> Messages for a test failure.
</p>

View File

@@ -0,0 +1,692 @@
page.title=Testing In Other IDEs
@jd:body
<div id="qv-wrapper">
<div id="qv">
<h2>In this document</h2>
<ol>
<li>
<a href="#CreateTestProjectCommand">Working with Test Projects</a>
<ol>
<li>
<a href="#CreateTestProject">Creating a test project</a>
</li>
<li>
<a href="#UpdateTestProject">Updating a test project</a>
</li>
</ol>
</li>
<li>
<a href="#CreateTestApp">Creating a Test Package</a>
</li>
<li>
<a href="#RunTestsCommand">Running Tests</a>
<ol>
<li>
<a href="#RunTestsAnt">Quick build and run with Ant</a>
</li>
<li>
<a href="#RunTestsDevice">Running tests on a device or emulator</a>
</li>
</ol>
</li>
<li>
<a href="#AMSyntax">Using the Instrument Command</a>
<ol>
<li>
<a href="#AMOptionsSyntax">Instrument options</a>
</li>
<li>
<a href="#RunTestExamples">Instrument examples</a>
</li>
</ol>
</li>
</ol>
<h2>See Also</h2>
<ol>
<li>
<a href="{@docRoot}guide/topics/testing/testing_android.html">
Testing Fundamentals</a>
</li>
<li>
<a href="{@docRoot}guide/developing/tools/adb.html">Android Debug Bridge</a>
</li>
</ol>
</div>
</div>
<p>
This document describes how to create and run tests directly from the command line.
You can use the techniques described here if you are developing in an IDE other than Eclipse
or if you prefer to work from the command line. This document assumes that you already know how
to create a Android application in your programming environment. Before you start this
document, you should read the topic
<a href="{@docRoot}guide/topics/testing/testing_android.html">Testing Fundamentals</a>,
which provides an overview of Android testing.
</p>
<p>
If you are developing in Eclipse with ADT, you can set up and run your tests
directly in Eclipse. For more information, please read
<a href="{@docRoot}guide/developing/testing/testing_eclipse.html">
Testing in Eclipse, with ADT</a>.
</p>
<h2 id="CreateTestProjectCommand">Working with Test Projects</h2>
<p>
You use the <code>android</code> tool to create test projects.
You also use <code>android</code> to convert existing test code into an Android test project,
or to add the <code>run-tests</code> Ant target to an existing Android test project.
These operations are described in more detail in the section <a href="#UpdateTestProject">
Updating a test project</a>. The <code>run-tests</code> target is described in
<a href="#RunTestsAnt">Quick build and run with Ant</a>.
</p>
<h3 id="CreateTestProject">Creating a test project</h3>
<p>
To create a test project with the <code>android</code> tool, enter:
</p>
<pre>
android create test-project -m &lt;main_path&gt; -n &lt;project_name&gt; -p &lt;test_path&gt;
</pre>
<p>
You must supply all the flags. The following table explains them in detail:
</p>
<table>
<tr>
<th>Flag</th>
<th>Value</th>
<th>Description</th>
</tr>
<tr>
<td><code>-m, --main</code></td>
<td>
Path to the project of the application under test, relative to the test package
directory.
</td>
<td>
For example, if the application under test is in <code>source/HelloAndroid</code>, and
you want to create the test project in <code>source/HelloAndroidTest</code>, then the
value of <code>--main</code> should be <code>../HelloAndroid</code>.
<p>
To learn more about choosing the location of test projects, please read
<a href="{@docRoot}guide/topics/testing/testing_android.html#TestProjects">
Testing Fundamentals</a>.
</p>
</td>
</tr>
<tr>
<td><code>-n, --name</code></td>
<td>Name that you want to give the test project.</td>
<td>&nbsp;</td>
</tr>
<tr>
<td><code>-p, --path</code></td>
<td>Directory in which you want to create the new test project.</td>
<td>
The <code>android</code> tool creates the test project files and directory structure
in this directory. If the directory does not exist, <code>android</code> creates it.
</td>
</tr>
</table>
<p>
If the operation is successful, <code>android</code> lists to STDOUT the names of the files
and directories it has created.
</p>
<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>.
</p>
<p>
The operation also creates an <code>AndroidManifest.xml</code> file with instrumentation
information. When you run the test, Android uses this information to load the application you
are testing and control it with instrumentation.
</p>
<p>
For example, suppose you create the <a href="{@docRoot}resources/tutorials/hello-world.html">
Hello, World</a> tutorial application in the directory <code>~/source/HelloAndroid</code>.
In the tutorial, this application uses the package name <code>com.example.helloandroid</code>
and the activity name <code>HelloAndroid</code>. You can to create the test for this in
<code>~/source/HelloAndroidTest</code>. To do so, you enter:
</p>
<pre>
$ cd ~/source
$ android create test-project -m ../HelloAndroid -n HelloAndroidTest -p HelloAndroidTest
</pre>
<p>
This creates a directory called <code>~/src/HelloAndroidTest</code>. In the new directory you
see the file <code>AndroidManifest.xml</code>. This file contains the following
instrumentation-related elements and attributes:
</p>
<ul>
<li>
<code>&lt;application&gt;</code>: to contain the
<code>&lt;uses-library&gt;</code> element.
</li>
<li>
<code>&lt;uses-library android:name=&quot;android.test.runner&quot;</code>:
specifies this testing application uses the <code>android.test.runner</code> library.
</li>
<li>
<code>&lt;instrumentation&gt;</code>: contains attributes that control Android
instrumentation. The attributes are:
<ul>
<li>
<code>android:name=&quot;android.test.InstrumentationTestRunner&quot;</code>:
{@link android.test.InstrumentationTestRunner} runs test cases. It extends both
JUnit test case runner classes and Android instrumentation classes.
</li>
<li>
<code>android:targetPackage=&quot;com.example.helloandroid&quot;</code>: specifies
that the tests in HelloAndroidTest should be run against the application with the
<em>Android</em> package name <code>com.example.helloandroid</code>. This is the
package name of the <a
href="{@docRoot}resources/tutorials/hello-world.html">Hello, World</a>
tutorial application.
</li>
<li>
<code>android:label=&quot;Tests for .HelloAndroid&quot;</code>: specifies a
user-readable label for the instrumentation class. By default,
the <code>android</code> tool gives it the value &quot;Tests for &quot; plus
the name of the main Activity of the application under test.
</li>
</ul>
</li>
</ul>
<h3 id="UpdateTestProject">Updating a test project</h3>
<p>
You use the <code>android</code> tool when you need to change the path to the
project of the application under test. If you are changing an existing test project created in
Eclipse with ADT so that you can also build and run it from the command line, you must use the
"create" operation. See the section <a href="#CreateTestProject">Creating a test project</a>.
</p>
<p class="note">
<strong>Note:</strong> If you change the Android package name of the application under test,
you must <em>manually</em> change the value of the <code>&lt;android:targetPackage&gt;</code>
attribute within the <code>AndroidManifest.xml</code> file of the test package.
Running <code>android update test-project</code> does not do this.
</p>
<p>
To update a test project with the <code>android</code> tool, enter:
</p>
<pre>android update-test-project -m &lt;main_path&gt; -p &lt;test_path&gt;</pre>
<table>
<tr>
<th>Flag</th>
<th>Value</th>
<th>Description</th>
</tr>
<tr>
<td><code>-m, --main</code></td>
<td>The path to the project of the application under test, relative to the test project</td>
<td>
For example, if the application under test is in <code>source/HelloAndroid</code>, and
the test project is in <code>source/HelloAndroidTest</code>, then the value for
<code>--main</code> is <code>../HelloAndroid</code>.
</td>
</tr>
<tr>
<td><code>-p, --path</code></td>
<td>The of the test project.</td>
<td>
For example, if the test project is in <code>source/HelloAndroidTest</code>, then the
value for <code>--path</code> is <code>HelloAndroidTest</code>.
</td>
</tr>
</table>
<p>
If the operation is successful, <code>android</code> lists to STDOUT the names of the files
and directories it has created.
</p>
<h2 id="CreateTestApp">Creating a Test Package</h2>
<p>
Once you have created a test project, you populate it with a test package.
The application does not require an {@link android.app.Activity Activity},
although you can define one if you wish. Although your test package can
combine Activities, Android test class extensions, JUnit extensions, or
ordinary classes, you should extend one of the Android test classes or JUnit classes,
because these provide the best testing features.
</p>
<p>
If you run your tests with {@link android.test.InstrumentationTestRunner}
(or a related test runner), then it will run all the methods in each class. You can modify
this behavior by using the {@link junit.framework.TestSuite TestSuite} class.
</p>
<p>
To create a test package, start with one of Android's test classes in the Java package
{@link android.test android.test}. These extend the JUnit
{@link junit.framework.TestCase TestCase} class. With a few exceptions, the Android test
classes also provide instrumentation for testing.
</p>
<p>
For test classes that extend {@link junit.framework.TestCase TestCase}, you probably want to
override the <code>setUp()</code> and <code>tearDown()</code> methods:
</p>
<ul>
<li>
<code>setUp()</code>: This method is invoked before any of the test methods in the class.
Use it to set up the environment for the test. You can use <code>setUp()</code>
to instantiate a new <code>Intent</code> object with the action <code>ACTION_MAIN</code>.
You can then use this intent to start the Activity under test.
<p class="note">
<strong>Note:</strong> If you override this method, call
<code>super.setUp()</code> as the first statement in your code.
</p>
</li>
<li>
<code>tearDown()</code>: This method is invoked after all the test methods in the class. Use
it to do garbage collection and re-setting before moving on to the next set of tests.
<p class="note"><strong>Note:</strong> If you override this method, you must call
<code>super.tearDown()</code> as the <em>last</em> statement in your code.</p>
</li>
</ul>
<p>
Another useful convention is to add the method <code>testPreConditions()</code> to your test
class. Use this method to test that the application under test is initialized correctly. If this
test fails, you know that that the initial conditions were in error. When this happens, further
test results are suspect, regardless of whether or not the tests succeeded.
</p>
<p>
To learn more about creating test packages, see the topic <a
href="{@docRoot}guide/topics/testing/testing_android.html">Testing Fundamentals</a>,
which provides an overview of Android testing. If you prefer to follow a tutorial,
try the <a href="{@docRoot}resources/tutorials/testing/activity_test.html">Activity Testing</a>
tutorial, which leads you through the creation of tests for an actual Android application.
</p>
<h2 id="RunTestsCommand">Running Tests</h2>
<p>
You run tests from the command line, either with Ant or with an
<a href="{@docRoot}guide/developing/tools/adb.html">
Android Debug Bridge (adb)</a> shell.
</p>
<h3 id="RunTestsAnt">Quick build and run with Ant</h3>
<p>
You can use Ant to run all the tests in your test project, using the target
<code>run-tests</code>, which is created automatically when you create a test project with
the <code>android</code> tool.
</p>
<p>
This target re-builds your main project and test project if necessary, installs the test
application to the current AVD or device, and then runs all the test classes in the test
application. The results are directed to <code>STDOUT</code>.
</p>
<p>
You can update an existing test project to use this feature. To do this, use the
<code>android</code> tool with the <code>update test-project</code> option. This is described
in the section <a href="#UpdateTestProject">Updating a test project</a>.
</p>
<h3 id="RunTestsDevice">Running tests on a device or emulator</h3>
<p>
When you run tests from the command line with
<a href="{@docRoot}guide/developing/tools/adb.html">
Android Debug Bridge (adb)</a>, you get more options for choosing the tests
to run than with any other method. You can select individual test methods, filter tests
according to their annotation, or specify testing options. Since the test run is controlled
entirely from a command line, you can customize your testing with shell scripts in various ways.
</p>
<p>
To run a test from the command line, you run <code>adb shell</code> to start a command-line
shell on your device or emulator, and then in the shell run the <code>am instrument</code>
command. You control <code>am</code> and your tests with command-line flags.
</p>
<p>
As a shortcut, you can start an <code>adb</code> shell, call <code>am instrument</code>, and
specify command-line flags all on one input line. The shell opens on the device or emulator,
runs your tests, produces output, and then returns to the command line on your computer.
</p>
<p>
To run a test with <code>am instrument</code>:
</p>
<ol>
<li>
If necessary, rebuild your main application and test package.
</li>
<li>
Install your test package and main application Android package files
(<code>.apk</code> files) to your current Android device or emulator</li>
<li>
At the command line, enter:
<pre>
$ adb shell am instrument -w &lt;test_package_name&gt;/&lt;runner_class&gt;
</pre>
<p>
where <code>&lt;test_package_name&gt;</code> is the Android package name of your test
application, and <code>&lt;runner_class&gt;</code> is the name of the Android test
runner class you are using. The Android package name is the value of the
<code>package</code> attribute of the <code>manifest</code> element in the manifest file
(<code>AndroidManifest.xml</code>) of your test package. The Android test runner
class is usually {@link android.test.InstrumentationTestRunner}.
</p>
<p>
Your test results appear in <code>STDOUT</code>.
</p>
</li>
</ol>
<p>
This operation starts an <code>adb</code> shell, then runs <code>am instrument</code>
with the specified parameters. This particular form of the command will run all of the tests
in your test package. You can control this behavior with flags that you pass to
<code>am instrument</code>. These flags are described in the next section.
</p>
<h2 id="AMSyntax">Using the am instrument Command</h2>
<p>
The general syntax of the <code>am instrument</code> command is:
</p>
<pre>
am instrument [flags] &lt;test_package&gt;/&lt;runner_class&gt;
</pre>
<p>
The main input parameters to <code>am instrument</code> are described in the following table:
</p>
<table>
<tr>
<th>
Parameter
</th>
<th>
Value
</th>
<th>
Description
</th>
</tr>
<tr>
<td>
<code>&lt;test_package&gt;</code>
</td>
<td>
The Android package name of the test package.
</td>
<td>
The value of the <code>package</code> attribute of the <code>manifest</code>
element in the test package's manifest file.
</td>
</tr>
<tr>
<td>
<code>&lt;runner_class&gt;</code>
</td>
<td>
The class name of the instrumented test runner you are using.
</td>
<td>
This is usually {@link android.test.InstrumentationTestRunner}.
</td>
</tr>
</table>
<p>
The flags for <code>am instrument</code> are described in the following table:
</p>
<table>
<tr>
<th>
Flag
</th>
<th>
Value
</th>
<th>
Description
</th>
</tr>
<tr>
<td>
<code>-w</code>
</td>
<td>
(none)
</td>
<td>
Forces <code>am instrument</code> to wait until the instrumentation terminates
before terminating itself. The net effect is to keep the shell open until the tests
have finished. This flag is not required, but if you do not use it, you will not
see the results of your tests.
</td>
</tr>
<tr>
<td>
<code>-r</code>
</td>
<td>
(none)
</td>
<td>
Outputs results in raw format. Use this flag when you want to collect
performance measurements, so that they are not formatted as test results. This flag is
designed for use with the flag <code>-e perf true</code> (documented in the section
<a href="#AMOptionsSyntax">Instrument options</a>).
</td>
</tr>
<tr>
<td>
<code>-e</code>
</td>
<td>
&lt;test_options&gt;
</td>
<td>
Provides testing options as key-value pairs. The
<code>am instrument</code> tool passes these to the specified instrumentation class
via its <code>onCreate()</code> method. You can specify multiple occurrences of
<code>-e &lt;test_options&gt;</code>. The keys and values are described in the
section <a href="#AMOptionsSyntax">am instrument options</a>.
<p>
The only instrumentation class that uses these key-value pairs is
{@link android.test.InstrumentationTestRunner} (or a subclass). Using them with
any other class has no effect.
</p>
</td>
</tr>
</table>
<h3 id="AMOptionsSyntax">am instrument options</h3>
<p>
The <code>am instrument</code> tool passes testing options to
<code>InstrumentationTestRunner</code> or a subclass in the form of key-value pairs,
using the <code>-e</code> flag, with this syntax:
</p>
<pre>
-e &lt;key&gt; &lt;value&gt;
</pre>
<p>
Some keys accept multiple values. You specify multiple values in a comma-separated list.
For example, this invocation of <code>InstrumentationTestRunner</code> provides multiple
values for the <code>package</code> key:
</p>
<pre>
$ adb shell am instrument -w -e package com.android.test.package1,com.android.test.package2 \
&gt; com.android.test/android.test.InstrumentationTestRunner
</pre>
<p>
The following table describes the key-value pairs and their result. Please review the
<strong>Usage Notes</strong> following the table.
</p>
<table>
<tr>
<th>Key</th>
<th>Value</th>
<th>Description</th>
</tr>
<tr>
<td>
<code>package</code>
</td>
<td>
&lt;Java_package_name&gt;
</td>
<td>
The fully-qualified <em>Java</em> package name for one of the packages in the test
application. Any test case class that uses this package name is executed. Notice that
this is not an <em>Android</em> package name; a test package has a single
Android package name but may have several Java packages within it.
</td>
</tr>
<tr>
<td rowspan="2"><code>class</code></td>
<td>&lt;class_name&gt;</td>
<td>
The fully-qualified Java class name for one of the test case classes. Only this test
case class is executed.
</td>
</tr>
<tr>
<td>&lt;class_name&gt;<strong>#</strong>method name</td>
<td>
A fully-qualified test case class name, and one of its methods. Only this method is
executed. Note the hash mark (#) between the class name and the method name.
</td>
</tr>
<tr>
<td><code>func</code></td>
<td><code>true</code></td>
<td>
Runs all test classes that extend {@link android.test.InstrumentationTestCase}.
</td>
</tr>
<tr>
<td><code>unit</code></td>
<td><code>true</code></td>
<td>
Runs all test classes that do <em>not</em> extend either
{@link android.test.InstrumentationTestCase} or
{@link android.test.PerformanceTestCase}.
</td>
</tr>
<tr>
<td><code>size</code></td>
<td>
[<code>small</code> | <code>medium</code> | <code>large</code>]
</td>
<td>
Runs a test method annotated by size. The annotations are <code>@SmallTest</code>,
<code>@MediumTest</code>, and <code>@LargeTest</code>.
</td>
</tr>
<tr>
<td><code>perf</code></td>
<td><code>true</code></td>
<td>
Runs all test classes that implement {@link android.test.PerformanceTestCase}.
When you use this option, also specify the <code>-r</code> flag for
<code>am instrument</code>, so that the output is kept in raw format and not
re-formatted as test results.
</td>
</tr>
<tr>
<td><code>debug</code></td>
<td><code>true</code></td>
<td>
Runs tests in debug mode.
</td>
</tr>
<tr>
<td><code>log</code></td>
<td><code>true</code></td>
<td>
Loads and logs all specified tests, but does not run them. The test
information appears in <code>STDOUT</code>. Use this to verify combinations of other
filters and test specifications.
</td>
</tr>
<tr>
<td><code>emma</code></td>
<td><code>true</code></td>
<td>
Runs an EMMA code coverage analysis and writes the output to
<code>/data//coverage.ec</code> on the device. To override the file location, use the
<code>coverageFile</code> key that is described in the following entry.
<p class="note">
<strong>Note:</strong> This option requires an EMMA-instrumented build of the test
application, which you can generate with the <code>coverage</code> target.
</p>
</td>
</tr>
<tr>
<td><code>coverageFile</code></td>
<td><code>&lt;filename&gt;</code></td>
<td>
Overrides the default location of the EMMA coverage file on the device. Specify this
value as a path and filename in UNIX format. The default filename is described in the
entry for the <code>emma</code> key.
</td>
</tr>
</table>
<strong><code>-e</code> Flag Usage Notes</strong>
<ul>
<li>
<code>am instrument</code> invokes
{@link android.test.InstrumentationTestRunner#onCreate(Bundle)}
with a {@link android.os.Bundle} containing the key-value pairs.
</li>
<li>
The <code>package</code> key takes precedence over the <code>class</code> key. If you
specifiy a package, and then separately specify a class within that package, Android
will run all the tests in the package and ignore the <code>class</code> key.
</li>
<li>
The <code>func</code> key and <code>unit</code> key are mutually exclusive.
</li>
</ul>
<h3 id="RunTestExamples">Usage examples</h3>
<p>
The following sections provide examples of using <code>am instrument</code> to run tests.
They are based on the following structure:</p>
<ul>
<li>
The test package has the Android package name <code>com.android.demo.app.tests</code>
</li>
<li>
There are three test classes:
<ul>
<li>
<code>UnitTests</code>, which contains the methods
<code>testPermissions</code> and <code>testSaveState</code>.
</li>
<li>
<code>FunctionTests</code>, which contains the methods
<code>testCamera</code>, <code>testXVGA</code>, and <code>testHardKeyboard</code>.
</li>
<li>
<code>IntegrationTests</code>,
which contains the method <code>testActivityProvider</code>.
</li>
</ul>
</li>
<li>
The test runner is {@link android.test.InstrumentationTestRunner}.
</li>
</ul>
<h4>Running the entire test package</h4>
<p>
To run all of the test classes in the test package, enter:
</p>
<pre>
$ adb shell am instrument -w com.android.demo.app.tests/android.test.InstrumentationTestRunner
</pre>
<h4>Running all tests in a test case class</h4>
<p>
To run all of the tests in the class <code>UnitTests</code>, enter:
</p>
<pre>
$ adb shell am instrument -w \
&gt; -e class com.android.demo.app.tests.UnitTests \
&gt; com.android.demo.app.tests/android.test.InstrumentationTestRunner
</pre>
<p>
<code>am instrument</code> gets the value of the <code>-e</code> flag, detects the
<code>class</code> keyword, and runs all the methods in the <code>UnitTests</code> class.
</p>
<h4>Selecting a subset of tests</h4>
<p>
To run all of the tests in <code>UnitTests</code>, and the <code>testCamera</code> method in
<code>FunctionTests</code>, enter:
</p>
<pre>
$ adb shell am instrument -w \
&gt; -e class com.android.demo.app.tests.UnitTests,com.android.demo.app.tests.FunctionTests#testCamera \
&gt; com.android.demo.app.tests/android.test.InstrumentationTestRunner
</pre>
<p>
You can find more examples of the command in the documentation for
{@link android.test.InstrumentationTestRunner}.
</p>

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,435 @@
page.title=MonkeyImage
@jd:body
<style>
h4.jd-details-title {background-color: #DEE8F1;}
</style>
<p>
A monkeyrunner class to hold an image of the device or emulator's screen. The image is
copied from the screen buffer during a screenshot. This object's methods allow you to
convert the image into various storage formats, write the image to a file, copy parts of
the image, and compare this object to other <code>MonkeyImage</code> objects.
</p>
<p>
You do not need to create new instances of <code>MonkeyImage</code>. Instead, use
<code><a href="{@docRoot}guide/developing/tools/MonkeyDevice.html#takeSnapshot">
MonkeyDevice.takeSnapshot()</a></code> to create a new instance from a screenshot. For example, use:
</p>
<pre>
newimage = MonkeyDevice.takeSnapshot()
</pre>
<h2>Summary</h2>
<table id="pubmethods" class="jd-sumtable">
<tr>
<th colspan="12" style="background-color: #E2E2E2">Methods</th>
</tr>
<tr class="api" >
<td class="jd-typecol">
<nobr>
<em>string</em>
</nobr>
</td>
<td class="jd-linkcol" width="100%">
<nobr>
<span class="sympad">
<a href="#convertToBytes">convertToBytes</a>
</span>
(<em>string</em> format)
</nobr>
<div class="jd-descrdiv">
Converts the current image to a particular format and returns it as a
<em>string</em> that you can then access as an <em>iterable</em> of binary bytes.
</div>
</td>
</tr>
<tr class="api" >
<td class="jd-typecol">
<nobr>
<em>tuple</em>
</nobr>
</td>
<td class="jd-linkcol" width="100%">
<nobr>
<span class="sympad">
<a href="#getRawPixel">getRawPixel</a>
</span>
(<em>integer</em> x,
<em>integer</em> y)
</nobr>
<div class="jd-descrdiv">
Returns the single pixel at the image location (x,y), as an
a <em>tuple</em> of <em>integer</em>, in the form (a,r,g,b).
</div>
</td>
</tr>
<tr class="api" >
<td class="jd-typecol">
<nobr>
<em>integer</em>
</nobr>
</td>
<td class="jd-linkcol" width="100%">
<nobr>
<span class="sympad">
<a href="#getRawPixelInt">getRawPixelInt</a>
</span>
(<em>integer</em> x,
<em>integer</em> y)
</nobr>
<div class="jd-descrdiv">
Returns the single pixel at the image location (x,y), as
a 32-bit <em>integer</em>.
</div>
</td>
</tr>
<tr class="api" >
<td class="jd-typecol">
<nobr>
<code>
<a href="{@docRoot}guide/developing/tools/MonkeyImage.html">MonkeyImage</a>
</code>
</nobr>
</td>
<td class="jd-linkcol" width="100%">
<nobr>
<span class="sympad">
<a href="#getSubImage">getSubImage</a>
</span>
(<em>tuple</em> rect)
</nobr>
<div class="jd-descrdiv">
Creates a new <code>MonkeyImage</code> object from a rectangular selection of the
current image.
</div>
</td>
</tr>
<tr class="api" >
<td class="jd-typecol">
<nobr>
<em>boolean</em>
</nobr>
</td>
<td class="jd-linkcol" width="100%">
<nobr>
<span class="sympad">
<a href="#sameAs">sameAs</a>
</span>
(<code><a href="{@docRoot}guide/developing/tools/MonkeyImage.html">MonkeyImage</a></code>
other,
<em>float</em> percent)
</nobr>
<div class="jd-descrdiv">
Compares this <code>MonkeyImage</code> object to another and returns the result of
the comparison. The <code>percent</code> argument specifies the percentage
difference that is allowed for the two images to be "equal".
</div>
</td>
</tr>
<tr class="api" >
<td class="jd-typecol">
<nobr>
<em>void</em>
</nobr>
</td>
<td class="jd-linkcol" width="100%">
<nobr>
<span class="sympad">
<a href="#writeToFile">writeToFile</a>
</span>
(<em>string</em> path,
<em>string</em> format)
</nobr>
<div class="jd-descrdiv">
Writes the current image to the file specified by <code>filename</code>, in the
format specified by <code>format</code>.
</div>
</td>
</tr>
</table>
<!-- ========= METHOD DETAIL ======== -->
<!-- Public methods -->
<h2>Public Methods</h2>
<A NAME="convertToBytes"></A>
<div class="jd-details api ">
<h4 class="jd-details-title">
<span class="normal">
<em>string</em>
</span>
<span class="sympad">convertToBytes</span>
<span class="normal">
(
<em>string</em> format)
</span>
</h4>
<div class="jd-details-descr">
<div class="jd-tagdata jd-tagdescr">
<p>
Converts the current image to a particular format and returns it as a <em>string</em>
that you can then access as an <em>iterable</em> of binary bytes.
</p>
</div>
<div class="jd-tagdata">
<h5 class="jd-tagtitle">Arguments</h5>
<table class="jd-tagtable">
<tr>
<th>format</th>
<td>
The desired output format. All of the common raster output formats are supported.
The default value is "png" (Portable Network Graphics).
</td>
</tr>
</table>
</div>
</div>
</div>
<A NAME="getRawPixel"></A>
<div class="jd-details api ">
<h4 class="jd-details-title">
<span class="normal">
<em>tuple</em>
</span>
<span class="sympad">getRawPixel</span>
<span class="normal">
(<em>integer</em> x,
<em>integer</em> y)
</span>
</h4>
<div class="jd-details-descr">
<div class="jd-tagdata jd-tagdescr">
<p>
Returns the single pixel at the image location (x,y), as an
a <em>tuple</em> of <em>integer</em>, in the form (a,r,g,b).
</p>
</div>
<div class="jd-tagdata">
<h5 class="jd-tagtitle">Arguments</h5>
<table class="jd-tagtable">
<tr>
<th>x</th>
<td>
The horizontal position of the pixel, starting with 0 at the left of the screen in the
orientation it had when the screenshot was taken.
</td>
</tr>
<tr>
<th>y</th>
<td>
The vertical position of the pixel, starting with 0 at the top of the screen in the
orientation it had when the screenshot was taken.
</td>
</tr>
</table>
</div>
<div class="jd-tagdata">
<h5 class="jd-tagtitle">Returns</h5>
<ul class="nolist">
<li>
A tuple of integers representing the pixel, in the form (a,r,g,b) where
a is the alpha channel value, and r, g, and b are the red, green, and blue values,
respectively.
</li>
</ul>
</div>
</div>
</div>
<A NAME="getRawPixelInt"></A>
<div class="jd-details api ">
<h4 class="jd-details-title">
<span class="normal">
<em>tuple</em>
</span>
<span class="sympad">getRawPixelInt</span>
<span class="normal">
(<em>integer</em> x,
<em>integer</em> y)
</span>
</h4>
<div class="jd-details-descr">
<div class="jd-tagdata jd-tagdescr">
<p>
Returns the single pixel at the image location (x,y), as an
an <em>integer</em>. Use this method to economize on memory.
</p>
</div>
<div class="jd-tagdata">
<h5 class="jd-tagtitle">Arguments</h5>
<table class="jd-tagtable">
<tr>
<th>x</th>
<td>
The horizontal position of the pixel, starting with 0 at the left of the screen in the
orientation it had when the screenshot was taken.
</td>
</tr>
<tr>
<th>y</th>
<td>
The vertical position of the pixel, starting with 0 at the top of the screen in the
orientation it had when the screenshot was taken.
</td>
</tr>
</table>
</div>
<div class="jd-tagdata">
<h5 class="jd-tagtitle">Returns</h5>
<ul class="nolist">
<li>
The a,r,g, and b values of the pixel as 8-bit values combined into a 32-bit
integer, with a as the leftmost 8 bits, r the next rightmost, and so forth.
</li>
</ul>
</div>
</div>
</div>
<A NAME="getSubImage"></A>
<div class="jd-details api ">
<h4 class="jd-details-title">
<span class="normal">
<code>
<a href="{@docRoot}guide/developing/tools/MonkeyImage.html">MonkeyImage</a>
</code>
</span>
<span class="sympad">getSubImage</span>
<span class="normal">
(<em>tuple</em> rect)
</span>
</h4>
<div class="jd-details-descr">
<div class="jd-tagdata jd-tagdescr">
<p>
Creates a new <code>MonkeyImage</code> object from a rectangular selection of the
current image.
</p>
</div>
<div class="jd-tagdata">
<h5 class="jd-tagtitle">Arguments</h5>
<table class="jd-tagtable">
<tr>
<th>rect</th>
<td>
A tuple (x, y, w, h) specifying the selection. x and y specify the 0-based pixel
position of the upper left-hand corner of the selection. w specifies the width of the
region, and h specifies its height, both in units of pixels.
<p>
The image's orientation is the same as the screen orientation at the time the
screenshot was made.
</p>
</td>
</tr>
</table>
</div>
<div class="jd-tagdata">
<h5 class="jd-tagtitle">Returns</h5>
<ul class="nolist">
<li>
A new <code>MonkeyImage</code> object containing the selection.
</li>
</ul>
</div>
</div>
</div>
<A NAME="sameAs"></A>
<div class="jd-details api ">
<h4 class="jd-details-title">
<span class="normal">
<em>boolean</em>
</span>
<span class="sympad">sameAs</span>
<span class="normal">
(
<code>
<a href="{@docRoot}guide/developing/tools/MonkeyImage.html">MonkeyImage</a>
</code> otherImage,
<em>float</em> percent
)
</span>
</h4>
<div class="jd-details-descr">
<div class="jd-tagdata jd-tagdescr">
<p>
Compares this <code>MonkeyImage</code> object to another and returns the result of
the comparison. The <code>percent</code> argument specifies the percentage
difference that is allowed for the two images to be "equal".
</p>
</div>
<div class="jd-tagdata">
<h5 class="jd-tagtitle">Arguments</h5>
<table class="jd-tagtable">
<tr>
<th>other</th>
<td>
Another <code>MonkeyImage</code> object to compare to this one.
</td>
</tr>
<tr>
<th>
percent
</th>
<td>
A float in the range 0.0 to 1.0, inclusive, indicating
the percentage of pixels that need to be the same for the method to return
<code>true</code>. The default is 1.0, indicating that all the pixels
must match.
</td>
</tr>
</table>
</div>
<div class="jd-tagdata">
<h5 class="jd-tagtitle">Returns</h5>
<ul class="nolist">
<li>
Boolean <code>true</code> if the images match, or boolean <code>false</code> otherwise.
</li>
</ul>
</div>
</div>
</div>
<A NAME="writeToFile"></A>
<div class="jd-details api ">
<h4 class="jd-details-title">
<span class="normal">
void
</span>
<span class="sympad">writeToFile</span>
<span class="normal">
(<em>string</em> filename,
<em>string</em> format)
</span>
</h4>
<div class="jd-details-descr">
<div class="jd-tagdata jd-tagdescr">
<p>
Writes the current image to the file specified by <code>filename</code>, in the
format specified by <code>format</code>.
</p>
</div>
<div class="jd-tagdata">
<h5 class="jd-tagtitle">Arguments</h5>
<table class="jd-tagtable">
<tr>
<th>path</th>
<td>
The fully-qualified filename and extension of the output file.
</td>
</tr>
<tr>
<th>
format
</th>
<td>
The output format to use for the file. If no format is provided, then the
method tries to guess the format from the filename's extension. If no
extension is provided and no format is specified, then the default format of
"png" (Portable Network Graphics) is used.
</td>
</tr>
</table>
</div>
</div>
</div>

View File

@@ -0,0 +1,445 @@
page.title=MonkeyRunner
@jd:body
<style>
h4.jd-details-title {background-color: #DEE8F1;}
</style>
<p>
A monkeyrunner class that contains static utility methods.
</p>
<h2>Summary</h2>
<table id="pubmethods" class="jd-sumtable">
<tr>
<th colspan="12" style="background-color: #E2E2E2">Methods</th>
</tr>
<tr class="api" >
<td class="jd-typecol">
<nobr>
void
</nobr>
</td>
<td class="jd-linkcol" width="100%">
<nobr>
<span class="sympad">
<a href="#alert">alert</a>
</span>
(<em>string</em> message,
<em>string</em> title,
<em>string</em> okTitle)
</nobr>
<div class="jd-descrdiv">
Displays an alert dialog to the process running the current
program.
</div>
</td>
</tr>
<tr class="api" >
<td class="jd-typecol">
<nobr>
<em>integer</em>
</nobr>
</td>
<td class="jd-linkcol" width="100%">
<nobr>
<span class="sympad">
<a href="#choice">choice</a>
</span>
(<em>string</em> message,
<em>iterable</em> choices,
<em>string</em> title)
</nobr>
<div class="jd-descrdiv">
Displays a dialog with a list of choices to the process running the current program.
</div>
</td>
</tr>
<tr class="api" >
<td class="jd-typecol">
<nobr>
void
</nobr>
</td>
<td class="jd-linkcol" width="100%">
<nobr>
<span class="sympad">
<a href="#help">help</a>
</span>
(<em>string</em> format)
</nobr>
<div class="jd-descrdiv">
Displays the monkeyrunner API reference in a style similar to that of Python's
<code>pydoc</code> tool, using the specified format.
</div>
</td>
</tr>
<tr class="api" >
<td class="jd-typecol">
<nobr>
<em>string</em>
</nobr>
</td>
<td class="jd-linkcol" width="100%">
<nobr>
<span class="sympad">
<a href="#input">input</a>
</span>
(<em>string</em> message,
<em>string</em> initialValue,
<em>string</em> title,
<em>string</em> okTitle,
<em>string</em> cancelTitle)
</nobr>
<div class="jd-descrdiv">
Displays a dialog that accepts input.
</div>
</td>
</tr>
<tr class="api" >
<td class="jd-typecol">
<nobr>
void
</nobr>
</td>
<td class="jd-linkcol" width="100%">
<nobr>
<span class="sympad">
<a href="#sleep">sleep</a>
</span>
(<em>float</em> seconds)
</nobr>
<div class="jd-descrdiv">
Pauses the current program for the specified number of seconds.
</div>
</td>
</tr>
<tr class="api" >
<td class="jd-typecol">
<nobr>
<code>
<a href="{@docRoot}guide/developing/tools/MonkeyDevice.html">MonkeyDevice</a>
</code>
</nobr>
</td>
<td class="jd-linkcol" width="100%">
<nobr>
<span class="sympad">
<a href="#waitForConnection">waitForConnection</a>
</span>
(<em>float</em> timeout,
<em>string</em> deviceId)
</nobr>
<div class="jd-descrdiv">
Tries to make a connection between the <code>monkeyrunner</code> backend and the
specified device or emulator.
</div>
</td>
</tr>
</table>
<!-- ========= METHOD DETAIL ======== -->
<!-- Public methods -->
<h2>Public Methods</h2>
<A NAME="alert"></A>
<div class="jd-details api ">
<h4 class="jd-details-title">
<span class="normal">
<em>string</em>
</span>
<span class="sympad">alert</span>
<span class="normal">
(
<em>string</em> message,
<em>string</em> title,
<em>string</em> okTitle)
</span>
</h4>
<div class="jd-details-descr">
<div class="jd-tagdata jd-tagdescr">
<p>
Displays an alert dialog to the process running the current
program. The dialog is modal, so the program pauses until the user clicks the dialog's
button.
</p>
</div>
<div class="jd-tagdata">
<h5 class="jd-tagtitle">Arguments</h5>
<table class="jd-tagtable">
<tr>
<th>message</th>
<td>
The message to display in the dialog.
</td>
</tr>
<tr>
<th>title</th>
<td>
The dialog's title. The default value is "Alert".
</td>
</tr>
<tr>
<th>okTitle</th>
<td>
The text displayed in the dialog button. The default value is "OK".
</td>
</tr>
</table>
</div>
</div>
</div>
<A NAME="choice"></A>
<div class="jd-details api ">
<h4 class="jd-details-title">
<span class="normal">
<em>integer</em>
</span>
<span class="sympad">choice</span>
<span class="normal">
(<em>string</em> message,
<em>iterable</em> choices,
<em>string</em> title)
</span>
</h4>
<div class="jd-details-descr">
<div class="jd-tagdata jd-tagdescr">
<p>
Displays a dialog with a list of choices to the process running the current program. The
dialog is modal, so the program pauses until the user clicks one of the dialog's
buttons.
</p>
</div>
<div class="jd-tagdata">
<h5 class="jd-tagtitle">Arguments</h5>
<table class="jd-tagtable">
<tr>
<th>message</th>
<td>
The prompt message displayed in the dialog.
</td>
</tr>
<tr>
<th>choices</th>
<td>
A Python iterable containing one or more objects that are displayed as strings. The
recommended form is an array of strings.
</td>
</tr>
<tr>
<th>
title
</th>
<td>
The dialog's title. The default is "Input".
</td>
</tr>
</table>
</div>
<div class="jd-tagdata">
<h5 class="jd-tagtitle">Returns</h5>
<ul class="nolist">
<li>
If the user makes a selection and clicks the "OK" button, the method returns
the 0-based index of the selection within the iterable.
If the user clicks the "Cancel" button, the method returns -1.
</li>
</ul>
</div>
</div>
</div>
<A NAME="help"></A>
<div class="jd-details api ">
<h4 class="jd-details-title">
<span class="normal">
void
</span>
<span class="sympad">help</span>
<span class="normal">
(<em>string</em> format)
</span>
</h4>
<div class="jd-details-descr">
<div class="jd-tagdata jd-tagdescr">
<p>
Displays the monkeyrunner API reference in a style similar to that of Python's
<code>pydoc</code> tool, using the specified format.
</p>
</div>
<div class="jd-tagdata">
<h5 class="jd-tagtitle">Arguments</h5>
<table class="jd-tagtable">
<tr>
<th>format</th>
<td>
The markup format to use in the output. The possible values are "text" for plain text
or "html" for HTML.
</td>
</tr>
</table>
</div>
</div>
</div>
<A NAME="input"></A>
<div class="jd-details api ">
<h4 class="jd-details-title">
<span class="normal">
<em>string</em>
</span>
<span class="sympad">input</span>
<span class="normal">
(<em>string</em> message
<em>string</em> initialValue,
<em>string</em> title,
<em>string</em> okTitle,
<em>string</em> cancelTitle)
</span>
</h4>
<div class="jd-details-descr">
<div class="jd-tagdata jd-tagdescr">
<p>
Displays a dialog that accepts input and returns it to the program. The dialog is
modal, so the program pauses until the user clicks one of the dialog's buttons.
</p>
<p>
The dialog contains two buttons, one of which displays the okTitle value
and the other the cancelTitle value. If the user clicks the okTitle button,
the current value of the input box is returned. If the user clicks the cancelTitle
button, an empty string is returned.
</p>
</div>
<div class="jd-tagdata">
<h5 class="jd-tagtitle">Arguments</h5>
<table class="jd-tagtable">
<tr>
<th>message</th>
<td>
The prompt message displayed in the dialog.
</td>
</tr>
<tr>
<th>initialValue</th>
<td>
The initial value to display in the dialog. The default is an empty string.
</td>
</tr>
<tr>
<th>title</th>
<td>
The dialog's title. The default is "Input".
</td>
</tr>
<tr>
<th>okTitle</th>
<td>
The text displayed in the okTitle button. The default is "OK".
</td>
</tr>
<tr>
<th>cancelTitle</th>
<td>
The text displayed in the cancelTitle button. The default is "Cancel".
</td>
</tr>
</table>
</div>
<div class="jd-tagdata">
<h5 class="jd-tagtitle">Returns</h5>
<ul class="nolist">
<li>
If the user clicks the okTitle button, then the method returns the current value of
the dialog's input box. If the user clicks the cancelTitle button, the method returns
an empty string.
</li>
</ul>
</div>
</div>
</div>
<A NAME="sleep"></A>
<div class="jd-details api ">
<h4 class="jd-details-title">
<span class="normal">
void
</span>
<span class="sympad">sleep</span>
<span class="normal">
(
<em>float</em> seconds
)
</span>
</h4>
<div class="jd-details-descr">
<div class="jd-tagdata jd-tagdescr">
<p>
Pauses the current program for the specified number of seconds.
</p>
</div>
<div class="jd-tagdata">
<h5 class="jd-tagtitle">Arguments</h5>
<table class="jd-tagtable">
<tr>
<th>seconds</th>
<td>
The number of seconds to pause.
</td>
</tr>
</table>
</div>
</div>
</div>
<A NAME="waitForConnection"></A>
<div class="jd-details api ">
<h4 class="jd-details-title">
<span class="normal">
<code>
<a href="{@docRoot}guide/developing/tools/MonkeyDevice.html">MonkeyDevice</a>
</code>
</span>
<span class="sympad">waitForConnection</span>
<span class="normal">
(<em>float</em> timeout,
<em>string</em> deviceId)
</span>
</h4>
<div class="jd-details-descr">
<div class="jd-tagdata jd-tagdescr">
<p>
Tries to make a connection between the <code>monkeyrunner</code> backend and the
specified device or emulator.
</p>
</div>
<div class="jd-tagdata">
<h5 class="jd-tagtitle">Arguments</h5>
<table class="jd-tagtable">
<tr>
<th>timeout</th>
<td>
The number of seconds to wait for a connection. The default is to wait forever.
</td>
</tr>
<tr>
<th>
deviceId
</th>
<td>
A regular expression that specifies the serial number of the device or emulator. See
the topic
<a href="{@docRoot}guide/developing/tools/adb.html">Android Debug Bridge</a>
for a description of device and emulator serial numbers.
</td>
</tr>
</table>
</div>
<div class="jd-tagdata">
<h5 class="jd-tagtitle">Returns</h5>
<ul class="nolist">
<li>
A <code><a href="{@docRoot}guide/developing/tools/MonkeyDevice.html">MonkeyDevice</a></code>
instance for the device or emulator. Use this object to control and communicate with the
device or emulator.
</li>
</ul>
</div>
</div>
</div>

View File

@@ -0,0 +1,20 @@
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>

View File

@@ -0,0 +1,701 @@
page.title=Android Debug Bridge
@jd:body
<div id="qv-wrapper">
<div id="qv">
<h2>ADB quickview</h2>
<ul>
<li>Manage the state of an emulator or device</li>
<li>Run shell commands on a device</li>
<li>Manage port forwarding on an emulator or device</li>
<li>Copy files to/from an emulator or device</li>
</ul>
<h2>In this document</h2>
<ol>
<li><a href="#issuingcommands">Issuing ADB Commands</a></li>
<li><a href="#devicestatus">Querying for Emulator/Device Instances</a></li>
<li><a href="#directingcommands">Directing Commands to a Specific Emulator/Device Instance</a></li>
<li><a href="#move">Installing an Application</a></li>
<li><a href="#forwardports">Forwarding Ports</a></li>
<li><a href="#copyfiles">Copying Files to or from an Emulator/Device Instance</a></li>
<li><a href="#commandsummary">Listing of adb Commands </a></li>
<li><a href="#shellcommands">Issuing Shell Commands</a></li>
<li><a href="#logcat">Enabling logcat Logging</a></li>
<li><a href="#stopping">Stopping the adb Server</a></li>
</ol>
<h2>See also</h2>
<ol>
<li><a href="emulator.html">Emulator</a></li>
</ol>
</div>
</div>
<!--
<p>Android Debug Bridge (adb) is a versatile tool that </a>. </p>
<p>Some of ways you can use adb include:</p>
<ul>
</ul>
<p>The sections below introduce adb and describe many of its common uses. </p>
<h2>Contents</h2>
<dl>
<dt><a href="#overview">Overview</a></dt>
<dt><a href="#issuingcommands">Issuing adb Commands</a></dt>
<dt><a href="#devicestatus">Querying for Emulator/Device Instances</a></dt>
<dt><a href="#directingcommands">Directing Commands to a Specific Emulator/Device Instance</a></dt>
<dt><a href="#move">Installing an Application</a></dt>
<dt><a href="#forwardports">Forwarding Ports</a></dt>
<dt><a href="#copyfiles">Copying Files to or from an Emulator/Device Instance</a></dt>
<dt><a href="#commandsummary">Listing of adb Commands </a></dt>
<dt><a href="#shellcommands">Issuing Shell Commands</a></dt>
<dd><a href="#sqlite">Examining sqlite3 Databases from a Remote Shell</a></dd>
<dd><a href="#monkey">UI/Application Exerciser Monkey</a></dd>
<dd><a href="#othershellcommands">Other Shell Commands</a></dd>
<dt><a href="#logcat">Enabling logcat Logging</a> </dt>
<dd><a href="#usinglogcat">Using logcat Commands</a></dd>
<dd><a href="#filteringoutput">Filtering Log Output</a></dd>
<dd><a href="#outputformat">Controlling Log Output Format</a></dd>
<dd><a href="#alternativebuffers">Viewing Alternative Log Buffers</a></dd>
<dd><a href="#stdout">Viewing stdout and stderr</a></dd>
<dd><a href="#logcatoptions">Listing of logcat Command Options</a></dd>
<dt><a href="#stopping">Stopping the adb Server</a> </dt>
</dl>
<a name="overview"></a>
<h2>Overview</h2>
-->
<p>Android Debug Bridge (adb) is a versatile tool lets you manage the state of an emulator instance or Android-powered device. It is a client-server program that includes three components: </p>
<ul>
<li>A client, which runs on your development machine. You can invoke a client from a shell by issuing an adb command. Other Android tools such as the ADT plugin and DDMS also create adb clients. </li>
<li>A server, which runs as a background process on your development machine. The server manages communication between the client and the adb daemon running on an emulator or device. </li>
<li>A daemon, which runs as a background process on each emulator or device instance. </li>
</ul>
<p>You can find the {@code adb} tool in {@code &lt;sdk&gt;/platform-tools/}.</p>
<p>When you start an adb client, the client first checks whether there is an adb server process already running. If there isn't, it starts the server process. When the server starts, it binds to local TCP port 5037 and listens for commands sent from adb clients&mdash;all adb clients use port 5037 to communicate with the adb server. </p>
<p>The server then sets up connections to all running emulator/device instances. It locates emulator/device instances by scanning odd-numbered ports in the range 5555 to 5585, the range used by emulators/devices. Where the server finds an adb daemon, it sets up a connection to that port. Note that each emulator/device instance acquires a pair of sequential ports &mdash; an even-numbered port for console connections and an odd-numbered port for adb connections. For example: </p>
<p style="margin-left:2em">
Emulator 1, console: 5554<br/>
Emulator 1, adb: 5555<br>
Emulator 2, console: 5556<br>
Emulator 2, adb: 5557 ...
</p>
<p>As shown, the emulator instance connected to adb on port 5555 is the same as the instance whose console listens on port 5554. </p>
<p>Once the server has set up connections to all emulator instances, you can use adb commands to control and access those instances. Because the server manages connections to emulator/device instances and handles commands from multiple adb clients, you can control any emulator/device instance from any client (or from a script).</p>
<p>The sections below describe the commands that you can use to access adb capabilities and manage the state of an emulator/device. Note that if you are developing Android applications in Eclipse and have installed the ADT plugin, you do not need to access adb from the command line. The ADT plugin provides a transparent integration of adb into the Eclipse IDE. However, you can still use adb directly as necessary, such as for debugging.</p>
<a name="issuingcommands"></a>
<h2>Issuing adb Commands</h2>
<p>You can issue adb commands from a command line on your development machine or from a script. The usage is: </p>
<pre>adb [-d|-e|-s &lt;serialNumber&gt;] &lt;command&gt; </pre>
<p>When you issue a command, the program invokes an adb client. The client is not specifically associated with any emulator instance, so if multiple emulators/devices are running, you need to use the <code>-d</code> option to specify the target instance to which the command should be directed. For more information about using this option, see <a href="#directingcommands">Directing Commands to a Specific Emulator/Device Instance</a>. </p>
<a name="devicestatus"></a>
<h2>Querying for Emulator/Device Instances</h2>
<p>Before issuing adb commands, it is helpful to know what emulator/device instances are connected to the adb server. You can generate a list of attached emulators/devices using the <code>devices</code> command: </p>
<pre>adb devices</pre>
<p>In response, adb prints this status information for each instance:</p>
<ul>
<li>Serial number &mdash; A string created by adb to uniquely identify an emulator/device instance by its
console port number. The format of the serial number is <code>&lt;type&gt;-&lt;consolePort&gt;</code>.
Here's an example serial number: <code>emulator-5554</code></li>
<li>State &mdash; The connection state of the instance. Three states are supported:
<ul>
<li><code>offline</code> &mdash; the instance is not connected to adb or is not responding.</li>
<li><code>device</code> &mdash; the instance is now connected to the adb server. Note that this state does not
imply that the Android system is fully booted and operational, since the instance connects to adb
while the system is still booting. However, after boot-up, this is the normal operational state of
an emulator/device instance.</li>
</ul>
</li>
</ul>
<p>The output for each instance is formatted like this: </p>
<pre>[serialNumber] [state]</pre>
<p>Here's an example showing the <code>devices</code> command and its output:</p>
<pre>$ adb devices
List of devices attached
emulator-5554&nbsp;&nbsp;device
emulator-5556&nbsp;&nbsp;device
emulator-5558&nbsp;&nbsp;device</pre>
<p>If there is no emulator/device running, adb returns <code>no device</code>.</p>
<a name="directingcommands"></a>
<h2>Directing Commands to a Specific Emulator/Device Instance</h2>
<p>If multiple emulator/device instances are running, you need to specify a target instance when issuing adb commands. To so so, use the <code>-s</code> option in the commands. The usage for the <code>-s</code> option is:</p>
<pre>adb -s &lt;serialNumber&gt; &lt;command&gt; </pre>
<p>As shown, you specify the target instance for a command using its adb-assigned serial number. You can use the <code>devices</code> command to obtain the serial numbers of running emulator/device instances. </p>
<p>Here is an example: </p>
<pre>adb -s emulator-5556 install helloWorld.apk</pre>
<p>Note that, if you issue a command without specifying a target emulator/device instance using <code>-s</code>, adb generates an error.
<a name="move"></a>
<h2>Installing an Application</h2>
<p>You can use adb to copy an application from your development computer and install it on an emulator/device instance. To do so, use the <code>install</code> command. With the command, you must specify the path to the .apk file that you want to install:</p>
<pre>adb install &lt;path_to_apk&gt;</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>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>
<a name="forwardports"></a>
<h2>Forwarding Ports</h2>
<p>You can use the <code>forward</code> command to set up arbitrary port forwarding &mdash; forwarding of requests on a specific host port to a different port on an emulator/device instance. Here's how you would set up forwarding of host port 6100 to emulator/device port 7100:</p>
<pre>adb forward tcp:6100 tcp:7100</pre>
<p>You can also use adb to set up forwarding to named abstract UNIX domain sockets, as illustrated here:</p>
<pre>adb forward tcp:6100 local:logd </pre>
<a name="copyfiles"></a>
<h2>Copying Files to or from an Emulator/Device Instance</h2>
<p>You can use the adb commands <code>pull</code> and <code>push</code> to copy files to and from an emulator/device instance's data file. Unlike the <code>install</code> command, which only copies an .apk file to a specific location, the <code>pull</code> and <code>push</code> commands let you copy arbitrary directories and files to any location in an emulator/device instance. </p>
<p>To copy a file or directory (recursively) <em>from</em> the emulator or device, use</p>
<pre>adb pull &lt;remote&gt; &lt;local&gt;</pre>
<p>To copy a file or directory (recursively) <em>to</em> the emulator or device, use</p>
<pre>adb push &lt;local&gt; &lt;remote&gt;</pre>
<p>In the commands, <code>&lt;local&gt;</code> and <code>&lt;remote&gt;</code> refer to the paths to the target files/directory on your development machine (local) and on the emulator/device instance (remote).</p>
<p>Here's an example: </p>
<pre>adb push foo.txt /sdcard/foo.txt</pre>
<a name="commandsummary"></a>
<h2>Listing of adb Commands</h2>
<p>The table below lists all of the supported adb commands and explains their meaning and usage. </p>
<table>
<tr>
<th>Category</th>
<th>Command</th>
<th>Description</th>
<th>Comments</th>
</tr>
<tr>
<td rowspan="3">Options</td>
<td><code>-d</code></td>
<td>Direct an adb command to the only attached USB device.</td>
<td>Returns an error if more than one USB device is attached.</td>
</tr>
<tr>
<td><code>-e</code></td>
<td>Direct an adb command to the only running emulator instance.</td>
<td>Returns an error if more than one emulator instance is running. </td>
</tr>
<tr>
<td><code>-s&nbsp;&lt;serialNumber&gt;</code></td>
<td>Direct an adb command a specific emulator/device instance, referred to by its adb-assigned serial number (such as "emulator-5556").</td>
<td>If not specified, adb generates an error.</td>
</tr>
<tr>
<td rowspan="3">General</td>
<td><code>devices</code></td>
<td>Prints a list of all attached emulator/device instances.</td>
<td>See <a href="#devicestatus">Querying for Emulator/Device Instances</a> for more information.</td>
</tr>
<tr>
<td><code>help</code></td>
<td>Prints a list of supported adb commands.</td>
<td>&nbsp;</td>
</tr>
<tr>
<td><code>version</code></td>
<td>Prints the adb version number. </td>
<td>&nbsp;</td>
</tr>
<tr>
<td rowspan="3">Debug</td>
<td ><code>logcat&nbsp;[&lt;option&gt;] [&lt;filter-specs&gt;]</code></td>
<td>Prints log data to the screen. </td>
<td>&nbsp;</td>
</tr>
<tr>
<td><code>bugreport</code></td>
<td>Prints <code>dumpsys</code>, <code>dumpstate</code>, and <code>logcat</code> data to the screen, for the purposes of bug reporting. </td>
<td>&nbsp;</td>
</tr>
<tr>
<td><code>jdwp</code></td>
<td>Prints a list of available JDWP processes on a given device. </td>
<td>You can use the <code>forward jdwp:&lt;pid&gt;</code> port-forwarding specification to connect to a specific JDWP process. For example: <br>
<code>adb forward tcp:8000 jdwp:472</code><br>
<code>jdb -attach localhost:8000</code></p>
</td>
</tr>
<tr>
<td rowspan=3">Data</td>
<td><code>install&nbsp;&lt;path-to-apk&gt;</code></td>
<td>Pushes an Android application (specified as a full path to an .apk file) to the data file of an emulator/device. </td>
<td>&nbsp;</td>
</tr>
<tr>
<td><code>pull&nbsp;&lt;remote&gt;&nbsp;&lt;local&gt;</code></td>
<td>Copies a specified file from an emulator/device instance to your development computer. </td>
<td>&nbsp;</td>
</tr>
<tr>
<td><code>push&nbsp;&lt;local&gt;&nbsp;&lt;remote&gt;</code></td>
<td>Copies a specified file from your development computer to an emulator/device instance. </td>
<td>&nbsp;</td>
</tr>
<tr>
<td rowspan="2">Ports and Networking</td>
<td><code>forward&nbsp;&lt;local&gt;&nbsp;&lt;remote&gt;</code></td>
<td>Forwards socket connections from a specified local port to a specified remote port on the emulator/device instance. </td>
<td>Port specifications can use these schemes:
<ul><li><code>tcp:&lt;portnum&gt;</code></li>
<li><code>local:&lt;UNIX domain socket name&gt;</code></li>
<li><code>dev:&lt;character device name&gt;</code></li>
<li><code>jdwp:&lt;pid&gt;</code></li></ul>
</td>
</tr>
<tr>
<td><code>ppp&nbsp;&lt;tty&gt;&nbsp;[parm]...</code></td>
<td>Run PPP over USB.
<ul>
<li><code>&lt;tty&gt;</code> &mdash; the tty for PPP stream. For example <code>dev:/dev/omap_csmi_ttyl</code>. </li>
<li><code>[parm]... </code> &mdash zero or more PPP/PPPD options, such as <code>defaultroute</code>, <code>local</code>, <code>notty</code>, etc.</li></ul>
<p>Note that you should not automatically start a PPP connection. </p></td>
<td></td>
</tr>
<tr>
<td rowspan="3">Scripting</td>
<td><code>get-serialno</code></td>
<td>Prints the adb instance serial number string.</td>
<td rowspan="2">See <a href="#devicestatus">Querying for Emulator/Device Instances</a> for more information. </td>
</tr>
<tr>
<td><code>get-state</code></td>
<td>Prints the adb state of an emulator/device instance.</td>
</td>
</tr>
<tr>
<td><code>wait-for-device</code></td>
<td>Blocks execution until the device is online &mdash; that is, until the instance state is <code>device</code>.</td>
<td>You can prepend this command to other adb commands, in which case adb will wait until the emulator/device instance is connected before issuing the other commands. Here's an example:
<pre>adb wait-for-device shell getprop</pre>
Note that this command does <em>not</em> cause adb to wait until the entire system is fully booted. For that reason, you should not prepend it to other commands that require a fully booted system. As an example, the <code>install</code> requires the Android package manager, which is available only after the system is fully booted. A command such as
<pre>adb wait-for-device install &lt;app&gt;.apk</pre>
would issue the <code>install</code> command as soon as the emulator or device instance connected to the adb server, but before the Android system was fully booted, so it would result in an error. </td>
</tr>
<tr>
<td rowspan="2">Server</td>
<td><code>start-server</code></td>
<td>Checks whether the adb server process is running and starts it, if not.</td>
<td>&nbsp;</td>
</tr>
<tr>
<td><code>kill-server</code></td>
<td>Terminates the adb server process.</td>
<td>&nbsp;</td>
</tr>
<tr>
<td rowspan="2">Shell</td>
<td><code>shell</code></td>
<td>Starts a remote shell in the target emulator/device instance.</td>
<td rowspan="2">See <a href="#shellcommands">Issuing Shell Commands</a> for more information. </td>
</tr>
<tr>
<td><code>shell&nbsp;[&lt;shellCommand&gt;]</code></td>
<td>Issues a shell command in the target emulator/device instance and then exits the remote shell.</td>
</tr>
</table>
<a name="shellcommands"></a>
<h2>Issuing Shell Commands</h2>
<p>Adb provides an ash shell that you can use to run a variety of commands on an emulator
or device. The command binaries are stored in the file system of the emulator or device,
in this location: </p>
<pre>/system/bin/...</pre>
<p>You can use the <code>shell</code> command to issue commands, with or without entering the adb remote shell on the emulator/device. </p>
<p>To issue a single command without entering a remote shell, use the <code>shell</code> command like this: </p>
<pre>adb [-d|-e|-s {&lt;serialNumber&gt;}] shell &lt;shellCommand&gt;</pre>
<p>To drop into a remote shell on a emulator/device instance, use the <code>shell</code> command like this:</p>
<pre>adb [-d|-e|-s {&lt;serialNumber&gt;}] shell</pre>
<p>When you are ready to exit the remote shell, use <code>CTRL+D</code> or <code>exit</code> to end the shell session. </p>
<p>The sections below provide more information about shell commands that you can use.</p>
<a name="sqlite" id="sqlite"></a>
<h3>Examining sqlite3 Databases from a Remote Shell</h3>
<p>From an adb remote shell, 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>, enter a remote shell on the emulator instance, as described above, then invoke the tool using the <code>sqlite3</code> command. Optionally, when invoking <code>sqlite3</code> you can specify the full path to the database you want to explore. Emulator/device instances store SQLite3 databases in the folder <code><span chatdir="1"><span chatindex="259474B4B070F261">/data/data/<em>&lt;package_name&gt;</em>/databases</span></span>/</code>. </p>
<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 &quot;.help&quot; for instructions
<em>.... enter commands, then quit...</em>
sqlite&gt; .exit </pre>
<p>Once you've invoked <code>sqlite3</code>, you can issue <code>sqlite3</code> commands in the shell. To exit and return to the adb remote shell, use <code>exit</code> or <code>CTRL+D</code>.
<a name="monkey"></a>
<h3>UI/Application Exerciser Monkey</h3>
<p>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.</p>
<p>The simplest way to use the monkey is with the following command, which will launch your
application and send 500 pseudo-random events to it.</p>
<pre>$ adb shell monkey -v -p your.package.name 500</pre>
<p>For more information about command options for Monkey, see the complete
<a href="{@docRoot}guide/developing/tools/monkey.html" title="monkey">UI/Application Exerciser Monkey</a> documentation page.</p>
<a name="othershellcommands"></a>
<h3>Other Shell Commands</h3>
<p>The table below lists several of the adb shell commands available. For a complete list of commands and programs, start an emulator instance and use the <code>adb -help</code> command. </p>
<pre>adb shell ls /system/bin</pre>
<p>Help is available for most of the commands. </p>
<table>
<tr>
<th>Shell Command</th>
<th>Description</th>
<th>Comments</th>
</tr>
<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>
</tr>
<tr>
<td><code>dumpstate</code></td>
<td>Dumps state to a file.</td>
</tr>
<tr>
<td><code>logcat&nbsp;[&lt;option&gt;]...&nbsp;[&lt;filter-spec&gt;]...</code></td>
<td>Enables radio logging and prints output to the screen. </td>
</tr>
<tr>
<td><code>dmesg</code></td>
<td>Prints kernel debugging messages to the screen. </td>
</tr>
<tr>
<td><code>start</code></td>
<td>Starts (restarts) an emulator/device instance.</td>
<td>&nbsp;</td>
</tr>
<tr>
<td><code>stop</code></td>
<td>Stops execution of an emulator/device instance.</td>
<td>&nbsp;</td>
</tr>
</table>
<a name="logcat"></a>
<h2>Enabling logcat Logging</h2>
<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.</p>
<a name="usinglogcat"></a>
<h3>Using logcat Commands</h3>
<p>You can use the <code>logcat</code> command to view and follow the contents of the system's log buffers. The general usage is:</p>
<pre>[adb] logcat [&lt;option&gt;] ... [&lt;filter-spec&gt;] ...</pre>
<p>The sections below explain filter specifications and the command options. See <a href="#logcatoptions">Listing of logcat Command Options</a> for a summary of options. </p>
<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>
<a name="filteringoutput"></a>
<h3>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>
<ul>
<li><code>V</code> &mdash; Verbose (lowest priority)</li>
<li><code>D</code> &mdash; Debug</li>
<li><code>I</code> &mdash; Info</li>
<li><code>W</code> &mdash; Warning</li>
<li><code>E</code> &mdash; Error</li>
<li><code>F</code> &mdash; Fatal</li>
<li><code>S</code> &mdash; Silent (highest priority, on which nothing is ever printed)</li>
</ul>
</ul>
<p>You can obtain a list of tags used in the system, together with priorities, by running <code>logcat</code> and observing the first two columns
of each message, given as <code>&lt;priority&gt;/&lt;tag&gt;</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 &mdash; 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 &mdash; 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 <code>logcat</code> 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 <code>logcat</code> from a remote shell or using <code>adb shell logcat</code>.</p>
<a name="outputformat"></a>
<h3>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> &mdash; Display priority/tag and PID of originating process (the default format).</li>
<li><code>process</code> &mdash; Display PID only.</li>
<li><code>tag</code> &mdash; Display the priority/tag only. </li>
<li><code>thread</code> &mdash; Display process:thread and priority/tag only. </li>
<li><code>raw</code> &mdash; Display the raw log message, with no other metadata fields.</li>
<li><code>time</code> &mdash; Display the date, invocation time, priority/tag, and PID of the originating process.</li>
<li><code>long</code> &mdash; Display all metadata fields and separate messages with a blank lines.</li>
</ul>
<p>When starting <code>logcat</code>, you can specify the output format you want by using the <code>-v</code> option:</p>
<pre>[adb] logcat [-v &lt;format&gt;]</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>
<a name="alternativebuffers"></a>
<h3>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 start <code>logcat</code> 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> &mdash; View the buffer that contains radio/telephony related messages.</li>
<li><code>events</code> &mdash; View the buffer containing events-related messages.</li>
<li><code>main</code> &mdash; View the main log buffer (default)</li>
</ul>
<p>The usage of the <code>-b</code> option is:</p>
<pre>[adb] logcat [-b &lt;buffer&gt;]</pre>
<p>Here's an example of how to view a log buffer containing radio and telephony messages: </p>
<pre>adb logcat -b radio</b></pre>
<a name="stdout"></a>
<h3>Viewing stdout and stderr</h3>
<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>
<a name="logcatoptions"></a>
<h3>Listing of logcat Command Options</h3>
<table>
<tr>
<th>Option</th>
<th>Description</th>
</tr>
<tr>
<td><code>-b&nbsp;&lt;buffer&gt;</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&nbsp;&lt;filename&gt;</code></td>
<td>Writes log message output to <code>&lt;filename&gt;</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&nbsp;&lt;count&gt;</code></td>
<td>Sets the maximum number of rotated logs to <code>&lt;count&gt;</code>. The default value is 4. Requires the <code>-r</code> option. </td>
</tr>
<tr>
<td><code>-r&nbsp;&lt;kbytes&gt;</code></td>
<td>Rotates the log file every <code>&lt;kbytes&gt;</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&nbsp;&lt;format&gt;</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>
<a name="stopping"></a>
<h2>Stopping the adb Server</h2>
<p>In some cases, you might need to terminate the adb server process and then restart it. For example, if adb does not respond to a command, you can terminate the server and restart it and that may resolve the problem. </p>
<p>To stop the adb server, use the <code>kill-server</code>. You can then restart the server by issuing any adb command. </p>

View File

@@ -0,0 +1,10 @@
<html>
<head>
<meta http-equiv="refresh" content="0;url=http://developer.android.com/sdk/eclipse-adt.html">
<title>Redirecting...</title>
</head>
<body>
<p>You should be redirected. Please <a
href="http://developer.android.com/sdk/eclipse-adt.html">click here</a>.</p>
</body>
</html>

View File

@@ -0,0 +1,305 @@
page.title=Designing a Remote Interface Using AIDL
@jd:body
<div id="qv-wrapper">
<div id="qv">
<h2>In this document</h2>
<ol>
<li><a href="#implementing">Implementing IPC Using AIDL</a>
<ol>
<li><a href="#aidlsyntax">Create an .aidl File</a></li>
<li><a href="#implementtheinterface">Implementing the Interface</a></li>
<li><a href="#exposingtheinterface">Exposing Your Interface to Clients</a></li>
<li><a href="#parcelable">Pass by value Parameters using Parcelables</a></li>
</ol>
</li>
<li><a href="#calling">Calling an IPC Method</a></li>
</ol>
</div>
</div>
<p>Since each application runs in its own process, and you can write a service that
runs in a different process from your Application's UI, sometimes you need to pass objects
between processes. On the Android platform, one process can not normally access the memory
of another process. So to talk, they need to decompose their objects into primitives that
the operating system can understand, and "marshall" the object across that boundary for you.</p>
<p>The code to do that marshalling is tedious to write, so we provide the AIDL tool to do it
for you.</p>
<p>AIDL (Android Interface Definition Language) is an <a
href="http://en.wikipedia.org/wiki/Interface_description_language">IDL</a>
language used to generate code that enables two processes on an Android-powered device
to talk using interprocess communication (IPC). If you have code
in one process (for example, in an Activity) that needs to call methods on an
object in another process (for example, a Service), you would use AIDL to
generate code to marshall the parameters.</p>
<p>The AIDL IPC mechanism
is interface-based, similar to COM or Corba, but lighter weight. It uses a proxy
class to pass values between the client and the implementation. </p>
<h2 id="implementing">Implementing IPC Using AIDL</h2>
<p>Follow these steps to implement an IPC service using AIDL.</p>
<ol>
<li><strong><a href="#aidlsyntax">Create your .aidl file</a> </strong>- This
file defines an interface (<em>YourInterface</em>.aidl) that defines the
methods and fields available to a client. </li>
<li><strong>Add the .aidl file to your makefile</strong> - (the ADT Plugin for Eclipse
manages this for you). Android includes the compiler, called
AIDL, in the <code>tools/</code> directory. </li>
<li><strong><a href="#implementtheinterface">Implement your interface methods</a></strong> -
The AIDL compiler creates an interface in the Java programming language from your AIDL interface.
This interface has an inner abstract class named Stub that inherits the
interface (and implements a few additional methods necessary for the IPC
call). You must create a class that extends <em>YourInterface</em>.Stub
and implements the methods you declared in your .aidl file. </li>
<li><strong><a href="#exposingtheinterface">Expose your interface to clients</a></strong> -
If you're writing a service, you should extend {@link
android.app.Service Service} and override {@link android.app.Service#onBind
Service.onBind(Intent)} to return an instance of your class that implements your
interface. </li>
</ol>
<h3 id="aidlsyntax">Create an .aidl File</h3>
<p>AIDL is a simple syntax that lets you declare an interface with one or more
methods, that can take parameters and return values. These parameters and return
values can be of any type, even other AIDL-generated interfaces. <em>However, it
is important to note</em> that you <em>must</em> import all non-built-in types,
<em>even if they are defined in the same package as your interface</em>.
Here are the data types that AIDL can support: </p>
<ul>
<li>Primitive Java programming language types (int, boolean, etc)
&mdash; No <code>import</code> statement is needed. </li>
<li>One of the following classes (no <code>import</code> statements needed):
<ul>
<li><strong>String</strong></li>
<li><strong>List</strong> - All elements in the List must be one of the types
in this list, including other AIDL-generated interfaces and
parcelables. List may optionally be used as a "generic" class (e.g.
List&lt;String&gt;).
The actual concrete class that the other side will receive
will always be an ArrayList, although the method will be generated
to use the List interface. </li>
<li><strong>Map</strong> - All elements in the Map must be of one of the
types in this list, including other AIDL-generated interfaces and
parcelables. Generic maps, (e.g. of the form Map&lt;String,Integer&gt;
are not supported.
The actual concrete class that the other side will receive
will always be a HashMap, although the method will be generated
to use the Map interface.</li>
<li><strong>CharSequence</strong> - This is useful for the CharSequence
types used by {@link android.widget.TextView TextView} and other
widget objects. </li>
</ul>
</li>
<li>Other AIDL-generated interfaces, which are always passed by reference.
An <code>import</code> statement is always needed for these.</li>
<li>Custom classes that implement the <a href="#parcelable">Parcelable
protocol</a> and are passed by value.
An <code>import</code> statement is always needed for these.</li>
</ul>
<p>Here is the basic AIDL syntax:</p>
<pre>// My AIDL file, named <em>SomeClass</em>.aidl
// Note that standard comment syntax is respected.
// Comments before the import or package statements are not bubbled up
// to the generated interface, but comments above interface/method/field
// declarations are added to the generated interface.
// Include your fully-qualified package statement.
package com.android.sample;
// See the list above for which classes need
// import statements (hint--most of them)
import com.android.sample.IAtmService;
// Declare the interface.
interface IBankAccountService {
// Methods can take 0 or more parameters, and
// return a value or void.
int getAccountBalance();
void setOwnerNames(in List&lt;String&gt; names);
// Methods can even take other AIDL-defined parameters.
BankAccount createAccount(in String name, int startingDeposit, in IAtmService atmService);
// All non-Java primitive parameters (e.g., int, bool, etc) require
// a directional tag indicating which way the data will go. Available
// values are in, out, inout. (Primitives are in by default, and cannot be otherwise).
// Limit the direction to what is truly needed, because marshalling parameters
// is expensive.
int getCustomerList(in String branch, out String[] customerList);
}</pre>
<h3 id="implementtheinterface">Implementing the Interface</h3>
<p>AIDL generates an interface file for you with the same name as your .aidl
file. If you are using the Eclipse plugin, AIDL will automatically be run as part of
the build process (you don't need to run AIDL first and then build your project).
If you are not using the plugin, you should run AIDL first. </p>
<p>The generated interface
includes an abstract inner class named Stub that declares all the methods
that you declared in your .aidl file. Stub also defines a few helper methods,
most notably asInterface(), which takes an IBinder (passed to a client's onServiceConnected()
implementation when applicationContext.bindService() succeeds), and returns an
instance of the interface used to call the IPC methods. See the section
<a href="#calling">Calling an IPC Method</a> for more details on how to make this cast.</p>
<p>To implement your interface, extend <em>YourInterface</em>.Stub,
and implement the methods. (You can create the .aidl file and implement the stub
methods without building between--the Android build process will process .aidl
files before .java files.) </p>
<p>Here is an example of implementing an interface called IRemoteService, which exposes
a single method, getPid(), using an anonymous instance:</p>
<pre>// No need to import IRemoteService if it's in the same project.
private final IRemoteService.Stub mBinder = new IRemoteService.Stub(){
public int getPid(){
return Process.myPid();
}
}</pre>
<p>A few rules about implementing your interface: </p>
<ul>
<li>No exceptions that you throw will be sent back to the caller.</li>
<li>By default, IPC calls are synchronous. If you know that an IPC service takes more than
a few milliseconds to complete, you should not call it in the Activity/View thread,
because it might hang the application (Android might display an &quot;Application
is Not Responding&quot; dialog).
Try to call them in a separate thread. </li>
<li>Only methods are supported; you cannot declare static fields in an AIDL interface.</li>
</ul>
<h3 id="exposingtheinterface">Exposing Your Interface to Clients</h3>
<p>Now that you've got your interface implementation, you need to expose it to clients.
This is known as &quot;publishing your service.&quot; To publish a service,
inherit {@link android.app.Service Service} and implement {@link android.app.Service#onBind
Service.onBind(Intent)} to return an instance of the class that implements your interface.
Here's a code snippet of a service that exposes the IRemoteService
interface to clients. </p>
<pre>public class RemoteService extends Service {
...
{@include development/samples/ApiDemos/src/com/example/android/apis/app/RemoteService.java
exposing_a_service}
}</pre>
<h3 id="parcelable">Pass by value Parameters using Parcelables</h3>
<p>If you have a class that you would like to send from one process to another through
an AIDL interface, you can do that. You must ensure that the code for your class is available
to the other side of the IPC. Generally, that means that you're talking to a service that you
started.</p>
<p>There are five parts to making a class support the Parcelable protocol:</b>
<ol>
<li>Make your class implement the {@link android.os.Parcelable} interface.</li>
<li>Implement the method <code>public void writeToParcel(Parcel out)</code> that takes the
current state of the object and writes it to a parcel.</li>
value in a parcel into your object.</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>Last but not least, create an aidl file
that declares your parcelable class (as shown below). If you are using a custom build process,
do not add the aidl file to your build. Similar to a header file in C, the aidl file isn't
compiled.</li>
</ol>
<p>AIDL will use these methods and fields in the code it generates to marshall and unmarshall
your objects.</p>
<p>Here is an example of how the {@link android.graphics.Rect} class implements the
Parcelable protocol.</p>
<pre class="prettyprint">
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&lt;Rect&gt; CREATOR = new Parcelable.Creator&lt;Rect&gt;() {
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>Here is Rect.aidl for this example</p>
<pre class="prettyprint">
package android.graphics;
// Declare Rect so AIDL can find it and knows that it implements
// the parcelable protocol.
parcelable Rect;
</pre>
<p>The marshalling in the 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"><b>Warning:</b> Don't forget the security implications of receiving data from
other processes. In this case, the rect will read four numbers from the parcel,
but it is up to you to ensure that these are within the acceptable range of
values for whatever the caller is trying to do. See
<a href="{@docRoot}guide/topics/security/security.html">Security and Permissions</a> for more
on how to keep your application secure from malware.</p>
<h2 id="calling">Calling an IPC Method</h2>
<p>Here are the steps a calling class should make to call your remote interface: </p>
<ol>
<li>Declare a variable of the interface type that your .aidl file defined. </li>
<li>Implement {@link android.content.ServiceConnection ServiceConnection}. </li>
<li>Call {@link android.content.Context#bindService(android.content.Intent,android.content.ServiceConnection,int)
Context.bindService()}, passing in your ServiceConnection implementation. </li>
<li>In your implementation of {@link android.content.ServiceConnection#onServiceConnected(android.content.ComponentName,android.os.IBinder)
ServiceConnection.onServiceConnected()}, you will receive an {@link android.os.IBinder
IBinder} instance (called <em>service</em>). Call <code><em>YourInterfaceName</em>.Stub.asInterface((IBinder)<em>service</em>)</code> to
cast the returned parameter to <em>YourInterface</em> type.</li>
<li>Call the methods that you defined on your interface. You should always trap
{@link android.os.DeadObjectException} exceptions, which are thrown when
the connection has broken; this will be the only exception thrown by remote
methods.</li>
<li>To disconnect, call {@link android.content.Context#unbindService(android.content.ServiceConnection)
Context.unbindService()} with the instance of your interface. </li>
</ol>
<p>A few comments on calling an IPC service:</p>
<ul>
<li>Objects are reference counted across processes. </li>
<li>You can send anonymous objects
as method arguments. </li>
</ul>
<p>Here is some sample code demonstrating calling an AIDL-created service, taken
from the Remote Service sample in the ApiDemos project.</p>
<p>{@sample development/samples/ApiDemos/src/com/example/android/apis/app/RemoteService.java
calling_a_service}</p>

View File

@@ -0,0 +1,447 @@
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.&nbsp;&nbsp;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.&nbsp;&nbsp;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.&nbsp;&nbsp;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 &gt; 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 &mdash; 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>&lt;AVD name&gt;.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\&lt;user&gt;\.android\</code> on Windows XP, and
<code>C:\Users\&lt;user&gt;\.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 &lt;path&gt;</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 &lt;name&gt; [-&lt;option&gt; &lt;value&gt;] ...</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 &lt;name&gt; </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 &lt;name&gt; -t &lt;targetID&gt; [-&lt;option&gt; &lt;value&gt;] ...
</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&nbsp;avds</code></td>
<td>&nbsp;</td>
<td>List all known AVDs, with name, path, target, and skin. </td>
<td>&nbsp;</td>
</tr>
<tr>
<td rowspan="6"><code>create&nbsp;avd</code></td>
<td><code>-n &lt;name&gt; or <br></code></td>
<td>The name for the AVD.</td>
<td>Required</td>
</tr>
<tr>
<td><code>-t &lt;targetID&gt;</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 &lt;path&gt;</code> or <br>
<code>-c &lt;size&gt;[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 &lt;path&gt;</code></td>
<td>Path to the location at which to create the directory for this AVD's
files.</td>
<td>&nbsp;</td>
</tr>
<tr>
<td><code>-s &lt;name&gt;</code> or <br>
<code>-s &lt;width&gt;-&lt;height&gt;</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
&lt;targetID&gt;</code> argument. Example: <code>-s HVGA-L</code></td>
</tr>
<tr>
<td><code>delete&nbsp;avd</code></td>
<td><code>-n &lt;name&gt;</code></td>
<td>Delete the specified AVD.</td>
<td>Required</td>
</tr>
<tr>
<td rowspan="3"><code>move&nbsp;avd</code></td>
<td><code>-n &lt;name&gt;</code></td>
<td>The name of the AVD to move.</td>
<td>Required</td>
</tr>
<tr>
<td><code>-p &lt;path&gt;</code></td>
<td>The path to the new location for the AVD.</td>
<td>&nbsp;</td>
</tr>
<tr>
<td><code>-r &lt;new-name&gt;</code></td>
<td>Rename the AVD.</td>
<td>&nbsp;</td>
</tr>
<tr>
<td><code>update&nbsp;avds</code></td>
<td>&nbsp;</td>
<td>Recompute the paths to all system images.</td>
<td>&nbsp;</td>
</tr>
</table>

View File

@@ -0,0 +1,191 @@
page.title=bmgr
@jd:body
<!-- quickview box content here -->
<div id="qv-wrapper">
<div id="qv">
<h2>bmgr quickview</h2>
<p><code>bmgr</code> lets you control the backup/restore system on an Android device.
<h2>In this document</h2>
<ol>
<li><a href="#backup">Forcing a Backup Operation</a></li>
<li><a href="#restore">Forcing a Restore Operation</a></li>
<li><a href="#other">Other Commands</a></li>
</ol>
<h2>See also</h2>
<ol>
<li><a href="{@docRoot}guide/topics/data/backup.html">Data Backup</a></li>
</ol>
</div>
</div>
<!-- normal page content here -->
<p><code>bmgr</code> is a shell tool you can use to interact with the Backup Manager
on Android devices supporting API Level 8 or greater. It provides commands to induce backup
and restore operations so that you don't need to repeatedly wipe data or take similar
intrusive steps in order to test your application's backup agent. These commands are
accessed via the <a href="{@docRoot}guide/developing/tools/adb.html">adb</a> shell.
<p>For information about adding support for backup in your application, read <a
href="{@docRoot}guide/topics/data/backup.html">Data Backup</a>, which includes a guide to testing
your application using {@code bmgr}.</p>
<h2 id="backup">Forcing a Backup Operation</h2>
<p>Normally, your application must notify the Backup Manager when its data has changed, via {@link
android.app.backup.BackupManager#dataChanged()}. The Backup Manager will then invoke your
backup agent's {@link
android.app.backup.BackupAgent#onBackup(ParcelFileDescriptor,BackupDataOutput,ParcelFileDescriptor)
onBackup()} implementation at some time in the future. However, instead of calling {@link
android.app.backup.BackupManager#dataChanged()}, you can invoke a backup request from the command
line by running the <code>bmgr backup</code> command:
<pre class="no-pretty-print">adb shell bmgr backup <em>&lt;package&gt;</em></pre>
<p><code><em>&lt;package&gt;</em></code> is the formal package name of the application you wish to
schedule for
backup. When you execute this backup command, your application's backup agent will be invoked to
perform a backup operation at some time in the future (via your {@link
android.app.backup.BackupAgent#onBackup(ParcelFileDescriptor,BackupDataOutput,ParcelFileDescriptor)
onBackup()} method), though there is no guarantee when it will occur. However, you can force all
pending backup operations to run immediately by using the <code>bmgr run</code> command:
<pre class="no-pretty-print">adb shell bmgr run</pre>
<p>This causes a backup pass to execute immediately, invoking the backup agents of all applications
that had previously called {@link android.app.backup.BackupManager#dataChanged()} since the
last backup operation, plus any applications which had been manually scheduled for
backup via <code>bmgr backup</code>.
<h2 id="restore">Forcing a Restore Operation</h2>
<p>Unlike backup operations, which are batched together and run on an occasional basis, restore
operations execute immediately. The Backup Manager currently provides two kinds of restore
operations. The first kind restores an entire device with the data that has been backed up. This
is typically performed only when a device is first provisioned (to replicate settings and other
saved state from the user's previous device) and is an operation that only the system can
perform. The second kind of restore operation restores
a single application to its "active" data set; that is, the application will abandon its current
data and revert to the last-known-good data that is held in the current backup image. You can
invoke this second restore operation with the {@link
android.app.backup.BackupManager#requestRestore(RestoreObserver) requestRestore()} method. The
Backup Manager will then invoke your backup agent's {@link
android.app.backup.BackupAgent#onRestore(BackupDataInput,int,ParcelFileDescriptor)
onRestore()} implementation.
<p>While testing your application, you can immediately invoke the restore operation (bypassing the
{@link android.app.backup.BackupManager#requestRestore(RestoreObserver) requestRestore()} method)
for your application by using the <code>bmgr restore</code> command:
<pre class="no-pretty-print">adb shell bmgr restore <em>&lt;package&gt;</em></pre>
<p><code><em>&lt;package&gt;</em></code> is the formal Java-style package name of the application
participating in the backup/restore mechanism, which you would like to restore. The Backup
Manager will immediately instantiate the application's backup agent and invoke it for restore. This
will happen even if your application is not currently running.
<h2 id="other">Other Commands</h2>
<h3>Wiping data</h3>
<p>The data for a single application can be erased from the active data set on demand. This is
very useful while you're developing a backup agent, in case bugs lead you to write corrupt data
or saved state information. You can wipe an application's data with the <code>bmgr wipe</code>
command:
<pre class="no-pretty-print">adb shell bmgr wipe <em>&lt;package&gt;</em></pre>
<p><code><em>&lt;package&gt;</em></code> is the formal package name of the application whose data
you wish to
erase. The next backup operation that the application's agent processes will look as
though the application had never backed anything up before.
<h3>Enabling and disabling backup</h3>
<p>You can see whether the Backup Manager is operational at all with the <code>bmgr
enabled</code> command:
<pre class="no-pretty-print">adb shell bmgr enabled</pre>
<p>This might be useful if your application's backup agent is never being invoked for backup, to
verify whether the operating system thinks it should be performing such operations at all.</p>
<p>You can also directly disable or enable the Backup Manager with this command:
<pre class="no-pretty-print">adb shell bmgr enable <em>&lt;boolean&gt;</em></pre>
<p><code><em>&lt;boolean&gt;</em></code> is either <code>true</code> or <code>false</code>.
This is equivalent to disabling or enabling backup in the device's main Settings UI.</p>
<p class="warning"><strong>Warning!</strong> When backup is disabled, the current backup transport
will explicitly wipe
the entire active data set from its backend storage. This is so that when a user says
they do <em>not</em> want their data backed up, the Backup Manager respects that wish. No further
data will be saved from the device, and no restore operations will be possible, unless the Backup
Manager is re-enabled (either through Settings or through the above <code>bmgr</code> command).
<!-- The following is not useful to applications, but may be some useful information some day...
<h2 id="transports">Applying a Backup Transport</h2>
<p>A "backup transport" is the code module responsible for moving backup and restore data
to and from some storage location. A device can have multipe transports installed, though only
one is active at any given time. Transports are identified by name. You can see what
transports are available on your device or emulator by running the
<code>bmgr list transports</code> command:
<pre class="no-pretty-print">adb shell bmgr list transports</pre>
<p>The output of this command is a list of the transports available on the device. The currently
active transport is flagged with a <code>*</code> character. Transport names may look like
component names (for example, <code>android/com.android.internal.backup.LocalTransport</code>),
but they need not be, and the strings are never used as direct class references. The use of
a component-like naming scheme is simply for purposes of preventing name collisions.
<p>You can change which transport is currently active from the command line as well:
<pre class="no-pretty-print">adb shell bmgr transport <em>&lt;name&gt;</em></pre>
<p><code><em>&lt;name&gt;</em></code> is one of the names as printed by the <code>bmgr list
transports</code>
command. From this point forward, backup and restore operations will be directed through the
newly-selected transport. Backup state tracking is managed separately for each transport, so
switching back and forth between them will not corrupt the saved state.
<h2 id="restoresets">Viewing Restore Sets</h2>
<p>All of the application data that a device has written to its backup transport is tracked
as a group that is collectively called a "restore set," because each data set is
most often manipulated during a restore operation. When a device is provisioned for the first
time, a new restore set is established. You can get a listing of all the restore sets available to
the current transport by running the <code>bmgr list sets</code> command:
<pre class="no-pretty-print">adb shell bmgr list sets</pre>
<p>The output is a listing of available restore sets, one per line. The first item on each line is
a token (a hexadecimal value that identifies the restore set to the transport). Following
the token is a string that briefly identifies the restore set.
Only the token is used within the backup and restore mechanism.
-->

View File

@@ -0,0 +1,251 @@
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 &quot;$HOME/.ddmsrc&quot;. </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 &quot;debugger pass-through&quot; 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 &quot;threads&quot; 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 &quot;jiffies&quot; (usually
10ms). </li>
<li> <strong>stime</strong> - cumulative time spent executing system code, in &quot;jiffies&quot; (usually
10ms). </li>
<li> <strong>Name</strong> - the name of the thread</li>
</ul>
<p> &quot;ID&quot; and &quot;Name&quot; 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>&lt;wpt></code>, in the first table),
and the tracks (<code>&lt;trk></code>,
in the second table, with support for multiple segments, <code>&lt;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>&lt;coordinates&gt;</code>
element. The value of which should be a single
set of longitude, latitude and altitude figures. For example:</p>
<pre>&lt;coordinates>-122.084143,37.421972,4&lt;/coordinates></pre>
<p>In your file, you may include multiple <code>&lt;Placemark></code> elements, each containing
a <code>&lt;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>&lt;MultiGeometry>&lt;LineString>lat1, long1, lat2, long2, ....&lt;/LineString>&lt;/MultiGeometry></code> methods.
There is also currently no support for the <code>&lt;TimeStamp></code> node inside
the <code>&lt;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>
&gt; <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>
&gt; <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> &gt;
<strong>Run logcat...</strong> in the menu bar.</li>
<li>To run <strong>dumpstate</strong> from Dalvik, select <strong>Device</strong> &gt; <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> &gt; <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> &gt; <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>

View File

@@ -0,0 +1,57 @@
page.title=Draw 9-patch
@jd:body
<p>The Draw 9-patch tool allows you to easily create a
{@link android.graphics.NinePatch} graphic using a WYSIWYG editor.</p>
<p>For an introduction to Nine-patch graphics and how they work, please read
the section about Nine-patch in the
<a href="{@docRoot}guide/topics/graphics/2d-graphics.html#nine-patch">2D Graphics</a>
document.</p>
<img src="{@docRoot}images/draw9patch-norm.png" style="float:right" alt="" height="300" width="341"
/>
<p>Here's a quick guide to create a Nine-patch graphic using the Draw 9-patch tool.
You'll need the PNG image with which you'd like to create a NinePatch.</p>
<ol>
<li>From a terminal, launch the <code>draw9patch</code> application from your SDK
<code>/tools</code> directory.
</li>
<li>Drag your PNG image into the Draw 9-patch window
(or <strong>File</strong> > <strong>Open 9-patch...</strong> to locate the file).
Your workspace will now open.
<p>The left pane is your drawing area, in which you can edit the lines for the
stretchable patches and content area. The right
pane is the preview area, where you can preview your graphic when stretched.</p>
</li>
<li>Click within the 1-pixel perimeter to draw the lines that define the stretchable
patches and (optional) content area. Right-click (or hold Shift and click, on Mac) to erase
previously drawn lines.
</li>
<li>When done, select <strong>File</strong> > <strong>Save 9-patch...</strong>
<p>Your image will be saved with the <code>.9.png</code> file name.</p>
</li>
</ol>
<p class="note"><strong>Note:</strong> A normal PNG file (<code>*.png</code>) will be
loaded with an empty one-pixel border added around the image, in which you can draw
the stretchable patches and content area.
A previously saved 9-patch file (<code>*.9.png</code>) will be loaded as-is,
with no drawing area added, because it already exists.</p>
<img src="{@docRoot}images/draw9patch-bad.png" style="float:right" alt="" height="300" width="341"
/>
<p>Optional controls include:</p>
<ul>
<li><strong>Zoom</strong>: Adjust the zoom level of the graphic in the drawing area.</li>
<li><strong>Patch scale</strong>: Adjust the scale of the images in the preview area.</li>
<li><strong>Show lock</strong>: Visualize the non-drawable area of the graphic on mouse-over.</li>
<li><strong>Show patches</strong>: Preview the stretchable patches in the drawing area (pink is a
stretchable patch).</li>
<li><strong>Show content</strong>: Highlight the content area in the preview images
(purple is the area in which content is allowed).</li>
<li><strong>Show bad patches</strong>: Adds a red border around patch areas that may
produce artifacts in the graphic when stretched. Visual coherence of your stretched
image will be maintained if you eliminate all bad patches.</li>
<ul>

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,98 @@
page.title=Hierarchy Viewer
@jd:body
<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>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>&lt;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>
<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>

View File

@@ -0,0 +1,109 @@
page.title=Tools Overview
@jd:body
<img src="{@docRoot}assets/images/android_wrench.png" alt="" align="right">
<p>The Android SDK includes a variety of custom tools that help you develop mobile
applications on the Android platform. The most important of these are the Android
Emulator and the Android Development Tools plugin for Eclipse, but the SDK also
includes a variety of other tools for debugging, packaging, and installing your
applications on the emulator. </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="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="layoutopt.html">layoutopt</a></dt>
<dd>This tool lets you quickly analyze your application's layouts 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 &lt;sdk&gt;/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="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
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>

View File

@@ -0,0 +1,62 @@
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
&lt;resources&gt;</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 &lt;FrameLayout/&gt; can be replaced with &lt;merge/&gt;
11:21 This LinearLayout layout or its FrameLayout parent is useless
samples/simple.xml
7:7 The root-level &lt;FrameLayout/&gt; can be replaced with &lt;merge/&gt;
samples/too_deep.xml
-1:-1 This layout has too many nested layouts: 13 levels, it should have &lt= 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 &lt;FrameLayout/&gt; can be replaced with &lt;merge/&gt;
-1:-1 This layout has too many views: 81 views, it should have &lt= 80!
samples/useless.xml
7:19 The root-level &lt;FrameLayout/&gt; can be replaced with &lt;merge/&gt;
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>
<h3>Usage</h3>
<p>To run <code>layoutopt</code> against a given list of layout resources:</p>
<pre>layoutopt &lt;list of xml files or directories></pre>
<p>For example:</p>
<pre>$ layoutopt res/layout-land</pre>
<pre>$ layoutopt res/layout/main.xml res/layout-land/main.xml</pre>

View File

@@ -0,0 +1,240 @@
page.title=UI/Application Exerciser Monkey
@jd:body
<p>The Monkey is a program that runs on your
<a href="{@docRoot}guide/developing/tools/emulator.html">emulator</a> 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.</p>
<a name="overview"></a>
<h2>Overview</h2>
<p>The Monkey is a command-line tool that that you can run on any emulator
instance or on a device. It sends a pseudo-random stream of
user events into the system, which acts as a stress test on the application software you are
developing.</p>
<p>The Monkey includes a number of options, but they break down into four primary
categories:</p>
<ul>
<li>Basic configuration options, such as setting the number of events to attempt.</li>
<li>Operational constraints, such as restricting the test to a single package.</li>
<li>Event types and frequencies.</li>
<li>Debugging options.</li>
</ul>
<p>When the Monkey runs, it generates events and sends them to the system. It also <i>watches</i>
the system under test and looks for three conditions, which it treats specially:</p>
<ul>
<li>If you have constrained the Monkey to run in one or more specific packages, it
watches for attempts to navigate to any other packages, and blocks them.</li>
<li>If your application crashes or receives any sort of unhandled exception, the Monkey
will stop and report the error.</li>
<li>If your application generates an <i>application not responding</i> error, the Monkey
will stop and report the error.</li>
</ul>
<p>Depending on the verbosity level you have selected, you will also see reports on the progress
of the Monkey and the events being generated.</p>
<a name="basics"></a>
<h2>Basic Use of the Monkey</h2>
<p>You can launch the Monkey using a command line on your development machine or from a script.
Because the Monkey runs in the emulator/device environment, you must launch it from a shell in
that environment. You can do this by prefacing <code>adb shell</code> to each command,
or by entering the shell and entering Monkey commands directly.</p>
<p>The basic syntax is: </p>
<pre>$ adb shell monkey [options] &lt;event-count&gt;</pre>
<p>With no options specified, the Monkey will launch in a quiet (non-verbose) mode, and will send
events to any (and all) packages installed on your target. Here is a more typical command line,
which will launch your application and send 500 pseudo-random events to it:</p>
<pre>$ adb shell monkey -p your.package.name -v 500</pre>
<a name="reference"></a>
<h2>Command Options Reference</h2>
<p>The table below lists all options you can include on the Monkey command line.</p>
<table>
<tr>
<th>Category</th>
<th>Option</th>
<th>Description</th>
</tr>
<tr>
<td rowspan="2">General</td>
<td><code>--help</code></td>
<td>Prints a simple usage guide.</td>
</tr>
<tr>
<td><code>-v</code></td>
<td>Each -v on the command line will increment the verbosity level.
Level 0 (the default) provides little information beyond startup notification, test completion, and
final results.
Level 1 provides more details about the test as it runs, such as individual events being sent to
your activities.
Level 2 provides more detailed setup information such as activities selected or not selected for
testing.</td>
</tr>
<tr>
<td rowspan="10">Events</td>
<td><code>-s &lt;seed&gt;</code></td>
<td>Seed value for pseudo-random number generator. If you re-run the Monkey with the same seed
value, it will generate the same sequence of events.</td>
</tr>
<tr>
<td><code>--throttle &lt;milliseconds&gt;</code></td>
<td>Inserts a fixed delay between events. You can use this option to slow down the Monkey.
If not specified, there is no delay and the events are generated as rapidly as possible.</td>
</tr>
<tr>
<td><code>--pct-touch &lt;percent&gt;</code></td>
<td>Adjust percentage of touch events.
(Touch events are a down-up event in a single place on the screen.)</td>
</tr>
<tr>
<td><code>--pct-motion &lt;percent&gt;</code></td>
<td>Adjust percentage of motion events.
(Motion events consist of a down event somewhere on the screen, a series of pseudo-random
movements, and an up event.)</td>
</tr>
<tr>
<td><code>--pct-trackball &lt;percent&gt;</code></td>
<td>Adjust percentage of trackball events.
(Trackball events consist of one or more random movements, sometimes followed by a click.)</td>
</tr>
<tr>
<td><code>--pct-nav &lt;percent&gt;</code></td>
<td>Adjust percentage of "basic" navigation events.
(Navigation events consist of up/down/left/right, as input from a directional input device.)</td>
</tr>
<tr>
<td><code>--pct-majornav &lt;percent&gt;</code></td>
<td>Adjust percentage of "major" navigation events.
(These are navigation events that will typically cause actions within your UI, such as
the center button in a 5-way pad, the back key, or the menu key.)</td>
</tr>
<tr>
<td><code>--pct-syskeys &lt;percent&gt;</code></td>
<td>Adjust percentage of "system" key events.
(These are keys that are generally reserved for use by the system, such as Home, Back, Start Call,
End Call, or Volume controls.)</td>
</tr>
<tr>
<td><code>--pct-appswitch &lt;percent&gt;</code></td>
<td>Adjust percentage of activity launches. At random intervals, the Monkey will issue a startActivity() call, as a way of maximizing
coverage of all activities within your package.</td>
</tr>
<tr>
<td><code>--pct-anyevent &lt;percent&gt;</code></td>
<td>Adjust percentage of other types of events. This is a catch-all for all other types of events such as keypresses, other less-used
buttons on the device, and so forth.</td>
</tr>
<tr>
<td rowspan="2">Constraints</td>
<td><code>-p &lt;allowed-package-name&gt;</code></td>
<td>If you specify one or more packages this way, the Monkey will <i>only</i> allow the system
to visit activities within those packages. If your application requires access to activities in
other packages (e.g. to select a contact) you'll need to specify those packages as well.
If you don't specify any packages, the Monkey will allow the system to launch activities
in all packages. To specify multiple packages, use the -p option multiple times &mdash; one -p
option per package.</td>
</tr>
<tr>
<td><code>-c &lt;main-category&gt;</code></td>
<td>If you specify one or more categories this way, the Monkey will <i>only</i> allow the
system to visit activities that are listed with one of the specified categories.
If you don't specify any categories, the Monkey will select activities listed with the category
Intent.CATEGORY_LAUNCHER or Intent.CATEGORY_MONKEY. To specify multiple categories, use the -c
option multiple times &mdash; one -c option per category.</td>
</tr>
<tr>
<td rowspan="8">Debugging</td>
<td><code>--dbg-no-events</code></td>
<td>When specified, the Monkey will perform the initial launch into a test activity, but
will not generate any further events.
For best results, combine with -v, one or more package constraints, and a non-zero throttle to keep the Monkey
running for 30 seconds or more. This provides an environment in which you can monitor package
transitions invoked by your application.</td>
</tr>
<tr>
<td><code>--hprof</code></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
on trace files.</td>
</tr>
<tr>
<td><code>--ignore-crashes</code></td>
<td>Normally, the Monkey will stop when the application crashes or experiences any type of
unhandled exception. If you specify this option, the Monkey will continue to send events to
the system, until the count is completed.</td>
</tr>
<tr>
<td><code>--ignore-timeouts</code></td>
<td>Normally, the Monkey will stop when the application experiences any type of timeout error such
as a "Application Not Responding" dialog. If you specify this option, the Monkey will continue to
send events to the system, until the count is completed.</td>
</tr>
<tr>
<td><code>--ignore-security-exceptions</code></td>
<td>Normally, the Monkey will stop when the application experiences any type of permissions error,
for example if it attempts to launch an activity that requires certain permissions. If you specify
this option, the Monkey will continue to send events to the system, until the count is
completed.</td>
</tr>
<tr>
<td><code>--kill-process-after-error</code></td>
<td>Normally, when the Monkey stops due to an error, the application that failed will be left
running. When this option is set, it will signal the system to stop the process in which the error
occurred.
Note, under a normal (successful) completion, the launched process(es) are not stopped, and
the device is simply left in the last state after the final event.</td>
</tr>
<tr>
<td><code>--monitor-native-crashes</code></td>
<td>Watches for and reports crashes occurring in the Android system native code. If --kill-process-after-error is set, the system will stop.</td>
</tr>
<tr>
<td><code>--wait-dbg</code></td>
<td>Stops the Monkey from executing until a debugger is attached to it.</td>
</tr>
</table>
<!-- TODO: add a section called "debugging" that covers ways to use it,
need to clear data, use of the seed, etc. -->
<!-- TODO: add a section that lays down a contract for Monkey output so it can be
scripted safely. -->

View File

@@ -0,0 +1,308 @@
page.title=monkeyrunner
@jd:body
<div id="qv-wrapper">
<div id="qv">
<h2>In this document</h2>
<ol>
<li>
<a href="#SampleProgram">A Simple monkeyrunner Program</a>
</li>
<li>
<a href="#APIClasses">The monkeyrunner API</a>
</li>
<li>
<a href="#RunningMonkeyRunner">Running monkeyrunner</a>
</li>
<li>
<a href="#Help">monkeyrunner Built-in Help</a>
</li>
<li>
<a href="#Plugins">Extending monkeyrunner with Plugins</a>
</li>
</ol>
<h2>See Also</h2>
<ol>
<li>
<a href="{@docRoot}guide/topics/testing/testing_android.html">Testing Fundamentals</a>
</li>
</ol>
</div>
</div>
<p>
The monkeyrunner tool provides an API for writing programs that control an Android device
or emulator from outside of Android code. With monkeyrunner, you can write a Python program
that installs an Android application or test package, runs it, sends keystrokes to it,
takes screenshots of its user interface, and stores screenshots on the workstation. The
monkeyrunner tool is primarily designed to test applications and devices at the
functional/framework level and for running unit test suites, but you are free to use it for
other purposes.
</p>
<p>
The monkeyrunner tool is not related to the
<a href="{@docRoot}guide/developing/tools/monkey.html">UI/Application Exerciser Monkey</a>,
also known as the <code>monkey</code> tool. The <code>monkey</code> tool runs in an
<code><a href="{@docRoot}guide/developing/tools/adb.html">adb</a></code> shell directly on the
device or emulator and generates pseudo-random streams of user and system events. In comparison,
the monkeyrunner tool controls devices and emulators from a workstation by sending specific
commands and events from an API.
</p>
<p>
The monkeyrunner tool provides these unique features for Android testing:
</p>
<ul>
<li>
Multiple device control: The monkeyrunner API can apply one or more
test suites across multiple devices or emulators. You can physically attach all the devices
or start up all the emulators (or both) at once, connect to each one in turn
programmatically, and then run one or more tests. You can also start up an emulator
configuration programmatically, run one or more tests, and then shut down the emulator.
</li>
<li>
Functional testing: monkeyrunner can run an automated start-to-finish test of an Android
application. You provide input values with keystrokes or touch events, and view the results
as screenshots.
</li>
<li>
Regression testing - monkeyrunner can test application stability by running an application
and comparing its output screenshots to a set of screenshots that are known to be correct.
</li>
<li>
Extensible automation - Since monkeyrunner is an API toolkit, you can develop an entire
system of Python-based modules and programs for controlling Android devices. Besides using
the monkeyrunner API itself, you can use the standard Python
<code><a href="http://docs.python.org/library/os.html">os</a></code> and
<code><a href="http://docs.python.org/library/subprocess.html">subprocess</a></code>
modules to call Android tools such as
<a href="{@docRoot}guide/developing/tools/adb.html">Android Debug Bridge</a>.
<p>
You can also add your own classes to the monkeyrunner API. This is described
in more detail in the section
<a href="#Plugins">Extending monkeyrunner with plugins</a>.
</p>
</li>
</ul>
<p>
The monkeyrunner tool uses <a href="http://www.jython.org/">Jython</a>, a
implementation of Python that uses the Java programming language. Jython allows the
monkeyrunner API to interact easily with the Android framework. With Jython you can
use Python syntax to access the constants, classes, and methods of the API.
</p>
<h2 id="SampleProgram">A Simple monkeyrunner Program</h2>
<p>
Here is a simple monkeyrunner program that connects to a device, creating a
<code><a href="{@docRoot}guide/developing/tools/MonkeyDevice.html">MonkeyDevice</a></code>
object. Using the <code>MonkeyDevice</code> object, the program installs an Android application
package, runs one of its activities, and sends key events to the activity.
The program then takes a screenshot of the result, creating a
<code><a href="{@docRoot}guide/developing/tools/MonkeyImage.html">MonkeyImage</a></code> object.
From this object, the program writes out a <code>.png</code> file containing the screenshot.
</p>
<pre>
# Imports the monkeyrunner modules used by this program
from com.android.monkeyrunner import MonkeyRunner, MonkeyDevice
# Connects to the current device, returning a MonkeyDevice object
device = MonkeyRunner.waitForConnection()
# Installs the Android package. Notice that this method returns a boolean, so you can test
# to see if the installation worked.
device.installPackage('myproject/bin/MyApplication.apk')
# Runs an activity in the application
device.startActivity(component='com.example.android.myapplication.MainActivity')
# Presses the Menu button
device.press('KEYCODE_MENU','DOWN_AND_UP')
# Takes a screenshot
result = device.takeSnapShot
# Writes the screenshot to a file
result.writeToFile('myproject/shot1.png','png')
</pre>
<h2 id="APIClasses">The monkeyrunner API</h2>
<p>
The monkeyrunner API is contained in three modules in the package
<code>com.android.monkeyrunner</code>:
</p>
<ul>
<li>
<code><a href="{@docRoot}guide/developing/tools/MonkeyRunner.html">MonkeyRunner</a></code>:
A class of utility methods for monkeyrunner programs. This class provides a method for
connecting monkeyrunner to a device or emulator. It also provides methods for
creating UIs for a monkeyrunner program and for displaying the built-in help.
</li>
<li>
<code><a href="{@docRoot}guide/developing/tools/MonkeyDevice.html">MonkeyDevice</a></code>:
Represents a device or emulator. This class provides methods for installing and
uninstalling packages, starting an Activity, and sending keyboard or touch events to an
application. You also use this class to run test packages.
</li>
<li>
<code><a href="{@docRoot}guide/developing/tools/MonkeyImage.html">MonkeyImage</a></code>:
Represents a screen capture image. This class provides methods for capturing screens,
converting bitmap images to various formats, comparing two MonkeyImage objects, and
writing an image to a file.
</li>
</ul>
<p>
In a Python program, you access each class as a Python module. The monkeyrunner tool
does not import these modules automatically. To import a module, use the
Python <code>from</code> statement:
</p>
<pre>
from com.android.monkeyrunner import &lt;module&gt;
</pre>
<p>
where <code>&lt;module&gt;</code> is the class name you want to import. You can import more
than one module in the same <code>from</code> statement by separating the module names with
commas.
</p>
<h2 id="RunningMonkeyRunner">Running monkeyrunner</h2>
<p>
You can either run monkeyrunner programs from a file, or enter monkeyrunner statements in
an interactive session. You do both by invoking the <code>monkeyrunner</code> command
which is found in the <code>tools/</code> subdirectory of your SDK directory.
If you provide a filename as an argument, the <code>monkeyrunner</code> command
runs the file's contents as a Python program; otherwise, it starts an interactive session.
</p>
<p>
The syntax of the <code>monkeyrunner</code> command is
</p>
<pre>
monkeyrunner -plugin &lt;plugin_jar&gt; &lt;program_filename&gt; &lt;program_options&gt;
</pre>
<p>
Table 1 explains the flags and arguments.
</p>
<p class="table-caption" id="table1">
<strong>Table 1.</strong> <code>monkeyrunner</code> flags and arguments.</p>
<table>
<tr>
<th>Argument</th>
<th>Description</th>
</tr>
<tr>
<td>
<nobr>
<code>-plugin &lt;plugin_jar&gt;</code>
</nobr>
</td>
<td>
(Optional) Specifies a <code>.jar</code> file containing a plugin for monkeyrunner.
To learn more about monkeyrunner plugins, see
<a href="#Plugins">Extending monkeyrunner with plugins</a>. To specify more than one
file, include the argument multiple times.
</td>
</tr>
<tr>
<td>
<nobr>
<code>&lt;program_filename&gt;</code>
</nobr>
</td>
<td>
If you provide this argument, the <code>monkeyrunner</code> command runs the contents
of the file as a Python program. If the argument is not provided, the command starts an
interactive session.
</td>
</tr>
<tr>
<td>
<code>&lt;program_options&gt;</code>
</td>
<td>
(Optional) Flags and arguments for the program in &lt;program_file&gt;.
</td>
</tr>
</table>
<h2 id="Help">monkeyrunner Built-in Help</h2>
<p>
You can generate an API reference for monkeyrunner by running:
</p>
<pre>
monkeyrunner &lt;format&gt; help.py &lt;outfile&gt;
</pre>
<p>
The arguments are:
</p>
<ul>
<li>
<code>&lt;format&gt;</code> is either <code>text</code> for plain text output
or <code>html</code> for HTML output.
</li>
<li>
<code>&lt;outfile&gt;</code> is a path-qualified name for the output file.
</li>
</ul>
<h2 id="Plugins">Extending monkeyrunner with Plugins</h2>
<p>
You can extend the monkeyrunner API with classes you write in the Java programming language
and build into one or more <code>.jar</code> files. You can use this feature to extend the
monkeyrunner API with your own classes or to extend the existing classes. You can also use this
feature to initialize the monkeyrunner environment.
</p>
<p>
To provide a plugin to monkeyrunner, invoke the <code>monkeyrunner</code> command with the
<code>-plugin &lt;plugin_jar&gt;</code> argument described in
<a href="#table1">table 1</a>.
</p>
<p>
In your plugin code, you can import and extend the the main monkeyrunner classes
<code>MonkeyDevice</code>, <code>MonkeyImage</code>, and <code>MonkeyRunner</code> in
<code>com.android.monkeyrunner</code> (see <a href="#APIClasses">The monkeyrunner API</a>).
</p>
<p>
Note that plugins do not give you access to the Android SDK. You can't import packages
such as <code>com.android.app</code>. This is because monkeyrunner interacts with the
device or emulator below the level of the framework APIs.
</p>
<h3>The plugin startup class</h3>
<p>
The <code>.jar</code> file for a plugin can specify a class that is instantiated before
script processing starts. To specify this class, add the key
<code>MonkeyRunnerStartupRunner</code> to the <code>.jar</code> file's
manifest. The value should be the name of the class to run at startup. The following
snippet shows how you would do this within an <code>ant</code> build script:
</p>
<pre>
&lt;jar jarfile=&quot;myplugin&quot; basedir="&#36;&#123;build.dir&#125;&quot;&gt;
&lt;manifest&gt;
&lt;attribute name=&quot;MonkeyRunnerStartupRunner&quot; value=&quot;com.myapp.myplugin&quot;/&gt;
&lt;/manifest&gt;
&lt;/jar&gt;
</pre>
<p>
To get access to monkeyrunner's runtime environment, the startup class can implement
<code>com.google.common.base.Predicate&lt;PythonInterpreter&gt;</code>. For example, this
class sets up some variables in the default namespace:
</p>
<pre>
package com.android.example;
import com.google.common.base.Predicate;
import org.python.util.PythonInterpreter;
public class Main implements Predicate&lt;PythonInterpreter&gt; {
&#64;Override
public boolean apply(PythonInterpreter anInterpreter) {
/*
* Examples of creating and initializing variables in the monkeyrunner environment's
* namespace. During execution, the monkeyrunner program can refer to the variables "newtest"
* and "use_emulator"
*
*/
anInterpreter.set("newtest", "enabled");
anInterpreter.set("use_emulator", 1);
return true;
}
}
</pre>

View File

@@ -0,0 +1,95 @@
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>&lt;sdk&gt;/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] &lt;size&gt;[K|M] &lt;file&gt;</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
&lt;size&gt;. 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 &lt;file&gt;</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>

View File

@@ -0,0 +1,187 @@
page.title=ProGuard
@jd:body
<div id="qv-wrapper">
<div id="qv">
<h2>In this document</h2>
<ol>
<li><a href="#enabling">Enabling ProGuard</a></li>
<li><a href="#configuring">Configuring ProGuard</a></li>
<li>
<a href="#decoding">Decoding Obfuscated Stack Traces</a>
<ol>
<li><a href="#considerations">Debugging considerations for published
applications</a></li>
</ol>
</li>
</ol>
<h2>See also</h2>
<ol>
<li><a href="http://proguard.sourceforge.net/manual/introduction.html">ProGuard
Manual</a></li>
<li><a href="http://proguard.sourceforge.net/manual/retrace/introduction.html">ProGuard
ReTrace Manual</a></li>
</ol>
</div>
</div>
<p>The ProGuard tool shrinks, optimizes, and obfuscates your code by removing unused code and
renaming classes, fields, and methods with semantically obscure names. The result is a smaller
sized <code>.apk</code> file that is more difficult to reverse engineer. Because ProGuard makes your
application harder to reverse engineer, it is important that you use it
when your application utilizes features that are sensitive to security like when you are
<a href="{@docRoot}guide/publishing/licensing.html">Licensing Your Applications</a>.</p>
<p>ProGuard is integrated into the Android build system, so you do not have to invoke it
manually. ProGuard runs only when you build your application in release mode, so you do not
have to deal with obfuscated code when you build your application in debug mode.
Having ProGuard run is completely optional, but highly recommended.</p>
<p>This document describes how to enable and configure ProGuard as well as use the
<code>retrace</code> tool to decode obfuscated stack traces.</p>
<h2 id="enabling">Enabling ProGuard</h2>
<p>When you create an Android project, a <code>proguard.cfg</code> file is automatically
generated in the root directory of the project. This file defines how ProGuard optimizes and
obfuscates your code, so it is very important that you understand how to customize it for your
needs. The default configuration file only covers general cases, so you most likely have to edit
it for your own needs. See the following section about <a href="#configuring">Configuring ProGuard</a> for information on
customizing the ProGuard configuration file.</p>
<p>To enable ProGuard so that it runs as part of an Ant or Eclipse build, set the
<code>proguard.config</code> property in the <code>&lt;project_root&gt;/default.properties</code>
file. The path can be an absolute path or a path relative to the project's root.</p>
<p>If you left the <code>proguard.cfg</code> file in its default location (the project's root directory),
you can specify its location like this:</p>
<pre class="no-pretty-print">
proguard.config=proguard.cfg
</pre>
<p>
You can also move the the file to anywhere you want, and specify the absolute path to it:
</p>
<pre class="no-pretty-print">
proguard.config=/path/to/proguard.cfg
</pre>
<p>When you build your application in release mode, either by running <code>ant release</code> or
by using the <em>Export Wizard</em> in Eclipse, the build system automatically checks to see if
the <code>proguard.config</code> property is set. If it is, ProGuard automatically processes
the application's bytecode before packaging everything into an <code>.apk</code> file. Building in debug mode
does not invoke ProGuard, because it makes debugging more cumbersome.</p>
<p>ProGuard outputs the following files after it runs:</p>
<dl>
<dt><code>dump.txt</code></dt>
<dd>Describes the internal structure of all the class files in the <code>.apk</code> file</dd>
<dt><code>mapping.txt</code></dt>
<dd>Lists the mapping between the original and obfuscated class, method, and field names.
This file is important when you receive a bug report from a release build, because it
translates the obfuscated stack trace back to the original class, method, and member names.
See <a href="#decoding">Decoding Obfuscated Stack Traces</a> for more information.</dd>
<dt><code>seeds.txt</code></dt>
<dd>Lists the classes and members that are not obfuscated</dd>
<dt><code>usage.txt</code></dt>
<dd>Lists the code that was stripped from the <code>.apk</code></dd>
</ul>
<p>These files are located in the following directories:</p>
<ul>
<li><code>&lt;project_root&gt;/bin/proguard</code> if you are using Ant.</li>
<li><code>&lt;project_root&gt;/proguard</code> if you are using Eclipse.</li>
</ul>
<p class="caution"><strong>Caution:</strong> Every time you run a build in release mode, these files are
overwritten with the latest files generated by ProGuard. Save a copy of them each time you release your
application in order to de-obfuscate bug reports from your release builds.
For more information on why saving these files is important, see
<a href="#considerations">Debugging considerations for published applications</a>.
</p>
<h2 id="configuring">Configuring ProGuard</h2>
<p>For some situations, the default configurations in the <code>proguard.cfg</code> file will
suffice. However, many situations are hard for ProGuard to analyze correctly and it might remove code
that it thinks is not used, but your application actually needs. Some examples include:</p>
<ul>
<li>a class that is referenced only in the <code>AndroidManifest.xml</code> file</li>
<li>a method called from JNI</li>
<li>dynamically referenced fields and methods</li>
</ul>
<p>The default <code>proguard.cfg</code> file tries to cover general cases, but you might
encounter exceptions such as <code>ClassNotFoundException</code>, which happens when ProGuard
strips away an entire class that your application calls.</p>
<p>You can fix errors when ProGuard strips away your code by adding a <code>-keep</code> line in
the <code>proguard.cfg</code> file. For example:</p>
<pre>
-keep public class &lt;MyClass&gt;
</pre>
<p>There are many options and considerations when using the <code>-keep</code> option, so it is
highly recommended that you read the <a href="http://proguard.sourceforge.net/manual/introduction.html">ProGuard
Manual</a> for more information about customizing your configuration file. The <a href=
"http://proguard.sourceforge.net/manual/usage.html#keepoverview">Overview of Keep options</a> and
<a href="http://proguard.sourceforge.net/index.html#/manual/examples.html">Examples section</a>
are particularly helpful. The <a href=
"http://proguard.sourceforge.net/manual/troubleshooting.html">Troubleshooting</a> section of the
ProGuard Manual outlines other common problems you might encounter when your code gets stripped
away.</p>
<h2 id="decoding">Decoding Obfuscated Stack Traces</h2>
<p>When your obfuscated code outputs a stack trace, the method names are obfuscated, which makes
debugging hard, if not impossible. Fortunately, whenever ProGuard runs, it outputs a
<code>&lt;project_root&gt;/bin/proguard/mapping.txt</code> file, which shows you the original
class, method, and field names mapped to their obfuscated names.</p>
<p>The <code>retrace.bat</code> script on Windows or the <code>retrace.sh</code> script on Linux
or Mac OS X can convert an obfuscated stack trace to a readable one. It is located in the
<code>&lt;sdk_root&gt;/tools/proguard/</code> directory. The syntax for executing the
<code>retrace</code> tool is:</p>
<pre>retrace.bat|retrace.sh [-verbose] mapping.txt [&lt;stacktrace_file&gt;]</pre>
<p>For example:</p>
<pre>retrace.bat -verbose mapping.txt obfuscated_trace.txt</pre>
<p>If you do not specify a value for <em>&lt;stacktrace_file&gt;</em>, the <code>retrace</code> tool reads
from standard input.</p>
<h3 id="considerations">Debugging considerations for published applications</h3>
<p>Save the <code>mapping.txt</code> file for every release that you publish to your users.
By retaining a copy of the <code>mapping.txt</code> file for each release build,
you ensure that you can debug a problem if a user encounters a bug and submits an obfuscated stack trace.
A project's <code>mapping.txt</code> file is overwritten every time you do a release build, so you must be
careful about saving the versions that you need.</p>
<p>For example, say you publish an application and continue developing new features of
the application for a new version. You then do a release build using ProGuard soon after. The
build overwrites the previous <code>mapping.txt</code> file. A user submits a bug report
containing a stack trace from the application that is currently published. You no longer have a way
of debugging the user's stack trace, because the <code>mapping.txt</code> file associated with the version
on the user's device is gone. There are other situations where your <code>mapping.txt</code> file can be overwritten, so
ensure that you save a copy for every release that you anticipate you have to debug.</p>
<p>How you save the <code>mapping.txt</code> file is your decision. For example, you can rename them to
include a version or build number, or you can version control them along with your source
code.</p>

View File

@@ -0,0 +1,319 @@
page.title=Traceview: A Graphical Log Viewer
@jd:body
<div id="qv-wrapper">
<div id="qv">
<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>
</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>&lt;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>&lt;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 &lt;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&rsquo;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 &quot;parents&quot; and called methods as &quot;children.&quot;
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 &quot;offset to data&quot; 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 &quot;exited&quot; 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>
<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 &lt;init&gt; ()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>&lt;ref> <em>callname</em> (&lt;inc-ms>,
&lt;exc-ms>,&lt;numcalls>)</code>, where</p>
<ul>
<li><code>&lt;ref></code> -- Call reference number, as used in trace logs</li>
<li><code>&lt;inc-ms></code> -- Inclusive elapsed time (milliseconds spent in method, including all child methods)</li>
<li><code>&lt;exc-ms></code> -- Exclusive elapsed time (milliseconds spent in method, not including any child methods)</li>
<li><code>&lt;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] &lt;trace-base-name></pre>
<p>The tool then loads trace log data from &lt;trace-base-name>.data and &lt;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&nbsp;&lt;trace-base-name> </code></td>
<td>Diff with this trace name</td>
</tr>
<tr>
<td><code>-g&nbsp;&lt;outfile> </code></td>
<td>Generate output to &lt;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&nbsp;&lt;trace-base-name> </code></td>
<td>URL base to the location of the sortable javascript file</td>
</tr>
<tr>
<td><code>-t&nbsp;&lt;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>

View File

@@ -0,0 +1,65 @@
page.title=zipalign
@jd:body
<p>zipalign is an archive alignment tool that provides important
optimization to Android application (.apk) files.
The purpose is to ensure that all uncompressed data starts
with a particular alignment relative to the start of the file. Specifically,
it causes all uncompressed data within the .apk, such as images or raw files,
to be aligned on 4-byte boundaries. This
allows all portions to be accessed directly with {@code mmap()} even if they
contain binary data with alignment restrictions.
The benefit is a reduction in the amount of RAM consumed
when running the application.</p>
<p>This tool should always be used to align your .apk file before
distributing it to end-users. The Android build tools can handle
this for you. When using Eclipse with the ADT plugin, the Export Wizard
will automatically zipalign your .apk after it signs it with your private key.
The build scripts used
when compiling your application with Ant will also zipalign your .apk,
as long as you have provided the path to your keystore and the key alias in
your project {@code build.properties} file, so that the build tools
can sign the package first.</p>
<p class="caution"><strong>Caution:</strong> zipalign must only be performed
<strong>after</strong> the .apk file has been signed with your private key.
If you perform zipalign before signing, then the signing procedure will undo
the alignment. Also, do not make alterations to the aligned package.
Alterations to the archive, such as renaming or deleting entries, will
potentially disrupt the alignment of the modified entry and all later
entries. And any files added to an "aligned" archive will not be aligned.</p>
<p>The adjustment is made by altering the size of
the "extra" field in the zip Local File Header sections. Existing data
in the "extra" fields may be altered by this process.</p>
<p>For more information about how to use zipalign when building your
application, please read <a href="{@docRoot}guide/publishing/app-signing.html">Signing
Your Application</a>.</p>
<h3>Usage</h3>
<p>To align {@code infile.apk} and save it as {@code outfile.apk}:</p>
<pre>zipalign [-f] [-v] &lt;alignment> infile.apk outfile.apk</pre>
<p>To confirm the alignment of {@code existing.apk}:</p>
<pre>zipalign -c -v &lt;alignment> existing.apk</pre>
<p>The {@code &lt;alignment>} is an integer that defines the byte-alignment boundaries.
This must always be 4 (which provides 32-bit alignment) or else it effectively
does nothing.</p>
<p>Flags:</p>
<ul>
<li>{@code -f} : overwrite existing outfile.zip</li>
<li>{@code -v} : verbose output</li>
<li>{@code -c} : confirm the alignment of the given file</li>
</ul>

View File

@@ -0,0 +1,643 @@
<?cs # Table of contents for Dev Guide.
For each document available in translation, add an localized title to this TOC.
Do not add localized title for docs not available in translation.
Below are template spans for adding localized doc titles. Please ensure that
localized titles are added in the language order specified below.
?>
<ul>
<li>
<h2><span class="en">Android Basics</span>
<span class="de" style="display:none">Einführung in Android</span>
<span class="es" style="display:none">Información básica sobre Android</span>
<span class="fr" style="display:none">Présentation d'Android</span>
<span class="it" style="display:none">Nozioni di base su Android</span>
<span class="ja" style="display:none">Android </span>
<span class="zh-CN" style="display:none">Android </span>
<span class="zh-TW" style="display:none">Android </span>
</h2>
<ul>
<li><a href="<?cs var:toroot ?>guide/basics/what-is-android.html">
<span class="en">What Is Android?</span>
<span class="de" style="display:none">Was ist Android?</span>
<span class="es" style="display:none">¿Qué es Android?</span>
<span class="fr" style="display:none">Qu'est-ce qu'Android&nbsp;?</span>
<span class="it" style="display:none">Che cos'è Android?</span>
<span class="ja" style="display:none">Android </span>
<span class="zh-CN" style="display:none">Android </span>
<span class="zh-TW" style="display:none"> Android</span>
</a></li>
<!-- <li><a style="color:gray;">The Android SDK</a></li> -->
<!-- <li><a style="color:gray;">Walkthrough for Developers</a></li> -->
<!-- quick overview of what it's like to develop on Android -->
</ul>
</li>
<li>
<h2>
<span class="en">Framework Topics</span>
<span class="de" style="display:none">Framework-Themen</span>
<span class="es" style="display:none">Temas sobre el framework</span>
<span class="fr" style="display:none">Thèmes relatifs au framework</span>
<span class="it" style="display:none">Argomenti relativi al framework</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 ?>guide/topics/fundamentals.html">
<span class="en">Application Fundamentals</span>
<span class="de" style="display:none">Anwendungsgrundlagen</span>
<span class="es" style="display:none">Fundamentos de las aplicaciones</span>
<span class="fr" style="display:none">Principes de base des applications</span>
<span class="it" style="display:none">Concetti fondamentali sulle applicazioni</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></li>
</ul>
<ul>
<li class="toggle-list">
<div><a href="<?cs var:toroot ?>guide/topics/ui/index.html">
<span class="en">User Interface</span>
</a></div>
<ul>
<li><a href="<?cs var:toroot ?>guide/topics/ui/declaring-layout.html">
<span class="en">Declaring Layout</span>
</a></li>
<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/dialogs.html">
<span class="en">Creating Dialogs</span>
</a></li>
<li><a href="<?cs var:toroot ?>guide/topics/ui/ui-events.html">
<span class="en">Handling UI Events</span>
</a></li>
<li class="toggle-list">
<div><a href="<?cs var:toroot ?>guide/topics/ui/notifiers/index.html">
<span class="en">Notifying the User</span>
</a></div>
<ul>
<li><a href="<?cs var:toroot ?>guide/topics/ui/notifiers/toasts.html">
<span class="en">Creating Toast Notifications</span>
</a></li>
<li><a href="<?cs var:toroot ?>guide/topics/ui/notifiers/notifications.html">
<span class="en">Creating Status Bar Notifications</span>
</a></li>
</ul>
</li>
<li><a href="<?cs var:toroot ?>guide/topics/ui/themes.html">
<span class="en">Applying Styles and Themes</span>
</a></li>
<li><a href="<?cs var:toroot ?>guide/topics/ui/custom-components.html">
<span class="en">Building Custom Components</span>
</a></li>
<li><a href="<?cs var:toroot ?>guide/topics/ui/binding.html">
<span class="en">Binding to Data with AdapterView</span>
</a></li>
<li><a href="<?cs var:toroot ?>guide/topics/ui/layout-objects.html">
<span class="en">Common Layout Objects</span>
</a></li>
<li><a href="<?cs var:toroot ?>guide/topics/ui/how-android-draws.html">
<span class="en">How Android Draws Views</span>
</a></li>
</ul>
</li>
<li class="toggle-list">
<div><a href="<?cs var:toroot ?>guide/topics/resources/index.html">
<span class="en">Application Resources</span>
</a></div>
<ul>
<li><a href="<?cs var:toroot ?>guide/topics/resources/providing-resources.html">
<span class="en">Providing Resources</span>
</a></li>
<li><a href="<?cs var:toroot ?>guide/topics/resources/accessing-resources.html">
<span class="en">Accessing Resources</span>
</a></li>
<li><a href="<?cs var:toroot ?>guide/topics/resources/runtime-changes.html">
<span class="en">Handling Runtime Changes</span>
</a></li>
<li><a href="<?cs var:toroot ?>guide/topics/resources/localization.html">
<span class="en">Localization</span>
</a></li>
<li class="toggle-list">
<div><a href="<?cs var:toroot ?>guide/topics/resources/available-resources.html">
<span class="en">Resource Types</span>
</a></div>
<ul>
<li><a href="<?cs var:toroot ?>guide/topics/resources/animation-resource.html">Animation</a></li>
<li><a href="<?cs var:toroot ?>guide/topics/resources/color-list-resource.html">Color State List</a></li>
<li><a href="<?cs var:toroot ?>guide/topics/resources/drawable-resource.html">Drawable</a></li>
<li><a href="<?cs var:toroot ?>guide/topics/resources/layout-resource.html">Layout</a></li>
<li><a href="<?cs var:toroot ?>guide/topics/resources/menu-resource.html">Menu</a></li>
<li><a href="<?cs var:toroot ?>guide/topics/resources/string-resource.html">String</a></li>
<li><a href="<?cs var:toroot ?>guide/topics/resources/style-resource.html">Style</a></li>
<li><a href="<?cs var:toroot ?>guide/topics/resources/more-resources.html">More Types</a></li>
</ul>
</li>
</ul>
</li>
<li><a href="<?cs var:toroot ?>guide/topics/intents/intents-filters.html">
<span class="en">Intents and Intent Filters</span>
</a></li>
<li class="toggle-list">
<div><a href="<?cs var:toroot ?>guide/topics/data/data-storage.html">
<span class="en">Data Storage</span>
</a></div>
<ul>
<li><a href="<?cs var:toroot ?>guide/topics/data/backup.html">
<span class="en">Data Backup</span>
</a>
</li>
</ul>
</li>
<li><a href="<?cs var:toroot ?>guide/topics/providers/content-providers.html">
<span class="en">Content Providers</span>
</a></li>
<li><a href="<?cs var:toroot ?>guide/topics/security/security.html">
<span class="en">Security and Permissions</span>
</a></li>
<!-- <li><a style="color:gray;">Processes and Threads</a></li> -->
<!-- <li><a style="color:gray;">Interprocess Communication</a></li> -->
<li class="toggle-list">
<div><a href="<?cs var:toroot ?>guide/topics/manifest/manifest-intro.html">
<span class="en">The AndroidManifest.xml File</span>
</a></div>
<ul>
<li><a href="<?cs var:toroot ?>guide/topics/manifest/action-element.html">&lt;action&gt;</a></li>
<li><a href="<?cs var:toroot ?>guide/topics/manifest/activity-element.html">&lt;activity&gt;</a></li>
<li><a href="<?cs var:toroot ?>guide/topics/manifest/activity-alias-element.html">&lt;activity-alias&gt;</a></li>
<li><a href="<?cs var:toroot ?>guide/topics/manifest/application-element.html">&lt;application&gt;</a></li>
<li><a href="<?cs var:toroot ?>guide/topics/manifest/category-element.html">&lt;category&gt;</a></li>
<li><a href="<?cs var:toroot ?>guide/topics/manifest/data-element.html">&lt;data&gt;</a></li>
<li><a href="<?cs var:toroot ?>guide/topics/manifest/grant-uri-permission-element.html">&lt;grant-uri-permission&gt;</a></li>
<li><a href="<?cs var:toroot ?>guide/topics/manifest/instrumentation-element.html">&lt;instrumentation&gt;</a></li>
<li><a href="<?cs var:toroot ?>guide/topics/manifest/intent-filter-element.html">&lt;intent-filter&gt;</a></li>
<li><a href="<?cs var:toroot ?>guide/topics/manifest/manifest-element.html">&lt;manifest&gt;</a></li>
<li><a href="<?cs var:toroot ?>guide/topics/manifest/meta-data-element.html">&lt;meta-data&gt;</a></li>
<li><a href="<?cs var:toroot ?>guide/topics/manifest/path-permission-element.html">&lt;path-permission&gt;</a></li>
<li><a href="<?cs var:toroot ?>guide/topics/manifest/permission-element.html">&lt;permission&gt;</a></li>
<li><a href="<?cs var:toroot ?>guide/topics/manifest/permission-group-element.html">&lt;permission-group&gt;</a></li>
<li><a href="<?cs var:toroot ?>guide/topics/manifest/permission-tree-element.html">&lt;permission-tree&gt;</a></li>
<li><a href="<?cs var:toroot ?>guide/topics/manifest/provider-element.html">&lt;provider&gt;</a></li>
<li><a href="<?cs var:toroot ?>guide/topics/manifest/receiver-element.html">&lt;receiver&gt;</a></li>
<li><a href="<?cs var:toroot ?>guide/topics/manifest/service-element.html">&lt;service&gt;</a></li>
<li><a href="<?cs var:toroot ?>guide/topics/manifest/supports-screens-element.html">&lt;supports-screens&gt;</a></li> <!-- ##api level 4## -->
<li><a href="<?cs var:toroot ?>guide/topics/manifest/uses-configuration-element.html">&lt;uses-configuration&gt;</a></li>
<li><a href="<?cs var:toroot ?>guide/topics/manifest/uses-feature-element.html">&lt;uses-feature&gt;</a></li> <!-- ##api level 4## -->
<li><a href="<?cs var:toroot ?>guide/topics/manifest/uses-library-element.html">&lt;uses-library&gt;</a></li>
<li><a href="<?cs var:toroot ?>guide/topics/manifest/uses-permission-element.html">&lt;uses-permission&gt;</a></li>
<li><a href="<?cs var:toroot ?>guide/topics/manifest/uses-sdk-element.html">&lt;uses-sdk&gt;</a></li>
</ul>
</li>
</ul>
<ul>
<li class="toggle-list">
<div><a href="<?cs var:toroot ?>guide/topics/graphics/index.html">
<span class="en">Graphics</span>
</a></div>
<ul>
<li><a href="<?cs var:toroot ?>guide/topics/graphics/2d-graphics.html">
<span class="en">2D Graphics</span>
</a></li>
<li><a href="<?cs var:toroot ?>guide/topics/graphics/opengl.html">
<span class="en">3D with OpenGL</span>
</a></li>
</ul>
</li>
<li><a href="<?cs var:toroot ?>guide/topics/media/index.html">
<span class="en">Audio and Video</span>
</a></li>
<!--<li class="toggle-list">
<div><a style="color:gray;">Sensors</a></div>
<ul>
<li><a style="color:gray;">Camera</a></li>
<li><a style="color:gray;">Compass</a></li>
<li><a style="color:gray;">Accelerometer</a></li>
</ul>
</li> -->
<li class="toggle-list">
<div><a href="<?cs var:toroot ?>guide/topics/location/index.html">
<span class="en">Location and Maps</span>
</a></div>
<ul>
<li><a href="<?cs var:toroot ?>guide/topics/location/obtaining-user-location.html">
<span class="en">Obtaining User Location</span>
</a></li>
</ul>
</li>
<!--<li class="toggle-list">
<div><a style="color:gray;">Wireless Controls</a></div>
<ul>
<li><a style="color:gray;">Wi-Fi</a></li>
</ul>
</li> -->
<!--<li><a style="color:gray;">Localization</a></li> -->
<li><a href="<?cs var:toroot ?>guide/topics/appwidgets/index.html">
<span class="en">App Widgets</span>
</a></li>
<li><a href="<?cs var:toroot?>guide/topics/wireless/bluetooth.html">
<span class="en">Bluetooth</span>
</a></li>
<li><a href="<?cs var:toroot?>guide/topics/nfc/index.html">
<span class="en">Near Field Communication</span></a>
<span class="new">new!</span></li>
<li><a href="<?cs var:toroot?>guide/topics/network/sip.html">
<span class="en">Session Initiation Protocol</span></a>
<span class="new">new!</span>
</li>
<li class="toggle-list">
<div><a href="<?cs var:toroot?>guide/topics/search/index.html">
<span class="en">Search</span>
</a></div>
<ul>
<li><a href="<?cs var:toroot?>guide/topics/search/search-dialog.html">Using the Android Search Dialog</a></li>
<li><a href="<?cs var:toroot?>guide/topics/search/adding-recent-query-suggestions.html">Adding Recent Query Suggestions</a></li>
<li><a href="<?cs var:toroot?>guide/topics/search/adding-custom-suggestions.html">Adding Custom Suggestions</a></li>
<li><a href="<?cs var:toroot?>guide/topics/search/searchable-config.html">Searchable Configuration</a></li>
</ul>
</li>
<li><a href="<?cs var:toroot?>guide/topics/admin/device-admin.html">
<span class="en">Device Administration</span>
</a>
</li>
<li class="toggle-list">
<div>
<a href="<?cs var:toroot?>guide/topics/testing/index.html">
<span class="en">Testing</span>
</a>
</div>
<ul>
<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>
</li>
</ul>
</li>
<li>
<h2>
<span class="en">Android Market Topics</span>
</h2>
<ul>
<li><a href="<?cs var:toroot ?>guide/publishing/licensing.html">
<span class="en">Application Licensing</span></a>
</li>
<li class="toggle-list">
<div><a href="<?cs var:toroot?>guide/market/billing/index.html">
<span class="en">In-app Billing</span></a>
<span class="new">new!</span>
</div>
<ul>
<li><a href="<?cs var:toroot?>guide/market/billing/billing_about.html">
<span class="en">About this Release</span></a>
</li>
<li><a href="<?cs var:toroot?>guide/market/billing/billing_overview.html">
<span class="en">In-app Billing Overview</span></a>
</li>
<li><a href="<?cs var:toroot?>guide/market/billing/billing_integrate.html">
<span class="en">Implementing In-app Billing</span></a>
</li>
<li><a href="<?cs var:toroot?>guide/market/billing/billing_best_practices.html">
<span class="en">Security and Design</span></a>
</li>
<li><a href="<?cs var:toroot?>guide/market/billing/billing_testing.html">
<span class="en">Testing In-app Billing</span></a>
</li>
<li><a href="<?cs var:toroot?>guide/market/billing/billing_admin.html">
<span class="en">Administering In-app Billing</span></a>
</li>
<li><a href="<?cs var:toroot?>guide/market/billing/billing_reference.html">
<span class="en">In-app Billing Reference</span></a>
</li>
</ul>
</li>
<li><a href="<?cs var:toroot ?>guide/appendix/market-filters.html">
<span class="en">Market Filters</span></a>
</li>
</ul>
</li>
<li>
<h2><span class="en">Developing</span>
<span class="de" style="display:none">Entwicklung</span>
<span class="es" style="display:none">Desarrollo</span>
<span class="fr" style="display:none">Développement</span>
<span class="it" style="display:none">Sviluppo</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="">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>
</a></li>
<li class="toggle-list">
<div>
<a href="<?cs var:toroot ?>guide/developing/testing/index.html">
<span class="en">Testing</span>
</a>
</div>
<ul>
<li>
<a href="<?cs var:toroot ?>guide/developing/testing/testing_eclipse.html">
<span class="en">Testing 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>
</a>
</li>
</ul>
</li>
<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 class="toggle-list">
<div>
<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">
<span class="en">MonkeyDevice</span>
</a>
<span class="new">new!</span>
</li>
<li>
<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">
<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/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>
</ul>
</li>
<li>
<h2><span class="en">Publishing</span>
<span class="de" style="display:none">Veröffentlichung</span>
<span class="es" style="display:none">Publicación</span>
<span class="fr" style="display:none">Publication</span>
<span class="it" style="display:none">Pubblicazione</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 ?>guide/publishing/app-signing.html">
<span class="en">Signing Your Applications</span>
<span class="de" style="display:none">Signieren Ihrer Anwendungen</span>
<span class="es" style="display:none">Firma de aplicaciones</span>
<span class="fr" style="display:none">Attribution de votre signature <br />à vos applications</span>
<span class="it" style="display:none">Firma delle applicazioni</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></li>
<li><a href="<?cs var:toroot ?>guide/publishing/versioning.html">
<span class="en">Versioning Your Applications</span>
<span class="de" style="display:none">Versionsverwaltung für Ihre <br />Anwendungen</span>
<span class="es" style="display:none">Versiones de las aplicaciones</span>
<span class="fr" style="display:none">Attribution d'une version à vos applications</span>
<span class="it" style="display:none">Controllo versioni delle applicazioni</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></li>
<li><a href="<?cs var:toroot ?>guide/publishing/preparing.html">
<span class="en">Preparing to Publish</span>
<span class="de" style="display:none">Vorbereitung auf die Veröffentlichung</span>
<span class="es" style="display:none">Publicación de aplicaciones</span>
<span class="fr" style="display:none">Préparation à la publication</span>
<span class="it" style="display:none">Preparativi per la pubblicazione</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></li>
<li><a href="<?cs var:toroot ?>guide/publishing/publishing.html">
<span class="en">Publishing Your Applications</span>
</a></li>
</ul>
</li>
<li>
<h2><span class="en">Best Practices</span>
<span class="de" style="display:none">Bewährte Verfahren</span>
<span class="es" style="display:none">Prácticas recomendadas</span>
<span class="fr" style="display:none">Meilleures pratiques</span>
<span class="it" style="display:none">Best practice</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 ?>guide/practices/compatibility.html">
<span class="en">Compatibility</span>
</a></li>
<li><a href="<?cs var:toroot ?>guide/practices/screens_support.html">
<span class="en">Supporting Multiple Screens</span>
</a></li>
<li class="toggle-list">
<div><a href="<?cs var:toroot ?>guide/practices/ui_guidelines/index.html">
<span class="en">UI Guidelines</span>
</a></div>
<ul>
<li class="toggle-list">
<div><a href="<?cs var:toroot ?>guide/practices/ui_guidelines/icon_design.html">
<span class="en">Icon Design</span>
</a></div>
<ul>
<li><a href="<?cs var:toroot ?>guide/practices/ui_guidelines/icon_design_launcher.html">
<span class="en">Launcher Icons</span>
</a></li>
<li><a href="<?cs var:toroot ?>guide/practices/ui_guidelines/icon_design_menu.html">
<span class="en">Menu Icons</span>
</a></li>
<li><a href="<?cs var:toroot ?>guide/practices/ui_guidelines/icon_design_status_bar.html">
<span class="en">Status Bar Icons</span>
</a></li>
<li><a href="<?cs var:toroot ?>guide/practices/ui_guidelines/icon_design_tab.html">
<span class="en">Tab Icons</span>
</a></li>
<li><a href="<?cs var:toroot ?>guide/practices/ui_guidelines/icon_design_dialog.html">
<span class="en">Dialog Icons</span>
</a></li>
<li><a href="<?cs var:toroot ?>guide/practices/ui_guidelines/icon_design_list.html">
<span class="en">List View Icons</span>
</a></li>
</ul>
</li>
<li><a href="<?cs var:toroot ?>guide/practices/ui_guidelines/widget_design.html">
<span class="en">App Widget Design</span>
</a></li>
<li><a href="<?cs var:toroot ?>guide/practices/ui_guidelines/activity_task_design.html">
<span class="en">Activity and Task Design</span>
</a></li>
<li><a href="<?cs var:toroot ?>guide/practices/ui_guidelines/menu_design.html">
<span class="en">Menu Design</span>
</a></li>
</ul>
</li>
</ul>
<ul>
<li><a href="<?cs var:toroot ?>guide/practices/design/performance.html">
<span class="en">Designing for Performance</span>
</a></li>
<li><a href="<?cs var:toroot ?>guide/practices/design/responsiveness.html">
<span class="en">Designing for Responsiveness</span>
</a></li>
<li><a href="<?cs var:toroot ?>guide/practices/design/seamlessness.html">
<span class="en">Designing for Seamlessness</span>
</a></li>
</ul>
</li>
<li>
<h2><span class="en">Web Applications</span>
</h2>
<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>
<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>
<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>
<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>
<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>
</ul>
</li>
<li>
<h2><span class="en">Appendix</span>
<span class="de" style="display:none">Anhang</span>
<span class="es" style="display:none">Apéndice</span>
<span class="fr" style="display:none">Annexes</span>
<span class="it" style="display:none">Appendice</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 ?>guide/appendix/api-levels.html">
<span class="en">Android API Levels</span>
</a></li>
<li><a href="<?cs var:toroot ?>guide/appendix/install-location.html">
<span class="en">App Install Location</span>
</a></li>
<li><a href="<?cs var:toroot ?>guide/appendix/media-formats.html">
<span class="en">Supported Media Formats</span>
</a></li>
<li><a href="<?cs var:toroot ?>guide/appendix/g-app-intents.html">
<span class="en">Intents List: Google Apps</span>
</a></li>
<li><a href="<?cs var:toroot ?>guide/appendix/glossary.html">
<span class="en">Glossary</span>
</a></li>
</ul>
</li>
</ul>
<script type="text/javascript">
<!--
buildToggleLists();
changeNavLang(getLangPref());
//-->
</script>

View File

@@ -0,0 +1,88 @@
page.title=The Developer's Guide
@jd:body
<p>
Welcome to the <i>Android Dev Guide</i>! The Dev Guide provides
a practical introduction to developing applications for Android and documentation about major
platform features. It explores the concepts behind Android, the framework for
constructing an application, and the tools for developing,
testing, and publishing software for the platform.
</p>
<p>
The Dev Guide holds most of the documentation for the Android
platform, except for reference material on the framework API.
For API specifications, go to the
<a href="{@docRoot}reference/packages.html">Reference</a>.
</p>
<p>
As you can see in the panel on the left, the Dev Guide is
divided into several sections:
<p>
<dl>
<dt><b>Android Basics</b></dt>
<dd>An initial orientation to Android &mdash; what it is,
what it offers, and how your application fits in.</dd>
<dt><b>Framework Topics</b></dt>
<dd>Discussions of particular parts of the Android framework
and API. For an overview of the framework, begin with
<a href="{@docRoot}guide/topics/fundamentals.html">Application
Fundamentals</a>. Then explore other topics &mdash; from
designing a user interface and setting up resources to storing
data and using permissions &mdash; as needed.</dd>
<dt><b>Android Market Topics</b></dt>
<dd>Documentation for topics that concern publishing and monetizing applications on Android
Market, such as how to enforce licensing policies and implement in-app billing.</dd>
<dt><b>Developing</b></dt>
<dd>Directions for using Android's development and debugging tools,
and for testing the results.</dd>
<dt><b>Publishing</b></dt>
<dd>Instructions on how to prepare your application for deployment
and how to publish it when it's ready.</dd>
<dt><b>Best Practices</b></dt>
<dd>Recommendations on preferred techniques for writing
applications that perform efficiently and work well for the
user.</dd>
<dt><b>Web Applications</b></dt>
<dd>Documentation about how to create web applications that work seamlessly on Android-powered
devices and create Android applications that embed web-based content.</dd>
<dt><b>Appendix</b></dt>
<dd>Reference information and specifications, as well as FAQs,
a glossary of terms, and other information.</dd>
</dl>
<p>
The first step in programming for Android is downloading the SDK
(software development kit). For instructions and information, visit the <a
href="{@docRoot}sdk/index.html">SDK</a> tab.
</p>
<p>
After you have the SDK, begin by looking through the Dev Guide.
If you want to start by getting a quick look at some code, the
<a href="{@docRoot}resources/tutorials/hello-world.html">Hello World</a>
tutorial walks you through a standard "Hello, World" application to introduce some basics of an
Android application. The
<a href="{@docRoot}guide/topics/fundamentals.html">Application
Fundamentals</a> document is a good place to start learning the basics about the application
framework.
</p>
<p>
For additional help, consider joining one or more of the Android
discussion groups. Go to the
<a href="{@docRoot}resources/community-groups.html">Developer Forums</a> page
for more information.
</p>
<p>To return to this page later, just click the "Dev Guide" tab while any Dev Guide page is loaded. </p>

View File

@@ -0,0 +1,73 @@
page.title=About this Release
@jd:body
<style type="text/css">
#jd-content {
background:transparent url({@docRoot}assets/images/preliminary.png) repeat scroll 0 0;
}
</style>
<div id="qv-wrapper">
<div id="qv">
<h2>In this document</h2>
<ol>
<li><a href="#billing-about">About this Release</a></li>
</ol>
<h2>Downloads</h2>
<ol>
<li><a href="{@docRoot}guide/market/billing/billing_integrate.html#billing-download">Sample Application</a></li>
</ol>
<h2>See also</h2>
<ol>
<li><a href="{@docRoot}guide/market/billing/billing_overview.html">Overview of In-app Billing</a></li>
<li><a href="{@docRoot}guide/market/billing/billing_integrate.html">Implementing In-app Billing</a></li>
<li><a href="{@docRoot}guide/market/billing/billing_best_practices.html">Security and Design</a></li>
<li><a href="{@docRoot}guide/market/billing/billing_testing.html">Testing In-app Billing</a></li>
<li><a href="{@docRoot}guide/market/billing/billing_admin.html">Administering In-app Billing</a></li>
<li><a href="{@docRoot}guide/market/billing/billing_reference.html">In-app Billing Reference</a></li>
</ol>
</div>
</div>
<div class="special" style="margin-right:345px">
<p>This documentation provides an early look at the Android Market In-app Billing service. The documentation may change without notice.</p>
</div>
<p>This documentation gives you an early look at the Android Market In-app Billing service. We are providing this documentation to help you get started designing your in-app billing implementation. </p>
<p>In addition to this documentation, we are providing a <a href="{@docRoot}guide/market/billing/billing_integrate.html#billing-download">sample application</a> that shows you how to implement in-app billing. Although you can compile the sample application, load it on a device, and run it, you cannot use it to make purchases at this time. In-app billing relies on version 2.3.0 (and higher) of the Android Market application, which may not be available yet.</p>
<p>In the coming weeks we plan to launch the testing phase of the in-app billing release. Following the testing phase we will launch in-app billing to the general public (see table 1 for a summary of upcoming launch milestones).
<p class="table-caption"><strong>Table 1.</strong> Summary of launch milestones for in-app billing.</p>
<table>
<tr>
<th>Release Phase</th>
<th>Android Market Application</th>
<th>Description</th>
</tr>
<tr>
<td>Early Development</td>
<td>Version 2.3.0 not available</td>
<td>Provides an early look at documentation and sample application.</td>
</tr>
<tr>
<td>Test Development</td>
<td>Version 2.3.0 available to developers and users</td>
<td>In-app billing service allows static testing with reserved product IDs. You cannot publish applications that use in-app billing.</td>
</tr>
<tr>
<td>Final Release</td>
<td>Version 2.3.0 available to developers and users</td>
<td>In-app billing service allows end-to-end testing of in-app billing. You can publish applications that use in-app billing.</td>
</tr>
</table>
<p>During the testing phase we will release version 2.3.0 of the Android Market application. This will allow you to test your in-app billing implementation using the <a href="{@docRoot}guide/market/billing/billing_testing.html#billing-testing-static">reserved product IDs and test responses</a>. However, you will not be able to test end-to-end in-app purchases during the testing phase, and you will not be able to publish an application that uses in in-app billing. </p>
<p>After the testing phase is complete, we will release in-app billing to the general public. This will enable you to perform end-to-end tests of your in-app billing implementation using your actual in-app products. You will also be able to publish applications that use in-app billing.</p>
<p>This documentation may change in the coming weeks as we move from the preview phase to the testing phase of this beta release. Be sure to check this documentation frequently for updates.</p>

View File

@@ -0,0 +1,185 @@
page.title=Administering In-app Billing
@jd:body
<style type="text/css">
#jd-content {
background:transparent url({@docRoot}assets/images/preliminary.png) repeat scroll 0 0;
}
</style>
<div id="qv-wrapper">
<div id="qv">
<h2>In this document</h2>
<ol>
<li><a href="#billing-list-setup">Creating a Product List</a></li>
<li><a href="#billing-purchase-type">Choosing a Purchase Type</a></li>
<li><a href="#billing-testing-setup">Setting up Test Accounts</a></li>
<li><a href="#billing-refunds">Handling Refunds</a></li>
<li><a href="#billing-support">Where to Get Support</a></li>
</ol>
<h2>Downloads</h2>
<ol>
<li><a href="{@docRoot}guide/market/billing/billing_integrate.html#billing-download">Sample Application</a></li>
</ol>
<h2>See also</h2>
<ol>
<li><a href="{@docRoot}guide/market/billing/billing_overview.html">Overview of In-app Billing</a></li>
<li><a href="{@docRoot}guide/market/billing/billing_integrate.html">Implementing In-app Billing</a></li>
<li><a href="{@docRoot}guide/market/billing/billing_best_practices.html">Security and Design</a></li>
<li><a href="{@docRoot}guide/market/billing/billing_testing.html">Testing In-app Billing</a></li>
<li><a href="{@docRoot}guide/market/billing/billing_reference.html">In-app Billing Reference</a></li>
</ol>
</div>
</div>
<div class="special" style="margin-right:345px">
<p>This documentation provides an early look at the Android Market In-app Billing service. The documentation may change without notice.</p>
</div>
<p>In-app billing frees you from processing financial transactions, but you still need to perform a few administrative tasks, including setting up and maintaining your product list on the publisher site, registering test accounts, and handling refunds when necessary.</p>
<p>You must have an Android Market publisher account to set up a product list and register test accounts. And you must have a Google Checkout merchant account to issue refunds to your users. If you already have a publisher account on Android Market, you can use your existing account. You do not need to register for a new account to support in-app billing. If you do not have a publisher account, you can register as an Android Market developer and set up a publisher account at the Android Market <a href="http://market.android.com/publish">publisher site</a>. If you do not have a Google Checkout merchant account, you can register for one at the <a href="http://checkout.google.com">Google Checkout site</a>.</p>
<h2 id="billing-list-setup">Creating a Product List</h2>
<p>The Android Market publisher site provides a product list for each of your published applications. You can sell an item using the in-app billing feature only if the item is listed on an application's product list. Each application has its own product list; you cannot sell items that are listed in another application's product list.</p>
<p>A product list contains information about the items you are selling, such as a product id, product description, and price (see figure 1). The product list stores only metadata about the items you are selling in your application. It does not store any digital content. You are responsible for storing and delivering the digital content that you sell in your applications.</p>
<div style="margin-bottom:2em;">
<img src="{@docRoot}images/billing_product_list.png" style="text-align:left;margin-bottom:0;" />
<div style="margin:0 2em;padding:0"><strong>Figure 1.</strong> An application's product list.</div>
</div>
<p>You can create a product list for a published application or a draft application that's been uploaded and saved to the Android Market site. However, the application's manifest must include the com.android.vending.BILLING permission. If an application's manifest does not include this permission, you will be able to edit existing items in the product list but you will not be able to add new items to the list. For more information, see <a href="#billing-permission">Modifying your application's AndroidManifest.xml file</a>.</p>
<p>To create a product list for an application, follow these steps:</p>
<ol>
<li><a href="http://market.android.com/publish">Log in</a> to your publisher account.</li>
<li>In the <strong>All Android Market listings</strong> panel, under the application name, click <strong>In-app Products</strong>.</li>
<li>On the In-app Products List page, click <strong>Add in-app product</strong>.</li>
<li>On the Create New In-app Product page (see figure 2), provide details about the item you are selling and then click <strong>Save</strong>.</li>
</ol>
<div style="margin-bottom:2em;">
<img src="{@docRoot}images/billing_list_form.png" style="text-align:left;margin-bottom:0;" />
<div style="margin:0 2em;padding:0"><strong>Figure 2.</strong> The Create New In-app Product page lets you add items to an application's product list.</div>
</div>
<p>You must enter the following information for each item in a product list:</p>
<ul>
<li><strong>In-app Product ID</strong>
<p>Product IDs are unique across an application's namespace. A product ID must start with a lowercase letter or a number, and must be composed using only lowercase letters (a-z), numbers (0-9), underlines (_), and dots (.). The product ID "android.test" is reserved, as are all product IDs that start with "android.test."</p>
<p>In addition, you cannot modify an item's product ID after it is created, and you cannot reuse a product ID, even if you delete the item previously using the product ID.</p>
</li>
<li><strong>Purchase type</strong>
<p>The purchase type can be "managed per user account" or "unmanaged." You can specify an item's purchase type only through the publisher site and you can never change an item's purchase type once you specify it. For more information, see <a href="#billing_purchase_type">Choosing a purchase type</a> later in this document.</p>
</li>
<li><strong>Publishing State</strong>
<p>An item's publishing state can be "published" or "unpublished." However, to be visible to a user during checkout, an item's publishing state must be set to "published" and the item's application must be published on Android Market. (Note: This is not true for test accounts: that is, an item is visible to a trusted tester if the application is not published and the item is published. See <a href="{@docRoot}guide/market/billing/billing_testing.html#billing-testing-real">Testing In-app Billing</a> for more information.)</p>
</li>
<li><strong>Language</strong>
<p>A product list inherits its language from the parent application.</p>
</li>
<li><strong>Title</strong>
<p>The title is a short descriptor for the item. For example, "sleeping potion." Titles must be unique across an application's namespace. Every item must have a title. The title is visible to users during checkout.</p>
</li>
<li><strong>Description</strong>
<p>The description is a long descriptor for the item. For example, "Instantly puts creatures to sleep. Does not work on angry elves." Every item must have a description. The description is visible to users during checkout.</p>
</li>
<li><strong>Price</strong>
<p>Every item must have a price greater than zero; you cannot sell free items.</p>
</li>
</ul>
<p class="note"><strong>Note</strong>: Be sure to plan your product ID namespace. You cannot reuse or modify product IDs after you save them.</p>
<h3 id="billing-purchase-type">Choosing a Purchase Type</h3>
<p>An item's purchase type controls how Android Market manages the purchase of the item. There are two purchase types: "managed per user account" and "unmanaged."</p>
<p>Items that are managed per user account can be purchased only once per user account. When an item is managed per user account, Android Market permanently stores the transaction information for each item on a per-user basis. This enables you to query Android Market with the <code>RESTORE_TRANSACTIONS</code> request and restore the state of the items a specific user has purchased.</p>
<p>If a user attempts to purchase a managed item that has already been purchased, Android Market displays an "Item already purchased" error. This occurs during checkout, when Android Market displays the price and description information on the checkout page. When the user dismisses the error message, the checkout page disappears and the user returns to your user interface. As a best practice, your application should prevent the user from seeing this error. The sample application demonstrates how you can do this by keeping track of items that are managed and already purchased and not allowing users to select those items from the list. Your application should do something similar&mdash;either graying out the item or hiding it so that it cannot be selected.</p>
<p>The "manage by user account" purchase type is useful if you are selling items such as game levels or application features. These items are not transient and usually need to be restored whenever a user reinstalls your application, wipes the data on their device, or installs your application on a new device.</p>
<p>Items that are unmanaged do not have their transaction information stored on Android Market, which means you cannot query Android Market to retrieve transaction information for items whose purchase type is listed as unmanaged. You are responsible for managing the transaction information of unmanaged items. Also, unmanaged items can be purchased multiple times as far as Android Market is concerned, so it's also up to you to control how many times an unmanaged item can be purchased.</p>
<p>The "unmanaged" purchase type is useful if you are selling consumable items, such as fuel or magic spells. These items are consumed within your application and are usually purchased multiple times.</p>
<h2 id="billing-refunds">Handling Refunds</h2>
<p>The in-app billing feature does not allow users to send a refund request to Android Market. Refunds for purchases that were made with the in-app billing feature must be directed to you (the application developer). You can then process the refund through your Google Checkout merchant account. When you do this, Android Market receives a refund notification from Google Checkout, and Android Market sends a refund message to your application. Your application can handle this message the same way it handles the response from an application-initiated <code>REQUEST_PURCHASE</code> message so that ultimately your application receives a purchase state change message that includes information about the item that's been refunded.</p>
<h2 id="billing-testing-setup">Setting Up Test Accounts</h2>
<p>The Android Market publisher site lets you set up one or more test accounts. A test account is a regular Google account that you register on the publisher site as a test account. Test accounts are authorized to make in-app purchases from applications that you have uploaded to the Android Market site but have not yet published.</p>
<p>You can use any Google account as a test account. Test accounts are useful if you want to let multiple people test in-app billing on applications without giving them access to your publisher account's sign-in credentials. If you want to own and control the test accounts, you can create the accounts yourself and distribute the credentials to your developers or testers.</p>
<p>Test accounts have three limitations:</p>
<ul>
<li>Test account users can make purchase requests only within applications that are already uploaded to your publisher account (although the application doesn't need to be published).</li>
<li>Test accounts can only be used to purchase items that are listed (and published) in an application's product list.</li>
<li>Test account users do not have access to your publisher account and cannot upload applications to your publisher account.</li>
</ul>
<p>To add test accounts to your publisher account, follow these steps:</p>
<ol>
<li><a href="http://market.android.com/publish">Log in</a> to your publisher account.</li>
<li>On the upper left part of the page, under your name, click <strong>Edit profile</strong>.</li>
<li>On the Edit Profile page, scroll down to the Licensing &amp; In-app Billing panel (see figure 3).</li>
<li>In Test Accounts, add the email addresses for the test accounts you want to register, separating each account with a comma.</li>
<li>Click <strong>Save</strong> to save your profile changes.</li>
</ol>
<div style="margin-bottom:2em;">
<img src="{@docRoot}images/billing_public_key.png" style="text-align:left;margin-bottom:0;" />
<div style="margin:0 2em;padding:0"><strong>Figure 3.</strong> The Licensing and In-app Billing
panel of your account's Edit Profile page lets you register test accounts.</div>
</div>
<h2 id="billing-support">Where to Get Support</h2>
<p>If you have questions or encounter problems while implementing in-app billing, contact the support resources listed in the following table (see table 2). By directing your queries to the correct forum, you can get the support you need more quickly.</p>
<p class="table-caption" id="support-table"><strong>Table 2.</strong> Developer support resources for Android Market in-app billing.</p>
<table>
<tr>
<th>Support Type</th>
<th>Resource</th>
<th>Range of Topics</th>
</tr>
<tr>
<td rowspan="2">Development and testing issues</td>
<td>Google Groups: <a href="http://groups.google.com/group/android-developers">android-developers</a> </td>
<td rowspan="2">In-app billing integration questions, user experience ideas, handling of responses, obfuscating code, IPC, test environment setup.</td>
</tr>
<tr>
<td>Stack Overflow: <a
href="http://stackoverflow.com/questions/tagged/android">http://stackoverflow.com/questions/tagged/android</a></td>
</tr>
<tr>
<td>Accounts, publishing, and deployment issues</td>
<td><a href="http://www.google.com/support/forum/p/Android+Market">Android
Market Help Forum</a></td>
<td>Publisher accounts, Android Market key pair, test accounts, server responses, test responses, application deployment and results.</td>
</tr>
<tr>
<td>Market billing issue tracker</td>
<td><a href="http://code.google.com/p/marketbilling/issues/">Market billing
project issue tracker</a></td>
<td>Bug and issue reports related specifically to in-app billing sample code.</td>
</tr>
</table>
<p>For general information about how to post to the groups listed above, see <a href="{@docRoot}resources/community-groups.html">Developer Forums</a> document in the Resources tab.</p>

View File

@@ -0,0 +1,79 @@
page.title=Security and Design
@jd:body
<style type="text/css">
#jd-content {
background:transparent url({@docRoot}assets/images/preliminary.png) repeat scroll 0 0;
}
</style>
<div id="qv-wrapper">
<div id="qv">
<h2>In this document</h2>
<ol>
<li><a href="#billing-security">Security Best Practices</a></li>
</ol>
<h2>Downloads</h2>
<ol>
<li><a href="{@docRoot}guide/market/billing/billing_integrate.html#billing-download">Sample Application</a></li>
</ol>
<h2>See also</h2>
<ol>
<li><a href="{@docRoot}guide/market/billing/billing_overview.html">Overview of In-app Billing</a></li>
<li><a href="{@docRoot}guide/market/billing/billing_integrate.html">Implementing In-app Billing</a></li>
<li><a href="{@docRoot}guide/market/billing/billing_testing.html">Testing In-app Billing</a></li>
<li><a href="{@docRoot}guide/market/billing/billing_admin.html">Administering In-app Billing</a></li>
<li><a href="{@docRoot}guide/market/billing/billing_reference.html">In-app Billing Reference</a></li>
</ol>
</div>
</div>
<div class="special" style="margin-right:345px">
<p>This documentation provides an early look at the Android Market In-app Billing service. The documentation may change without notice.</p>
</div>
<p>As you design your in-app billing implementation, be sure to follow the security and design guidelines that are discussed in this document. These guidelines are recommended best practices for anyone who is using the Android Market In-app Billing service and can be incorporated into any in-app billing implementation.</p>
<h2>Security Best Practices</h2>
<h4>Perform signature verification tasks on a server</h4>
<p>If practical, you should perform signature verification on a remote server and not on a device. Implementing the verification process on a server makes it difficult for attackers to break the verification process by reverse engineering your .apk file. If you do offload security processing to a remote server, be sure that the device-server handshake is secure.</p>
<h4>Protect your unlocked content</h4>
<p>To prevent malicious users from redistributing your unlocked content, do not bundle it in your .apk file. Instead, do one of the following:</p>
<ul>
<li>Use a real-time service to deliver your content, such as a content feed. Delivering content through a real-time service allows you to keep your content fresh.</li>
<li>Use a remote server to deliver your content.</li>
</ul>
<p>When you deliver content from a remote server or a real-time service, you can store the unlocked content in device memory or store it on the device's SD card. If you store content on an SD card, be sure to encrypt the content and use a device-specific encryption key.</p>
<h4>Obfuscate your code</h4>
<p>You should obfuscate your in-app billing code so it is difficult for an attacker to reverse engineer security protocols and other application components. At a minimum, we recommend that you run an obfuscation tool like <a href="http://developer.android.com/guide/developing/tools/proguard.html">Proguard</a> on your code.</p>
<p>In addition to running an obfuscation program, we recommend that you use the following techniques to obfuscate your in-app billing code.</p>
<ul>
<li>Inline methods into other methods.</li>
<li>Construct strings on the fly instead of defining them as constants.</li>
<li>Use Java reflection to call methods.</li>
</ul>
<p>Using these techniques can help reduce the attack surface of your application and help minimize attacks that can compromise your in-app billing implementation.</p>
<div class="note">
<p><strong>Note:</strong> If you use Proguard to obfuscate your code, you must add the following line to your Proguard configuration file:</p>
<p><code>-keep class com.android.vending.billing.**</code></p>
</div>
<h4>Modify all sample application code</h4>
<p>The in-app billing sample application is publicly distributed and can be downloaded by anyone, which means it is relatively easy for an attacker to reverse engineer your application if you use the sample code exactly as it is published. The sample application is intended to be used only as an example. If you use any part of the sample application, you must modify it before you publish it or release it as part of a production application.</p>
<p>In particular, attackers look for known entry points and exit points in an application, so it is important that you modify these parts of your code that are identical to the sample application.</p>
<h4>Use secure random nonces</h4>
<p>Nonces must not be predictable or reused. Always use a cryptographically secure random number generator (like {@link java.security.SecureRandom}) when you generate nonces. This can help reduce replay attacks.</p>
<p>Also, if you are performing nonce verification on a server, make sure that you generate the nonces on the server.</p>
<h4>Take action against trademark and copyright infringement</h4>
<p>If you see your content being redistributed on Android Market, act quickly and decisively. File a <a href="http://market.android.com/support/bin/answer.py?hl=en&amp;answer=141511">trademark notice of infringement</a> or a <a href="http://www.google.com/android_dmca.html">copyright notice of infringement</a>.</p>
<h4>Implement a revocability scheme for unlocked content</h4>
<p>If you are using a remote server to deliver or manage content, have your application verify the purchase state of the unlocked content whenever a user accesses the content. This allows you to revoke use when necessary and minimize piracy.</p>
<h4>Protect your Android Market public key</h4>
<p>To keep your public key safe from malicious users and hackers, do not embed it in any code as a literal string. Instead, construct the string at runtime from pieces or use bit manipulation (for example, XOR with some other string) to hide the actual key. The key itself is not secret information, but you do not want to make it easy for a hacker or malicious user to replace the public key with another key.</p>

View File

@@ -0,0 +1,617 @@
page.title=Implementing In-app Billing
@jd:body
<style type="text/css">
#jd-content {
background:transparent url({@docRoot}assets/images/preliminary.png) repeat scroll 0 0;
}
</style>
<div id="qv-wrapper">
<div id="qv">
<h2>In this document</h2>
<ol>
<li><a href="#billing-download">Downloading the Sample Application</a></li>
<li><a href="#billing-add-aidl">Adding the AIDL file to your project</a></li>
<li><a href="#billing-permission">Updating Your Application's Manifest</a></li>
<li><a href="#billing-service">Creating a Service</a></li>
<li><a href="#billing-broadcast-receiver">Creating a BroadcastReceiver</a></li>
<li><a href="#billing-signatures">Creating a security processing component</a></li>
<li><a href="#billing-implement">Modifying Your Application Code</a></li>
</ol>
<h2>Downloads</h2>
<ol>
<li><a href="#billing-download">Sample Application</a></li>
</ol>
<h2>See also</h2>
<ol>
<li><a href="{@docRoot}guide/market/billing/billing_overview.html">Overview of In-app Billing</a></li>
<li><a href="{@docRoot}guide/market/billing/billing_best_practices.html">Security and Design</a></li>
<li><a href="{@docRoot}guide/market/billing/billing_testing.html">Testing In-app Billing</a></li>
<li><a href="{@docRoot}guide/market/billing/billing_admin.html">Administering In-app Billing</a></li>
<li><a href="{@docRoot}guide/market/billing/billing_reference.html">In-app Billing Reference</a></li>
</ol>
</div>
</div>
<div class="special" style="margin-right:345px">
<p>This documentation provides an early look at the Android Market In-app Billing service. The documentation may change without notice.</p>
</div>
<p>The Android Market In-app Billing service provides a straightforward, simple interface for sending in-app billing requests and managing in-app billing transactions using Android Market. This document helps you implement in-app billing by stepping through the primary implementation tasks, using the in-app billing sample application as an example.</p>
<p>Before you implement in-app billing in your own application, be sure that you read <a href="{@docRoot}guide/market/billing/billing_overview.html">Overview of In-app Billing</a> and <a href="{@docRoot}guide/market/billing/billing_best_practices.html">Security and Design</a>. These documents provide background information that will make it easier for you to implement in-app billing.</p>
<p>To implement in-app billing in your application, you need to do the following:</p>
<ol>
<li><a href="#billing-download">Download the in-app billing sample application</a>.</li>
<li><a href="#billing-add-aidl">Add the IMarketBillingService.aidl file</a> to your project.</li>
<li><a href="#billing-permission">Update your AndroidManifest.xml file</a>.</li>
<li><a href="#billing-service">Create a Service</a> and bind it to the <code>MarketBillingService</code> so your application can send billing requests and receive billing responses from the Android Market application.</li>
<li><a href="#billing-broadcast-receiver">Create a BroadcastReceiver</a> to handle broadcast intents from the Android Market application.</li>
<li><a href="#billing-signatures">Create a security processing component</a> to verify the integrity of the transaction messages that are sent by Android Market .</li>
<li><a href="#billing-implement">Modify your application code</a> to support in-app billing.</li>
</ol>
<h2 id="billing-download">Downloading the Sample Application</h2>
<p>The in-app billing sample application shows you how to perform several tasks that are common to all in-app billing implementations, including:</p>
<ul>
<li>Sending in-app billing requests to the Android Market application.</li>
<li>Handling synchronous responses from the Android Market application.</li>
<li>Handling broadcast intents (asynchronous responses) from the Android Market application.</li>
<li>Using in-app billing security mechanisms to verify the integrity of billing responses.</li>
<li>Creating a user interface that lets users select items for purchase.</li>
</ul>
<p>The sample application includes an application file (<code><code>Dungeons.java</code></code>), the AIDL file for the <code>MarketBillingService</code> (<code>IMarketBillingService.aidl</code>), and several classes that demonstrate in-app billing messaging. It also includes a class that demonstrates basic security tasks, such as signature verification.</p>
<p>Table 1 lists the source files that are included with the sample application.</p>
<p class="table-caption" id="source-files-table"><strong>Table 1.</strong>
In-app billing sample application source files.</p>
<table>
<tr>
<th>File</th>
<th>Description</th>
</tr>
<tr>
<td>IMarketBillingService.aidl</td>
<td>Android Interface Definition Library (AIDL) file that defines the IPC interface to the Android Market in-app billing service (<code>MarketBillingService</code>).</td>
</tr>
<tr>
<td>Dungeons.java</td>
<td>Sample application file that provides a UI for making purchases and diplaying purchase history.</td>
</tr>
<tr>
<td>PurchaseDatabase.java</td>
<td>A local database for storing purchase information.</td>
</tr>
<tr>
<td>BillingReceiver.java</td>
<td>A {@link android.content.BroadcastReceiver} that receives asynchronous response messages (broadcast intents) from Android Market. Forwards all messages to the <code>BillingService</code>.</td>
</tr>
<tr>
<td>BillingService.java</td>
<td>A {@link android.app.Service} that sends messages to Android Market on behalf of the application by connecting (binding) to the <code>MarketBillingService</code>.</td>
</tr>
<tr>
<td>ResponseHandler.java</td>
<td>A {@link android.os.Handler} that contains methods for updating the purchases database and the UI.</td>
</tr>
<tr>
<td>PurchaseObserver.java</td>
<td>An abstract class for observing changes related to purchases.</td>
</tr>
<tr>
<td>Security.java</td>
<td>Provides various security-related methods.</td>
</tr>
<tr>
<td>Consts.java</td>
<td>Defines various Android Market constants and sample application constants. All constants that are defined by Android Market must be defined the same way in your application.</td>
</tr>
<tr>
<td>Base64.java and Base64DecoderException.java</td>
<td>Provides conversion services from binary to Base64 encoding. The <code>Security</code> class relies on these utility classes.</td>
</tr>
</table>
<p>The in-app billing sample application is available as a downloadable component of the Android SDK. To download the sample application component, launch the Android SDK and AVD Manager and then select the "Market Billing package, revision 1" component (see figure 1), and click <strong>Install Selected</strong> to begin the download.</p>
<div style="margin-bottom:2em;">
<img src="{@docRoot}images/billing_package.png" style="text-align:left;margin-bottom:0;" />
<div style="margin:0 2em;padding:0"><strong>Figure 1.</strong> The Google Market
Billing package contains the sample application and the AIDL file. </div>
</div>
<p>When the download is complete, the Android SDK and AVD Manager saves the component into the following directory:</p>
<p><code>&lt;sdk&gt;/google-market_billing/</code></p>
<h2 id="billing-add-aidl">Adding the AIDL file to your project</h2>
<p>The sample application contains an Android Interface Definition Language (AIDL) file, which defines the interface to the Android Market in-app billing service <code>MarketBillingService</code>). When you add this file to your project, the Android build environment creates an interface file (<code>IMarketBillingService.java</code>). You can then use this interface to make billing requests by invoking IPC method calls.</p>
<p>If you are using the ADT plug-in with Eclipse, you can just add this file to your <code>/src</code> directory. Eclipse will automatically generate the interface file when you build your project (which should happen immediately). If you are not using the ADT plug-in, you can put the AIDL file into your project and use the Ant tool to build your project so that the <code>IMarketBillingService.java</code> file gets generated.</p>
<p>To add the <code>IMarketBillingService.aidl</code> file to your project, do the following:</p>
<ol>
<li>Create the following directory in your application's <code>/src</code> directory:
<p><code>com/android/vending/billing/</code></p>
</li>
<li>Copy the <code>IMarketBillingService.aidl</code> file into the <code>sample/src/com/android/vending/billing/</code> directory.</li>
<li>Build your application.</li>
</ol>
<p>You should now find a generated interface file named <code><code>IMarketBillingService.java</code></code> in the <code>gen</code> folder of your project.</p>
<h2 id="billing-permission">Updating Your Application's Manifest</h2>
<p>In-app billing relies on the Android Market application, which handles all communication between your application and the Android Market server. To use the Android Market application, your application must request the proper permission. You can do this by adding the <code>com.android.vending.BILLING</code> permission to your AndroidManifest.xml file. If your application does not declare the in-app billing permission, but attempts to send billing requests, Android Market will refuse the requests and respond with a <code>RESULT_DEVELOPER_ERROR</code> response code.</p>
<p>In addition to the billing permission, you need to declare the {@link android.content.BroadcastReceiver} that you will use to receive asynchronous response messages (broadcast intents) from Android Market, and you need to declare the {@link android.app.Service} that you will use to bind with the <code>IMarketBillingService</code> and send messages to Android Market. You must also declare <a href="{@docRoot}guide/topics/manifest/intent-filter-element.html">intent filters</a> for the {@link android.content.BroadcastReceiver} so that the Android system knows how to handle broadcast intents that are sent from the Android Market application.</p>
<p>For example, here's how the in-app billing sample application declares the billing permission, the {@link android.content.BroadcastReceiver}, the {@link android.app.Service}, and the intent filters. In the sample application, <code>BillingReceiver</code> is the {@link android.content.BroadcastReceiver} that handles broadcast intents from the Android Market application and <code>BillingService</code> is the {@link android.app.Service} that sends requests to the Android Market application.</p>
<pre>
&lt;?xml version="1.0" encoding="utf-8"?&gt;
&lt;manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.dungeons"
android:versionCode="1"
android:versionName="1.0"&gt;
&lt;uses-permission android:name="com.android.vending.BILLING" /&gt;
&lt;application android:icon="@drawable/icon" android:label="@string/app_name"&gt;
&lt;activity android:name=".Dungeons" android:label="@string/app_name"&gt;
&lt;intent-filter&gt;
&lt;action android:name="android.intent.action.MAIN" /&gt;
&lt;category android:name="android.intent.category.LAUNCHER" /&gt;
&lt;/intent-filter&gt;
&lt;/activity&gt;
&lt;service android:name="BillingService" /&gt;
&lt;receiver android:name="BillingReceiver"&gt;
&lt;intent-filter&gt;
&lt;action android:name="com.android.vending.billing.IN_APP_NOTIFY" /&gt;
&lt;action android:name="com.android.vending.billing.RESPONSE_CODE" /&gt;
&lt;action android:name="com.android.vending.billing.PURCHASE_STATE_CHANGED" /&gt;
&lt;/intent-filter&gt;
&lt;/receiver&gt;
&lt;/application&gt;
&lt;/manifest&gt;
</pre>
<h2 id="billing-service">Creating a Local Service</h2>
<p>Your application must have a local {@link android.app.Service} to facilitate messaging between your application and Android Market. At a minimum, this service must do the following:</p>
<ul>
<li>Bind to the <code>MarketBillingService</code>.
<li>Send billing requests (as IPC method calls) to the Android Market application. The five types of billing requests include:
<ul>
<li><code>CHECK_BILLING_SUPPORTED</code> requests</li>
<li><code>REQUEST_PURCHASE</code> requests</li>
<li><code>GET_PURCHASE_INFORMATION</code> requests</li>
<li><code>CONFIRM_NOTIFICATIONS</code> requests</li>
<li><code>RESTORE_TRANSACTIONS</code> requests</li>
</ul>
</li>
<li>Handle the synchronous response messages that are returned with each billing request.</li>
</ul>
<h3>Binding to the MarketBillingService</h3>
<p>Binding to the <code>MarketBillingService</code> is relatively easy if you've already added the <code>IMarketBillingService.aidl</code> file to your project. The following code sample shows how to use the {@link android.content.Context#bindService bindService()} method to bind a service to the <code>MarketBillingService</code>. You could put this code in your service's {@link android.app.Activity#onCreate onCreate()} method.</p>
<pre>
try {
boolean bindResult = mContext.bindService(
new Intent("com.android.vending.billing.MarketBillingService.BIND"), this, Context.BIND_AUTO_CREATE);
if (bindResult) {
Log.i(TAG, "Service bind successful.");
} else {
Log.e(TAG, "Could not bind to the MarketBillingService.");
}
} catch (SecurityException e) {
Log.e(TAG, "Security exception: " + e);
}
</pre>
<p>After you bind to the service, you need to create a reference to the <code>IMarketBillingService</code> interface so you can make billing requests via IPC method calls. The following code shows you how to do this using the {@link android.content.ServiceConnection#onServiceConnected onServiceConnected()} callback method.</p>
<pre>
/**
* The Android system calls this when we are connected to the MarketBillingService.
*/
public void onServiceConnected(ComponentName name, IBinder service) {
Log.i(TAG, "MarketBillingService connected.");
mService = IMarketBillingService.Stub.asInterface(service);
}
</pre>
<p>You can now use the <code>mService</code> reference to invoke the <code>sendBillingRequest()</code> method.</p>
<p>For a complete implementation of a service that binds to the <code>MarketBillingService</code>, see the <code>BillingService</code> class in the sample application.</p>
<h3>Sending billing requests to the MarketBillingService</h3>
<p>Now that your {@link android.app.Service} has a reference to the <code>IMarketBillingService</code> interface, you can use that reference to send billing requests (via IPC method calls) to the <code>MarketBillingService</code>. The <code>MarketBillingService</code> IPC interface exposes a single public method (<code>sendBillingRequest()</code>), which takes a single {@link android.os.Bundle} parameter. The Bundle that you deliver with this method specifies the type of request you want to perform, using various key-value pairs. For instance, one key indicates the type of request you are making, another indicates the item being purchased, and another identifies your application. The <code>sendBillingRequest()</code> method immediately returns a Bundle containing an initial response code. However, this is not the complete purchase response; the complete response is delivered with an asynchronous broadcast intent. For more information about the various Bundle keys that are supported by the <code>MarketBillingService</code>, see <a href="{@docRoot}guide/market/billing/billing_reference.html#billing-interface">In-app Billing Service Interface</a>.</p>
<p>You can use the <code>sendBillingRequest()</code> method to send five types of billing requests. The five request types are specified using the <code>BILLING_REQUEST</code> Bundle key. This Bundle key can have the following five values:</p>
<ul>
<li><code>CHECK_BILLING_SUPPORTED</code>&mdash;verifies that the Android Market application supports in-app billing.</li>
<li><code>REQUEST_PURCHASE</code>&mdash;sends a purchase request for an in-app item.</li> <li><code>GET_PURCHASE_INFORMATION</code>&mdash;retrieves transaction information for a purchase or refund.</li>
<li><code>CONFIRM_NOTIFICATIONS</code>&mdash;acknowledges that you received the transaction information for a purchase or refund.</li>
<li><code>RESTORE_TRANSACTIONS</code>&mdash;retrieves a user's transaction history for <a href="{@docRoot}guide/market/billing/billing_admin.html#billing-purchase-type">managed purchases</a>.</li>
</ul>
<p>To make any of these billing requests, you first need to build an initial Bundle that contains the three keys that are required for all requests: <code>BILLING_REQUEST</code>, <code>API_VERSION</code>, and <code>PACKAGE_NAME</code>. The following code sample shows you how to create a helper method named <code>makeRequestBundle()</code> that does this.</p>
<pre>
protected Bundle makeRequestBundle(String method) {
Bundle request = new Bundle();
request.putString(BILLING_REQUEST, method);
request.putInt(API_VERSION, 1);
request.putString(PACKAGE_NAME, getPackageName());
return request;
</pre>
<p>To use this helper method, you pass in a <code>String</code> that corresponds to one of the five types of billing requests. The method returns a Bundle that has the three required keys defined. The following sections show you how to use this helper method when you send a billing request.<p>
<p class="caution"><strong>Important</strong>: You must make all in-app billing requests from your application's main thread.</p>
<h4>Verifying that in-app billing is supported (CHECK_BILLING_SUPPPORTED)</h4>
<p>The following code sample shows how to verify whether the Android Market application supports in-app billing. In the sample, <code>mService</code> is an instance of the <code>MarketBillingService</code> interface.</p>
<pre>
/**
* Request type is CHECK_BILLING_SUPPORTED
*/
Bundle request = makeRequestBundle("CHECK_BILLING_SUPPORTED");
Bundle response = mService.sendBillingRequest(request);
// Do something with this response.
}
</pre>
<p>The <code>makeRequestBundle()</code> method constructs an initial Bundle, which contains the three keys that are required for all requests: <code>BILLING_REQUEST</code>, <code>API_VERSION</code>, and <code>PACKAGE_NAME</code>. The request returns a synchronous {@link android.os.Bundle} response, which contains only a single key: <code>RESPONSE_CODE</code>. The <code>RESPONSE_CODE</code> key can have the following values:</p>
<ul>
<li><code>RESULT_OK</code>&mdash;in-app billing is supported.</li>
<li><code>RESULT_BILLING_UNAVAILABLE</code>&mdash;in-app billing is not supported or the in-app billing API version you specified is not recognized.</li>
<li><code>RESULT_ERROR</code>&mdash;there was an error connecting with the Android Market appliction.</li>
<li><code>RESULT_DEVELOPER_ERROR</code>&mdash;the application is trying to make an in-app billing request but the application has not declared the com.android.vending.BILLING permission in its manifest. Can also indicate that an application is not properly signed, or that you sent a malformed request.</li>
</ul>
<p>The <code>CHECK_BILLING_SUPPORTED</code> request does not trigger any asynchronous responses (broadcast intents).</p>
<h4>Making a purchase request (REQUEST_PURCHASE)</h4>
<p>To make a purchase request you must do the following:</p>
<ul>
<li>Send the <code>REQUEST_PURCHASE</code> request.</li>
<li>Launch the {@link android.app.PendingIntent} that is returned from the Android Market application.</li>
<li>Handle the broadcast intents that are sent by the Android Market application.</li>
</ul>
<h5>Making the request</h5>
<p>You must specify four keys in the request {@link android.os.Bundle}. The following code sample shows how to set these keys and make a purchase request for a single in-app item. In the sample, <code>mProductId</code> is the Android Market product ID of an in-app item (which is listed in the application's <a href="{@docRoot}guide/market/billing/billing_admin.html#billing-list-setup">product list</a>), and <code>mService</code> is an instance of the <code>MarketBillingService</code> interface.</p>
<pre>
/**
* Request type is REQUEST_PURCHASE
*/
Bundle request = makeRequestBundle("REQUEST_PURCHASE");
request.putString(ITEM_ID, mProductId);
// Note that the developer payload is optional.
if (mDeveloperPayload != null) {
request.putString(DEVELOPER_PAYLOAD, mDeveloperPayload);
Bundle response = mService.sendBillingRequest(request);
// Do something with this response.
}
</pre>
<p>The <code>makeRequestBundle()</code> method constructs an initial Bundle, which contains the three keys that are required for all requests: <code>BILLING_REQUEST</code>, <code>API_VERSION</code>, and <code>PACKAGE_NAME</code>. The <code>ITEM_ID</code> key is then added to the Bundle prior to invoking the <code>sendBillingRequest()</code> method.</p>
<p>The request returns a synchronous {@link android.os.Bundle} response, which contains three keys: <code>RESPONSE_CODE</code>, <code>PURCHASE_INTENT</code>, and <code>REQUEST_ID</code>. The <code>RESPONSE_CODE</code> key provides you with the status of the request and the <code>REQUEST_ID</code> key provides you with a unique request identifier for the request. The <code>PURCHASE_INTENT</code> key provides you with a {@link android.app.PendingIntent}, which you can use to launch the checkout UI.</p>
<h5>Launching the pending intent</h5>
<p>How you use the pending intent depends on which version of Android a device is running. On Android 1.6, you must use the pending intent to launch the checkout UI in its own separate task instead of your application's activity stack. On Android 2.0 and higher, you can use the pending intent to launch the checkout UI on your application's activity stack. The following code shows you how to do this. You can find this code in the PurchaseObserver.java file in the sample application.</p>
<pre>
void startBuyPageActivity(PendingIntent pendingIntent, Intent intent) {
if (mStartIntentSender != null) {
// This is on Android 2.0 and beyond. The in-app checkout page activity
// will be on the activity stack of the application.
try {
// This implements the method call:
// mActivity.startIntentSender(pendingIntent.getIntentSender(),
// intent, 0, 0, 0);
mStartIntentSenderArgs[0] = pendingIntent.getIntentSender();
mStartIntentSenderArgs[1] = intent;
mStartIntentSenderArgs[2] = Integer.valueOf(0);
mStartIntentSenderArgs[3] = Integer.valueOf(0);
mStartIntentSenderArgs[4] = Integer.valueOf(0);
mStartIntentSender.invoke(mActivity, mStartIntentSenderArgs);
} catch (Exception e) {
Log.e(TAG, "error starting activity", e);
}
} else {
// This is on Android 1.6. The in-app checkout page activity will be on its
// own separate activity stack instead of on the activity stack of
// the application.
try {
pendingIntent.send(mActivity, 0 /* code */, intent);
} catch (CanceledException e) {
Log.e(TAG, "error starting activity", e);
}
}
}
</pre>
<p class="note">You must launch the pending intent from an activity context and not an application context.</p>
<h5>Handling broadcast intents</h5>
<p>A <code>REQUEST_PURCHASE</code> request also triggers two asynchronous responses (broadcast intents). First, the Android Market application sends an <code>ACTION_RESPONSE_CODE</code> broadcast intent, which provides error information about the request. Next, if the request was successful, the Android Market application sends an <code>ACTION_NOTIFY</code> broadcast intent. This message contains a notification ID, which you can use to retrieve the transaction details for the <code>REQUEST_PURCHASE</code> request.</p>
<p>Keep in mind, the Android Market application also sends an <code>ACTION_NOTIFY</code> for refunds. For more information, see <a href="{@docRoot}guide/market/billing/billing_overview.html#billing-action-notify">Handling ACTION_NOTIFY messages</a>.</p>
<h4>Retrieving transaction information for a purchase or refund (GET_PURCHASE_INFORMATION)</h4>
<p>You retrieve transaction information in response to an <code>ACTION_NOTIFY</code> broadcast intent. The <code>ACTION_NOTIFY</code> message contains a notification ID, which you can use to retrieve transaction information.</p>
<p>To retrieve transaction information for a purchase or refund you must specify five keys in the request {@link android.os.Bundle}. The following code sample shows how to set these keys and make the request. In the sample, <code>mService</code> is an instance of the <code>MarketBillingService</code> interface.</p>
<pre>
/**
* Request type is GET_PURCHASE_INFORMATION
*/
Bundle request = makeRequestBundle("GET_PURCHASE_INFORMATION");
request.putLong(REQUEST_NONCE, mNonce);
request.putStringArray(NOTIFY_IDS, mNotifyIds);
Bundle response = mService.sendBillingRequest(request);
// Do something with this response.
}
</pre>
<p>The <code>makeRequestBundle()</code> method constructs an initial Bundle, which contains the three keys that are required for all requests: <code>BILLING_REQUEST</code>, <code>API_VERSION</code>, and <code>PACKAGE_NAME</code>. The additional keys are then added to the bundle prior to invoking the <code>sendBillingRequest()</code> method. The <code>REQUEST_NONCE</code> key contains a cryptographically secure nonce (number used once) that you must generate. The Android Market application returns this nonce with the <code>ACTION_PURCHASE_STATE_CHANGED</code> broadcast intent so you can verify the integrity of the transaction information. The <code>NOTIFY_IDS</code> key contains an array of notification IDs, which you received in the <code>ACTION_NOTIFY</code> broadcast intent.</p>
<p>The request returns a synchronous {@link android.os.Bundle} response, which contains two keys: <code>RESPONSE_CODE</code> and <code>REQUEST_ID</code>. The <code>RESPONSE_CODE</code> key provides you with the status of the request and the <code>REQUEST_ID</code> key provides you with a unique request identifier for the request.</p>
<p>A <code>GET_PURCHASE_INFORMATION</code> request also triggers two asynchronous responses (broadcast intents). First, the Android Market application sends an <code>ACTION_RESPONSE_CODE</code> broadcast intent, which provides status and error information about the request. Next, if the request was successful, the Android Market application sends an <code>ACTION_PURCHASE_STATE_CHANGED</code> broadcast intent. This message contains detailed transaction information. The transaction information is contained in a signed JSON string (unencrypted). The message includes the signature so you can verify the integrity of the signed string.</p>
<h4>Acknowledging transaction information (CONFIRM_NOTIFICATIONS)</h4>
<p>To acknowledge that you received transaction information you send a <code>CONFIRM_NOTIFICATIONS</code> request. You must specify four keys in the request {@link android.os.Bundle}. The following code sample shows how to set these keys and make the request. In the sample, <code>mService</code> is an instance of the <code>MarketBillingService</code> interface.</p>
<pre>
/**
* Request type is CONFIRM_NOTIFICATIONS
*/
Bundle request = makeRequestBundle("CONFIRM_NOTIFICATIONS");
request.putStringArray(NOTIFY_IDS, mNotifyIds);
Bundle response = mService.sendBillingRequest(request);
// Do something with this response.
}
</pre>
<p>The <code>makeRequestBundle()</code> method constructs an initial Bundle, which contains the three keys that are required for all requests: <code>BILLING_REQUEST</code>, <code>API_VERSION</code>, and <code>PACKAGE_NAME</code>. The additional <code>NOTIFY_IDS</code> key is then added to the bundle prior to invoking the <code>sendBillingRequest()</code> method. The <code>NOTIFY_IDS</code> key contains an array of notification IDs, which you received in an <code>ACTION_NOTIFY</code> broadcast intent and also used in a <code>GET_PURCHASE_INFORMATION</code> request.</p>
<p>The request returns a synchronous {@link android.os.Bundle} response, which contains two keys: <code>RESPONSE_CODE</code> and <code>REQUEST_ID</code>. The <code>RESPONSE_CODE</code> key provides you with the status of the request and the <code>REQUEST_ID</code> key provides you with a unique request identifier for the request.</p>
<p>A <code>CONFIRM_NOTIFICATIONS</code> request triggers a single asynchronous response&mdash;an <code>ACTION_RESPONSE_CODE</code> broadcast intent. This broadcast intent provides status and error information about the request.</p>
<h4>Restoring transaction information (RESTORE_TRANSACTIONS)</h4>
<p>To restore a user's transaction information, you send a <code>RESTORE_TRANSACTIONS</code> request. You must specify four keys in the request {@link android.os.Bundle}. The following code sample shows how to set these keys and make the request. In the sample, <code>mService</code> is an instance of the <code>MarketBillingService</code> interface.</p>
<pre>
/**
* Request type is RESTORE_TRANSACTIONS
*/
Bundle request = makeRequestBundle("RESTORE_TRANSACTIONS");
request.putLong(REQUEST_NONCE, mNonce);
Bundle response = mService.sendBillingRequest(request);
// Do something with this response.
}
</pre>
<p>The <code>makeRequestBundle()</code> method constructs an initial Bundle, which contains the three keys that are required for all requests: <code>BILLING_REQUEST</code>, <code>API_VERSION</code>, and <code>PACKAGE_NAME</code>. The additional <code>REQUEST_NONCE</code> key is then added to the bundle prior to invoking the <code>sendBillingRequest()</code> method. The <code>REQUEST_NONCE</code> key contains a cryptographically secure nonce (number used once) that you must generate. The Android Market application returns this nonce with the transactions information contained in the <code>ACTION_PURCHASE_STATE_CHANGED</code> broadcast intent so you can verify the integrity of the transaction information.</p>
<p>The request returns a synchronous {@link android.os.Bundle} response, which contains two keys: <code>RESPONSE_CODE</code> and <code>REQUEST_ID</code>. The <code>RESPONSE_CODE</code> key provides you with the status of the request and the <code>REQUEST_ID</code> key provides you with a unique request identifier for the request.</p>
<p>A <code>RESTORE_TRANSACTIONS</code> request also triggers two asynchronous responses (broadcast intents). First, the Android Market application sends an <code>ACTION_RESPONSE_CODE</code> broadcast intent, which provides status and error information about the request. Next, if the request was successful, the Android Market application sends an <code>ACTION_PURCHASE_STATE_CHANGED</code> broadcast intent. This message contains the detailed transaction information. The transaction information is contained in a signed JSON string (unencrypted). The message includes the signature so you can verify the integrity of the signed string.</p>
<h3>Other service tasks</h3>
<p>You may also want your {@link android.app.Service} to receive intent messages from your {@link android.content.BroadcastReceiver}. You can use these intent messages to convey the information that was sent asynchronously from the Android Market application to your {@link android.content.BroadcastReceiver}. To see an example of how you can send and receive these intent messages, see the BillingReceiver.java and BillingService.java files in the sample application. You can use these samples as a basis for your own implementation. However, if you use any of the code from the sample application, be sure you follow the guidelines in <a href="{@docRoot}guide/market/billing/billing_best_practices.html">Security and Design</a>.</p>
<h2 id="billing-broadcast-receiver">Creating a BroadcastReceiver</h2>
<p>The Android Market application uses broadcast intents to send asynchronous billing responses to your application. To receive these intent messages, you need to create a {@link android.content.BroadcastReceiver} that can handle the following intents:</p>
<ul>
<li>ACTION_RESPONSE_CODE
<p>This broadcast intent contains an Android Market response code, and is sent after you make an in-app billing request. For more information about the response codes that are sent with this response, see <a href="{@docRoot}guide/market/billing/billing_reference.html#billing-codes">Android Market Response Codes for In-app Billing</a>.</p>
</li>
<li>ACTION_NOTIFY
<p>This response indicates that a purchase has changed state, which means a purchase succeeded, was canceled, or was refunded. For more information about notification messages, see <a href="{@docRoot}guide/market/billing/billing_reference.html#billing-intents">In-app Billing Broadcast Intents</a></p>
</li>
<li>ACTION_PURCHASE_STATE_CHANGED
<p>This broadcast intent contains detailed information about one or more transactions. For more information about purchase state messages, see <a href="{@docRoot}guide/market/billing/billing_reference.html#billing-intents">In-app Billing Broadcast Intents</a></p>
</li>
</ul>
<p>Each of these broadcast intents provide intent extras, which your {@link android.content.BroadcastReceiver} must handle. The intent extras are listed in the following table (see table 1).</p>
<p class="table-caption"><strong>Table 1.</strong> Description of broadcast intent extras that are sent in response to billing requests.</p>
<table>
<tr>
<th>Intent</th>
<th>Extra</th>
<th>Description</th>
</tr>
<tr>
<td><code>ACTION_RESPONSE_CODE</code></td>
<td><code>INAPP_REQUEST_ID</code></td>
<td>A <code>long</code> representing a request ID. A request ID identifies a specific billing request and is returned by Android Market at the time a request is made.</td>
</tr>
<tr>
<td><code>ACTION_RESPONSE_CODE</code></td>
<td><code>INAPP_RESPONSE_CODE</code></td>
<td>An <code>int</code> representing the actual Android Market server response code.</td>
</tr>
<tr>
<td><code>ACTION_NOTIFY</code></td>
<td><code>NOTIFICATION_ID</code></td>
<td>A <code>String</code> representing the notification ID for a given purchase state change. Android Market notifies you when there is a purchase state change and the notification includes a unique notification ID. To get the details of the purchase state change, you send the notification ID with the <code>GET_PURCHASE_INFORMATION</code> request.</td>
</tr>
<tr>
<td><code>ACTION_PURCHASE_STATE_CHANGED</code></td>
<td><code>INAPP_SIGNED_DATA</code></td>
<td>A <code>String</code> representing the signed JSON string. The JSON string contains information about the billing transaction, such as order number, amount, and the item that was purchased or refunded.</td>
</tr>
<tr>
<td><code>ACTION_PURCHASE_STATE_CHANGED</code></td>
<td><code>INAPP_SIGNATURE</code></td>
<td>A <code>String</code> representing the signature of the JSON string.</td>
</tr>
</table>
<p>The following code sample shows how to handle these broadcast intents and intent extras within a {@link android.content.BroadcastReceiver}. The BroadcastReceiver in this case is named <code>BillingReceiver</code>, just as it is in the sample application.</p>
<pre>
public class BillingReceiver extends BroadcastReceiver {
private static final String TAG = "BillingReceiver";
// Intent actions that we receive in the BillingReceiver from Android Market.
// These are defined by Android Market and cannot be changed.
// The sample application defines these in the Consts.java file.
public static final String ACTION_NOTIFY = "com.android.vending.billing.IN_APP_NOTIFY";
public static final String ACTION_RESPONSE_CODE = "com.android.vending.billing.RESPONSE_CODE";
public static final String ACTION_PURCHASE_STATE_CHANGED =
"com.android.vending.billing.PURCHASE_STATE_CHANGED";
// The intent extras that are passed in an intent from Android Market.
// These are defined by Android Market and cannot be changed.
// The sample application defines these in the Consts.java file.
public static final String NOTIFICATION_ID = "notification_id";
public static final String INAPP_SIGNED_DATA = "inapp_signed_data";
public static final String INAPP_SIGNATURE = "inapp_signature";
public static final String INAPP_REQUEST_ID = "request_id";
public static final String INAPP_RESPONSE_CODE = "response_code";
&#64;Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (ACTION_PURCHASE_STATE_CHANGED.equals(action)) {
String signedData = intent.getStringExtra(INAPP_SIGNED_DATA);
String signature = intent.getStringExtra(INAPP_SIGNATURE);
// Do something with the signedData and the signature.
} else if (ACTION_NOTIFY.equals(action)) {
String notifyId = intent.getStringExtra(NOTIFICATION_ID);
// Do something with the notifyId.
} else if (ACTION_RESPONSE_CODE.equals(action)) {
long requestId = intent.getLongExtra(INAPP_REQUEST_ID, -1);
int responseCodeIndex = intent.getIntExtra(INAPP_RESPONSE_CODE,
ResponseCode.RESULT_ERROR.ordinal());
// Do something with the requestId and the responseCodeIndex.
} else {
Log.w(TAG, "unexpected action: " + action);
}
}
// Perform other processing here, such as forwarding intent messages to your local service.
}
</pre>
<p>In addition to receiving broadcast intents from the Android Market application, your {@link android.content.BroadcastReceiver} must handle the information it received in the broadcast intents. Usually, your {@link android.content.BroadcastReceiver} does this by sending the information to a local service (discussed in the next section). The BillingReceiver.java file in the sample application shows you how to do this. You can use this sample as a basis for your own {@link android.content.BroadcastReceiver}. However, if you use any of the code from the sample application, be sure you follow the guidelines that are discussed in <a href="{@docRoot}guide/market/billing/billing_best_practices.html">Security and Design </a>.</p>
<h2 id="billing-signatures">Verifying Signatures and Nonces</h2>
<p>The in-app billing service uses two mechanisms to help verify the integrity of the transaction information you receive from Android Market: nonces and signatures. A nonce (number used once) is a cryptographically secure number that your application generates and sends with every <code>GET_PURCHASE_INFORMATION</code> and <code>RESTORE_TRANSACTIONS</code> request. The nonce is returned with the <code>ACTION_PURCHASE_STATE_CHANGED</code> broadcast intent, enabling you to verify that any given <code>ACTION_PURCHASE_STATE_CHANGED</code> response corresponds to an actual request that you made. Every <code>ACTION_PURCHASE_STATE_CHANGED</code> broadcast intent also includes a signed JSON string and a signature, which you can use to verify the integrity of the response.</p>
<p>Your application must provide a way to generate, manage, and verify nonces. The following sample code shows some simple methods you can use to do this.</p>
<pre>
private static final SecureRandom RANDOM = new SecureRandom();
private static HashSet&lt;Long&gt; sKnownNonces = new HashSet&lt;Long&gt;();
public static long generateNonce() {
long nonce = RANDOM.nextLong();
sKnownNonces.add(nonce);
return nonce;
}
public static void removeNonce(long nonce) {
sKnownNonces.remove(nonce);
}
public static boolean isNonceKnown(long nonce) {
return sKnownNonces.contains(nonce);
}
</pre>
<p>Your application must also provide a way to verify the signatures that accompany every <code>ACTION_PURCHASE_STATE_CHANGED</code> broadcast intent. The Security.java file in the sample application shows you how to do this. If you use this file as a basis for your own security implementation, be sure to follow the guidelines in <a href="{@docRoot}guide/market/billing/billing_best_practices.html">Security and Design</a> and obfuscate your code.</p>
<p>You will need to use your Android Market public key to perform the signature verification. The following procedure shows you how to retrieve Base64-encoded public key from the Android Market publisher site.</p>
<ol>
<li>Log in to your <a href="http://market.android.com/publish">publisher account</a>.</li>
<li>On the upper left part of the page, under your name, click <strong>Edit profile</strong>.</li>
<li>On the Edit Profile page, scroll down to the Licensing &amp; In-app Billing panel (see figure 2).</li>
<li>Copy your public key to the clipboard.</li>
</ol>
<p class="caution"><strong>Important</strong>: To keep your public key safe from malicious users and hackers, do not embed your public key as an entire literal string. Instead, construct the string at runtime from pieces or use bit manipulation (for example, XOR with some other string) to hide the actual key. The key itself is not secret information, but you do not want to make it easy for a hacker or malicious user to replace the public key with another key.</p>
<div style="margin-bottom:2em;">
<img src="{@docRoot}images/billing_public_key.png" style="text-align:left;margin-bottom:0;" />
<div style="margin:0 2em;padding:0"><strong>Figure 2.</strong> The Licensing and In-app Billing
panel of your account's Edit Profile page lets you see your public key.</div>
</div>
<h2 id="billing-implement">Modifying Your Application Code</h2>
<p>After you finish adding in-app billing components to your project, you are ready to modify your application's code. For a typical implementation, like the one that is demonstrated in the sample application, this means you need to write code to do the following: </p>
<ul>
<li>Create a storage mechanism for storing users' purchase information.</li>
<li>Create a user interface that lets users select items for purchase.</li>
</ul>
<p>The sample code in <code>Dungeons.java</code> shows you how to do both of these tasks.</p>
<h3>Creating a storage mechanism for storing purchase information</h3>
<p>You must set up a database or some other mechanism for storing users' purchase information. The sample application provides an example database (PurchaseDatabase.java); however, the example database has been simplified for clarity and does not exhibit the security best practices that we recommend. If you have a remote server, we recommend that you store purchase information on your server instead of in a local database on a device. For more information about security best practices, see <a href="{@docRoot}guide/market/billing/billing_best_practices.html">Security and Design</a>.</p>
<p class="note"><strong>Note</strong>: If you store any purchase information on a device, be sure to encrypt the data and use a device-specific encryption key.</p>
<h3>Creating a user interface for selecting items</h3>
<p>You must provide users with a means for selecting items that they want to purchase. Android Market provides the checkout user interface (which is where the user provides a form of payment and approves the purchase), but your application must provide a control (widget) that invokes the <code>sendBillingRequest()</code> method when a user selects an item for purchase.</p>
<p>You can render the control and trigger the <code>sendBillingRequest()</code> method any way you want. The sample application uses a spinner widget and a button to present items to a user and trigger a billing request (see <code>Dungeons.java</code>). The user interface also shows a list of recently purchased items.</p>

View File

@@ -0,0 +1,267 @@
page.title=Overview of In-app Billing
@jd:body
<style type="text/css">
#jd-content {
background:transparent url({@docRoot}assets/images/preliminary.png) repeat scroll 0 0;
}
</style>
<div id="qv-wrapper">
<div id="qv">
<h2>In this document</h2>
<ol>
<li><a href="#billing-arch">In-app Billing Architecture</a></li>
<li><a href="#billing-msgs">In-app Billing Messages</a></li>
<ol>
<li><a href="#billing-request">Request messages</a></li>
<li><a href="#billing-response">Broadcast intents</a></li>
<li><a href="#billing-message-sequence">Messaging sequence</a></li>
<li><a href="#billing-action-notify">Handling ACTION_NOTIFY messages</a></li>
</ol>
<li><a href="#billing-security">Security Controls</a></li>
<li><a href="#billing-limitations">Requirements and Limitations</a></li>
</ol>
<h2>Downloads</h2>
<ol>
<li><a href="{@docRoot}guide/market/billing/billing_integrate.html#billing-download">Sample Application</a></li>
</ol>
<h2>See also</h2>
<ol>
<li><a href="{@docRoot}guide/market/billing/billing_integrate.html">Implementing In-app Billing</a></li>
<li><a href="{@docRoot}guide/market/billing/billing_best_practices.html">Security and Design</a></li>
<li><a href="{@docRoot}guide/market/billing/billing_testing.html">Testing In-app Billing</a></li>
<li><a href="{@docRoot}guide/market/billing/billing_admin.html">Administering In-app Billing</a></li>
<li><a href="{@docRoot}guide/market/billing/billing_reference.html">In-app Billing Reference</a></li>
</ol>
</div>
</div>
<div class="special" style="margin-right:345px">
<p>This documentation provides an early look at the Android Market In-app Billing service. The documentation may change without notice.</p>
</div>
<p>The Android Market In-app Billing service is an Android Market feature that provides checkout processing for in-app purchases. To use the service, your application sends a billing request to the service for a specific in-app product. The service then handles all of the checkout details for the transaction, including requesting and validating the form of payment and processing the financial transaction. When the checkout process is complete, the service sends your application the purchase details, such as the order number, the order date and time, and the price paid. At no point does your application have to handle any financial transactions; that role is provided by the in-app billing service.</p>
<h2 id="billing-arch">In-app Billing Architecture</h2>
<p>In-app billing uses an asynchronous message loop to convey billing requests and billing responses between your application and the Android Market server. In practice, your application never directly communicates with the Android Market server (see figure 1). Instead, your application sends billing requests to the Android Market application over interprocess communication (IPC) and receives purchase responses from the Android Market application in the form of asynchronous broadcast intents. Your application does not manage any network connections between itself and the Android Market server or use any special APIs from the Android platform.</p>
<p>Some in-app billing implementations may also use a private remote server to deliver content or validate transactions, but a remote server is not required to implement in-app billing. A remote server can be useful if you are selling digital content that needs to be delivered to a user's device, such as media files or photos. You might also use a remote server to store users' transaction history or perform various in-app billing security tasks, such as signature verification. Although you can handle all security-related tasks in your application, performing those tasks on a remote server is recommended because it helps make your application less vulnerable to security attacks.</p>
<div class="figure" style="width:440px">
<img src="{@docRoot}images/billing_arch.png" alt=""/>
<p class="img-caption"><strong>Figure 1.</strong> Your application sends and receives billing messages through the Android Market application, which handles all communication with the Android Market server.</p>
</div>
<p>A typical in-app billing implementation relies on three components:</p>
<ul>
<li>A {@link android.app.Service} (named <code>BillingService</code> in the sample application), which processes purchase messages from the application and sends billing requests to the in-app billing service.</li>
<li>A {@link android.content.BroadcastReceiver} (named <code>BillingReceiver</code> in the sample application), which receives all asynchronous billing responses from the Android Market application.</li>
<li>A security component (named <code>Security</code> in the sample application), which performs security-related tasks, such as signature verification and nonce generation. For more information about in-app billing security, see <a href="#billing-security">Security controls</a> later in this document.</li>
</ul>
<p>You may also want to incorporate two other components to support in-app billing:</p>
<ul>
<li>A response {@link android.os.Handler} (named <code>ResponseHandler</code> in the sample application), which provides application-specific processing of purchase notifications, errors, and other status messages.</li>
<li>An observer (named <code>PurchaseObserver</code> in the sample application), which is responsible for sending callbacks to your application so you can update your user interface with purchase information and status.</li>
</ul>
<p>In addition to these components, your application must provide a way to store information about users' purchases and some sort of user interface that lets users select items to purchase. You do not need to provide a checkout user interface. When a user initiates an in-app purchase, the Android Market application presents the checkout user interface to your user. When the user completes the checkout process, your application resumes.</p>
<h2 id="billing-msgs">In-app Billing Messages</h2>
<p>When the user initiates a purchase, your application sends billing messages to the in-app billing service (named <code>MarketBillingService</code>) using simple IPC method calls. The Android Market application responds to all billing requests synchronously, providing your application with status notifications and other information. The Android Market application also responds to some billing requests asynchronously, providing your application with error messages and detailed transaction information. The following section describes the basic request-response messaging that takes place between your application and the Android Market application.</p>
<h3 id="billing-request">In-app billing requests</h3>
<p>Your application sends in-app billing requests by invoking a single IPC method (<code>sendBillingRequest()</code>), which is exposed by the <code>MarketBillingService</code> interface. This interface is defined in an <a href="{@docRoot}guide/developing/tools/aidl.html">Android Interface Definition Language</a> file (<code>IMarketBillingService.aidl</code>). You can download this AIDL file with the in-app billing sample application.</p>
<p>The <code>sendBillingRequest()</code> method has a single {@link android.os.Bundle} parameter. The Bundle that you deliver must include several key-value pairs that specify various parameters for the request, such as the type of billing request you are making, the item that is being purchased, and the application that is making the request. For more information about the Bundle keys that are sent with a request, see <a href="{@docRoot}guide/market/billing/billing_reference.html#billing-interface">In-app Billing Service Interface</a>.
<p>One of the most important keys that every request Bundle must have is the <code>BILLING_REQUEST</code> key. This key lets you specify the type of billing request you are making. The in-app billing service supports the following five types of billing requests:</p>
<ul>
<li><code>CHECK_BILLING_SUPPORTED</code>
<p>This request verifies that the Android Market application supports in-app billing. You usually send this request when your application first starts up. This request is useful if you want to enable or disable certain UI features that are relevant only to in-app billing.</p>
</li>
<li><code>REQUEST_PURCHASE</code>
<p>This request sends a purchase message to the Android Market application and is the foundation of in-app billing. You send this request when a user indicates that he or she wants to purchase an item in your application. Android Market then handles the financial transaction by displaying the checkout user interface.</p>
</li>
<li><code>GET_PURCHASE_INFORMATION</code>
<p>This request retrieves the details of a purchase state change. A purchase changes state when a requested purchase is billed successfully or when a user cancels a transaction during checkout. It can also occur when a previous purchase is refunded. Android Market notifies your application when a purchase changes state, so you only need to send this request when there is transaction information to retrieve.</p>
</li>
<li><code>CONFIRM_NOTIFICATIONS</code>
<p>This request acknowledges that your application received the details of a purchase state change. Android Market sends purchase state change notifications to your application until you confirm that you received them.</p>
</li>
<li><code>RESTORE_TRANSACTIONS</code>
<p>This request retrieves a user's transaction status for managed purchases (see <a href="{@docRoot}guide/market/billing/billing_admin.html#billing-purchase-type">Choosing a Purchase Type</a> for more information). You should send this request only when you need to retrieve a user's transaction status, which is usually only when your application is reinstalled or installed for the first time on a device.</p>
</li>
</ul>
<h3 id="billing-response">In-app Billing Responses</h3>
<p>The Android Market application responds to in-app billing requests with both synchronous and asynchronous responses. The synchronous response is a {@link android.os.Bundle} with the following three keys:</p>
<ul>
<li><code>RESPONSE_CODE</code>
<p>This key provides status information and error information about a request.</p>
</li>
<li><code>PURCHASE_INTENT</code>
<p>This key provides a {@link android.app.PendingIntent}, which you use to launch the checkout activity.</p>
</li>
<li><code>REQUEST_ID</code>
<p>This key provides you with a request identifier, which you can use to match asynchronous responses with requests.</p>
</li>
</ul>
<p>Some of these keys are not relevant to every request. For more information, see <a href="#billing-message-sequence">Messaging sequence</a> later in this document.</p>
<p>The asynchronous response messages are sent in the form of individual broadcast intents and include the following:</p>
<ul>
<li><code>ACTION_RESPONSE_CODE</code>
<p>This response contains an Android Market server response code, and is sent after you make an in-app billing request. A server response code can indicate that a billing request was successfully sent to Android Market or it can indicate that some error occurred during a billing request. This response is <em>not</em> used to report any purchase state changes (such as refund or purchase information). For more information about the response codes that are sent with this response, see <a href="{@docRoot}guide/market/billing/billing_reference.html#billing-codes">Server Response Codes for In-app Billing</a>.</p>
</li>
<li><code>ACTION_NOTIFY</code>
<p>This response indicates that a purchase has changed state, which means a purchase succeeded, was canceled, or was refunded. This response contains one or more notification IDs. Each notification ID corresponds to a specific server-side message, and each messages contains information about one or more transactions. After your application receives an <code>ACTION_NOTIFY</code> broadcast intent, you send a <code>GET_PURCHASE_INFORMATION</code> request with the notification IDs to retrieve message details.</p>
</li>
<li><code>ACTION_PURCHASE_STATE_CHANGED</code>
<p>This response contains detailed information about one or more transactions. The transaction information is contained in a JSON string. The JSON string is signed and the signature is sent to your application along with the JSON string (unencrypted). To help ensure the security of your in-app billing messages, your application can verify the signature of this JSON string.</p>
</li>
</ul>
<p>The JSON string that is returned with the <code>ACTION_PURCHASE_STATE_CHANGED</code> intent provides your application with the details of one or more billing transactions. An example of this JSON string is shown below:</p>
<pre class="no-pretty-print" style="color:black">
{ "nonce" : 1836535032137741465,
"orders" :
{ "notificationId" : "android.test.purchased",
"orderId" : "transactionId.android.test.purchased",
"packageName" : "com.example.dungeons",
"productId" : "android.test.purchased",
"developerPayload" : "bGoa+V7g/yqDXvKRqq+JTFn4uQZbPiQJo4pf9RzJ",
"purchaseTime" : 1290114783411,
"purchaseState" : 0 }
}
</pre>
<p>The fields in the JSON string are described in the following table (see table 1):</p>
<p class="table-caption"><strong>Table 1.</strong> Description of JSON fields that are returned with an <code>ACTION_PURCHASE_STATE_CHANGED</code> intent.</p>
<table>
<tr>
<th>Field</th>
<th>Description</th>
</tr>
<tr>
<td>nonce</td>
<td>A number used once. Your application generates the nonce and sends it with the <code>GET_PURCHASE_INFORMATION</code> request. Android Market sends the nonce back as part of the JSON string so you can verify the integrity of the message.</td>
</tr>
<tr>
<td>notificationId</td>
<td>A unique identifier that is sent with an <code>ACTION_NOTIFY</code> broadcast intent. Each <code>notificationId</code> corresponds to a specify message that is waiting to be retrieved on the Android Market server. Your application sends back the <code>notificationId</code> with the <code>GET_PURCHASE_INFORMATION</code> message so Android Market can determine which messages you are retrieving.</td>
</tr>
<tr>
<td>orderId</td>
<td>A unique order identifier for the transaction. This corresponds to the Google Checkout Order ID.</td>
</tr>
<tr>
<td>packageName</td>
<td>The application package from which the purchase originated.</td>
</tr>
<tr>
<td>productId</td>
<td>The item's product identifier. Every item has a product ID, which you must specify in the application's product list on the Android Market publisher site.</td>
</tr>
<tr>
<td>purchaseTime</td>
<td>The time the product was purchased, in milliseconds since the epoch (Jan 1, 1970).</td>
</tr>
<tr>
<td>purchaseState</td>
<td>The enum value for the purchase state, which indicates whether the purchase was successful, canceled, or refunded.</td>
</tr>
<tr>
<td>developerPayload</td>
<td>A developer-specified string that is associated with an order. This field is returned in the JSON string that contains transaction information for an order. You can use this field to send information with an order. For example, you can use this field to send index keys with an order, which is useful if you are using a database to store purchase information. We recommend that you do not use this field to send data or content.</td>
</tr>
</table>
<h3 id="billing-message-sequence">Messaging sequence</h3>
<p>The messaging sequence for a typical purchase request is shown in Figure 2. Request types for each <code>sendBillingRequest()</code> method are shown in <strong>bold</strong>, responses are shown in standard text. For clarity, Figure 2 does not show the <code>ACTION_RESPONSE_CODE</code> broadcast intents that are sent for every request. These responses provide status information or error information and are returned after each request.</p>
<p>The basic message sequence for an in-app purchase request is as follows:</p>
<ol>
<li>Your application sends a purchase request (<code>REQUEST_PURCHASE</code> type), specifying a product ID and other parameters.</li>
<li>The Android Market application sends your application a Bundle with a <code>RESPONSE_CODE</code>, <code>PURCHASE_INTENT</code>, and <code>REQUEST_ID</code>. The <code>PURCHASE_INTENT</code> provides a {@link android.app.PendingIntent}, which your application uses to start the checkout flow for the given product ID.</li>
<li>Your application launches the pending intent, which launches the checkout UI.</li>
<li>When the checkout flow finishes (that is, the user successfully purchases the item or cancels the purchase), Android Market sends your application a notification message (an <code>ACTION_NOTIFY</code> intent). The notification message includes a notification ID, which references the completed transaction.</li>
<li>Your application requests the transaction information by sending a <code>GET_PURCHASE_STATE_CHANGED</code> request, specifying the notification ID for the transaction.</li>
<li>The Android Market application sends a Bundle with a <code>RESPONSE_CODE</code> and a <code>REQUEST_ID</code>.
<li>Android Market sends the transaction information to your application in an <code>ACTION_PURCHASE_STATE_CHANGED</code> intent.</li>
<li>Your application confirms that you received the transaction information for the given notification ID by sending a confirmation message (<code>CONFIRM_NOTIFICATIONS</code> type), specifying the notification ID for which you received transaction information.</li>
<li>The Android Market applications sends your application a Bundle with a <code>RESPONSE_CODE</code> and a <code>REQUEST_ID</code>.</li>
</ol>
<p class="note"><strong>Note:</strong> You must launch the pending intent from an activity context and not an application context.</p>
<div style="margin:2em 1em 1em 1em;">
<img src="{@docRoot}images/billing_request_purchase.png" style="text-align:left;" />
<div style="margin:.25em 1.25em;padding:0"><strong>Figure 2.</strong> Message sequence for a typical purchase request. Request types for each <code>sendBillingRequest()</code> method are shown in <strong>bold</strong> (<code>ACTION_RESPONSE_CODE</code> broadcast intents have been omitted).</div>
</div>
<p>The messaging sequence for a restore transaction request is shown in Figure 3. The request type for the <code>sendBillingRequest()</code> method is shown in <strong>bold</strong>, the responses are shown in standard text.</p>
<div class="figure" style="width:490px">
<img src="{@docRoot}images/billing_restore_transactions.png" alt=""/>
<p class="img-caption"><strong>Figure 3.</strong> Message sequence for a restore transactions request.</p>
</div>
<p>The request triggers three responses. The first is a {@link android.os.Bundle} with a <code>RESPONSE_CODE</code> and a <code>REQUEST_ID</code>. Next, the Android Market application sends an <code>ACTION_RESPONSE_CODE</code> broadcast intent, which provides status information or error information about the request. As always, the <code>ACTION_RESPONSE_CODE</code> message references a specific request ID, so you can determine which request an <code>ACTION_RESPONSE_CODE</code> message pertains to.</p>
<p>The <code>RESTORE_TRANSACTIONS</code> request type also triggers an <code>ACTION_PURCHASE_STATE_CHANGED</code> broadcast intent, which contains the same type of transaction information that is sent during a purchase request, although you do not need to respond to this intent with a <code>CONFIRM_NOTIFICATIONS</code> message.</p>
<p>The messaging sequence for checking whether in-app billing is supported is shown in Figure 4. The request type for the <code>sendBillingRequest()</code> method is shown in <strong>bold</strong>, the response is shown in regular text.</p>
<div class="figure" style="width:454px">
<img src="{@docRoot}images/billing_check_supported.png" alt=""/>
<p class="img-caption"><strong>Figure 4.</strong> Message sequence for checking whether in-app billing is supported.</p>
</div>
<p>The synchronous response for a <code>CHECK_BILLING_SUPPORTED</code> request provides a server response code. A <code>RESULT_OK</code> response code indicates that in-app billing is supported; a <code>RESULT_BILLING_UNAVAILABLE</code> response code indicates that the Android Market application does not support in-app billing and may need to be updated. A <code>SERVER_ERROR</code> can also be returned, indicating that there was a problem with the Android Market server. The <code>RESULT_BILLING_UNAVAILABLE</code> response code can also indicate that the user is ineligible for in-app billing (for example, the user resides in a country that does not allow in-app billing).</p>
<h3 id="billing-action-notify">Handling ACTION_NOTIFY messages</h3>
<p>Usually, your application receives an <code>ACTION_NOTIFY</code> intent from Android Market in response to a <code>REQUEST_PURCHASE</code> message (see figure 2). The <code>ACTION_NOTIFY</code> intent informs your application that the state of a requested purchase has changed. To retrieve the details of that state change, your application sends a <code>GET_PURCHASE_INFORMATION</code> request. Android Market responds with an <code>ACTION_PURCHASE_STATE_CHANGED</code> intent, which contains the details of the purchase state change. Your application then sends a <code>CONFIRM_NOTIFICATIONS</code> message, informing Android Market that you've received the purchase state change information.</p>
<p>When Android Market receives a <code>CONFIRM_NOTIFICATIONS</code> message for a given message, it usually stops sending <code>ACTION_NOTIFY</code> intents for that message. However, there are some cases where Android Market may send repeated <code>ACTION_NOTIFY</code> intents for a message even though your application has sent a <code>CONFIRM_NOTIFICATIONS</code> message. This can occur if a device loses network connectivity while you are sending the <code>CONFIRM_NOTIFICATIONS</code> message. In this case, Android Market might not receive your <code>CONFIRM_NOTIFICATIONS</code> message and it could send multiple <code>ACTION_NOTIFY</code> messages until it receives acknowledgement that you received the message. Therefore, your application must be able to recognize that the subsequent <code>ACTION_NOTIFY</code> messages are for a previously processed transaction. You can do this by checking the <code>orderID</code> that's contained in the JSON string because every transaction has a unique <code>orderId</code>.</p>
<p>Your application may also receive <code>ACTION_NOTIFY</code> intents even though your application has not sent a <code>REQUEST_PURCHASE</code> message. This can occur when a user has your application installed on two (or more) devices and the user makes an in-app purchase from one of the devices. In this case, Android Market sends an <code>ACTION_NOTIFY</code> message to the second device, informing the application that there is a purchase state change. Your application can handle this message the same way it handles the response from an application-initiated <code>REQUEST_PURCHASE</code> message, so that ultimately your application receives a purchase state change message that includes information about the item that's been purchased. This scenario applies only to items that have their <a href="{@docRoot}guide/market/billing/billing_admin.html#billing-purchase-type">purchase type</a> set to "managed per user account."</p>
<h2 id="billing-security">Security Controls</h2>
<p>To help ensure the integrity of the transaction information that is sent to your application, Android Market signs the JSON string that is contained in the <code>ACTION_PURCHASE_STATE_CHANGED</code> broadcast intent. Android Market uses the private key that is associated with your publisher account to create this signature. The publisher site generates an RSA key pair for each publisher account. You can find the public key portion of this key pair on your account's profile page. It is the same public key that is used with Android Market licensing.</p>
<p>When Android Market signs a billing response, it includes the signed JSON string (unencrypted) and the signature. When your application receives this signed response you can use the public key portion of your RSA key pair to verify the signature. By performing signature verification you can help detect responses that have been tampered with or that have been spoofed. You can perform this signature verification step in your application; however, if your application connects to a secure remote server then we recommend that you perform the signature verification on that server.</p>
<p>In-app billing also uses nonces (a random number used once) to help verify the integrity of the purchase information that's returned from Android Market. Your application must generate a nonce and send it with a <code>GET_PURCHASE_INFORMATION</code> request and a <code>RESTORE_TRANSACTIONS</code> request. When Android Market receives the request, it adds the nonce to the JSON string that contains the transaction information. The JSON string is then signed and returned to your application. When your application receives the JSON string, you need to verify the nonce as well as the signature of the JSON string.</p>
<p>For more information about best practices for security and design, see <a href="{@docRoot}guide/market/billing/billing_best_practices.html">Security and Design</a>.</p>
<h2 id="billing-limitations">In-app Billing Requirements and Limitations</h2>
<p>Before you get started with in-app billing, be sure to review the following requirements and limitations.</p>
<ul>
<li>In-app billing can be implemented only in applications that you publish through Android Market.</li>
<li>You must have a Google Checkout merchant account to use the in-app billing service.</li>
<li>An application can use in-app billing only if the current Android Market application is installed on its host device and the device is running Android 1.6 (API level 4) or higher.</li>
<li>A device must be running version 2.3.0 (or higher) of the Android Market application to support in-app billing.</li>
<li>You can use in-app billing to sell only digital content. You cannot use in-app billing to sell physical goods, personal services, or anything that requires physical delivery.</li>
<li>Android Market does not provide any form of content delivery. You are responsible for delivering the digital content that you sell in your applications.</li>
<li>You cannot implement in-app billing on a device that never connects to the network. To complete in-app purchase requests, a device must be able to access the Android Market server over the network. </li>
</ul>

View File

@@ -0,0 +1,262 @@
page.title=In-app Billing Reference
@jd:body
<style type="text/css">
#jd-content {
background:transparent url({@docRoot}assets/images/preliminary.png) repeat scroll 0 0;
}
</style>
<div id="qv-wrapper">
<div id="qv">
<h2>In this document</h2>
<ol>
<li><a href="#billing-codes">Server Response Codes for In-app Billing</a></li>
<li><a href="#billing-interface">In-app Billing Service Interface</a></li>
<li><a href="#billing-intents">In-app Billing Broadcast Intents</a></li>
</ol>
<h2>Downloads</h2>
<ol>
<li><a href="{@docRoot}guide/market/billing/billing_integrate.html#billing-download">Sample Application</a></li>
</ol>
<h2>See also</h2>
<ol>
<li><a href="{@docRoot}guide/market/billing/billing_overview.html">Overview of In-app Billing</a></li>
<li><a href="{@docRoot}guide/market/billing/billing_integrate.html">Implementing In-app Billing</a></li>
<li><a href="{@docRoot}guide/market/billing/billing_best_practices.html">Security and Design</a></li>
<li><a href="{@docRoot}guide/market/billing/billing_testing.html">Testing In-app Billing</a></li>
<li><a href="{@docRoot}guide/market/billing/billing_admin.html">Administering In-app Billing</a></li>
</ol>
</div>
</div>
<div class="special" style="margin-right:345px">
<p>This documentation provides an early look at the Android Market In-app Billing service. The documentation may change without notice.</p>
</div>
<p>The following document provides technical reference information for the following:</p>
<ul>
<li><a href="#billing-codes">Android Market Server Response Codes for In-app Billing</a></li>
<li><a href="#billing-interface">In-app Billing Interface Parameters</a></li>
<li><a href="#billing-intents">In-app Billing Broadcast Intents</a></li>
</ul>
<h2 id="billing-codes">Android Market Server Response Codes for In-app Billing</h2>
<p>The following table lists all of the server response codes that are sent from Android Market to your application. Android Market sends these response codes asynchronously as <code>INAPP_RESPONSE_CODE</code> extras in the <code>ACTION_RESPONSE_CODE</code> broadcast intent. Your application must handle all of these response codes.</p>
<p class="table-caption" id="response-codes-table"><strong>Table 1.</strong> Summary of response codes returned by Android Market.</p>
<table>
<tr>
<th>Response Code</th>
<th>Description</th>
</tr>
<tr>
<td><code>RESULT_OK</code></td>
<td>Indicates that the request was sent to the server successfully. When this code is returned in response to a <code>CHECK_BILLING_SUPPORTED</code> request, indicates that billing is supported.</td>
</tr>
<tr>
<td><code>RESULT_USER_CANCELED</code></td>
<td>Indicates that the user pressed the back button on the checkout page instead of buying the item.</td>
</tr>
<tr>
<td><code>RESULT_SERVICE_UNAVAILABLE</code></td>
<td>Indicates that the network connection is down.</td>
</tr>
<tr>
<td><code>RESULT_BILLING_UNAVAILABLE</code></td>
<td>Indicates that the <code>BILLING_API_VERSION</code> that you specified is not recognized by the Android Market application and that the Android Market application may have to be updated. Can also indicate that the user is ineligible for in-app billing. For example, the user resides in a country that does not allow in-app purchases.</td>
</tr>
<tr>
<td><code>RESULT_ITEM_UNAVAILABLE</code></td>
<td>Indicates that Android Market cannot find the requested item in the application's product list. This can happen if the product ID is misspelled in your <code>REQUEST_PURCHASE</code> request or if an item is unpublished in the application's product list.</td>
</tr>
<tr>
<td><code>RESULT_ERROR</code></td>
<td>Indicates an unexpected server error.</td>
</tr>
<tr>
<td><code>RESULT_DEVELOPER_ERROR</code></td>
<td>Indicates that an application is trying to make an in-app billing request but the application has not declared the com.android.vending.BILLING permission in its manifest. Can also indicate that an application is not properly signed, or that you sent a malformed request, such as a request with missing Bundle keys or a request that uses an unrecognized request type.</td>
</tr>
</table>
<h2 id="billing-interface">In-app Billing Service Interface</h2>
<p>The following section describes the interface for the Android Market In-app Billing service. The interface is defined in the <code>IMarketBillingService.aidl</code> file, which is included with the in-app billing <a href="{@docRoot}guide/market/billing/billing_integrate.html#billing-download">sample application</a>.</p>
<p>The interface consists of a single request method <code>sendBillingRequest()</code>. This method takes a single {@link android.os.Bundle} parameter. The Bundle parameter includes several key-value pairs, which are summarized in Table 2.</p>
<p class="table-caption"><strong>Table 2.</strong> Description of Bundle keys passed in a <code>sendBillingRequest()</code> request.</p>
<table>
<tr>
<th>Key</th>
<th>Type</th>
<th>Possible Values</th>
<th>Required?</th>
<th>Description</th>
</tr>
<tr>
<td><code>BILLING_REQUEST</code></td>
<td>String</td>
<td><code>CHECK_BILLING_SUPPORTED</code>, <code>REQUEST_PURCHASE</code>, <code>GET_PURCHASE_INFORMATION</code>, <code>CONFIRM_NOTIFICATIONS</code>, or <code>RESTORE_TRANSACTIONS</code></td>
<td>Yes</td>
<td>The type of billing request you are making with the <code>sendBillingRequest()</code> request. The possible values are discussed more below this table.</td>
</tr>
<tr>
<td><code>BILLING_API_VERSION</code></td>
<td>int</td>
<td>0 (for alpha release); 1 (for beta release)</td>
<td>Yes</td>
<td>The version of the in-app billing service you are using.</td>
</tr>
<tr>
<td><code>PACKAGE_NAME</code></td>
<td>String</td>
<td>A valid package name.</td>
<td>Yes</td>
<td>The name of the application that is making the request.</td>
</tr>
<tr>
<td><code>ITEM_ID</code></td>
<td>String</td>
<td>Any valid product identifier.</td>
<td>Required for <code>REQUEST_PURCHASE</code> requests.</td>
<td>The product ID of the item you are making a billing request for. Every in-app item that you sell using the in-app billing service must have a unique product ID, which you specify on the Android Market publisher site.</td>
</tr>
<tr>
<td><code>NONCE</code></td>
<td>long</td>
<td>Any valid long value.</td>
<td>Required for <code>GET_PURCHASE_INFORMATION</code> and <code>RESTORE_TRANSACTIONS</code> requests.</td>
<td>A number used once. Your application must generate and send a nonce with each <code>GET_PURCHASE_INFORMATION</code> and <code>RESTORE_TRANSACTIONS</code> request. The nonce is returned with the <code>ACTION_PURCHASE_STATE_CHANGED</code> intent, so you can use this value to verify the integrity of transaction responses form Android Market.</td>
</tr>
<tr>
<td><code>NOTIFY_IDS</code></td>
<td>Array of long values</td>
<td>Any valid array of long values</td>
<td>Required for <code>GET_PURCHASE_INFORMATION</code> and <code>CONFIRM_NOTIFICATIONS</code> requests.</td>
<td>An array of notification identifiers. A notification ID is sent to your application in an <code>ACTION_NOTIFY</code> intent every time a purchase changes state. You use the notification to retrieve the details of the purchase state change.</td>
</tr>
<tr>
<td><code>DEVELOPER_PAYLOAD</code></td>
<td>String</td>
<td>Any valid String less than 256 characters long.</td>
<td>No</td>
<td>A developer-specified string that is associated with an order. This field is returned in the JSON string that contains transaction information for an order. You can use this field to send information with an order. For example, you can use this field to send index keys with an order, which is useful if you are using a database to store purchase information. We recommend that you do not use this field to send data or content.</td>
</tr>
</table>
<p>The <code>BILLING_REQUEST</code> key can have the following values:</p>
<ul>
<li><code>CHECK_BILLING_SUPPORTED</code>
<p>This request verifies that the Android Market application supports in-app billing. You usually send this request when your application first starts up. This request is useful if you want to enable or disable certain UI features that are relevant only to in-app billing.</p>
</li>
<li><code>REQUEST_PURCHASE</code>
<p>This request sends a purchase message to the Android Market application and is the foundation of in-app billing. You send this request when a user indicates that he or she wants to purchase an item in your application. Android Market then handles the financial transaction by displaying the checkout user interface.</p>
</li>
<li><code>GET_PURCHASE_INFORMATION</code>
<p>This request retrieves the details of a purchase state change. A purchase state change can occur when a purchase request is billed successfully or when a user cancels a transaction during checkout. It can also occur when a previous purchase is refunded. Android Market notifies your application when a purchase changes state, so you only need to send this request when there is transaction information to retrieve.</p>
</li>
<li><code>CONFIRM_NOTIFICATIONS</code>
<p>This request acknowledges that your application received the details of a purchase state change. That is, this message confirms that you sent a <code>GET_PURCHASE_INFORMATION</code> request for a given notification and that you received the purchase information for the notification.</p>
</li>
<li><code>RESTORE_TRANSACTIONS</code>
<p>This request retrieves a user's transaction status for managed purchases (see <a href="{@docRoot}guide/market/billing/billing_admin.html#billing-purchase-type">Choosing a Purchase Type</a> for more information). You should send this message only when you need to retrieve a user's transaction status, which is usually only when your application is reinstalled or installed for the first time on a device.</p>
</li>
</ul>
<p>Every in-app billing request generates a synchronous response. The response is a {@link android.os.Bundle} and can include one or more of the following keys:</p>
<ul>
<li><code>RESPONSE_CODE</code>
<p>This key provides status information and error information about a request.</p>
</li>
<li><code>PURCHASE_INTENT</code>
<p>This key provides a {@link android.app.PendingIntent}, which you use to launch the checkout activity.</p>
</li>
<li><code>REQUEST_ID</code>
<p>This key provides you with a request identifier, which you can use to match asynchronous responses with requests.</p>
</li>
</ul>
<p>Some of these keys are not relevant to certain types of requests. Table 3 shows which keys are returned for each request type.</p>
<p class="table-caption"><strong>Table 3.</strong> Description of Bundle keys that are returned with each in-app billing request type.</p>
<table>
<tr>
<th>Request Type</th>
<th>Keys Returned</th>
<th>Possible Response Codes</th>
</tr>
<tr>
<td><code>CHECK_BILLING_SUPPORTED</code></td>
<td><code>RESPONSE_CODE</code></td>
<td><code>RESULT_OK</code>, <code>RESULT_BILLING_UNAVAILABLE</code>, <code>RESULT_ERROR</code>, <code>RESULT_DEVELOPER_ERROR</code></td>
</tr>
<tr>
<td><code>REQUEST_PURCHASE</code></td>
<td><code>RESPONSE_CODE</code>, <code>PURCHASE_INTENT</code>, <code>REQUEST_ID</code></td>
<td><code>RESULT_OK</code>, <code>RESULT_ERROR</code>, <code>RESULT_DEVELOPER_ERROR</code></td>
</tr>
<tr>
<td><code>GET_PURCHASE_INFORMATION</code></td>
<td><code>RESPONSE_CODE</code>, <code>REQUEST_ID</code></td>
<td><code>RESULT_OK</code>, <code>RESULT_ERROR</code>, <code>RESULT_DEVELOPER_ERROR</code></td>
</tr>
<tr>
<td><code>CONFIRM_NOTIFICATIONS</code></td>
<td><code>RESPONSE_CODE</code>, <code>REQUEST_ID</code></td>
<td><code>RESULT_OK</code>, <code>RESULT_ERROR</code>, <code>RESULT_DEVELOPER_ERROR</code></td>
</tr>
<tr>
<td><code>RESTORE_TRANSACTIONS</code></td>
<td><code>RESPONSE_CODE</code>, <code>REQUEST_ID</code></td>
<td><code>RESULT_OK</code>, <code>RESULT_ERROR</code>, <code>RESULT_DEVELOPER_ERROR</code></td>
</tr>
</table>
<h2 id="billing-intents">In-app Billing Broadcast Intents</h2>
<p>The following section describes the in-app billing broadcast intents that are sent by the Android Market application. These broadcast intents inform your application about in-app billing actions that have occurred. Your application must implement a {@link android.content.BroadcastReceiver} to receive these broadcast intents, such as the <code>BillingReceiver</code> that's shown in the in-app billing <a href="{@docRoot}guide/market/billing/billing_integrate.html#billing-download">sample application</a>.</p>
<h4>ACTION_RESPONSE_CODE</h4>
<p>This broadcast intent contains an Android Market response code, and is sent after you make an in-app billing request. A server response code can indicate that a billing request was successfully sent to Android Market or it can indicate that some error occurred during a billing request. This intent is not used to report any purchase state changes (such as refund or purchase information). For more information about the response codes that are sent with this response, see <a href="#billing-codes">Android Market Response Codes for In-app Billing</a>.</p>
<h5>Extras</h5>
<ul type="none">
<li><code>INAPP_REQUEST_ID</code>&mdash;a long representing a request ID. A request ID identifies a specific billing request and is returned by Android Market at the time a request is made.</li>
<li><code>INAPP_RESPONSE_CODE</code>&mdash;an int representing the Android Market server response code.</li>
</ul>
<h4>ACTION_NOTIFY</h4>
<p>This response indicates that a purchase has changed state, which means a purchase succeeded, was canceled, or was refunded. This response contains one or more notification IDs. Each notification ID corresponds to a specific server-side message, and each messages contains information about one or more transactions. After your application receives an <code>ACTION_NOTIFY</code> broadcast intent, you send a <code>GET_PURCHASE_INFORMATION</code> request with the notification IDs to retrieve the message details.</p>
<h5>Extras</h5>
<ul type="none">
<li><code>NOTIFICATION_ID</code>&mdash;a string representing the notification ID for a given purchase state change. Android Market notifies you when there is a purchase state change and the notification includes a unique notification ID. To get the details of the purchase state change, you send the notification ID with the <code>GET_PURCHASE_INFORMATION</code> request.</li>
</ul>
<h4>ACTION_PURCHASE_STATE_CHANGED</h4>
<p>This broadcast intent contains detailed information about one or more transactions. The transaction information is contained in a JSON string. The JSON string is signed and the signature is sent to your application along with the JSON string (unencrypted). To help ensure the security of your in-app billing messages, your application can verify the signature of this JSON string.</p>
<h5>Extras</h5>
<ul type="none">
<li><code>INAPP_SIGNED_DATA</code>&mdash;a string representing the signed JSON string.</li>
<li><code>INAPP_SIGNATURE</code>&mdash;a string representing the signature.</li>
</ul>

View File

@@ -0,0 +1,180 @@
page.title=Testing In-app Billing
@jd:body
<style type="text/css">
#jd-content {
background:transparent url({@docRoot}assets/images/preliminary.png) repeat scroll 0 0;
}
</style>
<div id="qv-wrapper">
<div id="qv">
<h2>In this document</h2>
<ol>
<li><a href="#billing-testing-static">Testing in-app purchases with static responses</a></li>
<li><a href="#billing-testing-real">Testing in-app purchases using your own product IDs</a></li>
</ol>
<h2>Downloads</h2>
<ol>
<li><a href="{@docRoot}guide/market/billing/billing_integrate.html#billing-download">Sample Application</a></li>
</ol>
<h2>See also</h2>
<ol>
<li><a href="{@docRoot}guide/market/billing/billing_overview.html">Overview of In-app Billing</a></li>
<li><a href="{@docRoot}guide/market/billing/billing_integrate.html">Implementing In-app Billing</a></li>
<li><a href="{@docRoot}guide/market/billing/billing_best_practices.html">Security and Design</a></li>
<li><a href="{@docRoot}guide/market/billing/billing_admin.html">Administering In-app Billing</a></li>
<li><a href="{@docRoot}guide/market/billing/billing_reference.html">In-app Billing Reference</a></li>
</ol>
</div>
</div>
<div class="special" style="margin-right:345px">
<p>This documentation provides an early look at the Android Market In-app Billing service. The documentation may change without notice.</p>
</div>
<p>The Android Market publisher site provides several tools that help you test your in-app billing implementation before it is published. You can use these tools to create test accounts and purchase special reserved items that send static billing responses to your application.</p>
<p>To test in-app billing in an application you must install the application on an Android-powered device. You cannot use the Android emulator to test in-app billing. The device you use for testing must run a standard version of the Android 1.6 or later platform (API level 4 or higher), and have the most current version of the Android Market application installed. If a device is not running the most current Android Market application, your application won't be able to send in-app billing requests to Android Market. For general information about how to set up a device for use in developing Android applications, see <a
href="{@docRoot}guide/developing/device.html">Developing on a Device</a>.</p>
<p>The following section shows you how to set up and use the in-app billing test tools.</p>
<p class="note"><strong>Note</strong>: Debug log messages are turned off by default in the sample application. You can turn them on by setting the variable <code>DEBUG</code> to <code>true</code> in the <code>Consts.java</code> file.</p>
<h2 id="billing-testing-static">Testing in-app purchases with static responses</h2>
<p>We recommend that you first test your in-app billing implementation using static responses from Android Market. This enables you to verify that your application is handling the primary Android Market responses correctly and that your application is able to verify the signature correctly.</p>
<p>To test your implementation with static responses, you make an in-app billing request using a special item that has a reserved product ID. Each reserved product ID returns a specific static response from Android Market. No money is transferred when you make in-app billing requests with the reserved product IDs. Also, you cannot specify the form of payment when you make a billing request with a reserved product ID. Figure 1 shows the checkout flow for the reserved item that has the product ID android.test.purchased.</p>
<div style="margin:2em 1em 1em 1em;">
<img src="{@docRoot}images/billing_test_flow.png" style="text-align:left;" />
<div style="margin:.25em 1.25em;padding:0"><strong>Figure 1.</strong> Checkout flow for the special reserved item android.test.purchased.</div>
</div>
<p>You do not need to list the reserved products in your application's product list. Android Market already knows about the reserved product IDs. Also, you do not need to upload your application to the publisher site to perform static response tests with the reserved product IDs. You can simply install your application on a device, log into the device, and make billing requests using the reserved product IDs.</p>
<p>There are four reserved product IDs for testing static in-app billing responses:</p>
<ul>
<li><strong>android.test.purchased</strong>
<p>When you make an in-app billing request with this product ID, Android Market responds as though you successfully purchased an item. The response includes a JSON string, which contains fake purchase information (for example, a fake order ID). In some cases, the JSON string is signed and the response includes the signature so you can test your signature verification implementation using these responses.</p>
</li>
<li><strong>android.test.canceled</strong>
<p>When you make an in-app billing request with this product ID Android Market responds as though the purchase was canceled. This can occur when an error is encountered in the order process, such as an invalid credit card, or when you cancel a user's order before it is charged.</p>
</li>
<li><strong>android.test.refunded</strong>
<p>When you make an in-app billing request with this product ID, Android Market responds as though the purchase was refunded. Refunds cannot be initiated through the in-app billing feature. Refunds must be initiated by you (the merchant). A refund message is sent to your app by Android Market only when Android Market gets notification from Google Checkout that a refund has been made.</p>
</li>
<li><strong>android.test.item_unavailable</strong>
<p>When you make an in-app billing request with this product ID Android Market responds as though the item being purchased was not listed in your app's product list.</p>
</li>
</ul>
<p>In some cases, the reserved items may return signed static responses, which lets you test signature verification in your application. To test signature verification with the special reserved product IDs, you may need to set up <a href="{@docRoot}guide/market/billing/billing_admin.html#billing-testing-setup">trusted tester accounts</a> or upload your application as a unpublished draft application. The following table (Table 1) shows you the conditions under which static responses are signed.</p>
<p class="table-caption" id="static-responses-table"><strong>Table 1.</strong>
Conditions under which static responses are signed.</p>
<table>
<tr>
<th>Application ever been published?</th>
<th>Draft application uploaded and unpublished?</th>
<th>User who is running the application</th>
<th>Static response signature</th>
</tr>
<tr>
<td>No</td>
<td>No</td>
<td>Any</td>
<td>Unsigned</td>
</tr>
<tr>
<td>No</td>
<td>No</td>
<td>Developer</td>
<td>Signed</td>
</tr>
<tr>
<td>Yes</td>
<td>No</td>
<td>Any</td>
<td>Unsigned</td>
</tr>
<tr>
<td>Yes</td>
<td>No</td>
<td>Developer</td>
<td>Signed</td>
</tr>
<tr>
<td>Yes</td>
<td>No</td>
<td>Trusted tester</td>
<td>Signed</td>
</tr>
<tr>
<td>Yes</td>
<td>Yes</td>
<td>Any</td>
<td>Signed</td>
</tr>
</table>
<p>To make an in-app billing request with a reserved product ID, you simply construct a normal <code>REQUEST_PURCHASE</code> request, but instead of using a real product ID from your application's product list you use one of the reserved product IDs.</p>
<p class="note"><strong>Note</strong>: Making in-app billing requests with the reserved product IDs overrides the usual Android Market production system. When you send an in-app billing request for a reserved product ID, the quality of service will not be comparable to the production environment.</p>
<h2 id="billing-testing-real">Testing In-app Purchases Using Your Own Product IDs</h2>
<p>After you finish your static response testing, and you verify that signature verification is working in your application, you can test your in-app billing implementation by making actual in-app purchases. Testing real in-app purchases enables you to test the end-to-end in-app billing experience, including the actual responses from Android Market and the actual checkout flow that users will experience in your application.</p>
<p class="note"><strong>Note</strong>: You do not need to publish your application to do end-to-end testing. You only need to upload your draft application to perform end-to-end testing.</p>
<p>To test your in-app billing implementation with actual in-app purchases, you will need to register at least one test account on the Android Market publisher site. You cannot use your developer account to test the complete in-app purchase process because Google Checkout does not let you buy items from yourself. If you have not set up test accounts before, see <a href="{@docRoot}guide/market/billing/billing_admin.html#billing-testing-setup">Setting up test accounts</a>.</p>
<p>Also, a test account can purchase an item in your product list only if the item is published. The application does not need to be published, but the item does need to be published.</p>
<p>When you use a test account to purchase items, the account is billed through Google Checkout and your Google Checkout merchant account receives a payout for the purchase. Therefore, you need to refund purchases that are made with test accounts, otherwise the purchases will show up as actual payouts to your merchant account.</p>
<p>To test your in-app billing implementation with actual purchases, follow these steps:</p>
<ol>
<li>Upload your application as a draft application to the publisher site. You do not need to publish your application to perform end-to-end testing with real product IDs.</li>
<li>Add items to the application's product list. Make sure that you publish the items (the application can remain unpublished).
<p>See <a href="{@docRoot}guide/market/billing/billing_admin.html#billing-catalog">Creating a product list</a> to learn how to do this.</p>
</li>
<li>Install your application on an Android-powered device.
<p>See <a href="{@docRoot}guide/developing/device.html">Developing on a Device</a> for more information about how to do this.</p>
</li>
<li>Sign in to the device using one of the <a href="{@docRoot}guide/market/billing/billing_admin.html#billing-testing-setup">trusted tester accounts</a> that you registered on the Android Market site.
<p>We recommend that you make the test account the primary account on the device. To sign in to a device, do the following:</p>
<ol>
<li>Open Settings &gt; Accounts &amp; sync</li>
<li>Select <strong>Add Account</strong> and choose to add a "Google" account.</li>
<li>Select <strong>Next</strong> and then <strong>Sign in</strong>.</li>
<li>Enter the username and password of the test account.</li>
<li>Select <strong>Sign in</strong>. The system signs you in to the new account.</li>
</ol>
</li>
<li>Make in-app purchases in your application.</li>
</ol>
<p class="note"><strong>Note:</strong> The only way to change the primary account on a device is to do a factory reset, making sure you log on with your primary account first.</p>
<p>When you are finished testing your in-app billing implementation, you are ready to
publish your application on Android Market. You can follow the normal steps for <a
href="{@docRoot}guide/publishing/preparing.html">preparing</a>, <a
href="{@docRoot}guide/publishing/app-signing.html">signing</a>, and <a
href="{@docRoot}guide/publishing/publishing.html">publishing your application</a>.
</p>

View File

@@ -0,0 +1,67 @@
page.title=Adding In-app Billing to Your Applications
@jd:body
<style type="text/css">
#jd-content {
background:transparent url({@docRoot}assets/images/preliminary.png) repeat scroll 0 0;
}
</style>
<div id="qv-wrapper">
<div id="qv">
<h2>Topics</h2>
<ol>
<li><a href="{@docRoot}guide/market/billing/billing_overview.html">Overview of In-app Billing</a></li>
<li><a href="{@docRoot}guide/market/billing/billing_integrate.html">Implementing In-app Billing</a></li>
<li><a href="{@docRoot}guide/market/billing/billing_best_practices.html">Security and Design</a></li>
<li><a href="{@docRoot}guide/market/billing/billing_testing.html">Testing In-app Billing</a></li>
<li><a href="{@docRoot}guide/market/billing/billing_admin.html">Administering In-app Billing</a></li>
</ol>
<h2>Reference</h2>
<ol>
<li><a href="{@docRoot}guide/market/billing/billing_reference.html">In-app Billing Reference</a></li>
</ol>
<h2>Downloads</h2>
<ol>
<li><a href="{@docRoot}guide/market/billing/billing_integrate.html#billing-download">Sample Application</a></li>
</ol>
</div>
</div>
<div class="special" style="margin-right:345px">
<p>This documentation provides an early look at the Android Market In-app Billing service. The documentation may change without notice.</p>
</div>
<p>In-app billing is an Android Market service that lets you sell digital content in your applications. You can use the service to sell a wide range of content, including downloadable content such as media files or photos, and virtual content such as game levels or potions.</p>
<p>When you use the Android Market In-app Billing service to sell an item, Android Market handles all checkout details so your application never has to directly process any financial transactions. Android Market uses the same checkout service that is used for application purchases, so your users experience a consistent and familiar purchase flow (see figure 1). Also, the transaction fee for in-app purchases is the same as the transaction fee for application purchases (30%).</p>
<p>Any application that you publish through Android Market can implement in-app billing. No special account or registration is required other than an Android Market publisher account and a Google Checkout merchant account. Also, because the service uses no dedicated framework APIs, you can add in-app billing to any application that uses a minimum API level of 4 or higher.</p>
<p>To help you integrate in-app billing into your application, the Android SDK provides a sample application that demonstrates a simple implementation of in-app billing. The sample application contains examples of billing-related classes you can use to implement in-app billing in your application. It also contains examples of the database, user interface, and business logic you might use to implement in-app billing.</p>
<p class="caution"><strong>Important</strong>: Although the sample application is a working example of how you can implement in-app billing, we <em>strongly recommend</em> that you modify and obfuscate the sample code before you use it in a production application. For more information, see <a href="{@docRoot}guide/market/billing/billing_best_practices.html">Security and Design</a>.</p>
<div style="margin:2em 1em 1em 1em;">
<img src="{@docRoot}images/billing_checkout_flow.png" style="text-align:left;" />
<div style="margin:.25em 1.25em;padding:0"><strong>Figure 1.</strong> Applications initiate in-app billing requests through their own UI (first screen). Android Market responds to the request by providing the checkout user interface (middle screen). When checkout is complete, the application resumes.</div>
</div>
<p>To learn more about the in-app billing service and start integrating in-app billing into your applications, read the following documents:</p>
<dl>
<dt><strong><a href="{@docRoot}guide/market/billing/billing_overview.html">Overview of In-app Billing</a></strong></dt>
<dd>Learn how the service works and what a typical in-app billing implementation looks like.</dd>
<dt><strong><a href="{@docRoot}guide/market/billing/billing_integrate.html">Implementing In-app Billing</a></strong></dt>
<dd>Use this step-by-step guide to start incorporating in-app billing into your application.</dd>
<dt><strong><a href="{@docRoot}guide/market/billing/billing_best_practices.html">Security and Design</a></strong></dt>
<dd>Review these best practices to help ensure that your in-app billing implementation is secure and well designed.</dd>
<dt><strong><a href="{@docRoot}guide/market/billing/billing_testing.html">Testing In-app Billing</a></strong></dt>
<dd>Understand how the in-app billing test tools work and learn how to test your in-app billing implementation.</dd>
<dt><strong><a href="{@docRoot}guide/market/billing/billing_admin.html">Administering In-app Billing</a></strong></dt>
<dd>Learn how to set up your product list, register test accounts, and handle refunds.</dd>
<dt><strong><a href="{@docRoot}guide/market/billing/billing_reference.html">In-app Billing Reference</a></strong></dt>
<dd>Get detailed information about Android Market response codes and the in-app billing interface.</dd>
</dl>

View File

@@ -0,0 +1,247 @@
page.title=Android Compatibility
@jd:body
<div id="qv-wrapper">
<div id="qv">
<h2>See also</h2>
<ol>
<li><a
href="{@docRoot}guide/appendix/market-filters.html">Market Filters</a></li>
<li><a
href="{@docRoot}guide/topics/resources/providing-resources.html#AlternativeResources">Providing Alternative Resources</a></li>
<li><a
href="{@docRoot}guide/practices/screens_support.html">Supporting Multiple Screens</a></li>
<li style="margin-top:3px;"><code><a
href="{@docRoot}guide/topics/manifest/supports-screens-element.html">&lt;supports-screens&gt;</a></code></li>
<li><code><a
href="{@docRoot}guide/topics/manifest/uses-configuration-element.html">&lt;uses-configuration&gt;</a></code></li>
<li><code><a
href="{@docRoot}guide/topics/manifest/uses-feature-element.html">&lt;uses-feature&gt;</a></code></li>
<li><code><a
href="{@docRoot}guide/topics/manifest/uses-library-element.html">&lt;uses-library&gt;</a></code></li>
<li><code><a
href="{@docRoot}guide/topics/manifest/uses-permission-element.html">&lt;uses-permission&gt;</a></code></li>
<li><code><a
href="{@docRoot}guide/topics/manifest/uses-sdk-element.html">&lt;uses-sdk&gt;</code></a></li>
</ol>
</div> </div>
<p>Android is designed to run on many different types of devices. For
developers, the range and number of devices means a huge potential audience: the
more devices that run Android apps, the more users who can access your app. In
exchange, however, it also means that your apps will have to cope with that same
variety of hardware.</p>
<p>Fortunately, Android has built-in tools and support that make it easy for
your apps to do that, while at the same time letting you maintain control of
what types of devices your app is available to. With a bit of forethought and
some minor changes in your app's manifest file, you can ensure that users
whose devices cant run your app will never see it in the Android Market, and
will not get in trouble by downloading it. This page explains how you can
control which devices have access to your apps, and how to prepare your apps to
make sure they reach the right audience.</p>
<h3 id="defined">What does “compatibility” mean?</h3>
<p>A device is “Android compatible” if it can correctly run apps written for the
<em>Android execution environment</em>. The exact details of the Android execution
environment</em> are defined by the Android Compatibility Definition Document,
but the single most important characteristic of a compatible device is the
ability to install and correctly run an Android <code>.apk</code> file.</p>
<p>There is exactly one Android API for each <a
href="{@docRoot}guide/appendix/api-levels.html">API level</a>, and its the same
API no matter what kind of device its installed on. No parts of the API are
optional, and you never have to worry about parts of the API missing on some
devices. Every compatible Android device your app will land on will include
every class and every API for that API level.</p>
<p>Of course, some APIs wont work correctly if a particular device lacks the
corresponding hardware or feature. But thats not a problem: we also designed
Android to prevent apps from being visible to devices which dont have features
the apps require. Weve built support for this right into the SDK tools, and
its part of the Android platform itself, as well as Android Market.</p>
<p>As a developer, you have complete control of how and where your apps are
available. Android provides tools as a first-class part of the platform that let
you manage this. You control the availability of your apps, so that they reach
only the devices capable of running them.</p>
<h3 id="how">How does it work?</h3>
<p>You manage your apps availability through a simple three-step process:</p>
<ol>
<li>You state the features your app requires by declaring <a
href="{@docRoot}guide/topics/manifest/uses-feature-element.html"><code>&lt;uses-feature&gt;</code></a>
elements its manifest file.</li>
<li>Devices are required to declare the features they include to Android
Market.</li>
<li>Android Market uses your apps stated requirements to filter it from devices
that dont meet those requirements.</li>
</ol>
<p>This way, users never even see apps that wont work properly on their
devices. As long as you accurately describe your apps requirements, you dont
need to worry about users blaming you for compatibility problems.</p>
<p>If youre familiar with web development, you may recognize this model as
“capability detection”. Web developers typically prefer this approach to
“browser detection”, because its very difficult to keep up as new browsers and
new versions of current browsers are released. By checking for support for
specific required capabilities instead of the current browser, web developers
get better fine-grained control. Thats the same approach Android uses: since
its impossible to keep up with all the Android devices being released, you
instead use the fine-grained controls Android provides.</p>
<h3>Filtering for technical reasons</h3>
<div class="sidebox-wrapper">
<img id="rule" src="{@docRoot}assets/images/grad-rule-qv.png">
<div id="qv-sub-rule">
<img src="{@docRoot}assets/images/icon_market.jpg" style="float:left;margin:0;padding:0;">
<p style="color:#669999;">Filtering on Android Market</p>
<p>Android Market filters the applications that are visible to users, so
that users can see and download only those applications that are compatible with
their devices.</p>
<p style="margin-top:1em;">One of the ways Market filters applications is by
feature compatibility. To do this, Market checks the
<code>&lt;uses-feature&gt;</code> elements in each application's manifest, to
establish the app's feature needs. Market then shows or hides the application to
each user, based on a comparison with the features available on the user's
device.
<p style="margin-top:1em;">For information about other filters that you can
use to control the availability of your apps, see the
<a href="{@docRoot}guide/appendix/market-filters.html">Market
Filters</a> document.</p>
</div>
</div>
<p>Android includes support for a lot of features, some hardware and some
software. Examples include compass and accelerometer sensors, cameras, and Live
Wallpapers. However, not every device will support every feature. For instance,
some devices dont have the hardware horsepower to display Live Wallpapers
well.</p>
<p>To manage this, Android defines <em>feature IDs</em>. Every capability has a
corresponding feature ID defined by the Android platform. For instance, the
feature ID for compass is <code>“android.hardware.sensor.compass”</code>,
while the feature
ID for Live Wallpapers is <code>“android.software.live_wallpapers”</code>. Each of these IDs
also has a corresponding Java-language constant on the
{@link android.content.pm.PackageManager} class that you can use to query whether
feature is supported at runtime. As Android adds support for new features in
future versions, new feature IDs will be added as well.</p>
<p>When you write your application, you specify which features your app requires
by listing their feature IDs in <code>&lt;uses-feature&gt;</code> elements in
the <code>AndroidManifest.xml</code> file. This is the information that Android
Market uses to match your app to devices that can run it. For instance, if you
state that your app requires android.software.live_wallpapers, it wont be shown
to devices that dont support Live Wallpapers.</p>
<p>This puts you in total control of your app &mdash; because you dont have to
declare these features. Consider an example involving cameras.</p>
<p>If youre building a really impressive next-generation augmented-reality app,
your app wont function at all without a camera. However, if youre building a
shopping app that only uses the camera for barcode scanning, users without
cameras might still find it useful even if they cant scan barcodes. While both
apps need to acquire the permission to access the camera, only the first app
needs to state that it requires a camera. (The shopping app can simply check at
runtime and disable the camera-related features if theres no camera
present.)</p>
<p>Since only you can say what the best approach is for your app, Android
provides the tools and lets you make your own tradeoff between maximizing
audience size and minimizing development costs.</p>
<h3 id="filtering">Filtering for business reasons</h3>
<p>Its possible that you may need to restrict your apps availability for
business or legal reasons. For instance, an app that displays train schedules
for the London Underground is unlikely to be useful to users outside the United
Kingdom. Other apps might not be permitted in certain countries for business or
legal reasons. For cases such as these, Android Market itself provides
developers with filtering options that allow them control their apps
availability for non-technical reasons.</p>
<p>The help information for Android Market provides full details, but in a
nutshell, developers can use the Market publisher UI to:</p>
<ul>
<li>List the countries an app is available in.</li>
<li>Select which carriers users are able to access the app.</li>
</ul>
<p>Filtering for technical compatibility (such as required hardware components)
is always based on information contained within your <code>.apk</code> file. But
filtering for non-technical reasons (such as geographic restrictions) is always
handled in the Market user interface.</p>
<h3 id="futureproofing">Future-proofing</h3>
<p>Theres one additional quirk that we havent yet addressed: protecting apps
from changes made to future versions of Android. If the Android platform
introduces a new feature or changes how existing features are handled, what
happens to existing apps that were written without any knowledge of the new
behavior?</p>
<p>Simply put, Android commits to not making existing apps available to devices
where they wont work properly, even when the platform changes. The best way to
explain this is through examples, so here are two:</p>
<ul>
<li>Android 1.0 through 1.5 required a 2 megapixel camera with auto-focus.
However, with version 1.6, Android devices were permitted to omit the auto-focus
capability, though a (fixed-focus) camera was still required. Some apps such as
barcode scanners do not function as well with cameras that do not auto-focus. To
prevent users from having a bad experience with those apps, existing apps that
obtain permission to use the Camera were assumed by default to require
auto-focus. This allowed Android Market to filter those apps from devices that
lack auto-focus.</li>
<li>Android 2.2, meanwhile, allowed the microphone to be optional on some
devices, such as set-top boxes. Android 2.2 included a new feature ID for the
microphone which allows developers to filter their apps if necessary, but
&mdash; as with camera &mdash; apps that obtain permission to record audio are
assumed to require the microphone feature by default. If your app can use a
microphone but doesnt strictly need it, you can explicitly state that you dont
require it; but unless you do that, your app wont be shown to devices without
microphones.</li>
</ul>
<p>In other words, whenever Android introduces new features or changes existing
ones, we will always take steps to protect existing applications so that they
dont end up being available to devices where they wont work.</p>
<p>This is implemented, in part, using the <code>aapt</code> tool in the SDK.
To see which features your app explicitly requires or is implicitly assumed to
require, you can use the command <code>aapt dump badging</code>.</p>
<h3 id="conclusion">Conclusion</h3>
<p>The goal of Android is to create a huge installed base for developers to take
advantage of. One of the ways we will achieve this is through different kinds of
hardware running the same software environment. But we also recognize that only
developers know which kinds of devices their apps make sense on. Weve built in
tools to the SDK and set up policies and requirements to ensure that developers
remain in control of their apps, today and in the future. With the information
you just read, and the resources listed in the sidebar of this document, you
can publish your app with the confidence that only users who can run it will
see it.</p>
<p>For more information about Android device compatibility, please visit:</p>
<p style="margin-left:2em;"><a href="http://source.android.com/compatibility/index.html">http://source.android.com/compatibility/index.html</a></p>

View File

@@ -0,0 +1,21 @@
page.title=Application Design Goals
@jd:body
<p>When learning how to build applications on a new platform, you first learn what APIs are available and how to use them. Later, you learn the nuances of the platform. Put another way: first you learn how you <em>can</em> build applications; later, you learn how you <em>should</em> build them, to ensure that your applications offer outstanding performance and a great user experience. </p>
<p>The documents below help you learn the nuances of Android and get started building great applications more quickly, They discuss important aspects of application design that directly influence the user experience of your application, when in the hands of a mobile device user. You should read and consider these design goals as you plan your application and throughout its development, especially if you are new to developing for mobile devices.</p>
<p>Successful mobile applications offer an outstanding user experience, in addition to a compelling technical feature set. The user experience is more than just its visual design or UI flow. It is also influenced by how well the application responds to the user's keypresses and other actions, how it well it interacts with other applications, and how fully and efficiently it uses device and system capabilities.</p>
<p>An outstanding user experience has three key characteristics: it is
<em>fast</em>; it is <em>responsive</em>; and it is <em>seamless</em>. Of course
every platform since the dawn of computing has probably cited those same three
qualities at one time or another. However, each platform achieves them in
different ways; the documents below explain how you can build Android
applications that are fast, responsive, and seamless. </p>
<ul>
<li><a href="performance.html">Designing for Performance</a> (writing efficient Android code)</a></li>
<li><a href="responsiveness.html">Designing for Responsiveness</a> (avoiding ANR)</a></li>
<li><a href="seamlessness.html">Designing for Seamlessness</a> (coexisting with other applications)</a></li>
</ul>

View File

@@ -0,0 +1,433 @@
page.title=Designing for Performance
@jd:body
<div id="qv-wrapper">
<div id="qv">
<h2>In this document</h2>
<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="#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="#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>
<li><a href="#closing_notes">Closing Notes</a></li>
</ol>
</div>
</div>
<p>An Android application will run on a mobile device with limited computing
power and storage, and constrained battery life. Because of
this, it should be <em>efficient</em>. Battery life is one reason you might
want to optimize your app even if it already seems to run "fast enough".
Battery life is important to users, and Android's battery usage breakdown
means users will know if your app is responsible draining their battery.</p>
<p>Note that although this document primarily covers micro-optimizations,
these will almost never make or break your software. Choosing the right
algorithms and data structures should always be your priority, but is
outside the scope of this document.</p>
<a name="intro" id="intro"></a>
<h2>Introduction</h2>
<p>There are two basic rules for writing efficient code:</p>
<ul>
<li>Don't do work that you don't need to do.</li>
<li>Don't allocate memory if you can avoid it.</li>
</ul>
<h2 id="optimize_judiciously">Optimize Judiciously</h2>
<p>This document is about Android-specific micro-optimization, so it assumes
that you've already used profiling to work out exactly what code needs to be
optimized, and that you already have a way to measure the effect (good or bad)
of any changes you make. You only have so much engineering time to invest, so
it's important to know you're spending it wisely.
<p>(See <a href="#closing_notes">Closing Notes</a> for more on profiling and
writing effective benchmarks.)
<p>This document also assumes that you made the best decisions about data
structures and algorithms, and that you've also considered the future
performance consequences of your API decisions. Using the right data
structures and algorithms will make more difference than any of the advice
here, and considering the performance consequences of your API decisions will
make it easier to switch to better implementations later (this is more
important for library code than for application code).
<p>(If you need that kind of advice, see Josh Bloch's <em>Effective Java</em>,
item 47.)</p>
<p>One of the trickiest problems you'll face when micro-optimizing an Android
app is that your app is pretty much guaranteed to be running on multiple
hardware platforms. Different versions of the VM running on different
processors running at different speeds. It's not even generally the case
that you can simply say "device X is a factor F faster/slower than device Y",
and scale your results from one device to others. In particular, measurement
on the emulator tells you very little about performance on any device. There
are also huge differences between devices with and without a JIT: the "best"
code for a device with a JIT is not always the best code for a device
without.</p>
<p>If you want to know how your app performs on a given device, you need to
test on that device.</p>
<a name="object_creation"></a>
<h2>Avoid Creating 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>
<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>
</ul>
<p>A somewhat more radical idea is to slice up multidimensional arrays into
parallel single one-dimension arrays:</p>
<ul>
<li>An array of ints is a much better than an array of Integers,
but this also generalizes to the fact that two parallel arrays of ints
are also a <strong>lot</strong> more efficient than an array of (int,int)
objects. The same goes for any combination of primitive types.</li>
<li>If you need to implement a container that stores tuples of (Foo,Bar)
objects, try to remember that two parallel Foo[] and Bar[] arrays are
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
code, you should try and be as efficient as possible.)</li>
</ul>
<p>Generally speaking, avoid creating short-term temporary objects if you
can. Fewer objects created mean less-frequent garbage collection, which has
a direct impact on user experience.</p>
<a name="myths" id="myths"></a>
<h2>Performance Myths</h2>
<p>Previous versions of this document made various misleading claims. We
address some of them here.</p>
<p>On devices without a JIT, it is true that invoking methods via a
variable with an exact type rather than an interface is slightly more
efficient. (So, for example, it was cheaper to invoke methods on a
<code>HashMap map</code> than a <code>Map map</code>, even though in both
cases the map was a <code>HashMap</code>.) It was not the case that this
was 2x slower; the actual difference was more like 6% slower. Furthermore,
the JIT makes the two effectively indistinguishable.</p>
<p>On devices without a JIT, caching field accesses is about 20% faster than
repeatedly accesssing the field. With a JIT, field access costs about the same
as local access, so this isn't a worthwhile optimization unless you feel it
makes your code easier to read. (This is true of final, static, and static
final fields too.)
<a name="prefer_static" id="prefer_static"></a>
<h2>Prefer Static Over Virtual</h2>
<p>If you don't need to access an object's fields, make your method static.
Invocations will be about 15%-20% faster.
It's also good practice, because you can tell from the method
signature that calling the method can't alter the object's state.</p>
<a name="internal_get_set" id="internal_get_set"></a>
<h2>Avoid Internal Getters/Setters</h2>
<p>In native languages like C++ it's common practice to use getters (e.g.
<code>i = getCount()</code>) instead of accessing the field directly (<code>i
= mCount</code>). This is an excellent habit for C++, because the compiler can
usually inline the access, and if you need to restrict or debug field access
you can add the code at any time.</p>
<p>On Android, this is a bad idea. Virtual method calls are expensive,
much more so than instance field lookups. It's reasonable to follow
common object-oriented programming practices and have getters and setters
in the public interface, but within a class you should always access
fields directly.</p>
<p>Without a JIT, direct field access is about 3x faster than invoking a
trivial getter. With the JIT (where direct field access is as cheap as
accessing a local), direct field access is about 7x faster than invoking a
trivial getter. This is true in Froyo, but will improve in the future when
the JIT inlines getter methods.</p>
<a name="use_final" id="use_final"></a>
<h2>Use Static Final For Constants</h2>
<p>Consider the following declaration at the top of a class:</p>
<pre>static int intVal = 42;
static String strVal = "Hello, world!";</pre>
<p>The compiler generates a class initializer method, called
<code>&lt;clinit&gt;</code>, that is executed when the class is first used.
The method stores the value 42 into <code>intVal</code>, and extracts a
reference from the classfile string constant table for <code>strVal</code>.
When these values are referenced later on, they are accessed with field
lookups.</p>
<p>We can improve matters with the "final" keyword:</p>
<pre>static final int intVal = 42;
static final String strVal = "Hello, world!";</pre>
<p>The class no longer requires a <code>&lt;clinit&gt;</code> method,
because the constants go into static field initializers in the dex file.
Code that refers to <code>intVal</code> will use
the integer value 42 directly, and accesses to <code>strVal</code> will
use a relatively inexpensive "string constant" instruction instead of a
field lookup. (Note that this optimization only applies to primitive types and
<code>String</code> constants, not arbitrary reference types. Still, it's good
practice to declare constants <code>static final</code> whenever possible.)</p>
<a name="foreach" id="foreach"></a>
<h2>Use Enhanced For Loop Syntax</h2>
<p>The enhanced for loop (also sometimes known as "for-each" loop) can be used
for collections that implement the Iterable interface and for arrays.
With collections, an iterator is allocated to make interface calls
to hasNext() and next(). With an ArrayList, a hand-written counted loop is
about 3x faster (with or without JIT), but for other collections the enhanced
for loop syntax will be exactly equivalent to explicit iterator usage.</p>
<p>There are several alternatives for iterating through an array:</p>
<pre> static class Foo {
int mSplat;
}
Foo[] mArray = ...
public void zero() {
int sum = 0;
for (int i = 0; i &lt; mArray.length; ++i) {
sum += mArray[i].mSplat;
}
}
public void one() {
int sum = 0;
Foo[] localArray = mArray;
int len = localArray.length;
for (int i = 0; i &lt; len; ++i) {
sum += localArray[i].mSplat;
}
}
public void two() {
int sum = 0;
for (Foo a : mArray) {
sum += a.mSplat;
}
}
</pre>
<p><strong>zero()</strong> is slowest, because the JIT can't yet optimize away
the cost of getting the array length once for every iteration through the
loop.</p>
<p><strong>one()</strong> is faster. It pulls everything out into local
variables, avoiding the lookups. Only the array length offers a performance
benefit.</p>
<p><strong>two()</strong> is fastest for devices without a JIT, and
indistinguishable from <strong>one()</strong> for devices with a JIT.
It uses the enhanced for loop syntax introduced in version 1.5 of the Java
programming language.</p>
<p>To summarize: use the enhanced for loop by default, but consider a
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 &lt;init&gt; 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>
<p>Consider the following class definition:</p>
<pre>public class Foo {
private int mValue;
public void run() {
Inner in = new Inner();
mValue = 27;
in.stuff();
}
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 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>
<pre>/*package*/ static int Foo.access$100(Foo foo) {
return foo.mValue;
}
/*package*/ static void Foo.access$200(Foo foo, int value) {
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
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>
<a name="avoidfloat" id="avoidfloat"></a>
<h2>Use Floating-Point Judiciously</h2>
<p>As a rule of thumb, floating-point is about 2x slower than integer on
Android devices. This is true on a FPU-less, JIT-less G1 and a Nexus One with
an FPU and the JIT. (Of course, absolute speed difference between those two
devices is about 10x for arithmetic operations.)</p>
<p>In speed terms, there's no difference between <code>float</code> and
<code>double</code> on the more modern hardware. Space-wise, <code>double</code>
is 2x larger. As with desktop machines, assuming space isn't an issue, you
should prefer <code>double</code> to <code>float</code>.</p>
<p>Also, even for integers, some chips have hardware multiply but lack
hardware divide. In such cases, integer division and modulus operations are
performed in software &mdash; something to think about if you're designing a
hash table or doing lots of math.</p>
<a name="library" id="library"></a>
<h2>Know And Use The Libraries</h2>
<p>In addition to all the usual reasons to prefer library code over rolling
your own, bear in mind that the system is at liberty to replace calls
to library methods with hand-coded assembler, which may be better than the
best code the JIT can produce for the equivalent Java. The typical example
here is <code>String.indexOf</code> and friends, which Dalvik replaces with
an inlined intrinsic. Similarly, the <code>System.arraycopy</code> method
is about 9x faster than a hand-coded loop on a Nexus One with the JIT.</p>
<p>(See also <em>Effective Java</em> item 47.)</p>
<a name="native_methods" id="native_methods"></a>
<h2>Use Native Methods Judiciously</h2>
<p>Native code isn't necessarily more efficient than Java. For one thing,
there's a cost associated with the Java-native transition, and the JIT can't
optimize across these boundaries. If you're allocating native resources (memory
on the native heap, file descriptors, or whatever), it can be significantly
more difficult to arrange timely collection of these resources. You also
need to compile your code for each architecture you wish to run on (rather
than rely on it having a JIT). You may even have to compile multiple versions
for what you consider the same architecture: native code compiled for the ARM
processor in the G1 can't take full advantage of the ARM in the Nexus One, and
code compiled for the ARM in the Nexus One won't run on the ARM in the G1.</p>
<p>Native code is primarily useful when you have an existing native codebase
that you want to port to Android, not for "speeding up" parts of a Java app.</p>
<p>(See also <em>Effective Java</em> item 54.)</p>
<a name="closing_notes" id="closing_notes"></a>
<h2>Closing Notes</h2>
<p>One last thing: always measure. Before you start optimizing, make sure you
have a problem. Make sure you can accurately measure your existing performance,
or you won't be able to measure the benefit of the alternatives you try.</p>
<p>Every claim made in this document is backed up by a benchmark. The source
to these benchmarks can be found in the <a href="http://code.google.com/p/dalvik/source/browse/#svn/trunk/benchmarks">code.google.com "dalvik" project</a>.</p>
<p>The benchmarks are built with the
<a href="http://code.google.com/p/caliper/">Caliper</a> microbenchmarking
framework for Java. Microbenchmarks are hard to get right, so Caliper goes out
of its way to do the hard work for you, and even detect some cases where you're
not measuring what you think you're measuring (because, say, the VM has
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
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
data to ensure that the resulting code actually runs faster when run without
Traceview.

View File

@@ -0,0 +1,140 @@
page.title=Designing for Responsiveness
@jd:body
<div id="qv-wrapper">
<div id="qv">
<h2>In this document</h2>
<ol>
<li><a href="#anr">What Triggers ANR?</a></li>
<li><a href="#avoiding">How to Avoid ANR</a></li>
<li><a href="#reinforcing">Reinforcing Responsiveness</a></li>
</ol>
</div>
</div>
<div class="figure">
<img src="{@docRoot}images/anr.png" alt="Screenshot of ANR dialog box" width="240" height="320"/>
<p><strong>Figure 1.</strong> An ANR dialog displayed to the user.</p>
</div>
<p>It's possible to write code that wins every performance test in the world,
but still sends users in a fiery rage when they try to use the application.
These are the applications that aren't <em>responsive</em> enough &mdash; the
ones that feel sluggish, hang or freeze for significant periods, or take too
long to process input. </p>
<p>In Android, the system guards against applications that are insufficiently
responsive for a period of time by displaying a dialog to the user, called the
Application Not Responding (ANR) dialog, shown at right in Figure 1. The user
can choose to let the application continue, but the user won't appreciate having
to act on this dialog every time he or she uses your application. It's critical
to design responsiveness into your application, so that the system never has
cause to display an ANR dialog to the user. </p>
<p>Generally, the system displays an ANR if an application cannot respond to
user input. For example, if an application blocks on some I/O operation
(frequently a network access), then the main application thread won't be able to
process incoming user input events. After a time, the system concludes that the
application is frozen, and displays the ANR to give the user the option to kill
it. </p>
<p>Similarly, if your application spends too much time building an elaborate in-memory
structure, or perhaps computing the next move in a game, the system will
conclude that your application has hung. It's always important to make
sure these computations are efficient using the techniques above, but even the
most efficient code still takes time to run.</p>
<p>In both of these cases, the recommended approach is to create a child thread and do
most of your work there. This keeps the main thread (which drives the user
interface event loop) running and prevents the system from concluding that your code
has frozen. Since such threading usually is accomplished at the class
level, you can think of responsiveness as a <em>class</em> problem. (Compare
this with basic performance, which was described above as a <em>method</em>-level
concern.)</p>
<p>This document describes how the Android system determines whether an
application is not responding and provides guidelines for ensuring that your
application stays responsive. </p>
<h2 id="anr">What Triggers ANR?</h2>
<p>In Android, application responsiveness is monitored by the Activity Manager
and Window Manager system services. Android will display the ANR dialog
for a particular application when it detects one of the following
conditions:</p>
<ul>
<li>No response to an input event (e.g. key press, screen touch)
within 5 seconds</li>
<li>A {@link android.content.BroadcastReceiver BroadcastReceiver}
hasn't finished executing within 10 seconds</li>
</ul>
<h2 id="avoiding">How to Avoid ANR</h2>
<p>Given the above definition for ANR, let's examine why this can occur in
Android applications and how best to structure your application to avoid ANR.</p>
<p>Android applications normally run entirely on a single (i.e. main) thread.
This means that anything your application is doing in the main thread that
takes a long time to complete can trigger the ANR dialog because your
application is not giving itself a chance to handle the input event or Intent
broadcast.</p>
<p>Therefore any method that runs in the main thread should do as little work
as possible. In particular, Activities should do as little as possible to set
up in key life-cycle methods such as <code>onCreate()</code> and
<code>onResume()</code>. Potentially long running operations such as network
or database operations, or computationally expensive calculations such as
resizing bitmaps should be done in a child thread (or in the case of databases
operations, via an asynchronous request). However, this does not mean that
your main thread should block while waiting for the child thread to
complete &mdash; nor should you call <code>Thread.wait()</code> or
<code>Thread.sleep()</code>. Instead of blocking while waiting for a child
thread to complete, your main thread should provide a {@link
android.os.Handler Handler} for child threads to post back to upon completion.
Designing your application in this way will allow your main thread to remain
responsive to input and thus avoid ANR dialogs caused by the 5 second input
event timeout. These same practices should be followed for any other threads
that display UI, as they are also subject to the same timeouts.</p>
<p>You can use {@link android.os.StrictMode} to help find potentially
long running operations such as network or database operations that
you might accidentally be doing your main thread.</p>
<p>The specific constraint on IntentReceiver execution time emphasizes what
they were meant to do: small, discrete amounts of work in the background such
as saving a setting or registering a Notification. So as with other methods
called in the main thread, applications should avoid potentially long-running
operations or calculations in BroadcastReceivers. But instead of doing intensive
tasks via child threads (as the life of a BroadcastReceiver is short), your
application should start a {@link android.app.Service Service} if a
potentially long running action needs to be taken in response to an Intent
broadcast. As a side note, you should also avoid starting an Activity from an
Intent Receiver, as it will spawn a new screen that will steal focus from
whatever application the user is currently has running. If your application
has something to show the user in response to an Intent broadcast, it should
do so using the {@link android.app.NotificationManager Notification
Manager}.</p>
<h2 id="reinforcing">Reinforcing Responsiveness</h2>
<p>Generally, 100 to 200ms is the threshold beyond which users will perceive
lag (or lack of "snappiness," if you will) in an application. As such, here
are some additional tips beyond what you should do to avoid ANR that will help
make your application seem responsive to users.</p>
<ul>
<li>If your application is doing work in the background in response to
user input, show that progress is being made ({@link
android.widget.ProgressBar ProgressBar} and {@link
android.app.ProgressDialog ProgressDialog} are useful for this).</li>
<li>For games specifically, do calculations for moves in a child
thread.</li>
<li>If your application has a time-consuming initial setup phase, consider
showing a splash screen or rendering the main view as quickly as possible
and filling in the information asynchronously. In either case, you should
indicate somehow that progress is being made, lest the user perceive that
the application is frozen.</li>
</ul>

View File

@@ -0,0 +1,249 @@
page.title=Designing for Seamlessness
@jd:body
<div id="qv-wrapper">
<div id="qv">
<h2>In this document</h2>
<ol>
<li><a href="#drop">Don't Drop Data</a></li>
<li><a href="#expose">Don't Expose Raw Data</a></li>
<li><a href="#interrupt">Don't Interrupt the User</a></li>
<li><a href="#threads">Got a Lot to Do? Do it in a Thread</a></li>
<li><a href="#multiple-activities">Don't Overload a Single Activity Screen</a></li>
<li><a href="#themes">Extend System Themes</a></li>
<li><a href="#flexui">Design Your UI to Work with Multiple Screen Resolutions</a></li>
<li><a href="#network">Assume the Network is Slow</a></li>
<li><a href="#keyboard">Don't Assume Touchscreen or Keyboard</a></li>
<li><a href="#battery">Do Conserve the Device Battery</a></li>
</ol>
</div>
</div>
<p>Even if your application is fast and responsive, certain design decisions can
still cause problems for users &mdash; because of unplanned interactions with
other applications or dialogs, inadvertent loss of data, unintended blocking,
and so on. To avoid these problems, it helps to understand the context in which
your applications run and the system interactions that can affect your
application. In short, you should strive to develop an application that
interacts seamlessly with the system and with other applications. </p>
<p>A common seamlessness problem is when an application's background process
&mdash; for example, a service or broadcast receiver &mdash; pops up a dialog in
response to some event. This may seem like harmless behavior, especially when
you are building and testing your application in isolation, on the emulator.
However, when your application is run on an actual device, your application may
not have user focus at the time your background process displays the dialog. So
it could end up that your application would display it's dialog behind the
active application, or it could take focus from the current application and
display the dialog in front of whatever the user was doing (such as dialing a
phone call, for example). That behavior would not work for your application or
for the user. </p>
<p>To avoid these problems, your application should use the proper system
facility for notifying the user &mdash; the
{@link android.app.Notification Notification} classes. Using
notifications, your application can signal the user that an event has
taken place, by displaying an icon in the status bar rather than taking
focus and interrupting the user.</p>
<p>Another example of a seamlessness problem is when an activity inadvertently
loses state or user data because it doesn't correctly implement the onPause()
and other lifecycle methods. Or, if your application exposes data intended to be
used by other applications, you should expose it via a ContentProvider, rather
than (for example) doing so through a world-readable raw file or database.</p>
<p>What those examples have in common is that they involve cooperating nicely
with the system and other applications. The Android system is designed to treat
applications as a sort of federation of loosely-coupled components, rather than
chunks of black-box code. This allows you as the developer to view the entire
system as just an even-larger federation of these components. This benefits you
by allowing you to integrate cleanly and seamlessly with other applications, and
so you should design your own code to return the favor.</p>
<p>This document discusses common seamlessness problems and how to avoid them.</p>
<h2 id="drop">Don't Drop Data</h2>
<p>Always keep in mind that Android is a mobile platform. It may seem obvious to
say it, but it's important to remember that another Activity (such as the
"Incoming Phone Call" app) can pop up over your own Activity at any moment.
This will fire the onSaveInstanceState() and onPause() methods, and will likely result in
your application being killed.</p>
<p>If the user was editing data in your application when the other Activity
appeared, your application will likely lose that data when your application is
killed. Unless, of course, you save the work in progress first. The "Android
Way" is to do just that: Android applications that accept or edit input should
override the onSaveInstanceState() method and save their state in some appropriate
fashion. When the user revisits the application, she should be able to
retrieve her data.</p>
<p>A classic example of a good use of this behavior is a mail application. If the
user was composing an email when another Activity started up, the application
should save the in-process email as a draft.</p>
<h2 id="expose">Don't Expose Raw Data</h2>
<p>If you wouldn't walk down the street in your underwear, neither should your
data. While it's possible to expose certain kinds of application to the world
to read, this is usually not the best idea. Exposing raw data requires other
applications to understand your data format; if you change that format, you'll
break any other applications that aren't similarly updated.</p>
<p>The "Android Way" is to create a ContentProvider to expose your data to other
applications via a clean, well-thought-out, and maintainable API. Using a
ContentProvider is much like inserting a Java language interface to split up and
componentize two tightly-coupled pieces of code. This means you'll be able to
modify the internal format of your data without changing the interface exposed
by the ContentProvider, and this without affecting other applications.</p>
<h2 id="interrupt">Don't Interrupt the User</h2>
<p>If the user is running an application (such as the Phone application during a
call) it's a pretty safe bet he did it on purpose. That's why you should avoid
spawning activities except in direct response to user input from the current
Activity.</p>
<p>That is, don't call startActivity() from BroadcastReceivers or Services running in
the background. Doing so will interrupt whatever application is currently
running, and result in an annoyed user. Perhaps even worse, your Activity may
become a "keystroke bandit" and receive some of the input the user was in the
middle of providing to the previous Activity. Depending on what your
application does, this could be bad news.</p>
<p>Instead of spawning Activity UIs directly from the background, you should
instead use the NotificationManager to set Notifications. These will appear in
the status bar, and the user can then click on them at his leisure, to see
what your application has to show him.</p>
<p>(Note that all this doesn't apply to cases where your own Activity is already
in the foreground: in that case, the user expects to see your next Activity in
response to input.)</p>
<h2 id="threads">Got a Lot to Do? Do it in a Thread</h2>
<p>If your application needs to perform some expensive or long-running
computation, you should probably move it to a thread. This will prevent the
dreaded "Application Not Responding" dialog from being displayed to the user,
with the ultimate result being the fiery demise of your application.</p>
<p>By default, all code in an Activity as well as all its Views run in the same
thread. This is the same thread that also handles UI events. For example, when
the user presses a key, a key-down event is added to the Activity's main
thread's queue. The event handler system needs to dequeue and handle that
event quickly; if it doesn't, the system concludes after a few seconds that
the application is hung and offers to kill it for the user.</p>
<p>If you have long-running code, running it inline in your Activity will run it
on the event handler thread, effectively blocking the event handler. This will
delay input processing, and result in the ANR dialogs. To avoid this, move
your computations to a thread. This <a
href="responsiveness.html">Design for Responsiveness</a> document
discusses how to do that..</p>
<h2 id="multiple-activities">Don't Overload a Single Activity Screen</h2>
<p>Any application worth using will probably have several different screens.
When designing the screens of your UI, be sure to make use of multiple Activity
object instances.</p>
<p>Depending on your development background, you may interpret an Activity as
similar to something like a Java Applet, in that it is the entry point for
your application. However, that's not quite accurate: where an Applet subclass
is the single entry point for a Java Applet, an Activity should be thought of
as one of potentially several entry points to your application. The only
difference between your "main" Activity and any others you might have is that
the "main" one just happens to be the only one that expressed an interest in
the "android.intent.action.MAIN" action in your AndroidManifest..xml file.</p>
<p>So, when designing your application, think of your application as a federation
of Activity objects. This will make your code a lot more maintainable in the long
run, and as a nice side effect also plays nicely with Android's application
history and "backstack" model.</p>
<h2 id="themes">Extend System Themes</h2>
<p>When it comes to the look-and-feel of the user interface, it's important to
blend in nicely. Users are jarred by applications which contrast with the user
interface they've come to expect. When designing your UIs, you should try and
avoid rolling your own as much as possible. Instead, use a Theme. You
can override or extend those parts of the theme that you need to, but at least
you're starting from the same UI base as all the other applications. For all
the details, read <a href="{@docRoot}guide/topics/ui/themes.html">Applying Styles and Themes</a>.</p>
<h2 id="flexui">Design Your UI to Work with Multiple Screen Resolutions</h2>
<p>Different Android-powered devices will support different screen resolutions.
Some will even be able to change resolutions on the fly, such as by switching
to landscape mode. It's important to make sure your layouts and drawables
are flexible enough to display properly on a variety of device screens.</p>
<p>Fortunately, this is very easy to do. In brief, what you must do is
provide different versions of your artwork (if you use any) for the key
resolutions, and then design your layout to accommodate various dimensions.
(For example, avoid using hard-coded positions and instead use relative
layouts.) If you do that much, the system handles the rest, and your
application looks great on any device.</p>
<h2 id="network">Assume the Network is Slow</h2>
<p>Android devices will come with a variety of network-connectivity options. All
will have some data-access provision, though some will be faster than others.
The lowest common denominator, however, is GPRS, the non-3G data service for
GSM networks. Even 3G-capable devices will spend lots of time on non-3G
networks, so slow networks will remain a reality for quite a long time to
come.</p>
<p>That's why you should always code your applications to minimize network
accesses and bandwidth. You can't assume the network is fast, so you should
always plan for it to be slow. If your users happen to be on faster networks,
then that's great &mdash; their experience will only improve. You want to avoid the
inverse case though: applications that are usable some of the time, but
frustratingly slow the rest based on where the user is at any given moment are
likely to be unpopular.</p>
<p>One potential gotcha here is that it's very easy to fall into this trap if
you're using the emulator, since the emulator uses your desktop computer's
network connection. That's almost guaranteed to be much faster than a cell
network, so you'll want to change the settings on the emulator that simulate
slower network speeds. You can do this in Eclipse, in the "Emulator Settings"
tab of your launch configuration or via a <a
href="{@docRoot}guide/developing/tools/emulator.html#netspeed">command-line
option</a> when starting the emulator.</p>
<h2 id="keyboard">Don't Assume Touchscreen or Keyboard</h2>
<p>
Android will support a variety of handset form-factors. That's a fancy way of
saying that some Android devices will have full "QWERTY" keyboards, while
others will have 40-key, 12-key, or even other key configurations. Similarly,
some devices will have touch-screens, but many won't.
</p><p>
When building your applications, keep that in mind. Don't make assumptions
about specific keyboard layouts -- unless, of course, you're really interested
in restricting your application so that it can only be used on those devices.
</p>
<h2 id="battery">Do Conserve the Device Battery</h2>
<p>
A mobile device isn't very mobile if it's constantly plugged into the
wall. Mobile devices are battery-powered, and the longer we can make that
battery last on a charge, the happier everyone is &mdash; especially the user.
Two of the biggest consumers of battery power are the processor, and the
radio; that's why it's important to write your applications to do as little
work as possible, and use the network as infrequently as possible.
</p><p>
Minimizing the amount of processor time your application uses really comes
down to <a href="performance.html">writing efficient
code</a>. To minimize the power drain from using the radio, be sure to handle
error conditions gracefully, and only fetch what you need. For example, don't
constantly retry a network operation if one failed. If it failed once, it's
likely because the user has no reception, so it's probably going to fail again
if you try right away; all you'll do is waste battery power.
</p><p>
Users are pretty smart: if your program is power-hungry, you can count on
them noticing. The only thing you can be sure of at that point is that your
program won't stay installed very long.
</p>

View File

@@ -0,0 +1,8 @@
<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>

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,467 @@
page.title=Icon Design Guidelines
parent.title=UI Guidelines
parent.link=index.html
@jd:body
<div id="qv-wrapper">
<div id="qv">
<h2>Quickview</h2>
<ul>
<li>You can use several types of icons in an Android application.</li>
<li>Your icons should follow the general specification in this document.</li>
<li>You should create separate icon sets for high-, medium-, and low-density screens.</li>
</ul>
<h2>In this document</h2>
<ol>
<li><a href="#templatespack">Using the Icon Templates Pack</a></li>
<li><a href="#icon-sets">Providing Density-Specific Icon Sets</a></li>
<li><a href="#design-tips">Tips for Designers</a></li>
</ol>
<h2>Topics</h2>
<ol>
<li><a href="icon_design_launcher.html">Launcher Icons</a></li>
<li><a href="icon_design_menu.html">Menu Icons</a></li>
<li><a href="icon_design_status_bar.html">Status Bar Icons</a></li>
<li><a href="icon_design_tab.html">Tab Icons</a></li>
<li><a href="icon_design_dialog.html">Dialog Icons</a></li>
<li><a href="icon_design_list.html">List View Icons</a></li>
</ol>
<h2>Downloads</h2>
<ol>
<li><a href="{@docRoot}shareables/icon_templates-v2.3.zip">Android Icon
Templates Pack, v2.3 &raquo;</a></li>
<li><a href="{@docRoot}shareables/icon_templates-v2.0.zip">Android Icon
Templates Pack, v2.0 &raquo;</a></li>
<li><a href="{@docRoot}shareables/icon_templates-v1.0.zip">Android Icon
Templates Pack, v1.0 &raquo;</a></li>
</ol>
<h2>See also</h2>
<ol>
<li><a href="{@docRoot}guide/practices/screens_support.html">Supporting Multiple
Screens</a></li>
</ol>
</div>
</div>
<p>Creating a unified look and feel throughout a user interface adds value to
your product. Streamlining the graphic style will also make the UI seem more
professional to users.</p>
<p>This document provides information to help you create icons for various parts
of your applications user interface that match the general styles used by the
Android 2.x framework. Following these guidelines will help you to create a
polished and unified experience for the user.</p>
<p>The following documents discuss detailed guidelines for the common types of
icons used throughout Android applications:</p>
<dl>
<dt><strong><a href="icon_design_launcher.html">Launcher Icons</a></strong></dt>
<dd>A Launcher icon is a graphic that represents your application on the
device's Home screen and in the Launcher window.</dd>
<dt><strong><a href="icon_design_menu.html">Menu Icons</a></strong></dt>
<dd>Menu icons are graphical elements placed in the options menu shown to
users when they press the Menu button.</dd>
<dt><strong><a href="icon_design_status_bar.html">Status Bar Icons</a></strong></dt>
<dd>Status bar icons are used to represent notifications from your
application in the status bar.</dd>
<dt><strong><a href="icon_design_tab.html">Tab Icons</a></strong></dt>
<dd>Tab icons are graphical elements used to represent individual tabs in a
multi-tab interface.</dd>
<dt><strong><a href="icon_design_dialog.html">Dialog Icons</a></strong></dt>
<dd>Dialog icons are shown in pop-up dialog boxes that prompt the user for
interaction.</dd>
<dt><strong><a href="icon_design_list.html">List View Icons</a></strong></dt>
<dd>List view icons are used with {@link android.widget.ListView} to
graphically represent list items. An example is the Settings application.</dd>
</dl>
<p>To get started creating your icons more quickly, you can download
the Android Icon Templates Pack.</p>
<h2 id="templatespack">Using the Android Icon Templates Pack</h2>
<p>The Android Icon Templates Pack is a collection of template designs,
textures, and layer styles that make it easier for you to create icons that
conform to the guidelines given in this document. We recommend downloading the
template pack archive before you start designing your icons.</p>
<p>The icon templates are provided in the Adobe Photoshop file format (.psd),
which preserves the layers and design treatments we used when creating the
standard icons for the Android platform. You can load the template files into
any compatible image-editing program, although your ability to work directly
with the layers and treatments may vary based on the program you are using.</p>
<p>You can obtain the latest Icon Templates Pack archive using the link below:
</p>
<p style="margin-left:2em"><a
href="{@docRoot}shareables/icon_templates-v2.3.zip">Download the Icon Templates
Pack for Android 2.3 &raquo;</a>
<p>For previous versions of the Icon Templates Pack, see the <em>Downloads</em>
section in the box at the top-right corner of this page.</p>
<h2 id="icon-sets">Providing Density-Specific Icon Sets</h2>
<p>Android is designed to run on a variety of devices that offer a range of
screen sizes and resolutions. When you design the icons for your application,
it's important keep in mind that your application may be installed on any of
those devices. As described in the <a
href="{@docRoot}guide/practices/screens_support.html">Supporting Multiple
Screens</a> document, the Android platform makes it straightforward for you to
provide icons in such a way that they will be displayed properly on any device,
regardless of the device's screen size or resolution.</p>
<p>In general, the recommended approach is to create a separate set of icons for
each of the three generalized screen densities listed in Table 1. Then,
store them in density-specific resource directories in your application. When
your application runs, the Android platform will check the characteristics of
the device screen and load icons from the appropriate density-specific
resources. For more information about how to store density-specific resources in
your application, see <a
href="{@docRoot}guide/practices/screens_support.html#qualifiers">Resource
directory qualifiers for screen size and density</a>. </p>
<p>For tips on how to create and manage icon sets for multiple densities, see
<a href="#design-tips">Tips for Designers</a>.</p>
<p class="table-caption" id="screens-table"><strong>Table 1.</strong> Summary of
finished icon dimensions for each of the three generalized screen densities, by
icon type.</p>
<table>
<tbody>
<tr>
<th>Icon Type</th><th colspan="3">Standard Asset Sizes (in Pixels), for
Generalized Screen Densities</th></tr>
<tr>
<td style="background-color:#f3f3f3"></td>
<th style="background-color:#f3f3f3;font-weight:normal">
<nobr>Low density screen <em>(ldpi)</em></nobr>
</th>
<th style="background-color:#f3f3f3;font-weight:normal">
<nobr>Medium density screen <em>(mdpi)</em></nobr>
</th>
<th style="background-color:#f3f3f3;font-weight:normal">
<nobr>High density screen <em>(hdpi)</em><nobr>
</th>
</tr>
<tr>
<th style="background-color:#f3f3f3;font-weight:normal">
Launcher
</th>
<td>
36 x 36 px
</td>
<td>
48 x 48 px
</td>
<td>
72 x 72 px
</td>
</tr>
<tr>
<th style="background-color:#f3f3f3;font-weight:normal">
Menu
</th>
<td>
36 x 36 px
</td>
<td>
48 x 48 px
</td>
<td>
72 x 72 px
</td>
</tr>
<tr>
<th style="background-color:#f3f3f3;font-weight:normal">
Status Bar (Android 2.3 and later)
</th>
<td>
12w x 19h px<br>
(preferred, width may vary)
</td>
<td>
16w x 25h px<br>
(preferred, width may vary)
</td>
<td>
24w x 38h px<br>
(preferred, width may vary)
</td>
</tr>
<tr>
<th style="background-color:#f3f3f3;font-weight:normal">
Status Bar (Android 2.2 and below)
</th>
<td>
19 x 19 px
</td>
<td>
25 x 25 px
</td>
<td>
38 x 38 px
</td>
</tr>
<tr>
<th style="background-color:#f3f3f3;font-weight:normal">
Tab
</th>
<td>
24 x 24 px
</td>
<td>
32 x 32 px
</td>
<td>
48 x 48 px
</td>
</tr>
<tr>
<th style="background-color:#f3f3f3;font-weight:normal">
Dialog
</th>
<td>
24 x 24 px
</td>
<td>
32 x 32 px
</td>
<td>
48 x 48 px
</td>
</tr>
<tr>
<th style="background-color:#f3f3f3;font-weight:normal">
List View
</th>
<td>
24 x 24 px
</td>
<td>
32 x 32 px
</td>
<td>
48 x 48 px
</td>
</tr>
</tbody>
</table>
<h2 id="design-tips">Tips for Designers</h2>
<p>Here are some tips that you might find useful as you develop icons or other
drawable assets for your application. The tips assume that you are using
Adobe Photoshop or a similar raster and vector image-editing program.</p>
<h3>Use common naming conventions for icon assets</h3>
<p>Try to name files so that related assets will group together inside a
directory when they are sorted alphabetically. In particular, it helps to use a
common prefix for each icon type. For example:</p>
<table>
<tr>
<th>Asset Type</th>
<th>Prefix</th>
<th>Example</th>
</tr>
<tr>
<td>Icons</td>
<td><code>ic_</code></td>
<td><code>ic_star.png</code></td>
</tr>
<tr>
<td>Launcher icons</td>
<td><code>ic_launcher</code></td>
<td><code>ic_launcher_calendar.png</code></td>
</tr>
<tr>
<td>Menu icons</td>
<td><code>ic_menu</code></td>
<td><code>ic_menu_archive.png</code></td>
</tr>
<tr>
<td>Status bar icons</td>
<td><code>ic_stat_notify</code></td>
<td><code>ic_stat_notify_msg.png</code></td>
</tr>
<tr>
<td>Tab icons</td>
<td><code>ic_tab</code></td>
<td><code>ic_tab_recent.png</code></td>
</tr>
<tr>
<td>Dialog icons</td>
<td><code>ic_dialog</code></td>
<td><code>ic_dialog_info.png</code></td>
</tr>
</table>
<p>Note that you are not required to use a shared prefix of any type &mdash;
doing so is for your convenience only.</p>
<h3>Set up a working space that organizes files for multiple densities</h3>
<p>Supporting multiple screen densities means you must create multiple versions
of the same icon. To help keep the multiple copies of files safe and easier to
find, we recommend creating a directory structure in your working space that
organizes asset files per resolution. For example:</p>
<pre>assets/...
ldpi/...
_pre_production/...
<em>working_file</em>.psd
<em>finished_asset</em>.png
mdpi/...
_pre_production/...
<em>working_file</em>.psd
<em>finished_asset</em>.png
hdpi/...
_pre_production/...
<em>working_file</em>.psd
<em>finished_asset</em>.png</pre>
<p>This structure parallels the density-specific structure in which you will
ultimately store the finished assets in your application's resources. Because
the structure in your working space is similar to that of the application, you
can quickly determine which assets should be copied to each application
resources directory. Separating assets by density also helps you detect any
variances in filenames across densities, which is important because
corresponding assets for different densities must share the same filename.</p>
<p>For comparison, here's the resources directory structure of a typical
application: </p>
<pre>res/...
drawable-ldpi/...
<em>finished_asset</em>.png
drawable-mdpi/...
<em>finished_asset</em>.png
drawable-hdpi/...
<em>finished_asset</em>.png</pre>
<h3>Use vector shapes where possible</h3>
<p>Many image-editing programs such as Adobe Photoshop allow you to use a
combination of vector shapes and raster layers and effects. When possible,
use vector shapes so that if the need arises, assets can be scaled up without
loss of detail and edge crispness.</p>
<p>Using vectors also makes it easy to align edges and corners to pixel
boundaries at smaller resolutions.</li>
<h3>Start with large artboards</h3>
<p>Because you will need to create assets for different screen densities, as
shown in <a href="#screens-table">Table 1</a>, it is best to start your icon
designs on large artboards with dimensions that are multiples of the target icon
sizes. For example, <a
href="{@docRoot}guide/practices/ui_guidelines/icon_design_launcher.html">launcher
icons</a> are 72, 48, or 36 pixels wide, depending on screen density. If you
initially draw launcher icons on an 864x864 artboard, it will be easier and
cleaner to tweak the icons when you scale the artboard down to the target
sizes for final asset creation.</p>
<p>It's also beneficial to add guide lines (also known as guides) to your large
artboard for the recommended safe margins at the highest target density.
Continuing with the example above, per the <a
href="{@docRoot}guide/practices/ui_guidelines/icon_design_launcher.html#size5">guidelines</a>,
launcher icon content should be 60x60 pixels (56x56 for square icons) within the
full 72x72 asset, or a safe margin of 6 pixels on each side. On an 864x864
artboard, this corresponds to horizontal and vertical guide lines 72 pixels from
each side of the artboard.</p>
<h3>When scaling, redraw bitmap layers as needed</h3>
<p>If you scaled an image up from a bitmap layer, rather than from a vector
layer, those layers will need to be redrawn manually to appear crisp at higher
densities. For example if a 60x60 circle was painted as a bitmap for
<code>mdpi</code> it will need to be repainted as a 90x90 circle for
<code>hdpi</code>.</p>
<h3>When saving image assets, remove unnecessary metadata</h3>
<p>To help keep each image asset as small as possible, make sure to remove any
unnecessary headers from the file, such as Adobe Fireworks metadata or Adobe
Photoshop headers. To remove the Photoshop header, follow these steps: </p>
<ol>
<li>Under the <strong>File</strong> menu, choose the <strong>Save for Web &amp;
Devices</strong> command </li>
<li>On the "Save for Web &amp; Devices" panel, set the Preset pop-up to
"PNG-24," set the pop-up under Presets to "PNG-24" as well, and select the
Transparency box (if the image uses transparency)</li>
<li>Select <strong>Save</strong>.</li>
</ol>
<p>It is also useful to use PNG file size optimization tools such as <a
href="http://optipng.sourceforge.net/">OptiPNG</a> or <a
href="http://pmt.sourceforge.net/pngcrush/">Pngcrush</a>.
<h3>Make sure that corresponding assets for different densities use the same
filenames</h3>
<p>Corresponding icon asset files for each density <strong>must use the same
filename</strong>, but be stored in density-specific resource directories. This
allows the system to look up and load the proper resource according to the
screen characteristics of the device. For this reason, make sure that the set of
assets in each directory is consistent and that the files do not use
density-specific suffixes.</p>
<p>For more information about density-specific resources
and how the system uses them to meet the needs of different devices, see <a
href="{@docRoot}guide/practices/screens_support.html">Supporting Multiple
Screens</a>.</p>

View File

@@ -0,0 +1,9 @@
<html>
<head>
<meta http-equiv="refresh" content="0;url=icon_design.html">
<title>Redirecting...</title>
</head>
<body>
<a href="icon_design.html">click here</a> if you are not redirected.
</body>
</html>

View File

@@ -0,0 +1,164 @@
page.title=Dialog Icons
parent.title=Icon Design Guidelines
parent.link=icon_design.html
@jd:body
<div id="qv-wrapper">
<div id="qv">
<h2>In this document</h2>
<ol>
<li><a href="#icon1">All Android Versions</a>
<ol>
<li><a href="#structure1">Structure</a></li>
<li><a href="#style1">Light, effects, and shadows</a></li>
</ol>
</li>
</ol>
<h2>See also</h2>
<ol>
<li><a href="{@docRoot}guide/practices/screens_support.html">Supporting Multiple
Screens</a></li>
</ol>
</div>
</div>
<p>Dialog icons are shown in pop-up dialog boxes that prompt the user for
interaction. They use a light gradient and inner
shadow in order to stand out against a dark background.</p>
<p>As described in <a href="icon_design.html#icon-sets">Providing
Density-Specific Icon Sets</a>, you should create separate icon sets for low-,
medium-, and high-density screens. This ensures that your icons will display
properly across the range of devices on which your application can be installed.
See Table 1 for a listing of the recommended finished icon sizes for each
density. Also, see <a href="icon_design.html#design-tips">Tips for Designers</a>
for suggestions on how to work with multiple sets of icons.</p>
<p class="table-caption"><strong>Table 1.</strong> Summary of finished dialog
icon dimensions for each of the three generalized screen densities.</p>
<table>
<tbody>
<tr>
<th style="background-color:#f3f3f3;font-weight:normal">
<nobr>Low density screen <em>(ldpi)</em></nobr>
</th>
<th style="background-color:#f3f3f3;font-weight:normal">
<nobr>Medium density screen <em>(mdpi)</em></nobr>
</th>
<th style="background-color:#f3f3f3;font-weight:normal">
<nobr>High density screen <em>(hdpi)</em><nobr>
</th>
</tr>
<tr>
<td>
24 x 24 px
</td>
<td>
32 x 32 px
</td>
<td>
48 x 48 px
</td>
</tr>
</tbody>
</table>
<p><strong>Final art must be exported as a transparent PNG file. Do not include
a background color</strong>.</p>
<p>Templates for creating icons in Adobe Photoshop are available in the <a
href="{@docRoot}guide/practices/ui_guidelines/icon_design.html#templatespack">Icon
Templates Pack</a>.</p>
<h2 id="icon1">All Android Versions</h2>
<p>The following guidelines describe how to design dialog icons for all versions
of the Android platform.</p>
<h3 id="structure1">Structure</h3>
<ul>
<li>Dialog icons have a 1 pixel safeframe. The base shape must fit within the
safeframe, but the anti-alias of a round shape can overlap the safeframe.</li>
<li>All dimensions specified on this page are based on a 32x32 pixel artboard size
in Adobe Photoshop. Keep 1 pixel of padding around the bounding box inside the
Photoshop template.</li>
</ul>
<table class="image-caption">
<tr>
<td class="image-caption-i">
<img src="{@docRoot}images/icon_design/dialog_icon.png" alt="A view of dialog
icon structure." />
</td>
<td class="image-caption-c">
<div class="caption grad-rule-top">
<p><strong>Figure 1. </strong>Safeframe and fill gradient for dialog icons.
Icon size is 32x32.</p>
</div>
</td>
</tr>
</table>
<h3 id="style1">Light, effects, and shadows</h3>
<p>Dialog icons are flat and pictured face-on. In order to stand out against a
dark background, they are built up using a light gradient and inner shadow.</p>
<table class="image-caption">
<tr>
<td class="image-caption-i">
<img src="{@docRoot}images/icon_design/dialog_light.png" alt="A view of light,
effects, and shadows for dialog icons."/>
</td>
<td class="image-caption-c">
<div class="caption grad-rule-top">
<p><strong>Figure 2. </strong>Light, effects, and shadows for dialog
icons.</p>
<div class="image-caption-nested">
<table>
<tr><td><em>1.</em></td><td>Front part:</td><td>gradient overlay | angle 90&deg;<br>bottom: r 223 | g 223 | b 223<br>top: r 249 | g 249 | b 249<br>bottom color location: 0%<br>top color location: 75%</td></tr>
<tr><td><em>2.</em></td><td>Inner shadow:</td><td>black | 25% opacity | <br>angle -90&deg; | distance 1px | size 0px</td></tr>
</table>
</div>
</div>
</td>
</tr>
</table>
<table>
<tr>
<td style="border:0;">
<h4 id="steps1">Step by step</h4>
<ol>
<li>Create the basic shapes using a tool like Adobe Illustrator.</li>
<li>Import the shape into a tool like Adobe Photoshop and scale to fit an image
of 32x32 px on a transparent background. </li>
<li>Add the effects seen in Figure 2 for the proper filter.</li>
<li>Export the icon at 32x32 as a PNG file with transparency enabled.</li>
</ol>
</td>
</tr>
</table>

View File

@@ -0,0 +1,520 @@
page.title=Launcher Icons
parent.title=Icon Design Guidelines
parent.link=icon_design.html
@jd:body
<div id="qv-wrapper">
<div id="qv">
<h2>In this document</h2>
<ol>
<li><a href="#market">Application Icons in Android Market</a></li>
<li><a href="#icon5">Android 2.0 and Later</a>
<ol>
<li><a href="#style5">Style</a></li>
<li><a href="#size5">Size</a></li>
<li><a href="#materialscolors5">Materials and colors</a></li>
<li><a href="#effects5">Effects</a></li>
<li><a href="#dodonts5">Do's and don'ts</a></li>
<li><a href="#examples5">Example icons</a></li>
</ol>
</li>
<li><a href="#icon1">Android 1.6 and Earlier</a></li>
</ol>
<h2>See also</h2>
<ol>
<li><a href="{@docRoot}guide/practices/screens_support.html">Supporting Multiple
Screens</a></li>
</ol>
</div>
</div>
<p>A Launcher icon is a graphic that represents your application on the device's
Home screen and in the Launcher window.</p>
<p>The user opens the Launcher by touching the icon at the bottom of the Home
screen. The Launcher opens and exposes the icons for all of the installed
applications. The user selects an application and opens it by touching the
Launcher icon or by means of any hardware navigation controls available, such as
a trackball or d-pad.</p>
<p>As described in <a href="icon_design.html#icon-sets">Providing
Density-Specific Icon Sets</a>, you should create separate icons for low-,
medium-, and high-density screens. This ensures that your icons will display
properly across the range of devices on which your application can be installed.
See <a href="icon_design.html#design-tips">Tips for Designers</a> for
suggestions on how to work with multiple sets of icons.</p>
<h2 id="market">Application Icons in Android Market</h2>
<p>If you are <a href="{@docRoot}guide/publishing/publishing.html">publishing
your application on Android Market</a>, you will also need to provide a 512x512
pixel, high-resolution application icon in the <a
href="http://market.android.com/publish">developer console</a> at upload-time.
This icon will be used in various locations in Android Market and does
not replace your launcher icon.</p>
<p>For tips and recommendations on creating high-resolution launcher icons that
can easily be scaled up to 512x512, see
<a href="{@docRoot}guide/practices/ui_guidelines/icon_design.html#design-tips">
Tips for Designers</a>.</p>
<p>For information and specifications about high-resolution application
icons in Android Market, see the following article:</p>
<p style="margin-left:2em"><a
href="http://market.android.com/support/bin/answer.py?answer=1078870">
Graphic Assets for your Application (Android Market Help) &raquo;</a>
<h2 id="icon5">Android 2.0 and Later</h2>
<p>Starting with Android 2.0, launcher icons should be front-facing, instead of
at a three-quarter perspective. The following guidelines describe how to design
launcher icons for Android 2.0 (API Level 5) and later.</p>
<h3 id="style5">Style</h3>
<p>The launcher icons that you create should follow the general style principles
below. The guidelines aren't meant to restrict what you can do with your icons,
but rather they are meant to emphasize the common approaches that your icons can
share with others on the device. Figure 1, at right, provides examples. </p>
<div class="figure">
<img src="{@docRoot}images/icon_design/IconGraphic_Icons_i.png"
width="340">
<p class="img-caption">
<strong>Figure 1.</strong> Example launcher icons for Android 2.0 and
greater.
</p>
</div>
<p>Clean and contemporary:</p>
<ul>
<li>Launcher icons should be modern and sometimes quirky; they should not
appear aged or ragged. You should avoid overused symbolic metaphors whenever
possible.</li>
</ul>
<p>Simple and iconic:</p>
<ul>
<li>Android Launcher icons are caricatural in nature; your icons should be
highly simplified and exaggerated, so that they are appropriate for use at small
sizes. Your icons should not be overly complicated. </li>
<li>Try featuring a single part of an application as a symbolic
representation of the whole (for example, the Music icon features a speaker).
</li>
<li>Consider using natural outlines and shapes, both geometric and organic,
with a realistic (but never photorealistic) rendering. </li>
<li>Your icons <em>should not</em> present a cropped view of a larger
image.</li>
</ul>
<p>Tactile and textured:</p>
<ul>
<li>Icons should feature non-glossy, textured material. See
<a href="#materialscolors5">Materials and colors</a>, below, for more
information.</li>
</ul>
<p>Forward-facing and top-lit:</p>
<ul>
<li><em>New for Android 2.0 and later platforms</em>: Android Launcher
icons should be forward-facing, with very little perspective, and they
should be top-lit.</li>
</ul>
<p class="note"><strong>Note:</strong> Android applies separate text labels
using the application name when displaying launcher icons, so you should avoid
embedding text in your icon and instead focus on designing a distinct and
memorable icon.</p>
<h3 id="size5">Size and positioning</h3>
<p>Launcher icons should use a variety of shapes and forms that are scaled and
positioned inside the asset to create consistent visual weight with other
icons.</p>
<p>Figure 2 illustrates various ways of positioning the icon inside the
asset. You should size the icons <em>smaller than the actual bounds of the
asset</em> to create a consistent visual weight and to allow for shadows. If
your icon is square or nearly square, it should be scaled even smaller.</p>
<p>In order to indicate the recommended size for the icon, each example in
Figure 2 includes three different guide rectangles:</p>
<ul>
<li>The red box is the bounding box for the full asset.</li>
<li>The blue box is the recommended bounding box for the actual icon.
The icon box is sized smaller than the full asset box so that there is space to
include shadows and allow for special icon treatments.</li>
<li>The orange box is the recommended bounding box for the actual icon when
the content is square. The box for square icons is smaller than that for other
icons to establish a consistent visual weight across the two types.</li>
</ul>
<table>
<tr>
<td style="border:0;">
<ol class="nolist">
<li>Launcher icon dimensions for high-density (<code>hdpi</code>) screens:</li>
<ol class="nolist">
<li>Full Asset: 72 x 72 px</li>
<li>Icon: 60 x 60 px</li>
<li>Square Icon: 56 x 56 px</li>
</ol>
</li>
</ol>
</td>
<td style="border:0;">
<img src="{@docRoot}images/icon_design/launcher_size_hdpi.png" width="450">
</td>
</tr>
<tr>
<td style="border:0;">
<ol class="nolist">
<li>Launcher icon dimensions for medium-density (<code>mdpi</code>) screens:</li>
<ol class="nolist">
<li>Full Asset: 48 x 48 px</li>
<li>Icon: 40 x 40 px</li>
<li>Square Icon: 38 x 38 px</li>
</ol>
</li>
</ol>
</td>
<td style="border:0;">
<img src="{@docRoot}images/icon_design/launcher_size_mdpi.png" width="450">
</td>
</tr>
<tr>
<td style="border:0;">
<ol class="nolist">
<li>Launcher icon dimensions for low-density (<code>ldpi</code>) screens:</li>
<ol class="nolist">
<li>Full Asset: 36 x 36 px</li>
<li>Icon: 30 x 30 px</li>
<li>Square Icon: 28 x 28 px</li>
</ol>
</li>
</ol>
</td>
<td style="border:0;">
<img src="{@docRoot}images/icon_design/launcher_size_ldpi.png" width="450">
</td>
</tr>
<tr>
<td style="border:0;"></td>
<td style="border:0;">
<p class="table-caption"><strong>Figure 2.</strong>
Launcher icon sizing and positioning inside the bounds of the
icon asset.</p>
</td>
</tr>
</table>
<h3 id="materialscolors5">Materials and colors</h3>
<p>Launcher icons should make use of tactile, top-lit, textured materials. Even
if your icon is just a simple shape, you should try to render in a way that
makes it appear to be sculpted from some real-world material.</p>
<p>Android launcher icons usually consist of a smaller shape within a
larger base shape and combine one neutral and one primary color. Icons may
use a combination of neutral colors but should maintain a fairly high level of
contrast. Icons should not use more than one primary color per icon, if
possible.</p>
<p>Launcher icons should use a limited color palette that includes a range
of neutral and primary colors. The icons should not be over-saturated.</p>
<p>The recommended color palette to use for Launcher icons is shown in Figure 3.
You can use elements of the palette for both the base color and the highlight
color. You can use the colors of the palette in conjunction with a
white-to-black vertical linear gradient overlay. This creates the impression
that the icon is lit from above and keeps the color less saturated.</p>
<img src="{@docRoot}images/icon_design/IconGraphic_Colors.png" width="530">
<p class="img-caption">
<strong>Figure 3.</strong> Recommended color palette for icons.</p>
<p>When you combine the materials in Figure 4 with a color highlight from the
recommended palette above, you can create materials combinations such as those
shown in Figure 5. To get you started, the
<a href="{@docRoot}guide/practices/ui_guidelines/icon_design.html#templatespack">Icon Templates Pack</a>
includes a Photoshop file (<code>ic_launcher_template/example_materials.psd</code>)
that provides all of the default materials, colors, and gradients. </p>
<table>
<tbody>
<tr>
<td style="border:0;">
<img src="{@docRoot}images/icon_design/IconGraphic_Materials.png" width="450">
<p class="img-caption">
<strong>Figure 4.</strong> Example materials that you can use to create
your icons.</p>
</td>
<td style="border:0;border-left:1px solid #ccc;margin-left:1em;padding-left:1em">
<img src="{@docRoot}images/icon_design/IconGraphic_AccentColor.png" width="450">
<p class="img-caption">
<strong>Figure 5.</strong> Examples of materials combined with base
and highlight colors from the recommended palette.</p>
</td>
</tr>
</tbody>
</table>
<h3 id="effects5">Effects</h3>
<p>Launcher icons are flat and the perspective is straight-on, rather than at an
angle. A drop shadow is used to create a sense of depth. Launcher icons can use
varying textures and lighting effects, but must be lit directly from above
(straight down).</p>
<p>In order to maintain consistency, all launcher icons should use the same
drop shadow effect, as shown in Figure 6.</p>
<table class="image-caption">
<tr>
<td class="image-caption-i">
<img src="{@docRoot}images/icon_design/launcher_style.png"/>
</td>
<td class="image-caption-c">
<div class="caption grad-rule-top">
<p><strong>Figure 6. </strong>Style, light and effects for launcher icons.</p>
<div class="image-caption-nested">
<p><em>Note: all pixel dimensions are for medium density and should be scaled appropriately for other densities.</em></p>
<table>
<tr><td><em>1.</em></td><td nowrap>Lighting:</td><td>Top-lit, using appropriate lighting details<br><br></td></tr>
<tr><td><em>2.</em></td><td nowrap>Drop shadow:</td><td><code>#000000</code>, 75% opacity<br>angle 90&deg;<br>distance 1px<br>size 3px<br><br></td></tr>
<tr><td><em>3.</em></td><td nowrap>Textures:</td><td>Tactile, appear to use real-world materials (monochromatic noise in example image)<br><br></td></tr>
</table>
</div>
</div>
</td>
</tr>
</table>
<h3 id="dodonts5">Do's and don'ts</h3>
<p>Below are some "do and don't" examples to consider when creating icons for
your application. </p>
<table>
<tr>
<td style="border:0;width:50%">
<h4>Android Launcher icons are...</h4>
<ul>
<li>Modern, minimal, matte, tactile, and textured</li>
<li>Forward-facing and top-lit, whole, limited in color
palette</li>
</ul>
</td>
<td style="border:0;width:50%">
<h4>Android Launcher icons are not...</h4>
<ul>
<li>Antique, over-complicated, glossy, flat vector</li>
<li>Rotated, Cropped, Over-Saturated</li>
</ul>
</td>
</tr>
<tr>
</table>
<img src="{@docRoot}images/icon_design/IconGraphic_DosDonts.png"/>
<p class="img-caption">
<strong>Figure 7.</strong> Side-by-side examples of "do's and don'ts" for
Android launcher icons. </p>
<h3 id="examples5">Example icons</h3>
<p>Shown below are examples of high-density launcher icons used by
Android applications. The icons are provided for your reference only &mdash;
please do not reuse these icons in your applications.</code>.</p>
<img src="{@docRoot}images/icon_design/IconGraphic_Icons.png" />
<h2 id="icon1">Android 1.6 and earlier</h2>
<p>The following guidelines describe how to design launcher icons for Android
1.6 (API Level 4) and earlier. Launcher icons for Android 1.6 and below are
simplified 3D icons with a fixed perspective. The required perspective is shown
in Figure 8.</p>
<h3 id="structure1">Structure</h3>
<ul>
<li>The base of a launcher icon can face either the top view or the front
view.</li>
<li>The majority of a launcher icons surface should be created using the
launcher icon <a href="#palette1">color palette</a>. To add emphasis, use
one or more bright accent colors to highlight specific characteristics.</li>
<li>All launcher icons must be created with rounded corners to make them look
friendly and simple—as shown in Figure 8.</li>
<li>All dimensions specified are based on a 250x250 pixel artboard size
in a vector graphics editor like Adobe Illustrator, where the icon fits within
the artboard boundaries.</li>
<li><strong>Final art must be scaled down and exported as a transparent PNG file
using a raster image editor such as Adobe Photoshop. Do not include a background
color.</strong></li>
<li>Templates for creating icons in Adobe Photoshop are available in the <a
href="{@docRoot}guide/practices/ui_guidelines/icon_design.html#templatespack">Icon
Templates Pack</a>.</li>
</ul>
<table class="image-caption">
<tr>
<td class="image-caption-i">
<img src="{@docRoot}images/icon_design/launcher_structure.png" alt="A view of
launcher icon corners and perspective angles" />
</td>
<td class="image-caption-c">
<div class="caption grad-rule-top">
<p><strong>Figure 8.</strong> Rounded corners and perspective angles for
launcher icons (90° is vertical).</p>
<div class="image-caption-nested">
<table>
<tr><td><em>1.</em></td><td>92°</td></tr>
<tr><td><em>2.</em></td><td>92°</td></tr>
<tr><td><em>3.</em></td><td>173°</td></tr>
<tr><td><em>4.</em></td><td>171°</td></tr>
<tr><td><em>5.</em></td><td>49°</td></tr>
<tr><td><em>6.</em></td><td>171°</td></tr>
<tr><td><em>7.</em></td><td>64°</td></tr>
<tr><td><em>8.</em></td><td>97°</td></tr>
<tr><td><em>9.</em></td><td>75°</td></tr>
<tr><td><em>10.</em></td><td>93°</td></tr>
<tr><td><em>11.</em></td><td>169°</td></tr>
</table>
</div>
</div>
</td>
</tr>
</table>
<h3 id="style1">Light, effects, and shadows</h3>
<p>Launcher icons are simplified 3D icons using light and shadows for
definition. A light source is placed slightly to the left in front of the icon,
and therefore the shadow expands to the right and back.</p>
<table class="image-caption">
<tr>
<td class="image-caption-i">
<img src="{@docRoot}images/icon_design/launcher_light.png" alt="A view of
light, effects, and shadows for launcher icons."/>
</td>
<td class="image-caption-c">
<div class="caption grad-rule-top">
<p><strong>Figure 9. </strong>Light, effects, and shadows for launcher icons.</p>
<div class="image-caption-nested">
<table>
<tr><td><em>1.</em></td><td>Edge highlight:</td><td>white</td></tr>
<tr><td><em>2.</em></td><td>Icon shadow:</td><td>black | 20px blur<br>50% opacity | angle 67°</td></tr>
<tr><td><em>3.</em></td><td>Front part:</td><td>Use light gradient from color palette</td></tr>
<tr><td><em>4.</em></td><td>Detail shadow:</td><td>black | 10px blur<br>75% opacity</td></tr>
<tr><td><em>5.</em></td><td> Side part:</td><td>Use medium gradient from color palette</td></tr>
</table>
</div>
</div>
</td>
</tr>
</table>
<table>
<tr>
<td style="border:0">
<h4 id="palette1">Launcher icon color palette</h4>
<table>
<tr>
<td class="image-caption-i"><img src="{@docRoot}images/icon_design/launcher_palette_white.png"/></td>
<td class="image-caption-c">White<br>r 255 | g 255 | b 255<br>Used for highlights on edges.</td>
</tr>
<tr>
<td class="image-caption-i"><img src="{@docRoot}images/icon_design/launcher_palette_gradient_light.png"/></td>
<td class="image-caption-c">Light gradient<br><em>1:&nbsp;&nbsp;</em>r 0 | g 0 | b 0<br><em>2:&nbsp;&nbsp;</em>r 217 | g 217 | b 217<br>Used on the front (lit) part of the icon.</td>
</tr>
<tr>
<td class="image-caption-i"><img src="{@docRoot}images/icon_design/launcher_palette_gradient_medium.png"/></td>
<td class="image-caption-c">Medium gradient<br><em>1:&nbsp;&nbsp;</em>r 190 | g 190 | b 190<br><em>2:&nbsp;&nbsp;</em>r 115 | g 115 | b 115<br>Used on the side (shaded) part of the icon.</td>
</tr>
<tr>
<td class="image-caption-i"><img src="{@docRoot}images/icon_design/launcher_palette_gradient_dark.png"/></td>
<td class="image-caption-c">Dark gradient<br><em>1:&nbsp;&nbsp;</em>r 100 | g 100 | b 100<br><em>2:&nbsp;&nbsp;</em>r 25 | g 25 | b 25<br>Used on details and parts in the shade of the icon.</td>
</tr>
<tr>
<td class="image-caption-i"><img src="{@docRoot}images/icon_design/launcher_palette_black.png"/></td>
<td class="image-caption-c">Black<br>r 0 | g 0 | b 0<br>Used as base color in shadows.</td>
</tr>
</table>
</td>
<td style="border:0">
<h4 id="steps1">Step by step</h4>
<ol>
<li>Create the basic shapes with a tool like Adobe Illustrator, using the
angles described in <a href="#structure1">Launcher icon: structure</a>.
The shapes and effects must fit within a 250x250 pixel artboard.</li>
<li>Add depth to shapes by extruding them and create the rounded corners as
described for the launcher icon structure.</li>
<li>Add details and colors. Gradients should be treated as if there is a light
source placed slightly to the left in front of the icon.</li>
<li>Create the shadows with the correct angle and blur effect.</li>
<li>Import the icon into a tool like Adobe Photoshop and scale to fit an image
size of 48x48 px on a transparent background.</li>
<li>Export the icon at 48x48 as a PNG file with transparency enabled.</li>
</ol>
</td>
</tr>
</table>

View File

@@ -0,0 +1,163 @@
page.title=List View Icons
parent.title=Icon Design Guidelines
parent.link=icon_design.html
@jd:body
<div id="qv-wrapper">
<div id="qv">
<h2>In this document</h2>
<ol>
<li><a href="#icon1">All Android Versions</a>
<ol>
<li><a href="#structure1">Structure</a></li>
<li><a href="#style1">Light, effects, and shadows</a></li>
</ol>
</li>
</ol>
<h2>See also</h2>
<ol>
<li><a href="{@docRoot}guide/practices/screens_support.html">Supporting Multiple
Screens</a></li>
</ol>
</div>
</div>
<p>List view icons look a lot like dialog icons, but they use an inner shadow
effect where the light source is above the object. They are also designed to be
used only in a {@link android.widget.ListView}. Examples include the Settings
application.</p>
<p>As described in <a href="icon_design.html#icon-sets">Providing
Density-Specific Icon Sets</a>, you should create separate icon sets for low-,
medium-, and high-density screens. This ensures that your icons will display
properly across the range of devices on which your application can be installed.
See Table 1 for a listing of the recommended finished icon sizes for each
density. Also, see <a href="icon_design.html#design-tips">Tips for Designers</a>
for suggestions on how to work with multiple sets of icons.</p>
<p class="table-caption"><strong>Table 1.</strong> Summary of finished list view
icon dimensions for each of the three generalized screen densities.</p>
<table>
<tbody>
<tr>
<th style="background-color:#f3f3f3;font-weight:normal">
<nobr>Low density screen <em>(ldpi)</em></nobr>
</th>
<th style="background-color:#f3f3f3;font-weight:normal">
<nobr>Medium density screen <em>(mdpi)</em></nobr>
</th>
<th style="background-color:#f3f3f3;font-weight:normal">
<nobr>High density screen <em>(hdpi)</em><nobr>
</th>
</tr>
<tr>
<td>
24 x 24 px
</td>
<td>
32 x 32 px
</td>
<td>
48 x 48 px
</td>
</tr>
</tbody>
</table>
<p><strong>Final art must be exported as a transparent PNG file. Do not include
a background color</strong>.</p>
<p>Templates for creating icons in Adobe Photoshop are available in the <a
href="{@docRoot}guide/practices/ui_guidelines/icon_design.html#templatespack">Icon
Templates Pack</a>.</p>
<h2 id="icon1">All Android Versions</h2>
<p>The following guidelines describe how to design dialog icons for all versions
of the Android platform.</p>
<h3 id="structure1">Structure</h3>
<ul>
<li>A list view icon normally has a 1 px safeframe, but it is OK to use the
safeframe area for the edge of the anti-alias of a round shape.</li>
<li>All dimensions specified are based on a 32x32 pixel artboard size in
Photoshop. Keep 1 pixel of padding around the bounding box inside the template.
</li>
</ul>
<table class="image-caption">
<tr>
<td class="image-caption-i">
<img src="{@docRoot}images/icon_design/listview_icon.png" alt="A view of list
view icon structure." />
</td>
<td class="image-caption-c">
<div class="caption grad-rule-top">
<p><strong>Figure 1. </strong>Safeframe and fill gradient for list view
icons. Icon size is 32x32.</p>
</div>
</td>
</tr>
</table>
<h3 id="style1">Light, effects, and shadows</h3>
<p>List view icons are flat and pictured face-on with an inner shadow. Built up
by a light gradient and inner shadow, they stand out well on a dark
background.</p>
<table class="image-caption">
<tr>
<td class="image-caption-i">
<img src="{@docRoot}images/icon_design/listview_icon_details.png" alt="A view
of light, effects, and shadows for list view icons."/>
</td>
<td class="image-caption-c">
<div class="caption grad-rule-top">
<p><strong>Figure 2. </strong>Light, effects, and shadows for list view
icons.</p>
<div class="image-caption-nested">
<table>
<tr><td><em>1.</em></td><td>Inner shadow:</td><td>black | 57 % opacity | angle 120&deg; | blend mode normal | distance 1px | size 1px <td></tr>
<tr><td><em>2.</em></td><td>Background:</td><td>black | standard system color <br>These icons are displayed in list views only.</td></tr>
<tr><td colspan="2">Note: The list view icon sits on 32x32 px artboard in Photoshop, without a safeframe.</td></tr>
</table>
</div>
</div>
</td>
</tr>
</table>
<table>
<tr>
<td style="border:0">
<h4 id="steps1">Step by step</h4>
<ol>
<li>Add the effects seen in Figure 2 for the proper filter.</li>
<li>Export the icon at 32x32 as a PNG file with transparency enabled.</li>
<li>Create the basic shapes using a tool like Adobe Illustrator.</li>
<li>Import the shape into a tool like Adobe Photoshop and scale to fit an image
of 32x32 px on a transparent background. </li>
</ol>
</td>
</tr>
</table>

View File

@@ -0,0 +1,349 @@
page.title=Menu Icons
parent.title=Icon Design Guidelines
parent.link=icon_design.html
@jd:body
<div id="qv-wrapper">
<div id="qv">
<h2>In this document</h2>
<ol>
<li><a href="#icon9">Android 2.3 and Later</a>
<ol>
<li><a href="#size9">Size</a></li>
<li><a href="#style9">Style, colors, and effects</a></li>
<li><a href="#dodonts9">Do's and don'ts</a></li>
<li><a href="#examples9">Example icons</a></li>
</ol>
</li>
<li><a href="#icon1">Android 2.2 and Earlier</a></li>
</ol>
<h2>See also</h2>
<ol>
<li><a href="{@docRoot}guide/practices/screens_support.html">Supporting Multiple
Screens</a></li>
</ol>
</div>
</div>
<p>Menu icons are graphical elements placed in the options menu shown to users
when they press the Menu button. They are drawn in a flat-front perspective and
in greyscale. Elements in a menu icon must not be visualized in 3D or
perspective.</p>
<p>As described in <a href="icon_design.html#icon-sets">Providing
Density-Specific Icon Sets</a>, you should create separate icon sets for low-,
medium-, and high-density screens. This ensures that your icons will display
properly across the range of devices on which your application can be installed.
See <a href="icon_design.html#design-tips">Tips for Designers</a>
for suggestions on how to work with multiple sets of icons.</p>
<p><strong>Final art must be exported as a transparent PNG file. Do not include
a background color</strong>.</p>
<p>Templates for creating icons in Adobe Photoshop are available in the <a
href="{@docRoot}guide/practices/ui_guidelines/icon_design.html#templatespack">Icon
Templates Pack</a>.</p>
<p class="caution"><strong>Caution:</strong> The style and content sizing of
menu icons have changed in Android 2.3 compared to
<a href="#icon1">previous versions</a>:
<br>
1. Icons have a larger safe frame; icon content is smaller within the full
asset. Final asset sizes have not changed.
<br>
2. The color palette is slightly lighter.
<br>
3. No outer glow effects are applied.
<br>
4. Menu icons can now be rendered on either dark or light backgrounds.
</p>
<h2 id="icon9">Android 2.3 and Later</h2>
<p>The following guidelines describe how to design menu icons for Android
2.3 (API Level 9) and later.</p>
<h3 id="size9">Size and positioning</h3>
<p>Menu icons can use a variety of shapes and forms and must be scaled and
positioned inside the asset to create consistent visual weight with other
icons.</p>
<p>Figure 1 illustrates various ways of positioning the icon inside the
asset. You should size the icons <em>smaller than the actual bounds of the
asset</em>, to create a consistent visual weight. If your icon is square or
nearly square, it should be scaled even smaller.</p>
<p>In order to indicate the recommended size for the icon, each example in
Figure 1 includes three different guide rectangles:</p>
<ul>
<li>The red box is the bounding box for the full asset.</li>
<li>The blue box is the recommended bounding box for the actual icon.
The icon box is sized smaller than the full asset box to allow for
varying icon shapes while maintaining a consistent visual weight.</li>
<li>The orange box is the recommended bounding box for the actual icon when
the content is square. The box for square icons is smaller than that for other
icons to establish a consistent visual weight across the two types.</li>
</ul>
<table>
<tr>
<td style="border:0;">
<ol class="nolist">
<li>Menu icon dimensions for high-density (<code>hdpi</code>) screens:</li>
<ol class="nolist">
<li>Full Asset: 72 x 72 px</li>
<li>Icon: 48 x 48 px</li>
<li>Square Icon: 44 x 44 px</li>
</ol>
</li>
</ol>
</td>
<td style="border:0;">
<img src="{@docRoot}images/icon_design/menu_size_hdpi.png" width="450">
</td>
</tr>
<tr>
<td style="border:0;">
<ol class="nolist">
<li>Menu icon dimensions for medium-density (<code>mdpi</code>) screens:</li>
<ol class="nolist">
<li>Full Asset: 48 x 48 px</li>
<li>Icon: 32 x 32 px</li>
<li>Square Icon: 30 x 30 px</li>
</ol>
</li>
</ol>
</td>
<td style="border:0;">
<img src="{@docRoot}images/icon_design/menu_size_mdpi.png" width="450">
</td>
</tr>
<tr>
<td style="border:0;">
<ol class="nolist">
<li>Menu icon dimensions for low-density (<code>ldpi</code>) screens:</li>
<ol class="nolist">
<li>Full Asset: 36 x 36 px</li>
<li>Icon: 24 x 24 px</li>
<li>Square Icon: 22 x 22 px</li>
</ol>
</li>
</ol>
</td>
<td style="border:0;">
<img src="{@docRoot}images/icon_design/menu_size_ldpi.png" width="450">
</td>
</tr>
<tr>
<td style="border:0;"></td>
<td style="border:0;">
<p class="table-caption"><strong>Figure 1.</strong>
Menu icon sizing and positioning inside the bounds of the
icon asset.</p>
</td>
</tr>
</table>
<h3 id="style9">Style, colors, and effects</h3>
<p>Menu icons are flat, pictured face on, and greyscale. A slight deboss and
some other effects, which are shown below, are used to create depth. Menu icons
should include rounded corners, but only when logically appropriate.</p>
<p>In order to maintain consistency, all menu icons must use the same
color palette and effects, as shown in Figure 2.</p>
<table class="image-caption">
<tr>
<td class="image-caption-i">
<img src="{@docRoot}images/icon_design/menu_style.png" alt="A view of light, effects, and shadows for menu icons."/>
</td>
<td class="image-caption-c">
<div class="caption grad-rule-top">
<p><strong>Figure 2. </strong>Style, light and effects for menu icons.</p>
<div class="image-caption-nested">
<p><em>Note: all pixel dimensions are for medium density and should be scaled appropriately for other densities.</em></p>
<table>
<tr><td><em>1.</em></td><td nowrap>Corner rounding:</td><td>2 pixel corner radius, when appropriate<br><br></td></tr>
<tr><td><em>2.</em></td><td nowrap>Fill gradient:</td><td>90&deg;, from <code>#8C8C8C</code> to <code>#B2B2B2</code><br><br></td></tr>
<tr><td><em>3.</em></td><td nowrap>Inner shadow:</td><td><code>#000000</code>, 20% opacity<br>angle 90&deg;<br>distance 2px<br>size 2px<br><br></td></tr>
<tr><td><em>4.</em></td><td nowrap>Inner bevel:</td><td>depth 1%<br>direction down<br>size 0px<br>angle 90&deg;<br>altitude 10&deg;<br>highlight <code>#ffffff</code>, 70% opacity<br>shadow <code>#000000</code>, 25% opacity</td></tr>
</table>
</div>
</div>
</td>
</tr>
</table>
<h3 id="dodonts9">Do's and don'ts</h3>
<p>Below are some "do and don't" examples to consider when creating menu icons for
your application. </p>
<img src="{@docRoot}images/icon_design/do_dont_menuicons.png">
<h3 id="examples9">Example icons</h3>
<p>Shown below are standard high-density menu icons that are used in the Android
platform.</p>
<p class="warning"><strong>Warning:</strong> Because these resources can change
between platform versions, you should not reference these icons using the
Android platform resource IDs (i.e. menu icons under
<code>android.R.drawable</code>). If you want to use any icons or other internal
drawable resources, you should store a local copy of those icons or drawables in
your application resources, then reference the local copy from your application
code. In that way, you can maintain control over the appearance of your icons,
even if the system's copy changes. Note that the grid below is not intended to
be complete.</p>
<img src="{@docRoot}images/icon_design/menu_standard.png" />
<h2 id="icon1">Android 2.2 and Earlier</h2>
<p>The following guidelines describe how to design menu icons for Android 2.2
(API Level 4) and earlier. Menu icons in Android 2.2 and below are drawn in a
flat-front perspective. Elements in a menu icon must not be visualized in 3D or
perspective.</p>
<h3 id="structure1">Structure</h3>
<ul>
<li>In order to maintain consistency, all menu icons must use the same
primary palette and the same effects. For more information, see the
menu icon <a href="#palette1">color palette</a>. </li>
<li>Menu icons should include rounded corners, but only when logically
appropriate. For example, in Figure 3 the logical place for rounded corners is
the roof and not the rest of the building.</span></li>
<li>All dimensions specified on this page are based on a 48x48 pixel artboard
size with a 6 pixel safeframe.</li>
<li>The menu icon effect (the outer glow) described in <a
href="#style1">Light, effects, and shadows</a> can overlap the 6px safeframe,
but only when necessary. The base shape must always stay inside the
safeframe.</li>
<li><strong>Final art must be exported as a transparent PNG file.</strong></li>
<li>Templates for creating menu icons in Adobe Photoshop are available in the
Icon Templates Pack.</li>
</ul>
<table class="image-caption">
<tr>
<td class="image-caption-i">
<img src="{@docRoot}images/icon_design/menu_structure.png" alt="A view of menu
icon structure." />
</td>
<td class="image-caption-c">
<div class="caption grad-rule-top">
<p><strong>Figure 3. </strong>Safeframe and corner-rounding for menu
icons. Icon size is 48x48.</p>
</div>
</td>
</tr>
</table>
<h3 id="style1">Light, effects, and shadows</h3>
<p>Menu icons are flat and pictured face on. A slight deboss and some other
effects, which are shown below, are used to create depth.</p>
<table class="image-caption">
<tr>
<td class="image-caption-i">
<img src="{@docRoot}images/icon_design/menu_light.png" alt="A view of light, effects, and shadows for launcher icons."/>
</td>
<td class="image-caption-c">
<div class="caption grad-rule-top">
<p><strong>Figure 4. </strong>Light, effects, and shadows for launcher icons.</p>
<div class="image-caption-nested">
<table>
<tr><td><em>1.</em></td><td>Front part:</td><td>Use fill gradient from primary color palette</td></tr>
<tr><td><em>2.</em></td><td>Inner shadow:</td><td>black | 20 % opacity<br>angle 90° | distance 2px<br>size 2px</td></tr>
<tr><td><em>3.</em></td><td>Outer glow:</td><td>white | 55% opacity <br>spread 10% | size 3px</td></tr>
<tr><td><em>5.</em></td><td>Inner bevel:</td><td>depth 1% | direction down size 0px<br>angle 90° | altitude 10°<br>highlight white 70% opacity<br>shadow black 25% opacity</td></tr>
</table>
</div>
</div>
</td>
</tr>
</table>
<table>
<tr>
<td style="border:0">
<h4 id="palette1">Color palette</h4>
<table>
<tr>
<td class="image-caption-i"><img src="{@docRoot}images/icon_design/menu_palette_white.png"/></td>
<td class="image-caption-c">White<br>r 255 | g 255 | b 255<br>Used for outer glow and bevel highlight.</td>
</tr>
<tr>
<td class="image-caption-i"><img src="{@docRoot}images/icon_design/menu_palette_gradient_medium.png"/></td>
<td class="image-caption-c">Fill gradient<br><em>1:&nbsp;&nbsp;</em>r 163 | g 163 | b 163<br><em>2:&nbsp;&nbsp;</em>r 120 | g 120 | b 120<br>Used as color fill.</td>
</tr>
<tr>
<td class="image-caption-i"><img src="{@docRoot}images/icon_design/menu_palette_black.png"/></td>
<td class="image-caption-c">Black<br>r 0 | g 0 | b 0<br>Used for inner shadow and bevel shadow.</td>
</tr>
</table>
</td>
<td style="border:0">
<h4 id="steps1">Step by step</h4>
<ol>
<li>Create the basic shapes using a tool like Adobe Illustrator.</li>
<li>Import the shape into a tool like Adobe Photoshop and scale to fit an image
of 48x48 px on a transparent background. Mind the safeframe.</li>
<li>Add the effects seen as described in Figure 4.</li>
<li>Export the icon at 48x48 as a PNG file with transparency enabled.</li>
</ol>
</td>
</tr>
</table>

View File

@@ -0,0 +1,330 @@
page.title=Status Bar Icons
parent.title=Icon Design Guidelines
parent.link=icon_design.html
@jd:body
<div id="qv-wrapper">
<div id="qv">
<h2>In this document</h2>
<ol>
<li><a href="#icon9">Android 2.3 and Later</a>
<ol>
<li><a href="#size9">Size</a></li>
<li><a href="#style9">Style, color, and effects</a></li>
<li><a href="#dodonts9">Do's and don'ts</a></li>
<li><a href="#examples9">Example icons</a></li>
</ol>
</li>
<li><a href="#icon1">Android 2.2 and Earlier</a></li>
</ol>
<h2>See also</h2>
<ol>
<li><a href="{@docRoot}guide/practices/screens_support.html">Supporting Multiple
Screens</a></li>
</ol>
</div>
</div>
<p>Status bar icons are used to represent notifications from your application in
the status bar.</p>
<p>As described in <a href="icon_design.html#icon-sets">Providing
Density-Specific Icon Sets</a>, you should create separate icon sets for low-,
medium-, and high-density screens. This ensures that your icons will display
properly across the range of devices on which your application can be installed.
See <a href="icon_design.html#design-tips">Tips for Designers</a> for
suggestions on how to work with multiple sets of icons.</p>
<p><strong>Final art must be exported as a transparent PNG file. Do not include
a background color</strong>.</p>
<p>Templates for creating icons in Adobe Photoshop are available in the <a
href="{@docRoot}guide/practices/ui_guidelines/icon_design.html#templatespack">Icon
Templates Pack</a>.</p>
<p class="warning"><strong>Warning:</strong>
The style and dimensions of status bar icons have changed drastically in
Android 2.3 compared to <a href="#icon1">previous versions</a>. <strong>To
provide support for all Android versions</strong>, developers should:
<br>
1. Place status bar icons for Android 2.3 and higher in the
<code>drawable-hdpi-v9</code>, <code>drawable-mdpi-v9</code>, and <code>drawable-ldpi-v9</code> directories.
<br>
2. Place status bar icons for previous versions in
<code>drawable-hdpi</code>, <code>drawable-mdpi</code>, and <code>drawable-ldpi</code> directories.
</p>
<h2 id="icon9">Android 2.3 and Later</h2>
<p>The following guidelines describe how to design status bar icons for Android
2.3 (API Level 9) and later.</p>
<h3 id="size9">Size and positioning</h3>
<p>Status bar icons should use simple shapes and forms and those must be
scaled and positioned inside the final asset.</p>
<p>Figure 1 illustrates various ways of positioning the icon inside the
asset. You should size the icons <em>smaller than the actual bounds of the
asset</em>. <strong>Status bar icons may vary in width, but only
minimally.</strong></p>
<p>In order to indicate the recommended size for the icon, each example in
Figure 1 includes two different guide rectangles:</p>
<ul>
<li>The red box is the bounding box for the full asset.</li>
<li>The blue box is the recommended bounding box for the actual icon.
The icon box is sized smaller vertically than the full asset box to allow for
varying icon shapes while maintaining a consistent visual weight.</li>
</ul>
<table>
<tr>
<td style="border:0;">
<ol class="nolist">
<li>Status bar icon dimensions for high-density (<code>hdpi</code>) screens:</li>
<ol class="nolist">
<li>Full Asset: 24w x 38h px (preferred, width may vary)</li>
<li>Icon: 24w x 24h px (preferred, width may vary)</li>
</ol>
</li>
</ol>
</td>
<td style="border:0;">
<img src="{@docRoot}images/icon_design/statusbar_size_hdpi.png" width="318">
</td>
</tr>
<tr>
<td style="border:0;">
<ol class="nolist">
<li>Status bar icon dimensions for medium-density (<code>mdpi</code>) screens:</li>
<ol class="nolist">
<li>Full Asset: 16w x 25 px (preferred, width may vary)</li>
<li>Icon: 16w x 16w px (preferred, width may vary)</li>
</ol>
</li>
</ol>
</td>
<td style="border:0;">
<img src="{@docRoot}images/icon_design/statusbar_size_mdpi.png" width="318">
</td>
</tr>
<tr>
<td style="border:0;">
<ol class="nolist">
<li>Status bar icon dimensions for low-density (<code>ldpi</code>) screens:</li>
<ol class="nolist">
<li>Full Asset: 12w x 19h px (preferred, width may vary)</li>
<li>Icon: 12w x 12h px (preferred, width may vary)</li>
</ol>
</li>
</ol>
</td>
<td style="border:0;">
<img src="{@docRoot}images/icon_design/statusbar_size_ldpi.png" width="318">
</td>
</tr>
<tr>
<td style="border:0;"></td>
<td style="border:0;">
<p class="table-caption"><strong>Figure 1.</strong>
Status bar icon sizing and positioning inside the bounds of the
icon asset.</p>
</td>
</tr>
</table>
<h3 id="style9">Style, colors, and effects</h3>
<p>Status bar icons are flat, matte, and pictured face-on.</p>
<table class="image-caption">
<tr>
<td class="image-caption-i">
<img src="{@docRoot}images/icon_design/statusbar_style.png" alt="A view of effects for status bar icons."/>
</td>
<td class="image-caption-c">
<div class="caption grad-rule-top">
<p><strong>Figure 2. </strong>Style and effects for status icons.</p>
<div class="image-caption-nested">
<p><em>Note: all pixel dimensions are for medium density and should be scaled appropriately for other densities.</em></p>
<table>
<tr><td><em>1.</em></td><td nowrap>Fill gradient:</td><td>90&deg;, from <code>#828282</code> to <code>#919191</code><br><br></td></tr>
<tr><td><em>2.</em></td><td nowrap>Inner shadow:</td><td><code>#FFFFFF</code>, 10% opacity<br>angle 90&deg;<br>distance 1px<br>size 0px<br><br></td></tr>
<tr><td><em>3.</em></td><td nowrap>Inner content:</td><td>Inner content should subtract from the outer shape and consist purely of transparent pixels.</td></tr>
</table>
</div>
</div>
</td>
</tr>
</table>
<h3 id="dosdonts9">Do's and don'ts</h3>
<p>Below are some "do and don't" examples to consider when creating status bar icons for
your application. </p>
<img src="{@docRoot}images/icon_design/do_dont_statusicons.png">
<h3 id="examples9">Example icons</h3>
<p>Shown below are standard high-density status bar icons that are used in
the Android platform.</p>
<p class="warning"><strong>Warning:</strong> Because these resources can change
between platform versions, you should not reference these icons using the
Android platform resource IDs (i.e. status bar icons under
<code>android.R.drawable</code>). If you want to use any icons or other internal
drawable resources, you should store a local copy of those icons or drawables in
your application resources, then reference the local copy from your application
code. In that way, you can maintain control over the appearance of your icons,
even if the system's copy changes. Note that the grid below is not intended to
be complete.</p>
<img src="{@docRoot}images/icon_design/statusbar_standard.png" />
<h2 id="icon1">Android 2.2 and Earlier</h2>
<p>The following guidelines describe how to design status bar icons for Android
2.2 (API Level 8) and earlier.</p>
<h3 id="structure1">Structure</h3>
<ul>
<li>Rounded corners must always be applied to the base shape and to the details
of a status bar icon shown Figure 3.</li>
<li>All dimensions specified are based on a 25x25 pixel artboard size with a 2
pixel safeframe.</li>
<li>Status bar icons can overlap the safeframe to the left and right when
necessary, but must not overlap the safeframe at the top and bottom.</li>
<li><strong>Final art must be exported as a transparent PNG file.</strong></li>
<li>Templates for creating status bar icons using Adobe Photoshop are available
in the Icon Templates Pack.</li>
</ul>
<table class="image-caption">
<tr>
<td class="image-caption-i">
<img src="{@docRoot}images/icon_design/statusbar_structure.png" alt="A view of
status bar icon structure." />
</td>
<td class="image-caption-c">
<div class="caption grad-rule-top">
<p><strong>Figure 3. </strong>Safeframe and corner-rounding for status bar
icons. Icon size is 25x25.</p>
</div>
</td>
</tr>
</table>
<h3 id="style1">Light, effects, and shadows</h3>
<p>Status bar icons are slightly debossed, high in contrast, and pictured
face-on to enhance clarity at small sizes.</p>
<table class="image-caption">
<tr>
<td class="image-caption-i">
<img src="{@docRoot}images/icon_design/statusbar_light.png"/>
</td>
<td class="image-caption-c">
<div class="caption grad-rule-top">
<p><strong>Figure 4. </strong>Light, effects, and shadows for status bar icons.</p>
<div class="image-caption-nested">
<table>
<tr><td><em>1.</em></td><td>Front part:</td><td>Use fill gradient from primary color palette</td></tr>
<tr><td><em>2.</em></td><td>Inner bevel:</td><td>depth 100% | direction down<br>size 0px | angle 90° |<br>altitude 30°<br>highlight white 75% opacity<br>shadow black 75% opacity</td></tr>
<tr><td><em>3.</em></td><td>Detail:</td><td>white</td></tr>
<tr><td><em>4.</em></td><td>Disabled detail:</td><td>grey gradient from palette<br>+ inner bevel: smooth | depth 1% | direction down | size 0px | angle 117° | <br>altitude 42° | highlight white 70% | no shadow</td></tr>
</table>
</div>
</div>
</td>
</tr>
</table>
<table>
<tr>
<td style="border:0">
<h4 id="palette1">Color palette</h4>
<p>Only status bar icons related to the phone function use full color; all other status bar icons should remain monochromatic.</p>
<table>
<tr>
<td class="image-caption-i"><img src="{@docRoot}images/icon_design/statusbar_palette_white.png"/></td>
<td class="image-caption-c">White<br>r 255 | g 255 | b 255<br>Used for details within the icons and bevel highlight.</td>
</tr>
<tr>
<td class="image-caption-i"><img src="{@docRoot}images/icon_design/statusbar_palette_grey.png"/></td>
<td class="image-caption-c">Grey gradient<br><em>1:&nbsp;&nbsp;</em>r 169 | g 169 | b 169<br><em>2:&nbsp;&nbsp;</em>r 126 | g 126 | b 126<br>Used for disabled details within the icon.</td>
</tr>
<tr>
<td class="image-caption-i"><img src="{@docRoot}images/icon_design/statusbar_palette_fill.png"/></td>
<td class="image-caption-c">Fill gradient<br><em>1:&nbsp;&nbsp;</em>1 r 105 | g 105 | b 105<br><em>2:&nbsp;&nbsp;</em>r 10 | g 10 | b 10<br>Used as color fill.</td>
</tr>
<tr>
<td class="image-caption-i"><img src="{@docRoot}images/icon_design/statusbar_palette_black.png"/></td>
<td class="image-caption-c">Black<br>r 0 | g 0 | b 0<br>Used for bevel shadow.</td>
</tr>
</table>
</td>
<td style="border:0">
<h4 id="steps1">Step by step</h4>
<ol>
<li>In a tool like Adobe Photoshop, create the base shape within a 25x25 px
image on a transparent background. Mind the safeframe, and keep the upper and
lower 2 pixels free.</li>
<li>Add rounded corners as specified in Figure 3.</li>
<li>Add light, effects, and shadows as specified in Figure 4.</li>
<li>Export the icon at 25x25 as a PNG file with transparency enabled.</li>
</ol>
</td>
</tr>
</table>

View File

@@ -0,0 +1,454 @@
page.title=Tab Icons
parent.title=Icon Design Guidelines
parent.link=icon_design.html
@jd:body
<div id="qv-wrapper">
<div id="qv">
<h2>In this document</h2>
<ol>
<li><a href="#tabstates">Providing Icons for Two Tab States</a>
<li><a href="#icon5">Android 2.0 and Later</a>
<ol>
<li><a href="#size5">Size</a></li>
<li><a href="#style5">Style, colors, and effects</a></li>
<li><a href="#dodonts5">Do's and don'ts</a></li>
<li><a href="#examples5">Example icons</a></li>
</ol>
</li>
<li><a href="#icon1">Android 1.6 and Earlier</a></li>
</ol>
<h2>See also</h2>
<ol>
<li><a href="{@docRoot}guide/practices/screens_support.html">Supporting Multiple
Screens</a></li>
</ol>
</div>
</div>
<p>Tab icons are graphical elements used to represent individual tabs in a
multi-tab interface. Each tab icon has two states: unselected and selected.</p>
<p>As described in <a href="icon_design.html#icon-sets">Providing
Density-Specific Icon Sets</a>, you should create separate icon sets for low-,
medium-, and high-density screens. This ensures that your icons will display
properly across the range of devices on which your application can be installed.
See <a href="icon_design.html#design-tips">Tips for Designers</a>
for suggestions on how to work with multiple sets of icons.</p>
<p><strong>Final art must be exported as a transparent PNG file. Do not include
a background color</strong>.</p>
<p>Templates for creating icons in Adobe Photoshop are available in the <a
href="{@docRoot}guide/practices/ui_guidelines/icon_design.html#templatespack">Icon
Templates Pack</a>.</p>
<p class="warning"><strong>Warning:</strong>
The style of tab icons has changed drastically in
Android 2.0 compared to <a href="#icon1">previous versions</a>. <strong>To
provide support for all Android versions</strong>, developers should:
<br>
1. Place tab icons for Android 2.0 and higher in the
<code>drawable-hdpi-v5</code>, <code>drawable-mdpi-v5</code>, and <code>drawable-ldpi-v5</code> directories.
<br>
2. Place tab icons for previous versions in
<code>drawable-hdpi</code>, <code>drawable-mdpi</code>, and <code>drawable-ldpi</code> directories.
<br>
3. Set <code>android:targetSdkVersion</code> to 5 or higher in the
<a href="{@docRoot}guide/topics/manifest/uses-sdk-element.html">&lt;uses-sdk&gt;</a>
in the <a href="{@docRoot}guide/topics/manifest/manifest-intro.html">application manifest</a>.
This will inform the system that it should render tabs using the new tab style.
</p>
<h2 id="tabstates">Providing Icons for Two Tab States</h2>
<p>Tab icons should have two states: unselected and selected. To provide icons
with multiple states, developers must create a
<a href="{@docRoot}guide/topics/resources/drawable-resource.html#StateList">state
list drawable</a> for each an icon, which is an XML file that lists which image
to use for the different UI states.</p>
<p>For example, for a tab widget with tabs named 'Friends' and 'Coworkers',
you can use a directory structure similar to the one below:</p>
<pre>res/...
drawable/...
<strong>ic_tab_friends.xml</strong>
<strong>ic_tab_coworkers.xml</strong>
drawable-ldpi/...
ic_tab_friends_selected.png
ic_tab_friends_unselected.png
ic_tab_coworkers_selected.png
ic_tab_coworkers_unselected.png
drawable-mdpi/...
ic_tab_friends_selected.png
ic_tab_friends_unselected.png
ic_tab_coworkers_selected.png
ic_tab_coworkers_unselected.png
drawable-hdpi/...
...
drawable-ldpi-v5/...
...
drawable-mdpi-v5/...
...
drawable-hdpi-v5/...
...</pre>
<p>The contents of the XML files listed above should reference the corresponding
selected and unselected icon drawables. For example, below is the code
for <code>ic_tab_friends.xml</code>:</p>
<pre>
&lt;?xml version="1.0" encoding="utf-8"?&gt;
&lt;selector xmlns:android="http://schemas.android.com/apk/res/android"&gt;
&lt;!-- selected state --&gt;
&lt;item android:drawable="@drawable/ic_tab_friends_selected"
android:state_selected="true"
android:state_pressed="false" /&gt;
&lt;!-- unselected state (default) --&gt;
&lt;item android:drawable="@drawable/ic_tab_friends_unselected" /&gt;
&lt;/selector&gt;
</pre>
<h2 id="icon5">Android 2.0 and Later</h2>
<p>The following guidelines describe how to design tab icons for Android
2.0 (API Level 5) and later.</p>
<h3 id="size5">Size and positioning</h3>
<p>Tab icons should use simple shapes and forms and those must be
scaled and positioned inside the final asset.</p>
<p>Figure 1 illustrates various ways of positioning the icon inside the
asset. You should size the icons <em>smaller than the actual bounds of the
asset</em>.</p>
<p>In order to indicate the recommended size for the icon, each example in
Figure 1 includes three different guide rectangles:</p>
<ul>
<li>The red box is the bounding box for the full asset.</li>
<li>The blue box is the recommended bounding box for the actual icon.
The icon box is sized smaller than the full asset box to allow for
special icon treatments.</li>
<li>The orange box is the recommended bounding box for the actual icon when
the content is square. The box for square icons is smaller than that for other
icons to establish a consistent visual weight across the two types.</li>
</ul>
<table>
<tr>
<td style="border:0;">
<ol class="nolist">
<li>Tab icon dimensions for high-density (<code>hdpi</code>) screens:</li>
<ol class="nolist">
<li>Full Asset: 48 x 48 px</li>
<li>Icon: 42 x 42 px</li>
</ol>
</li>
</ol>
</td>
<td style="border:0;">
<img src="{@docRoot}images/icon_design/tab_size_hdpi.png" width="385">
</td>
</tr>
<tr>
<td style="border:0;">
<ol class="nolist">
<li>Tab icon dimensions for medium-density (<code>mdpi</code>) screens:</li>
<ol class="nolist">
<li>Full Asset: 32 x 32 px</li>
<li>Icon: 28 x 28 px</li>
</ol>
</li>
</ol>
</td>
<td style="border:0;">
<img src="{@docRoot}images/icon_design/tab_size_mdpi.png" width="385">
</td>
</tr>
<tr>
<td style="border:0;">
<ol class="nolist">
<li>Tab icon dimensions for low-density (<code>ldpi</code>) screens:</li>
<ol class="nolist">
<li>Full Asset: 24 x 24 px</li>
<li>Icon: 22 x 22 px</li>
</ol>
</li>
</ol>
</td>
<td style="border:0;">
<img src="{@docRoot}images/icon_design/tab_size_ldpi.png" width="385">
</td>
</tr>
<tr>
<td style="border:0;"></td>
<td style="border:0;">
<p class="table-caption"><strong>Figure 1.</strong>
Tab icon sizing and positioning inside the bounds of the
icon asset.</p>
</td>
</tr>
</table>
<h3 id="style5">Style, colors, and effects</h3>
<p>Tab icons are flat, matte, and pictured face-on.</p>
<p>Tab icons should have two states: selected and unselected.</p>
<table class="image-caption">
<tr>
<td class="image-caption-i">
<img src="{@docRoot}images/icon_design/tab_style_unselected.png" alt="A view of effects for unselected tab icons."/>
</td>
<td class="image-caption-c">
<div class="caption grad-rule-top">
<p><strong>Figure 2. </strong>Style and effects for unselected tab icons.</p>
<div class="image-caption-nested">
<p><em>Note: all pixel dimensions are for medium density and should be scaled appropriately for other densities.</em></p>
<table>
<tr><td><em>1.</em></td><td nowrap>Fill color:</td><td><code>#808080</code><br><br></td></tr>
<tr><td><em>2.</em></td><td nowrap>Inner content:</td><td>Inner content should subtract from the outer shape and consist purely of transparent pixels.</td></tr>
</table>
</div>
</div>
</td>
</tr>
</table>
<table class="image-caption">
<tr>
<td class="image-caption-i">
<img src="{@docRoot}images/icon_design/tab_style_selected.png" alt="A view of effects for selected tab icons."/>
</td>
<td class="image-caption-c">
<div class="caption grad-rule-top">
<p><strong>Figure 3. </strong>Style and effects for selected tab icons.</p>
<div class="image-caption-nested">
<p><em>Note: all pixel dimensions are for medium density and should be scaled appropriately for other densities.</em></p>
<table>
<tr><td><em>1.</em></td><td nowrap>Fill color:</td><td><code>#FFFFFF</code><br><br></td></tr>
<tr><td><em>2.</em></td><td nowrap>Inner content:</td><td>Inner content should subtract from the outer shape and consist purely of transparent pixels.<br><br></td></tr>
<tr><td><em>3.</em></td><td nowrap>Outer glow:</td><td><code>#000000</code>, 25% opacity<br>size 3px</td></tr>
</table>
</div>
</div>
</td>
</tr>
</table>
<h3 id="dosdonts5">Do's and don'ts</h3>
<p>Below are some "do and don't" examples to consider when creating tab icons for
your application. </p>
<img src="{@docRoot}images/icon_design/do_dont_tabicons.png">
<h3 id="examples5">Example icons</h3>
<p>Shown below are standard high-density tab icons that are used in
the Android platform.</p>
<p class="warning"><strong>Warning:</strong>
Because these resources can change between platform versions, you
should not reference the system's copy of the resources. If you want to
use any icons or other internal drawable resources, you should store a
local copy of those icons or drawables in your application resources,
then reference the local copy from your application code. In that way, you can
maintain control over the appearance of your icons, even if the system's
copy changes. Note that the grid below is not intended to be complete.</p>
<img src="{@docRoot}images/icon_design/tab_standard.png" />
<h2 id="icon1">Android 1.6 and Earlier</h2>
<p>The following guidelines describe how to design tab icons for Android
1.6 (API Level 4) and earlier.</p>
<h4 id="structure1">Structure</h4>
<ul>
<li>Unselected tab icons have the same fill gradient and effects as
<a href="icon_design_menu.html#icon1">menu icons</a>,
but with no outer glow.</li>
<li>Selected tab icons look just like unselected tab icons, but with a fainter
inner shadow, and have the same front part gradient as
<a href="icon_design_dialog.html#icon1">dialog icons</a>.</li>
<li>Tab icons have a 1 px safeframe which should only be overlapped for the edge
of the anti-alias of a round shape.</li>
<li>All dimensions specified on this page are based on a 32x32 px artboard size.
Keep 1 px of padding around the bounding box inside the Photoshop template.</li>
</ul>
<table class="image-caption">
<tr>
<td class="image-caption-i">
<img src="{@docRoot}images/icon_design/tab_icon_unselected.png" alt="A view of
unselected tab icon structure." />
</td>
<td class="image-caption-c">
<div class="caption grad-rule-top">
<p><strong>Figure 3. </strong>Safeframe and fill gradient for unselected tab
icons. Icon size is 32x32.</p>
</div>
</td>
</tr>
<tr>
<td class="image-caption-i">
<img src="{@docRoot}images/icon_design/tab_icon_selected.png" alt="A view of
selected tab icon structure." />
</td>
<td class="image-caption-c">
<div class="caption grad-rule-top">
<p><strong>Figure 4. </strong>Safeframe and fill gradient for tab icons in
selected state. Icon size is 32x32.</p>
</div>
</td>
</tr>
</table>
<h3 id="unselectedtabdetails1">Unselected tab icon</h3>
<h4 id="unselectedtablight1">Light, effects, and shadows</h4>
<p>Unselected tab icons look just like the selected tab icons, but with a
fainter inner shadow, and the same front part gradient as the dialog icons.</p>
<table class="image-caption">
<tr>
<td class="image-caption-i">
<img src="{@docRoot}images/icon_design/tab_unselected_light.png" alt="A view
of light, effects, and shadows for unselected tab icons."/>
</td>
<td class="image-caption-c">
<div class="caption grad-rule-top">
<p><strong>Figure 5. </strong>Light, effects, and shadows for unselected
tab icons.</p>
<div class="image-caption-nested">
<table>
<tr><td><em>1.</em></td><td>Front part:</td><td>gradient overlay | angle 90°<br>bottom color: r 223 | g 223 | b 223<br>top color: r 249 | g 249 | b 249<br>bottom color location: 0%<br>top color location: 75%</td></tr>
<tr><td><em>2.</em></td><td>Inner shadow:</td><td>black | 10 % opacity | angle 90° distance 2px | size 2px</td></tr>
<tr><td><em>3.</em></td><td>Inner bevel:</td><td>depth 1% | direction down | size 0px | angle 90° | altitude 10°<br>highlight white 70% opacity<br>shadow black 25% opacity</td></tr>
</table>
</div>
</div>
</td>
</tr>
</table>
<table>
<tr>
<td style="border:0">
<h4 id="unselectedtabsteps1">Step by step</h4>
<ol>
<li>Create the basic shapes using a tool like Adobe Illustrator.</li>
<li>Import the shape to a tool like Adobe Photoshop and scale to fit an image of
32x32 px on a transparent background.</li>
<li>Add the effects seen in Figure 5 for the unselected state filter.</li>
<li>Export the icon at 32x32 as a PNG file with transparency enabled.</li>
</ol>
</td>
</tr>
</table>
<h3 id="selectedtabdetails1">Selected tab icon</h3>
<p>The selected tab icons have the same fill gradient and effects as the menu
icon, but with no outer glow.</p>
<table class="image-caption">
<tr>
<td class="image-caption-i">
<img src="{@docRoot}images/icon_design/tab_selected_light.png" alt="A view of
light, effects, and shadows for selected tab icons."/>
</td>
<td class="image-caption-c">
<div class="caption grad-rule-top">
<p><strong>Figure 6. </strong>Light, effects, and shadows for selected tab
icons.</p>
<div class="image-caption-nested">
<table>
<tr><td><em>1.</em></td><td>Front part:</td><td>Use fill gradient from color palette.</td></tr>
<tr><td><em>2.</em></td><td>Inner shadow:</td><td>black | 20% opacity | <br>angle 90° | distance 2px | <br>size 2px</td></tr>
<tr><td><em>3.</em></td><td>Inner bevel:</td><td>depth 1% | direction down | size 0px | angle 90° | <br>altitude 10°<br>highlight white 70% opacity<br>shadow black 25% opacity</td></tr>
</table>
</div>
</div>
</td>
</tr>
</table>
<table>
<tr>
<td style="border:0">
<h4 id="selectedtabpalette1">Color palette</h4>
<table>
<tr>
<td class="image-caption-i"><img src="{@docRoot}images/icon_design/menu_palette_gradient_medium.png"/></td>
<td class="image-caption-c">Fill gradient<br><em>1:&nbsp;&nbsp;</em>r 163 | g 163 | b 163<br><em>2:&nbsp;&nbsp;</em>r 120 | g 120 | b 120<br>Used as color fill on unselected tab icons.</td>
</tr>
</table>
</td>
<td style="border:0">
<h4 id="selectedtabsteps1">Step by step</h4>
<ol>
<li>Create the basic shape using a tool like Adobe Illustrator.</li>
<li>Import the shape into a tool like Adobe Photoshop and scale to fit a 32x32
px artboard with a transparent background. </li>
<li>Add the effects seen in Figure 6 for the selected state filter.</li>
<li>Export the icon at 32x32 as a PNG file with transparency enabled.</li>
</ol>
</td>
</tr>
</table>

View File

@@ -0,0 +1,57 @@
page.title=User Interface Guidelines
@jd:body
<img src="{@docRoot}assets/images/uiguidelines1.png" alt="" align="right">
<p>The Android UI team has begun developing guidelines for the interaction and
visual design of Android applications. Look here for articles that describe
these guidelines as we release them.</p>
<dl>
<dt><a href="{@docRoot}guide/practices/ui_guidelines/icon_design.html">Icon
Design Guidelines</a> and <a
href="{@docRoot}shareables/icon_templates-v2.3.zip">Android Icon Templates Pack
&raquo; </a></dt>
<dd>Your applications need a wide variety of icons, from a launcher icon to
icons in menus, dialogs, tabs, the status bar, and lists. The Icon Guidelines
describe each kind of icon in detail, with specifications for the size, color,
shading, and other details for making all your icons fit in the Android system.
The Icon Templates Pack is an archive of Photoshop and Illustrator templates and
filters that make it much simpler to create conforming icons.</dd>
</dl>
<dl>
<dt><a href="{@docRoot}guide/practices/ui_guidelines/widget_design.html">Widget Design Guidelines</a> </dt>
<dd>A widget displays an application's most important or timely information
at a glance, on a user's Home screen. These design guidelines describe how to
design widgets that fit with others on the Home screen. They include links to
graphics files and templates that will make your designer's life easier.</dd>
</dl>
<dl>
<dt><a href="{@docRoot}guide/practices/ui_guidelines/activity_task_design.html">Activity and Task Design Guidelines</a> </dt>
<dd>Activities are the basic, independent building blocks of applications.
As you design your application's UI and feature set, you are free to
re-use activities from other applications as if they were yours,
to enrich and extend your application. These guidelines
describe how activities work, illustrates them with examples, and
describes important underlying principles and mechanisms, such as
multitasking, activity reuse, intents, the activity stack, and
tasks. It covers this all from a high-level design perspective.
</dd>
<dt><a href="{@docRoot}guide/practices/ui_guidelines/menu_design.html">Menu Design Guidelines</a> </dt>
<dd>Android applications make use of Option menus and Context menus
that enable users to perform operations and navigate to other parts
of your application or to other applications. These guidelines describe
the difference between Options and Context menus, how to arrange
menu items, when to put commands on-screen, and other details about
menu design.
</dd>
</dl>

View File

@@ -0,0 +1,507 @@
page.title=Menu Design Guidelines
@jd:body
<div id="qv-wrapper">
<div id="qv">
<h2>Quickview</h2>
<ul>
<li>An Options menu is for any commands that are global to the current activity. </li>
<li>A Context menu is for any commands that apply to the current selection. </li>
<li>Place the most frequently used operations first. </li>
<li>Put only the most important commands fixed on the screen. </li>
<li>The commands on the Context menu that appears when you touch &amp; hold on an item should be duplicated on the activity you get to by a normal press on that item.
</ul>
<h2>In this document</h2>
<ol>
<li><a href=#tour_of_the_menus>Tour of the Menus</a>
<ol>
<li style="padding-top: 4px;"><a href=#options_menu>Options Menu</a></li>
<li style="padding-top: 4px;"><a href=#context_menu>Context Menu</a></li>
<li style="padding-top: 4px;"><a href=#comparison_of_options_and_context_menus>Comparison of Options &amp; Context Menus</a></li>
<li style="padding-top: 4px;"><a href=#commands_fixed>Commands Fixed in an Activity Screen</a></li>
</ol>
</li>
<li><a href=#guidelines>Guidelines</a>
<ol>
<li style="padding-top: 4px;"><a href=#separate_commands>Separate specific from global commands</a></li>
<li style="padding-top: 4px;"><a href=#most_frequently_used>Place most frequently used first</a></li>
<li style="padding-top: 4px;"><a href=#dont_put_commands>Don't put commands <em>only</em> in a Context menu</li>
<li style="padding-top: 4px;"><a href=#first_in_context_menu>First command in Context menu should be most intuitive</li>
<li style="padding-top: 4px;"><a href=#selecting_content_item>Selecting an item should perform most intuitive operation</a></li>
<li style="padding-top: 4px;"><a href=#context_menu_should_identify>A Context menu should identify the selected item</li>
<li style="padding-top: 4px;"><a href=#most_important_commands>Put only most important commands fixed on the screen</a></li>
<li style="padding-top: 4px;"><a href=#short_names>Use short names in Options icon menu</a></li>
<li style="padding-top: 4px;"><a href=#a_dialog_should_not_have_an_options_menu>A dialog should not have Options menu</a></li>
<li style="padding-top: 4px;"><a href=#do_not_substitute_message>If no Options menu, don't display message</a></li>
<li style="padding-top: 4px;"><a href=#dim_hide_menu_items>Dim or hide menu items not available</a></li>
</ol>
</li>
</ol>
<h2>See also</h2>
<ol>
<li><a href="http://android-developers.blogspot.com/2008/12/touch-mode.html">Touch mode</a></li>
<li><a href="{@docRoot}guide/practices/ui_guidelines/activity_task_design.html">Activity and Task Design</a></li>
</ol>
</div>
</div>
<p>
A menu holds a set of commands (user actions) that are normally hidden, and
are accessible by a button, key, or gesture. Menu commands provide a means
for performing operations and for navigating to other parts of your
application or other applications. Menus are useful for freeing screen space,
as an alternative to placing functionality and navigation, in buttons or other
user controls in the content area of your application.
</p>
<p>
The Android system provides two types of menus you can use to provide
functionality or navigation. Between them, you should be able to organize
the functionality and navigation for your application. Briefly:
<ul>
<li>The <em>Options menu</em> contains primary functionality that applies
globally to the current activity or starts a related activity.
It is typically invoked by a user pressing a hard button, often labeled MENU.</li>
<li>The <em>Context menu</em> contains secondary functionality for the currently
selected item. It is typically invoked by a user's touch &amp; hold
on an item. Like on the Options menu, the operation can run either
in the current or another activity.</li>
</ul>
</p>
<p>
All but the simplest applications have menus. The system automatically
lays the menus out and provides standard ways for users to access them.
In this sense, they are familiar and dependable ways for users to access
functionality across all applications. All menus are panels that "float"
on top of the activity screen and are smaller than full screen, so that the
application is still visible around its edges. This is a visual reminder
that a menu is an intermediary operation that disappears once it's used.
</p>
<p>
Let's start out with a quick tour of the menus.
</p>
<h2 id="tour_of_the_menus">Tour of the Menus</h2>
<p class="note"><strong>Note:</strong> Your menus and screens might not look
like those shown in this document; they may vary from one version of Android
or device to another.
</p>
<h3 id="options_menu">Options Menu</h3>
<p>
The Options menu contains commands that apply globally across the current
activity, or can start another activity. They do not apply to a selected
item in the content (a <a href="#context_menu">Context menu</a> does that).
</p>
<p>
On most devices, a user presses the MENU button to access the Options menu,
as shown in the screenshot below. To close the menu, the user presses
MENU again, or presses the BACK button.
In fact, to cancel out of any menu, press the BACK button. (Pressing the MENU
button or touching outside the menu also works.) Note that how to invoke this
menu may be different on different devices.
</p>
<p>
Each
<a href="{@docRoot}guide/practices/ui_guidelines/activity_task_design.html#activities">activity</a>
activity has its own set of operations and therefore its own Options menu.
An application with multiple activities would have a different Options menu
for each activity.
</p>
<p>
For example, in the message list view of an email program, the Options menu
might let you search the messages, compose a new message, refresh the list,
or change the email settings. The compose view of an email program would
have a different Options menu, such as adding a CC field, attaching a file,
or discarding the message.
</p>
<p id="options_icon_expanded_menus">
In order to handle a large number of menu items, the Options menu
progressively discloses them in two steps:
</p>
<ul>
<li>
<b>Options icon menu</b> - The first press of the MENU button displays a
non-scrollable grid of icons at the bottom of the screen. (On the G1
phone, up to 6 buttons typically appear.)
</li>
<li>
<b>Options expanded menu</b> - If the activity has more menu items than will
fit on the icon menu, then the last icon is labeled "More" &mdash; selecting it
displays a list that can contain any number of menu items and will scroll
as necessary.
</li>
</ul>
<img src={@docRoot}images/menu_design/MenuDiagram.png>
<p>
On some versions of Android, the user can display keyboard shortcuts in the
icon menu by long pressing the MENU button &mdash; the text in the icon menu
alternates between the command names and their keyboard shortcuts (if any).
</p>
<h3 id="context_menu">Context Menu</h3>
<p>
A Context menu is similar to a right-click context menu in a desktop
operating system. It is normally a shortcut that duplicates commands
found elsewhere.
</p>
<p>
A user can touch &amp; hold on content on the screen to
access a Context menu (if one exists), as shown in the screenshot below.
A Context menu is a list of menu items (commands) that can operate
on the selected content. The command can either be part of the current
activity, or the system can pass the selected content along to
an operation in another activity (by way of an
<a href="{@docRoot}guide/practices/ui_guidelines/activity_task_design.html#intents">intent</a>).
</p>
<p>
For example, in an email message list, a user can touch &amp; hold on
an email message to open a Context menu containing commands to read,
archive, or delete the message.
</p>
<p id="location">
A user can also touch &amp; hold a <em>location</em> on the screen to
access a Context menu. An example is when the user does touch &amp; hold
on a blank spot on the Home screen, a Context menu appears; selecting
an item from that menu inserts an icon at that location.
</p>
<img src={@docRoot}images/menu_design/ContextMenuDiagram.png>
<h4 id="context_menu_shortcut">Context Menu is a Shortcut</h4>
<p>
In the above example, if the user performs touch &amp; hold on the contact
"Obi Wan Kenobi", a Context menu opens. The commands provided in
this Context menu are the complete set of actions that can be performed
on this contact.
</p>
<p>
A normal touch on an item in the content activates the most intuitive
command for that selection &mdash; in this case, "View contact".
We recommend that the most intuitive command also be listed as the
first item in the Context menu. In this example, selecting the contact
"Obi Wan Kenobi" runs the same command "View contact" that is listed
at the top of the Context menu.
</p>
<p>
Also note, as shown in the following screenshot, the Context menu and the
next screen both hold the same complete set of commands that can be performed
on this contact. The Context menu displays the commands in a list,
while the "View contact" activity splits them into various items in the
Options menu, icon buttons and list items.
</p>
<p>
Because of this duplication, using the Context menu is considered a <em>shortcut</em>
for going to the next screen and performing the operation there. Context menus
are less discoverable than either buttons fixed on-screen or the Options menu.
Many users never discover or use Context menus. It is for this reason that, for
the most part, any command on a Context menu should also appear on the most
intuitive operation's screen. As the next section explains, text operations,
such as "Select text" might appear only on a Context menu. Also, rich
applications, such as browsers, which themselves can contain web applications,
may have commands on Context menus that are not available elsewhere.
</p>
<img src={@docRoot}images/menu_design/ContextMenuViewContactDiagram.png>
<h4>Text Commands in Context Menu</h4>
<p>
Text links and text fields in the content both have system-provided operations
that are common across all applications: operations such as "Select all", "Select text",
"Copy all", and "Add to dictionary". If the text field is editable, it also
has other operations, such as "Cut all" and "Input Method", and if text
is also on the clipboard, it has "Paste". The system automatically inserts
the appropriate menu items into the Context menu of text links and text
fields, as shown in the following screenshot.
</p>
<img src={@docRoot}images/menu_design/TextFieldContextMenuDiagram.png>
<h3 id="comparison_of_options_and_context_menus">Comparison of Options and Context Menus</h3>
<p>
An Options menu holds commands that are global to the activity while a
Context menu holds commands that apply only to an item in the content.
As shown in these diagrams, the user navigates to the menu, then
touches a menu item to perform an action or open a dialog.
</p>
<img src={@docRoot}images/menu_design/TaskFlowDiagram.png>
<p>
For more technical information on menus, see
<a href="{@docRoot}guide/topics/ui/menus.html">Creating Menus</a>.
</p>
<h3 id="commands_fixed">Commands Fixed in an Activity Screen</h4>
<p>
Commands can also be fixed directly on screen, typically in
text buttons, graphic buttons, or list items. This placement is by far the most
discoverable location for commands &mdash; a user can immediately see the command
without having to first press a button. This increased visibility needs to be
weighed against the space such user controls take up, or the sense that they
might clutter the visual design.
</p>
<h2 id="guidelines">Guidelines</h2>
<p>
Selecting the right kind of menu to present, and using menus
consistently, are critical factors in good application design. The following
guidelines should assist user experience designers and application developers
toward this end.
</p>
<h3 id="separate_commands">Separate selection-specific commands from global commands</h3>
<p>
Put any commands that are global to the current activity in the Options menu
or place them fixed in an activity screen; put commands that apply to the
current selection in the Context menu. (In any case, the command
could either run as part of this activity or start another activity.)
</p>
<p>
You can determine in which menu to place a command by what it operates on:
If the command acts on selected content (or a particular
<a href="#location">location</a>) on the screen, put the command in the
Context menu for that content. If the command acts on no specific content
or location, put it in the Options menu. This separation of commands
is enforced by the system in the following way. When you press the MENU
button to display the Options menu, the selected content becomes unselected,
and so cannot be operated on. For an explanation
of why the content becomes unselected, see the article on
<a href="http://android-developers.blogspot.com/2008/12/touch-mode.html">Touch mode</a>.
</p>
<p>
An example of a selection-specific Context menu is when a user performs a
touch &amp; hold on a person's name in a list view of a contacts application.
The Context menu would typically contain commands "View contact", "Call contact",
and "Edit contact".
</p>
<h3 id="most_frequently_used">Place the most frequently used operations first</h3>
<p>
Because of limited screen height, some menus may be scrollable, so it's
important to place the most important commands so they can be viewed without
scrolling. In the case of the Options menu, place the most frequently used
operation on its <a href="#options_icon_expanded_menus">icon menu</a>;
the user will have to select "More" to see the rest.
It's also useful to place similar commands in the same location &mdash;
for example, the Search icon might always be the first icon in the Options
menu across several activities that offer search.
</p>
<p>
In a Context menu, the most intuitive command should be first, followed
by commands in order of decreasing use, with the least used command at the bottom.
</p>
<h3 id="dont_put_commands">Don't put commands <em>only</em> in a Context menu</h3>
<p>
If a user can fully access your application without using Context menus,
then it's designed properly! In general, if part of your application is inaccessible
without using Context menus, then you need to duplicate those commands elsewhere.
</p>
<p>
Before opening a Context menu, it has no visual representation that identifies
its presence (whereas the Options menu has the MENU button), and so is not
particularly discoverable.
Therefore, in general, a Context menu should <em>duplicate</em> commands
found in the corresponding activity screen. For example, while it's useful to
let the user call a phone number from a Context menu invoked by touch
&amp; hold on a name in a list of contacts, that operation should <em>also</em>
be available by the user touching the phone number itself when viewing contact details.
See <a href="#context_menu_shortcut">shortcut</a> for an illustration of this example.
</p>
<h3 id="first_in_context_menu">The first command in a Context menu should be the selection's most intuitive command</h3>
<p>
As described under <a href="#context_menu_shortcut">shortcut</a>,
touching on an item in the content should activate the same command as touching
the first item in the Context menu. Both cases should be the most intuitive
operation for that item.
</p>
<h3 id="selecting_content_item">Selecting an item in the content should perform the most intuitive operation</h3>
<p>
In your application, when the user touches any actionable text (such as a link
or list item) or image (such as a photo icon), execute the operation most
likely to be desired by the user.
</p>
<p>
Some examples of primary operations:
</p>
<ul>
<li>Selecting an image executes "View image"</li>
<li>Selecting a media icon or filename executes "Play"</li>
<li>Selecting a URL link executes "Open link"</li>
<li>Selecting an address executes "Go to address" (in a maps application)</li>
</ul>
<p>
Note that selecting the same item in different contexts might invoke
different operations:
</p>
<ul>
<li>In a contact application, selecting a contact executes "View details"</li>
<li>In an IM application, selecting a contact executes "Start chat"</li>
<li>In an Email application, when adding a recipient to the "To" field
through the contact book, selecting a contact executes "Add to recipient
list"</li>
</ul>
<h3 id="context_menu_should_identify">A Context menu should identify the selected item</h3>
<p>
When a user does touch &amp; hold on an item, the Context menu should
contain the name of the selected item. Therefore,
when creating a Context menu, be sure to include a title and the name of the
selected item so that it's clear to the user what the context is.
For example, if a user selects a contact "Joan of Arc", put that name in the
title of the Context menu (using
{@link android.view.ContextMenu#setHeaderTitle(java.lang.CharSequence) setHeaderTitle}).
Likewise, a command to edit the contact should be called "Edit contact",
not just "Edit".
</p>
<h3 id="most_important_commands">Put only the most important commands fixed on the screen</h3>
<p>
By putting commands in menus, you free up the screen to hold more content.
On the other hand, fixing commands in the content area of an activity
makes them more prominent and easy to use.
</p>
<p>
Here are a number of important reasons to place commands fixed on the activity screen:
</p>
<ul>
<li>
To give a command the highest prominence, ensuring the command is obvious and won't be overlooked.<br>
Example: A "Buy" button in a store application.
</li>
<li>
When quick access to the command is important and going to the menu would be
tedious or slow.<br>
Example: Next/Previous buttons or Zoom In/Out buttons in an image viewing application.
</li>
<li>
When in the middle of an operation that needs to be completed.<br>
Example: Save/Discard buttons in an image crop activity.
</li>
<li>
Dialogs and wizards.<br>
Example: OK/Cancel buttons
</li>
<li>
For direct manipulation.<br>
Example: Dragging an icon in the Home screen to the trash
</li>
</ul>
<h3 id="short_names">Use short names in the Options icon menu</h3>
<p>
If a text label in the <a href="#options_icon_expanded_menus">Options icon menu</a>
is too long, the system truncates it in the middle. Thus, "Create Notification"
is truncated to something like "Create…ication". You have no control over
this truncation, so the best bet is to keep the text short. In some versions of Android,
when the icon is highlighted by a navigation key (such as a trackball), the
entire descriptive text may be shown as a marquee, where the words are
readable as they scroll by. <!--For more information, see the Text Guidelines
[update link].-->
</p>
<h3 id="a_dialog_should_not_have_an_options_menu">A dialog should not have an Options menu</h3>
<p>
When a dialog is displayed, pressing the MENU button should do nothing. This also holds true
for activities that look like dialogs. A dialog box is recognizable by being
smaller than full-screen, having zero to three buttons, is non-scrollable, and
possibly a list of selectable items that can include checkboxes or radio buttons.
<!--For examples of dialogs, see Text Guidelines.-->
</p>
<p>
The rationale behind not having a menu is that when a dialog is displayed, the user is in
the middle of a procedure and should not be allowed to start a new global task
(which is what the Option menu provides).
</p>
<h3 id="do_not_substitute_message">If an activity has no Options menu, do not display a message</h3>
<p>
When the user presses the MENU button, if there is no Options menu, the system
currently does nothing. We recommend you do not perform any action (such as
displaying a message). It's a better user experience for this behavior to be
consistent across applications.
</p>
<h3 id="dim_hide_menu_items">Dim or hide menu items that are not available in the current context</h3>
<p>
Sometimes a menu item's action cannot be performed &mdash; for example,
the "Forward" button in a browser cannot work until after the "Back"
button has been pressed. We recommend:
</p>
<ul>
<li>
<b>In Options menu</b> - disable the menu item, which dims the text and icon,
turning it gray. This applies to menu items in both the icon menu and the
"More" menu. It would be disorienting for the icon menu to change from 6
items to 5 items, and we treat the "More" menu the same way.
</li>
<li>
<b>In Context menu</b> - hide the menu item. This makes the menu shorter so the
user sees only available choices (which also reduces any scrolling).
</li>
</ul>
</body>
</html>

View File

@@ -0,0 +1,274 @@
page.title=Widget Design Guidelines
@jd:body
<div id="qv-wrapper">
<div id="qv">
<h2>Quickview</h2>
<ul>
<li>Widgets have six standard sizes on the Home screen</li>
<li>Widgets have standards for size, frames, shadows, and file format, which you can copy</li>
<li>A few tricks make it easier to design widgets that fit graphically on the Home screen</li>
</ul>
<h2>In this document</h2>
<ol>
<li><a href="#anatomy">Standard widget anatomy</a></li>
<li><a href="#design">Designing a widget</a></li>
<li><a href="#sizes">Standard widget sizes</a></li>
<li><a href="#frames">Standard widget frames</a></li>
<li><a href="#shadows">Standard widget shadows</a></li>
<li><a href="#tricks">Widget graphics tips and tricks</a></li>
<li><a href="#file">Widget graphics file format</a></li>
</ol>
<h2>See also</h2>
<ol>
<li><a href="{@docRoot}guide/topics/appwidgets/index.html">App Widgets</a></li>
<li><a href="http://android-developers.blogspot.com/2009/04/introducing-home-screen-widgets-and.html">AppWidgets blog post</a></li>
</ol>
</div>
</div>
<p>Widgets are a feature introduced in Android 1.5. A widget displays an
application's most important or timely information at a glance, on a user's Home
screen. The standard Android system image includes several examples of widgets,
including widgets for Analog Clock, Music, and other applications.</p>
<p>Users pick the widgets they want to display on their Home screens by touching
&amp; holding an empty area of the Home screen, selecting Widgets from the menu,
and then selecting the widget they want.</p>
<p><img src="{@docRoot}images/widget_design/widget_examples.png" alt="Example
Widgets"></p>
<p>This document describes how to design a widget so it fits graphically with
other widgets and with the other elements of the Android Home screen. It also
describes some standards for widget artwork and some widget graphics tips and
tricks from the Android team.<p>
<p>For information about developing widgets, see the <a
href="{@docRoot}guide/topics/appwidgets/index.html">AppWidgets</a> section of
the <em>Developer's Guide</em> and the <a
href="http://android-developers.blogspot.com/2009/04/introducing-home-screen-widgets-and.html">AppWidgets</a> blog post.</p>
<h2 id="anatomy">Standard widget anatomy</h2>
<p>Typical Android widgets have three main components: A bounding box, a frame,
and the widget's graphical controls and other elements. Well-designed widgets
leave some padding between the edges of the bounding box and the frame, and
between the inner edges of the frame and the widget's controls. Widgets designed
to fit visually with other widgets on the Home screen take cues from the other
elements on the Home screen for alignment; they also use standard shading
effects. All of these details are described in this document.
<p><strong>Standard Widget Sizes in Portrait Orientation</strong><br/>
<img src="{@docRoot}images/widget_design/widget_sizes_portrait.png"
alt="Standard Widget Sizes in Portrait Orientation"></p>
<p>&nbsp;</p>
<p><strong>Standard Widget Sizes in Landscape Orientation</strong><br/>
<img src="{@docRoot}images/widget_design/widget_sizes_landscape.png"
alt="Standard Widget Sizes in Landscape Orientation"></p>
<h2 id="design">Designing a widget</h2>
<ol>
<li><strong>Select a bounding box size for your widget.</strong></li>
<p>The most effective widgets display your application's most useful or timely
data in the smallest widget size. Users will weigh the usefulness or your widget
against the portion of the Home screen it covers, so the smaller the better.</p>
<p>All widgets must fit within the bounding box of one of the six supported
widget sizes, or better yet, within a pair of portrait and landscape orientation
sizes, so your widget looks good when the user switches screen
orientations.</p>
<p><a href="#sizes">Standard widget sizes</a> illustrates the bounding
dimensions of the six widget sizes (three in portrait and three in landscape
orientation).</p>
<li><strong>Select a matching frame.</strong></li>
<p><a href="#frames">Standard widget frames</a> illustrates the standard frames
for the six widget sizes, with links so you can download copies for your own
use. You don't have to use these frames for your widget, but if you do, your
widgets are more likely to fit visually with other widgets.</p>
<li><strong>Apply standard shadow effect to your graphics.</strong></li>
<p>Again, you don't have to use this effect, but <a href="#shadows">Standard
widget shadows</a> shows the Photoshop settings used for standard widgets.</p>
<li><strong>If your widget includes buttons, draw them in three states
(default, pressed, and selected).</strong></li>
<p>You can <a
href="{@docRoot}images/widget_design/Music_widget_button_states.psd">download a
Photoshop file that contains the three states of the Play button</a>, taken from
the Music widget, to analyze the Photoshop settings used for the three standard
button effects.</p>
<p><a href="{@docRoot}images/widget_design/Music_widget_button_states.psd"> <img
src="{@docRoot}images/widget_design/buttons.png" alt="Click to download
Photoshop template"></a></p>
<li><strong>Finish drawing your artwork and then scale and align it to
fit.</strong></li>
<p><a href="#tricks">Widget alignment tips and tricks</a> describes some
techniques for aligning your widget's graphics inside the standard frames, along
with a few other widget graphics tricks.</p>
<li><strong>Save your widget with the correct graphics file
settings.</strong></li>
<p><a href="#file">Windows graphics file format</a> describes the correct
settings for your widget graphics files.</p>
</ol>
<h2 id="sizes">Standard widget sizes</h2>
<p>There are six standard widget sizes, based on a Home screen grid of 4 x 4
(portrait) or 4 x 4 (landscape) cells. These dimensions are the bounding boxes
for the six standard widget sizes. The contents of typical widgets don't draw to
the edge of these dimensions, but fit inside a frame withing the bounding box,
as described in <a href="#design">Designing a widget</a>.</p>
<p>In portrait orientation, each cell is 80 pixels wide by 100 pixels tall (the
diagram shows a cell in portrait orientation). The three supported widget sizes
in portrait orientation are:<p>
<table>
<tr><th>Cells</th><th>Pixels</th></tr>
<tr><td>4 x 1</td><td>320 x 100</td></tr>
<tr><td>3 x 3</td><td>240 x 300</td></tr>
<tr><td>2 x 2</td><td>160 x 200</td></tr>
</table>
<p><img src="{@docRoot}images/widget_design/portrait_sizes.png" alt="Widget
dimensions in portrait orientation"></p>
<p>In landscape orientation, each cell is 106 pixels wide by 74 pixels tall. The
three supported widget sizes in landscape orientation are:</p>
<table>
<tr><th>Cells</th><th>Pixels</th></tr>
<tr><td>4 x 1</td><td>424 x 74</td></tr>
<tr><td>3 x 3</td><td>318 x 222</td></tr>
<tr><td>2 x 2</td><td>212 x 148</td></tr>
</table>
<p><img src="{@docRoot}images/widget_design/landscape_sizes.png" alt="Widget
dimensions in landscape orientation"></p>
<h2 id="frames">Standard widget frames</h2>
<p>For each of the six standard widget sizes there is a standard frame. You can
click the images of the frames in this section to download a Photoshop file for
that frame, which you can use for your own widgets.<p>
<p><a href="{@docRoot}images/widget_design/4x1_Widget_Frame_Portrait.psd"> <img
src="{@docRoot}images/widget_design/4x1_Widget_Frame_Portrait.png" alt="Click to
download"></a><br>4x1_Widget_Frame_Portrait.psd</p>
<p><a href="{@docRoot}images/widget_design/3x3_Widget_Frame_Portrait.psd"> <img
src="{@docRoot}images/widget_design/3x3_Widget_Frame_Portrait.png" alt="Click to
download"></a><br>3x3_Widget_Frame_Portrait.psd</p>
<p><a href="{@docRoot}images/widget_design/2x2_Widget_Frame_Portrait.psd"> <img
src="{@docRoot}images/widget_design/2x2_Widget_Frame_Portrait.png" alt="Click to
download"></a><br>2x2_Widget_Frame_Portrait.psd</p>
<p><a href="{@docRoot}images/widget_design/4x1_Widget_Frame_Landscape.psd"> <img
src="{@docRoot}images/widget_design/4x1_Widget_Frame_Landscape.png" alt="Click
to download"></a><br>4x1_Widget_Frame_Landscape.psd</p>
<p><a href="{@docRoot}images/widget_design/3x3_Widget_Frame_Landscape.psd"> <img
src="{@docRoot}images/widget_design/3x3_Widget_Frame_Landscape.png" alt="Click
to download"></a><br>3x3_Widget_Frame_Landscape.psd</p>
<p><a href="{@docRoot}images/widget_design/2x2_Widget_Frame_Landscape.psd"> <img
src="{@docRoot}images/widget_design/2x2_Widget_Frame_Landscape.png" alt="Click
to download"></a><br>2x2_Widget_Frame_Landscape.psd</p>
<h2 id="shadows">Standard widget shadows</h2>
<p>You can apply a shadow effect to your widget's artwork, so it matches other
standard Android widgets, using the following settings in the Photoshop Layer
Style dialog box.</p>
<p><img src="{@docRoot}images/widget_design/Layer_Style.png" alt="Layer Style
settings for standard shadows"></p>
<h2 id="tricks">Widget graphics tips and tricks</h2>
<p>The Android team has developed a few tricks for aligning widget artwork
within standard widget bounding boxes and frames, so the widget aligns visually
with other widgets and the other elements of the Home screen, as well as other
techniques for creating widgets.
<ul>
<li>Use a screen shot from the Android SDK emulator to align both the shapes and
shadows of your widget controls with the Search widget and with other elements
on the Home screen.</li>
<p>Cut the widget artwork asset" based on the full size of a cell, including any
padding you want. (That is, for a 4 x 1 widget, cut the asset at 320 by 100
pixels.)</p>
<p><img src="{@docRoot}images/widget_design/alignment.png" alt="Aligning widget
graphics" ></p>
<li>To reduce banding when exporting a widget, apply the following Photoshop Add
Noise setting to your graphic.</li>
<p><img src="{@docRoot}images/widget_design/Add_Noise.png" alt="Add Noise
settings for widget graphics" ></p>
<li>Apply 9-patch techniques to shrink the graphic and set the padding of the
content area. (<a href="{@docRoot}guide/developing/tools/draw9patch.html">See
the detailed guide here.</a>)</li>
<p><strong>Note:</strong> The current Android widget templates were designed
using a custom gradient angle, which means the 9-patch techniques can't be used
to optimize the size of the asset. However, 9-patch techniques were used to set
the content area padding.</p>
<li>In some cases, devices have low pixel depths that can cause visual banding
and dithering issues. To solve this, application developers should pass assets
through a "proxy" drawable defined as <code>XML:<nine-patch
android:src="@drawable/background" android:dither="true" /></code>. This
technique references the original artwork, in this case
<code>"background.9.png"</code>, and instructs the device to dither it as
needed.</li>
</ul>
<h2 id="file">Widget graphics file format</h2>
<p>Save your widget artwork using the appropriate bounding box size in PNG-24
format on a transparent background and in 8-bit color.</p>
<p><img src="{@docRoot}images/widget_design/file_format.png" alt="Widget graphics file format" ></p>

View File

@@ -0,0 +1,617 @@
page.title=Signing Your Applications
@jd:body
<div id="qv-wrapper">
<div id="qv">
<h2>Quickview</h2>
<ul>
<li>All Android apps <em>must</em> be signed</a></li>
<li>You can sign with a self-signed key</li>
<li>How you sign your apps is critical &mdash; read this document carefully</li>
<li>Determine your signing strategy early in the development process</li>
</ul>
<h2>In this document</h2>
<ol>
<li><a href="#overview">Overview</a></li>
<li><a href="#strategies">Signing Strategies</a></li>
<li><a href="#setup">Basic Setup for Signing</a></li>
<li><a href="#debugmode">Signing in Debug Mode</a></li>
<li><a href="#releasemode">Signing for Public Release</a>
<ol>
<li><a href="#cert">Obtain a suitable private key</a></li>
<li><a href="#releasecompile">Compile the application in release mode</a></li>
<li><a href="#signapp">Sign your application with your private key</a></li>
<li><a href="#align">Align the final APK package</a></li>
<li><a href="#ExportWizard">Compile and sign with Eclipse ADT</a></li>
</ol>
</li>
<li><a href="#secure-key">Securing Your Private Key</a></li>
</ol>
<h2>See also</h2>
<ol>
<li><a href="{@docRoot}guide/publishing/versioning.html">Versioning Your Applications</a></li>
<li><a href="{@docRoot}guide/publishing/preparing.html">Preparing to Publish</a></li>
</ol>
</div>
</div>
<p>This document provides information about signing your Android applications prior to publishing them for mobile device users.</p>
<h2 id="overview">Overview</h2>
<p>The Android system requires that all installed applications be digitally
signed with a certificate whose private key is held by the application's
developer. The Android system uses the certificate as a means of identifying the author of
an application and establishing trust relationships between applications. The certificate is not
used to control which applications the user can install. The certificate
does not need to be signed by a certificate authority: it is perfectly
allowable, and typical, for Android applications to use self-signed
certificates.</p>
<p>The important points to understand about signing Android applications are:</p>
<ul>
<li>All applications <em>must</em> be signed. The system will not install an application
that is not signed.</li>
<li>You can use self-signed certificates to sign your applications. No certificate authority
is needed.</li>
<li>When you are ready to release your application for end-users, you must sign it with a suitable private
key. You can not publish an application that is signed with the debug key generated
by the SDK tools.
</li>
<li>The system tests a signer certificate's expiration date only at install time. If an
application's signer certificate expires after the application is installed, the application
will continue to function normally.</li>
<li>You can use standard tools &mdash; Keytool and Jarsigner &mdash; to generate keys and
sign your application .apk files.</li>
<li>Once you have signed the application, use the <code>zipalign</code> tool to optimize the final APK package.</li>
</ul>
<p>The Android system will not install or run an application that is not signed appropriately. This
applies wherever the Android system is run, whether on an actual device or on the emulator.
For this reason, you must set up signing for your application before you will be able to
run or debug it on an emulator or device.</p>
<p>The Android SDK tools assist you in signing your applications when debugging. Both the ADT Plugin
for Eclipse and the Ant build tool offer two signing modes &mdash; <em>debug mode</em>
and <em>release mode</em>.
<ul>
<li>While developing and testing, you can compile in debug mode.
In debug mode, the build tools use the Keytool utility, included in the JDK, to create
a keystore and key with a known alias and password. At each compilation, the tools then use
the debug key to sign the application .apk file. Because the password is known, the tools
don't need to prompt you for the keystore/key password each time you compile.</li>
<li>When your application is ready for release, you must compile in release mode
and then sign the .apk <span style="color:red">with your private key</span>.
There are two ways to do this:
<ul>
<li>Using Keytool and Jarsigner in the command-line. In this approach,
you first compile your application to an <em>unsigned</em> .apk. You must then sign
the .apk manually with your private key
using Jarsigner (or similar tool). If you do not have a suitable private key already,
you can run Keytool manually to generate your own keystore/key and then sign your
application with Jarsigner.</li>
<li>Using the ADT Export Wizard. If you are developing in Eclipse with the ADT plugin,
you can use the Export Wizard to compile the application, generate a private key
(if necessary), and sign the .apk, all in a single process using the Export Wizard.
</li>
</ul>
</li>
</ul>
<p>Once your application is signed, don't forget to run {@code zipalign} on the APK
for additional optimization.</p>
<h2 id="strategies">Signing Strategies</h2>
<p>Some aspects of application signing may affect how you approach the development
of your application, especially if you are planning to release multiple
applications. </p>
<p>In general, the recommended strategy for all developers is to sign
all of your applications with the same certificate, throughout the expected
lifespan of your applications. There are several reasons why you should do so: </p>
<ul>
<li>Application upgrade &ndash; As you release updates to your application, you
will want to continue to sign the updates with the same certificate or set of
certificates, if you want users to upgrade seamlessly to the new version. When
the system is installing an update to an application, it compares the
certificate(s) in the new version with those in the existing version. If the
certificates match exactly, including both the certificate data and order, then
the system allows the update. If you sign the new version without using matching
certificates, you will also need to assign a different package name to the
application &mdash; in this case, the user installs the new version as a
completely new application. </li>
<li>Application modularity &ndash; The Android system allows applications that
are signed by the same certificate to run in the same process, if the
applications so requests, so that the system treats them as a single application.
In this way you can deploy your application in modules, and users can update
each of the modules independently if needed.</li>
<li>Code/data sharing through permissions &ndash; The Android system provides
signature-based permissions enforcement, so that an application can expose
functionality to another application that is signed with a specified
certificate. By signing multiple applications with the same certificate and
using signature-based permissions checks, your applications can share code and
data in a secure manner. </li>
</ul>
<p>Another important consideration in determining your signing strategy is
how to set the validity period of the key that you will use to sign your
applications.</p>
<ul>
<li>If you plan to support upgrades for a single application, you should ensure
that your key has a validity period that exceeds the expected lifespan of
that application. A validity period of 25 years or more is recommended.
When your key's validity period expires, users will no longer be
able to seamlessly upgrade to new versions of your application.</li>
<li>If you will sign multiple distinct applications with the same key,
you should ensure that your key's validity period exceeds the expected
lifespan of <em>all versions of all of the applications</em>, including
dependent applications that may be added to the suite in the future. </li>
<li>If you plan to publish your application(s) on Android Market, the
key you use to sign the application(s) must have a validity period
ending after 22 October 2033. The Market server enforces this requirement
to ensure that users can seamlessly upgrade Market applications when
new versions are available. </li>
</ul>
<p>As you design your application, keep these points in mind and make sure to
use a <a href="#cert">suitable certificate</a> to sign your applications. </p>
<h2 id="setup">Basic Setup for Signing</h2>
<p>Before you begin, you should make sure that
Keytool is available to the SDK build
tools. In most cases, you can tell the SDK build tools how to find Keytool by setting
your <code>JAVA_HOME</code> environment variable to references a suitable JDK.
Alternatively, you can add the JDK version of Keytool to your <code>PATH</code> variable.</p>
<p>If you are developing on a version of Linux that originally came with GNU Compiler for
Java, make sure that the system is using the JDK version of Keytool, rather than the gcj
version. If Keytool is already in your <code>PATH</code>, it might be pointing to a symlink at
<code>/usr/bin/keytool</code>. In this case, check the symlink target to be sure it points
to the Keytool in the JDK.</p>
<p>If you will release your application to the public, you will also need to have
the Jarsigner tool available on your machine. Both Jarsigner and Keytool are included
in the JDK. </p>
<h2 id="debugmode">Signing in Debug Mode</h2>
<p>The Android build tools provide a debug signing mode that makes it easier for you
to develop and debug your application, while still meeting the Android system
requirement for signing your .apk.
When using debug mode to build your app, the SDK tools invoke Keytool to automatically create
a debug keystore and key. This debug key is then used to automatically sign the .apk, so
you do not need to sign the package with your own key.</p>
<p>The SDK tools create the debug keystore/key with predetermined names/passwords:</p>
<ul>
<li>Keystore name: "debug.keystore"</li>
<li>Keystore password: "android"</li>
<li>Key alias: "androiddebugkey"</li>
<li>Key password: "android"</li>
<li>CN: "CN=Android Debug,O=Android,C=US"</li>
</ul></p>
<p>If necessary, you can change the location/name of the debug keystore/key or
supply a custom debug keystore/key to use. However, any custom debug
keystore/key must use the same keystore/key names and passwords as the default
debug key (as described above). (To do so in Eclipse/ADT, go to
<strong>Windows</strong> &gt; <strong>Preferences</strong> &gt;
<strong>Android</strong> &gt; <strong>Build</strong>.) </p>
<p class="caution"><strong>Caution:</strong> You <em>cannot</em> release your application
to the public when signed with the debug certificate.</p>
<h3>Eclipse Users</h3>
<p>If you are developing in Eclipse/ADT (and have set up Keytool as described above in
<a href="#setup">Basic Setup for Signing</a>),
signing in debug mode is enabled by default. When you run or debug your
application, ADT signs the .apk with the debug certificate, runs {@code zipalign} on the
package, then installs it on
the selected emulator or connected device. No specific action on your part is needed,
provided ADT has access to Keytool.</p>
<h3>Ant Users</h3>
<p>If you are using Ant to build your .apk files, debug signing mode
is enabled by using the <code>debug</code> option with the <code>ant</code> command
(assuming that you are using a <code>build.xml</code> file generated by the
<code>android</code> tool). When you run <code>ant debug</code> to
compile your app, the build script generates a keystore/key and signs the .apk for you.
The script then also aligns the .apk with the <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>
<h3 id="debugexpiry">Expiry of the Debug Certificate</h3>
<p>The self-signed certificate used to sign your application in debug mode (the default on
Eclipse/ADT and Ant builds) will have an expiration date of 365 days from its creation date.</p>
<p>When the certificate expires, you will get a build error. On Ant builds, the error
looks like this:</p>
<pre>debug:
[echo] Packaging bin/samples-debug.apk, and signing it with a debug key...
[exec] Debug Certificate expired on 8/4/08 3:43 PM</pre>
<p>In Eclipse/ADT, you will see a similar error in the Android console.</p>
<p>To fix this problem, simply delete the <code>debug.keystore</code> file.
The default storage location for AVDs is in <code>~/.android/</code> on OS X and Linux,
in <code>C:\Documents and Settings\<user>\.android\</code> on Windows XP, and in
<code>C:\Users\<user>\.android\</code> on Windows Vista.</p>
<p>The next time you build, the build tools will regenerate a new keystore and debug key.</p>
<p>Note that, if your development machine is using a non-Gregorian locale, the build
tools may erroneously generate an already-expired debug certificate, so that you get an
error when trying to compile your application. For workaround information, see the
troubleshooting topic <a href="{@docRoot}resources/faq/troubleshooting.html#signingcalendar">
I&nbsp;can't&nbsp;compile my app because the build tools generated an expired debug
certificate</a>. </p>
<h2 id="releasemode">Signing for Public Release</h2>
<p>When your application is ready for release to other users, you must:</p>
<ol>
<li><a href="#cert">Obtain a suitable private key</a></li>
<li><a href="#releasecompile">Compile the application in release mode</li>
<li><a href="#signapp">Sign your application with your private key</a></li>
<li><a href="#align">Align the final APK package</a></li>
</ol>
<p>If you are developing in Eclipse with the ADT plugin, you can use the Export Wizard
to perform the compile, sign, and align procedures. The Export Wizard even allows you to
generate a new keystore and private key in the process. So if you use Eclipse, you can
skip to <a href="#ExportWizard">Compile and sign with Eclipse ADT</a>.</p>
<h3 id="cert">1. Obtain a suitable private key</h3>
<p>In preparation for signing your application, you must first ensure that
you have a suitable private key with which to sign. A suitable private
key is one that:</p>
<ul>
<li>Is in your possession</li>
<li>Represents the personal, corporate, or organizational entity to be identified
with the application</li>
<li>Has a validity period that exceeds the expected lifespan of the application
or application suite. A validity period of more than 25 years is recommended.
<p>If you plan to publish your application(s) on Android Market, note that a
validity period ending after 22 October 2033 is a requirement. You can not upload an
application if it is signed with a key whose validity expires before that date.
</p></li>
<li>Is not the debug key generated by the Android SDK tools. </li>
</ul>
<p>The key may be self-signed. If you do not have a suitable key, you must
generate one using Keytool. Make sure that you have Keytool available, as described
in <a href="#setup">Basic Setup</a>.</p>
<p>To generate a self-signed key with Keytool, use the <code>keytool</code>
command and pass any of the options listed below (and any others, as
needed). </p>
<p class="warning"><strong>Warning:</strong> Keep your private key secure.
Before you run Keytool, make sure to read
<a href="#secure-key">Securing Your Private Key</a> for a discussion of how to keep
your key secure and why doing so is critically important to you and to users. In
particular, when you are generating your key, you should select strong passwords
for both the keystore and key.</p>
<table>
<tr>
<th>Keytool Option</th>
<th>Description</th>
</tr>
<tr>
<td><code>-genkey</code></td><td>Generate a key pair (public and private
keys)</td>
</tr>
<tr>
<td><code>-v</code></td><td>Enable verbose output.</td>
</tr>
<tr>
<td><code>-alias &lt;alias_name&gt;</code></td><td>An alias for the key. Only
the first 8 characters of the alias are used.</td>
</tr>
<tr>
<td><code>-keyalg &lt;alg&gt;</code></td><td>The encryption algorithm to use
when generating the key. Both DSA and RSA are supported.</td>
</tr>
<tr>
<td><code>-keysize &lt;size&gt;</code></td><td>The size of each generated key
(bits). If not supplied, Keytool uses a default key size of 1024 bits. In
general, we recommend using a key size of 2048 bits or higher. </td>
</tr>
<tr>
<td><code>-dname &lt;name&gt;</code></td><td><p>A Distinguished Name that describes
who created the key. The value is used as the issuer and subject fields in the
self-signed certificate. </p><p>Note that you do not need to specify this option
in the command line. If not supplied, Jarsigner prompts you to enter each
of the Distinguished Name fields (CN, OU, and so on).</p></td>
</tr>
<tr>
<td><code>-keypass &lt;password&gt;</code></td><td><p>The password for the
key.</p> <p>As a security precaution, do not include this option in your command
line. If not supplied, Keytool prompts you to enter the password. In this way,
your password is not stored in your shell history.</p></td>
</tr>
<tr>
<td><code>-validity &lt;valdays&gt;</code></td><td><p>The validity period for the
key, in days. </p><p><strong>Note:</strong> A value of 10000 or greater is recommended.</p></td>
</tr>
<tr>
<td><code>-keystore&nbsp;&lt;keystore-name&gt;.keystore</code></td><td>A name
for the keystore containing the private key.</td>
</tr>
<tr>
<td><code>-storepass &lt;password&gt;</code></td><td><p>A password for the
keystore.</p><p>As a security precaution, do not include this option in your
command line. If not supplied, Keytool prompts you to enter the password. In
this way, your password is not stored in your shell history.</p></td>
</tr>
</table>
<p>Here's an example of a Keytool command that generates a private key:</p>
<pre>$ keytool -genkey -v -keystore my-release-key.keystore
-alias alias_name -keyalg RSA -keysize 2048 -validity 10000</pre>
<p>Running the example command above, Keytool prompts you to provide
passwords for the keystore and key, and to provide the Distinguished
Name fields for your key. It then generates the keystore as a file called
<code>my-release-key.keystore</code>. The keystore and key are
protected by the passwords you entered. The keystore contains
a single key, valid for 10000 days. The alias is a name that you &mdash;
will use later, to refer to this keystore when signing your application. </p>
<p>For more information about Keytool, see the documentation at
<a
href="http://java.sun.com/j2se/1.5.0/docs/tooldocs/#security">
http://java.sun.com/j2se/1.5.0/docs/tooldocs/#security</a></p>
<h3 id="releasecompile">2. Compile the application in release mode</h3>
<p>In order to release your application to users, you must compile it in release mode.
In release mode, the compiled application is not signed by default and you will need
to sign it with your private key.</p>
<p class="caution"><strong>Caution:</strong>
You can not release your application unsigned, or signed with the debug key.</p>
<h4>With Eclipse</h4>
<p>To export an <em>unsigned</em> .apk from Eclipse, right-click the project in the Package
Explorer and select <strong>Android Tools</strong> > <strong>Export Unsigned Application
Package</strong>. Then specify the file location for the unsigned .apk.
(Alternatively, open your <code>AndroidManifest.xml</code> file in Eclipse, open
the <em>Overview</em> tab, and click <strong>Export an unsigned .apk</strong>.)</p>
<p>Note that you can combine the compiling and signing steps with the Export Wizard. See
<a href="#ExportWizard">Compiling and signing with Eclipse ADT</a>.</p>
<h4>With Ant</h4>
<p>If you are using Ant, you can enable release mode by using the <code>release</code> option
with the <code>ant</code> command. For example, if you are running Ant from the
directory containing your {@code build.xml} file, the command would look like this:</p>
<pre>ant release</pre>
<p>By default, the build script compiles the application .apk without signing it. The output file
in your project {@code bin/} will be <code><em>&lt;your_project_name></em>-unsigned.apk</code>.
Because the application .apk is still unsigned, you must manually sign it with your private
key and then align it using {@code zipalign}.</p>
<p>However, the Ant build script can also perform the signing
and aligning for you, if you have provided the path to your keystore and the name of
your key alias in the project's {@code build.properties} file. With this information provided,
the build script will prompt you for your keystore and alias password when you perform
<code>ant release</code>, it will sign the package and then align it. The final output
file in {@code bin/} will instead be
<code><em>&lt;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>
<h3 id="signapp">3. Sign your application with your private key</h3>
<p>When you have an application package that is ready to be signed, you can do sign it
using the Jarsigner tool. Make sure that you have Jarsigner available on your
machine, as described in <a href="#setup">Basic Setup</a>. Also, make sure that
the keystore containing your private key is available.</p>
<p>To sign your application, you run Jarsigner, referencing both the
application's .apk and the keystore containing the private key with which to
sign the .apk. The table below shows the options you could use. <p>
<table>
<tr>
<th>Jarsigner Option</th>
<th>Description</th>
</tr>
<tr>
<td><code>-keystore&nbsp;&lt;keystore-name&gt;.keystore</code></td><td>The name of
the keystore containing your private key.</td>
</tr>
<tr>
<td><code>-verbose</code></td><td>Enable verbose output.</td>
</tr>
<tr>
<td><code>-storepass &lt;password&gt;</code></td><td><p>The password for the
keystore. </p><p>As a security precaution, do not include this option
in your command line unless you are working at a secure computer.
If not supplied, Jarsigner prompts you to enter the password. In this
way, your password is not stored in your shell history.</p></td>
</tr>
<tr>
<td><code>-keypass &lt;password&gt;</code></td><td><p>The password for the private
key. </p><p>As a security precaution, do not include this option
in your command line unless you are working at a secure computer.
If not supplied, Jarsigner prompts you to enter the password. In this
way, your password is not stored in your shell history.</p></td>
</tr>
</table>
<p>Here's how you would use Jarsigner to sign an application package called
<code>my_application.apk</code>, using the example keystore created above.
</p>
<pre>$ jarsigner -verbose -keystore my-release-key.keystore
my_application.apk alias_name</pre>
<p>Running the example command above, Jarsigner prompts you to provide
passwords for the keystore and key. It then modifies the .apk
in-place, meaning the .apk is now signed. Note that you can sign an
.apk multiple times with different keys.</p>
<p>To verify that your .apk is signed, you can use a command like this:</p>
<pre>$ jarsigner -verify my_signed.apk</pre>
<p>If the .apk is signed properly, Jarsigner prints "jar verified".
If you want more details, you can try one of these commands:</p>
<pre>$ jarsigner -verify -verbose my_application.apk</pre>
<p>or</p>
<pre>$ jarsigner -verify -verbose -certs my_application.apk</pre>
<p>The command above, with the <code>-certs</code> option added, will show you the
"CN=" line that describes who created the key.</p>
<p class="note"><strong>Note:</strong> If you see "CN=Android Debug", this means the .apk was
signed with the debug key generated by the Android SDK. If you intend to release
your application, you must sign it with your private key instead of the debug
key.</p>
<p>For more information about Jarsigner, see the documentation at
<a href="http://java.sun.com/j2se/1.5.0/docs/tooldocs/#security">
http://java.sun.com/j2se/1.5.0/docs/tooldocs/#security</a></p>
<h3 id="align">4. Align the final APK package</h3>
<p>Once you have signed the .apk with your private key, run <code>zipalign</code> on the file.
This tool ensures that all uncompressed data starts with a particular byte alignment,
relative to the start of the file. Ensuring alignment at 4-byte boundaries provides
a performance optimization when installed on a device. When aligned, the Android
system is able to read files with {@code mmap()}, even if
they contain binary data with alignment restrictions, rather than copying all
of the data from the package. The benefit is a reduction in the amount of
RAM consumed by the running application.</p>
<p>The <code>zipalign</code> tool is provided with the Android SDK, inside the
<code>tools/</code> directory. To align your signed .apk, execute:</p>
<pre>zipalign -v 4 <em>your_project_name</em>-unaligned.apk <em>your_project_name</em>.apk</pre>
<p>The {@code -v} flag turns on verbose output (optional). {@code 4} is the
byte-alignment (don't use anything other than 4). The first file argument is
your signed .apk (the input) and the second file is the destination .apk file (the output).
If you're overriding an existing .apk, add the {@code -f} flag.</p>
<p class="caution"><strong>Caution:</strong> Your input .apk must be signed with your
private key <strong>before</strong> you optimize the package with {@code zipalign}.
If you sign it after using {@code zipalign}, it will undo the alignment.</p>
<p>For more information, read about the
<a href="{@docRoot}guide/developing/tools/zipalign.html">zipalign</a> tool.
<h3 id="ExportWizard">Compile and sign with Eclipse ADT</h3>
<p>If you are using Eclipse with the ADT plugin, you can use the Export Wizard to
export a <em>signed</em> .apk (and even create a new keystore,
if necessary). The Export Wizard performs all the interaction with
the Keytool and Jarsigner for you, which allows you to sign the package using a GUI
instead of performing the manual procedures to compile, sign,
and align, as discussed above. Once the wizard has compiled and signed your package,
it will also perfom package alignment with {@code zipalign}.
Because the Export Wizard uses both Keytool and Jarsigner, you should
ensure that they are accessible on your computer, as described above
in the <a href="#setup">Basic Setup for Signing</a>.</p>
<p>To create a signed and aligned .apk in Eclipse:</p>
<ol>
<li>Select the project in the Package
Explorer and select <strong>File > Export</strong>.</li>
<li>Open the Android folder, select Export Android Application,
and click <strong>Next</strong>.
<p>The Export Android Application wizard now starts, which will
guide you through the process of signing your application,
including steps for selecting the private key with which to sign the .apk
(or creating a new keystore and private key).</p>
<li>Complete the Export Wizard and your application will be compiled,
signed, aligned, and ready for distribution.</li>
</ol>
<h2 id="secure-key">Securing Your Private Key</h2>
<p>Maintaining the security of your private key is of critical importance, both
to you and to the user. If you allow someone to use your key, or if you leave
your keystore and passwords in an unsecured location such that a third-party
could find and use them, your authoring identity and the trust of the user
are compromised. </p>
<p>If a third party should manage to take your key without your knowledge or
permission, that person could sign and distribute applications that maliciously
replace your authentic applications or corrupt them. Such a person could also
sign and distribute applications under your identity that attack other
applications or the system itself, or corrupt or steal user data. </p>
<p>Your reputation as a developer entity depends on your securing your private
key properly, at all times, until the key is expired. Here are some tips for
keeping your key secure: </p>
<ul>
<li>Select strong passwords for the keystore and key.</li>
<li>When you generate your key with Keytool, <em>do not</em> supply the
<code>-storepass</code> and <code>-keypass</code> options at the command line.
If you do so, your passwords will be available in your shell history,
which any user on your computer could access.</li>
<li>Similarly, when signing your applications with Jarsigner,
<em>do not</em> supply the <code>-storepass</code> and <code>-keypass</code>
options at the command line. </li>
<li>Do not give or lend anyone your private key, and do not let unauthorized
persons know your keystore and key passwords.</li>
</ul>
<p>In general, if you follow common-sense precautions when generating, using,
and storing your key, it will remain secure. </p>

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,256 @@
page.title=Preparing to Publish: A Checklist
@jd:body
<p>Publishing an application means testing it, packaging it appropriately, and
making it available to users of Android-powered mobile devices.</p>
<p>If you plan to publish your application for installation on
Android-powered devices, there are several things you need to do, to get
your application ready. This document highlights the significant
checkpoints for preparing your application for a successful release.
</p>
<p>If you will publish your application on Android Market, please also see <a
href="{@docRoot}guide/publishing/publishing.html#market">Publishing on Android Market</a>
for specific preparation requirements for your application. </p>
<p>For general information about the ways that you can publish an applications,
see the <a href="{@docRoot}guide/publishing/publishing.html">Publishing Your
Applications</a> document. </p>
<div class="special">
<p><a href="#releaseready">Before you consider your application ready for release</a>:</p>
<ol>
<li>Test your application extensively on an actual device </li>
<li>Consider adding an End User License Agreement in your application</li>
<li>Consider adding licensing support</li>
<li>Specify an icon and label in the application's manifest</li>
<li>Turn off logging and debugging and clean up data/files</li>
</ol>
<p><a href="#finalcompile">Before you do the final compile of your application</a>:</p>
<ol start="6">
<li>Version your application</li>
<li>Obtain a suitable cryptographic key</li>
<li>Register for a Maps API Key, if your application is using MapView elements</li>
</ol>
<p><a href="#compile">Compile your application</a></p>
<p><a href="#post-compile">After you compile your application</a>:</p>
<ol start="9">
<li>Sign your application</li>
<li>Test your compiled application</li>
</ol>
</div>
<h2 id="releaseready">Before you consider your application ready for release</h2>
<h3 id="test">1. Test your application extensively on an actual device</h3>
<p>It's important to test your application as extensively as possible, in as
many areas as possible. To help you do that, Android provides a variety of
testing classes and tools. You can use
{@link android.app.Instrumentation Instrumentation} to run JUnit and other
test cases, and you can use testing
tools such as the <a href="{@docRoot}guide/developing/tools/monkey.html">UI/Application
Exerciser Monkey</a>. </p>
<ul>
<li>To ensure that your application will run properly for users, you should make
every effort to obtain one or more physical mobile device(s) of the type on
which you expect the application to run. You should then test your application
on the actual device, under realistic network conditions. Testing your
application on a physical device is very important, because it enables you to
verify that your user interface elements are sized correctly (especially for
touch-screen UI) and that your application's performance and battery efficiency
are acceptable.</li>
<li>If you can not obtain a mobile device of the type you are targeting for your
application, you can use emulator options such as <code>-dpi</code>,
<code>-device</code>, <code>-scale</code>, <code>-netspeed</code>,
<code>-netdelay</code>, <code>-cpu-delay</code> and others to model the
emulator's screen, network performance, and other attributes to match the target
device to the greatest extent possible. You can then test your application's UI
and performance. However, we strongly recommend that you test your application
on an actual target device before publishing it. </li>
<li>If you are targeting the <a href="http://www.t-mobileg1.com/">T-Mobile
G1</a> device for your application, make sure that your UI handles screen
orientation changes. </li>
</ul>
<h3 id="eula">2. Consider adding an End User License Agreement in your
application</h3>
<p>To protect your person, organization, and intellectual property, you may want
to provide an End User License Agreement (EULA) with your application.
<h3>3. Consider adding support for Android Market Licensing</h3>
<p>If you are publishing a paid application through Android Market, consider
adding support for Android Market Licensing. Licensing lets you control access
to your application based on whether the current user has purchased it.
Using Android Market Licensing is optional.
<p>For complete information about Android Market Licensing Service and how to
use it in your application, see <a
href="{@docRoot}guide/publishing/licensing.html">Licensing Your
Applications</a>.</p>
<h3 id="iconlabel">4. Specify an icon and label in the application's manifest</h3>
<p>The icon and label that you specify in an application's manifest are
important because they are displayed to users as your application's icon and
name. They are displayed on the device's Home screen, as well as in Manage
Applications, My Downloads, and elsewhere. Additionally, publishing services may
display the icon and label to users. </p>
<p>To specify an icon and label, you define the attributes
<code>android:icon</code> and <code>android:label</code> in the
<code>&lt;application&gt;</code> element of the manifest. </p>
<p>As regards the design of your icon, you should try to make it match as much
as possible the style used by the built-in Android applications.</p>
<h3 id="logging">5. Turn off logging and debugging and clean up data/files</h3>
<p>For release, you should make sure that debug facilities are turned off and
that debug and other unnecessary data/files are removed from your application
project.</p>
<ul>
<li>Remove the <code>android:debuggable="true"</code> attribute from the
<code>&lt;application&gt;</code> element of the manifest.</li>
<li>Remove log files, backup files, and other unnecessary files from the
application project.</li>
<li>Check for private or proprietary data and remove it as necessary.</li>
<li>Deactivate any calls to {@link android.util.Log} methods in the source
code.</li>
</ul>
<h2 id="finalcompile">Before you do the final compile of your application</h2>
<h3 id="versionapp">6. Version your application</h3>
<p>Before you compile your application, you must make sure that you have defined
a version number for your application, specifying an appropriate value for both
the <code>android:versionCode</code> and <code>android:versionName</code>
attributes of the <code>&lt;manifest&gt;</code> element in the application's
manifest file. Carefully consider your version numbering plans in the context of
your overall application upgrade strategy. </p>
<p>If you have previously released a version of your application, you must make
sure to increment the version number of the current application. You must
increment both the <code>android:versionCode</code> and
<code>android:versionName</code> attributes of the <code>&lt;manifest&gt;</code>
element in the application's manifest file, using appropriate values. </p>
<p>For detailed information about how to define version information for your
application, see <a href="{@docRoot}guide/publishing/versioning.html">Versioning
Your Applications</a>.</p>
<h3 id="cryptokey">7. Obtain a suitable cryptographic key</h3>
<p>If you have read and followed all of the preparation steps up to this point,
your application is compiled and ready for signing. Inside the .apk, the
application is properly versioned, and you've cleaned out extra files and
private data, as described above. </p>
<p>Before you sign your application, you need to make sure that you have a
suitable private key. For complete information about how to obtain (or generate)
a private key, see <a href="{@docRoot}guide/publishing/app-signing.html#cert">
Obtaining a Suitable Private Key</a>.</p>
<p>Once you have obtained (or generated) a suitable private key, you will use it
to:</p>
<ul>
<li>Register for a Maps API Key (see below), if your application uses MapView
elements.</li>
<li>Sign your application for release, later in the preparation process</li>
</ul>
<h3 id="mapsApiKey">8. Register for a Maps API Key, if your application is using
MapView elements</h3>
<div class="sidebox-wrapper">
<div class="sidebox"><p>
For complete information about getting a Maps API Key, see <a
href="http://code.google.com/android/add-ons/google-apis/mapkey.html">
Obtaining a Maps API Key</a>.</p>
</div>
</div>
<p>If your application uses one or more Mapview elements, you will need to
register your application with the Google
Maps service and obtain a Maps API Key, before your MapView(s) will be able to
retrieve data from Google Maps. To do so, you supply an MD5 fingerprint of your
signer certificate to the Maps service. </p>
<p>During development, you can get a temporary Maps API Key by registering the
debug key generated by the SDK tools. However, before publishing your
application, you must register for a new Maps API Key that is based on your
private key. </p>
<p>If your application uses MapView elements, the important points to understand
are:</p>
<ol>
<li>You <em>must</em> obtain the Maps API Key before you compile your
application for release, because you must add the Key to a special attribute in
each MapView element &mdash; <code>android:apiKey</code> &mdash; in your
application's layout files. If you are instantiating MapView objects directly
from code, you must pass the Maps API Key as a parameter in the constructor.
</li>
<li>The Maps API Key referenced by your application's MapView elements must be
registered (in Google Maps) to the certificate used to sign the application.
This is particularly important when publishing your application &mdash; your
MapView elements must reference a Key that is registered to the release
certificate that you will use to sign your application. </li>
<li>If you previously got a temporary Maps API Key by registering the debug
certificate generated by the SDK tools, you <em>must</em> remember to obtain a
new Maps API Key by registering your release certificate. You must then remember
to change the MapView elements to reference the new Key, rather than the Key
associated with the debug certificate. If you do not do so, your MapView
elements will not have permission to download Maps data. </li>
<li>If you change the private key that you will use to sign your application,
you <em>must</em> remember to obtain a new Maps API Key from the Google Maps
service. If you do not get a new Maps API Key and apply it to all MapView
elements, any MapView elements referencing the old Key will not have permission
to download Maps data. </li>
</ol>
<h2 id="compile">Compile your application</h2>
<p>When you've prepared your application as described in the previous sections,
you can compile your application for release.</p>
<h2 id="post-compile">After you compile your application</h2>
<h3 id="signapp">9. Sign your application</h3>
<p>Sign your application using your private key and then
align it with the {@code zipalign} tool. Signing your application
correctly is critically important. Please see
<a href="{@docRoot}guide/publishing/app-signing.html">Signing Your
Applications</a> for complete information. </p>
<h3 id="testapp">10. Test your compiled and signed application</h3>
<p>Before you release your compiled application, you should thoroughly test it
on the target mobile device (and target network, if possible). In particular,
you should make sure that any MapView elements in your UI are receiving maps
data properly. If they are not, go back to <a href="#mapsApiKey">Register for a
Maps API Key</a> and correct the problem. You should also ensure that the
application works correctly with any server-side services and data that you are
providing or are relying on and that the application handles any authentication
requirements correctly. </p>
<p>After testing, you are now ready to publish your application to mobile device
users.</p>

View File

@@ -0,0 +1,306 @@
page.title=Publishing Your Applications
@jd:body
<div id="qv-wrapper">
<div id="qv">
<h2>Quickview</h2>
<ul>
<li>You can publish your application using a hosted service such as Android Market or through a web server.</li>
<li>Before you publish, make sure you have prepared your application properly.</li>
<li>Android Market makes it easy for users of Android-powered devices to see and download your application.</li>
</ul>
<h2>In this document</h2>
<ol>
<li><a href="#overview">Publishing on Android Market</a>
<ol>
<li><a href="#marketupgrade">Publishing Updates on Android Market</a></li>
<li><a href="#marketLicensing">Using Android Market Licensing Service</a></li>
<li><a href="#marketintent">Using Intents to Launch the Market Application</a></li>
</ol></li>
<!--
<li><span style="color:ccc">Publishing on Other Hosted Services</a></li>
<li><span style="color:ccc">Publishing through a Web Server</a></li>
-->
</ol>
<h2>See also</h2>
<ol>
<li><a href="{@docRoot}guide/publishing/licensing.html">Licensing Your Applications</a></li>
<li><a href="{@docRoot}guide/publishing/preparing.html">Preparing to Publish</a></li>
</ol>
<div id="qv-extra">
<img id="rule" src="{@docRoot}assets/images/grad-rule-qv.png">
<div id="qv-sub-rule">
<img src="{@docRoot}assets/images/icon_market.jpg" style="float:left;margin:0;padding:0;">
<p style="color:#669999;">Interested in publishing your app on Android Market?</p>
<a id="publish-link" href="http://market.android.com/publish">Go to Android Market &raquo;</a>
</div>
</div>
</div>
</div>
<p>Publishing an application means testing it, packaging it appropriately, and making
it available to users of Android-powered mobile devices for download or sideload.</p>
<p>If you've followed the steps outlined in
<a href="{@docRoot}guide/publishing/preparing.html">Preparing to
Publish Your Applications</a>, the result of the process is a compiled .apk that
is signed with your release private key. Inside the .apk, the application is
properly versioned and any MapView elements reference a Maps API Key that you
obtained by registering the MD5 fingerprint of the same certificate used to sign
the .apk. Your application is now ready for publishing. </p>
<p>The sections below provide information about publishing your Android
application to mobile device users.</p>
<h2 id="overview">Publishing on Android Market</h2>
<p>Android Market is a hosted service that makes it easy for users to find and
download Android applications to their Android-powered devices, and makes it
easy for developers to publish their applications to Android users.</p>
<p>To publish your application on Android Market, you first need to register
with the service using your Google account and agree to the terms of service.
Once you are registered, you can upload your application to the service whenever
you want, as many times as you want, and then publish it when you are ready.
Once published, users can see your application, download it, and rate it using
the Market application installed on their Android-powered devices. </p>
<p>To register as an Android Market developer and get started with publishing,
visit the Android Market: </p>
<p style="margin-left:3em;"><a
href="http://market.android.com/publish">http://market.android.com/publish</a>
</p>
<p>If you plan to publish your application on Android Market, you must make sure
that it meets the requirements listed below, which are enforced by the Market
server when you upload the application.</p>
<div class="special">
<p>Requirements enforced by the Android Market server:</p>
<ol>
<li>Your application must be signed with a cryptographic private key whose
validity period ends after <span style="color:red">22 October 2033</span>. </li>
<li>Your application must define both an <code>android:versionCode</code> and an
<code>android:versionName</code> attribute in the
<a
href="{@docRoot}guide/topics/manifest/manifest-element.html"><code>&lt;manifest&gt;</code></a>
element of its manifest. The server uses the <code>android:versionCode</code> as
the basis for identifying the application internally and handling updates, and
it displays the <code>android:versionName</code> to users as the application's
version.</li>
<li>Your application must define both an <code>android:icon</code> and an
<code>android:label</code> attribute in the <code>&lt;application&gt;</code>
element of its manifest.</li>
</ol>
</div>
<h3 id="marketupgrade">Publishing Updates on Android Market</h3>
<p>At any time after publishing an application on Android Market, you can upload
and publish an update to the same application package. When you publish an
update to an application, users who have already installed the
application will automatically receive a notification that an update is
available for the application. They can then choose to update the application
to the latest version.</p>
<p>Before uploading the updated application, be sure that you have incremented
the <code>android:versionCode</code> and <code>android:versionName</code>
attributes in the <a
href="{@docRoot}guide/topics/manifest/manifest-element.html"><code>&lt;manifest&gt;</code></a>
element of the manifest file. Also, the package name must be the same and the
.apk must be signed with the same private key. If the package name and signing
certificate do <em>not</em> match those of the existing version, Market will
consider it a new application and will not offer it to users as an update.</p>
<h3 id="marketLicensing">Using Android Market Licensing Service</h3>
<p>Android Market offers a licensing service that lets you enforce licensing
policies for paid applications that you publish through Android Market. With
Android Market Licensing, your applications can query Android Market at run time
to obtain their licensing status for the current user, then allow or disallow
further use as appropriate. Using the service, you can apply a flexible
licensing policy on an application-by-application basis &mdash; each
application can enforce its licensing status in the way most appropriate
for it. </p>
<p>Any application that you publish through Android Market can use the Android
Market Licensing Service. The service uses no dedicated framework APIs, you can
add licensing to any legacy application that uses a minimum API level of 3 or
higher.</p>
<p>For complete information about Android Market Licensing Service and how to
use it in your application, see <a
href="{@docRoot}guide/publishing/licensing.html">Licensing Your
Applications</a>.</p>
<h3 id="marketintent">Using Intents to Launch the Market Application on
a Device</h3>
<p>Android-powered devices include a preinstalled Market application that gives
users access to the Android Market site. From Market, users can
browse or search available applications, read ratings and reviews, and
download/install applications.</p>
<p>You can launch the Market application from another Android
application by sending an Intent to the system. You might want to do
this, for example, to help the user locate and download an update to an
installed application, or to let the user know about related
applications that are available for download. </p>
<p>To launch Market, you send an ACTION_VIEW Intent, passing a Market-handled
URI string as the Intent data. In most cases, your application would call
startActivity() to send the ACTION_VIEW Intent with the Market-handled URI.</p>
<p>The URI that you supply with the Intent lets the system route the intent
properly and also expresses the type of action that you want Market to perform
after launch. Currently, you can have Market take these actions:</p>
<ul>
<li>Initiate a search for applications on Android Market, based on the query
parameters that you provide, or </li>
<li>Load the Details page for a specific application on Android Market, based on
the application's package name.</li>
</ul>
<h4>Initiating a search</h4>
<p>Your application can initiate a search on Android Market for applications
that match the query parameters that you provide. To do so, your application
sends an ACTION_VIEW Intent that includes a URI and query parameters in this
format:</p>
<p style="margin-left:2em"><code>market://search?q=&lt;paramtype&gt;:&lt;value&gt;</code></p>
<div class="sidebox-wrapper" xstyle="margin-bottom:2em;margin-top:.5em;width:90%;">
<img id="rule" src="{@docRoot}assets/images/grad-rule-qv.png">
<div id="qv-sub-rule">
<img src="{@docRoot}assets/images/icon_market.jpg" style="float:left;margin:0;padding:0;">
<p style="color:#669999;">Searches on Android Market</p>
<p>When you initiate a search, Android Market returns results from matches in
the public metadata supplied by developers in their Android Market profiles or
application publishing information, but not from the developer's private account
or from the certificate used to sign the application. </p>
</div>
</div>
<p>Using this URI format, you can search for applications by:</p>
<ul>
<li>Package name</li>
<li>Developer name</li>
<li>String match across application name, developer name, and
description, or </li>
<li>Any combination of the above</li>
</ul>
<p>The table at the bottom of this page specifies the <code>paramtypes</code>
and <code>values</code> that correspond to each of these types of search. </p>
<p>When you send an intent to initiate a search for applications, Market sends
the search query to the server and displays the result. To the user, the
experience is something like this: </p>
<ol>
<li>The user presses a link or button in your application.</li>
<li>The Market application launches and takes control of the screen, displaying
a progress indicator labeled "Searching" until it receives the search
results.</li>
<li>Market receives the search results and displays them. Depending on the query
parameters, the search results may include a list of one or more applications.
</li>
<li>From the results page, the user can select an app to go to its Details page,
which offers information about the app and lets the user download/purchase the
app.</li>
</ol>
<h4>Loading an application's Details page</h4>
<p>In Android Market, every application has a Details page that provides an
overview of the application for users. For example, the page includes a short
description of the app and screen shots of it in use, if supplied by the
developer, as well as feedback from users and information about the developer.
The Details page also includes an "Install" button that lets the user trigger
the download/purchase of the application.</p>
<p>If you want to refer the user to a specific appplication, your application
can take the user directly to the application's Details page. To do so, your
application sends an ACTION_VIEW Intent that includes a URI and query parameter
in this format:</p>
<p style="margin-left:2em"><code>market://details?id=&lt;packagename&gt;</code></p>
<p>In this case, the <code>packagename</code> parameter is target application's
fully qualified package name, as declared in the <code>package</code> attribute
of the <code>manifest</code> element in the application's manifest file. For example:</p>
<p style="margin-left:2em"><code>market://details?id=com.example.android.jetboy</code></p>
<h4>Android Market URIs</h4>
<p>The table below provides a list of URIs and actions currently
supported by the Market application.</p>
<p>Note that these URIs work only when passed as Intent data &mdash; you
can't currently load the URIs in a web browser, either on a desktop machine or
on the device. </p>
<table>
<tr>
<th width="25%">For this Result</th>
<th>Pass this URI with the ACTION_VIEW Intent</th>
<th width="36%">Comments</th>
</tr>
<tr>
<td>Display the Details screen for a specific application, as identified
by the app's fully qualified package name.</td>
<td><code>http://market.android.com/details?id=&lt;packagename&gt;</code>
or<br>
<code>market://details?id=&lt;packagename&gt;</code></td>
<td>Note that the package name that you specify is <em>not</em> specific to any
version of an application. Therefore, Market always displays the Details page for the
latest version of the application.</td>
</tr>
<tr>
<td>Search for an application by its fully qualified Java package name and
display the result.</td>
<td><code>http://market.android.com/search?q=pname:&lt;package&gt;</code> or<br>
<code>market://search?q=pname:&lt;package&gt;</code></td>
<td>Searches only the Java package name of applications. Returns only exact
matches.</td>
</tr>
<tr>
<td>Search for applications by developer name and display the results.</td>
<td><code>http://market.android.com/search?q=pub:&lt;Developer&nbsp;Name&gt;</code>
or<br> <code>market://search?q=pub:&lt;Developer Name&gt;</code></td>
<td>Searches only the "Developer Name" fields of Market public profiles.
Returns exact matches only. </td>
</tr>
<tr>
<td>Search for applications by substring and display the results.</td>
<td><code>http://market.android.com/search?q=&lt;substring&gt;</code> or
<br><code>market://search?q=&lt;substring&gt;</code></td>
<td>Searches all public fields (application title, developer name, and
application description) for all applications. Returns exact and partial
matches.</td>
</tr>
<tr>
<td>Search using multiple query parameters and display the results.</td>
<td>Example:<p><code>http://market.android.com/search?q=world pname:com.android.hello pub:Android</code></p></td>
<td>Returns a list of applications meeting all the supplied parameters. </td>
</tr>
</table>

View File

@@ -0,0 +1,175 @@
page.title=Versioning Your Applications
@jd:body
<div id="qv-wrapper">
<div id="qv">
<h2>Quickview</h2>
<ul>
<li>Your application <em>must</em> be versioned</a></li>
<li>You set the version in the application's manifest file</li>
<li>How you version your applications affects how users upgrade </li>
<li>Determine your versioning strategy early in the development process, including considerations for future releases.</li>
</ul>
<h2>In this document</h2>
<ol>
<li><a href="#appversioning">Setting Application Version</a></li>
<li><a href="#minsdkversion">Specifying Your Application's System API Requirements</a>
</ol>
<h2>See also</h2>
<ol>
<li><a href="{@docRoot}guide/publishing/preparing.html">Preparing to Publish Your Application</a></li>
<li><a href="{@docRoot}guide/publishing/publishing.html#market">Publishing On Android Market</a></li>
<li><a href="{@docRoot}guide/topics/manifest/manifest-intro.html">The AndroidManifest.xml File</a></li>
</ol>
</div>
</div>
<p>Versioning is a critical component of your application upgrade/maintenance
strategy. </p>
<ul>
<li>Users need to have specific information about the application version that
is installed on their devices and the upgrade versions available for
installation. </li>
<li>Other applications &mdash; including other applications that you publish as
a suite &mdash; need to query the system for your application's version, to
determine compatibility and identify dependencies.</li>
<li>Services through which you will publish your application(s) may also need to
query your application for its version, so that they can display the version to
users. A publishing service may also need to check the application version to
determine compatibility and establish upgrade/downgrade relationships.</li>
</ul>
<p>The Android system itself <em>does not ever</em> check the application version
information for an application, such as to enforce restrictions on upgrades,
compatibility, and so on. Instead, only users or applications themselves are
responsible for enforcing any version restrictions for applications themselves. </p>
<p>The Android system <em>does</em> check any system version compatibility expressed
by an application in its manifest, in the <code>minSdkVersion</code> attribute. This
allows an application to specify the minimum system API with which is compatible.
For more information see <a href="#minsdkversion">Specifying Minimum System API Version</a>.
<h2 id="appversioning">Setting Application Version</h2>
<p>To define the version information for your application, you set attributes in
the application's manifest file. Two attributes are available, and you should
always define values for both of them: </p>
<ul>
<li><code>android:versionCode</code> &mdash; An integer value that represents
the version of the application code, relative to other versions.
<p>The value is an integer so that other applications can programmatically
evaluate it, for example to check an upgrade or downgrade relationship. You can
set the value to any integer you want, however you should make sure that each
successive release of your application uses a greater value. The system does not
enforce this behavior, but increasing the value with successive releases is
normative. </p>
<p>Typically, you would release the first version of your application with
versionCode set to 1, then monotonically increase the value with each release,
regardless whether the release constitutes a major or minor release. This means
that the <code>android:versionCode</code> value does not necessarily have a
strong resemblance to the application release version that is visible to the
user (see <code>android:versionName</code>, below). Applications and publishing
services should not display this version value to users.</p>
</li>
<li><code>android:versionName</code> &mdash; A string value that represents the
release version of the application code, as it should be shown to users.
<p>The value is a string so that you can describe the application version as a
&lt;major&gt;.&lt;minor&gt;.&lt;point&gt; string, or as any other type of
absolute or relative version identifier. </p>
<p>As with <code>android:versionCode</code>, the system does not use this value
for any internal purpose, other than to enable applications to display it to
users. Publishing services may also extract the <code>android:versionName</code>
value for display to users.</p>
</li>
</ul>
<p>You define both of these version attributes in the
<code>&lt;manifest&gt;</code> element of the manifest file. </p>
<p>Here's an example manifest that shows the <code>android:versionCode</code>
and <code>android:versionName</code> attributes in the
<code>&lt;manifest&gt;</code> element. </p>
<pre>
&lt;?xml version="1.0" encoding="utf-8"?&gt;
&lt;manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.package.name"
android:versionCode="2"
android:versionName="1.1"&gt;
&lt;application android:icon="@drawable/icon" android:label="@string/app_name"&gt;
...
&lt;/application&gt;
&lt;/manifest&gt;
</pre>
<p>In this example, note that <code>android:versionCode</code> value indicates
that the current .apk contains the second release of the application code, which
corresponds to a minor follow-on release, as shown by the
<code>android:versionName</code> string. </p>
<p>The Android framework provides an API to let applications query the system
for version information about your application. To obtain version information,
applications use the
{@link android.content.pm.PackageManager#getPackageInfo(java.lang.String, int)}
method of {@link android.content.pm.PackageManager PackageManager}. </p>
<h2 id="minsdkversion">Specifying Your Application's System API Requirements</h2>
<p>If your application requires a specific minimum version of the Android
platform, or is designed only to support a certain range of Android platform
versions, you can specify those version requirements as API Level identifiers
in the application's manifest file. Doing so ensures that your
application can only be installed on devices that
are running a compatible version of the Android system. </p>
<p>To specify API Level requirements, add a <code>&lt;uses-sdk&gt;</code>
element in the application's manifest, with one or more of these attributes: </p>
<ul>
<li><code>android:minSdkVersion</code> &mdash; The minimum version
of the Android platform on which the application will run, specified
by the platform's API Level identifier. </li>
<li><code>android:targetSdkVersion</code> &mdash; Specifies the API Level
on which the application is designed to run. In some cases, this allows the
application to use manifest elements or behaviors defined in the target
API Level, rather than being restricted to using only those defined
for the minimum API Level.</li>
<li><code>android:maxSdkVersion</code> &mdash; The maximum version
of the Android platform on which the application is designed to run,
specified by the platform's API Level identifier. <strong>Important:</strong> Please read the <a
href="{@docRoot}guide/topics/manifest/uses-sdk-element.html"><code>&lt;uses-sdk&gt;</code></a>
documentation before using this attribute. </li>
</ul>
<p>When preparing to install your application, the system checks the value of this
attribute and compares it to the system version. If the
<code>android:minSdkVersion</code> value is greater than the system version, the
system aborts the installation of the application. Similarly, the system
installs your application only if its <code>android:maxSdkVersion</code>
is compatible with the platform version.</p>
<p>If you do not specify these attributes in your manifest, the system assumes
that your application is compatible with all platform versions, with no
maximum API Level. </p>
<p>To specify a minimum platform version for your application, add a
<code>&lt;uses-sdk&gt;</code> element as a child of
<code>&lt;manifest&gt;</code>, then define the
<code>android:minSdkVersion</code> as an attribute. </p>
<p>For more information, see the <a
href="{@docRoot}guide/topics/manifest/uses-sdk-element.html"><code>&lt;uses-sdk&gt;</code></a>
manifest element documentation and the <a
href="{@docRoot}guide/appendix/api-levels.html">API Levels</a> document.</p>

Binary file not shown.

After

Width:  |  Height:  |  Size: 43 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 52 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 15 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 18 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 5.3 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 13 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 27 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 5.9 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 6.4 KiB

View File

@@ -0,0 +1,15 @@
guide=true
page.title=Sample Code
@jd:body
<script type="text/javascript">
window.location = toRoot + "resources/samples/index.html";
</script>
<p><strong>This document has moved. Please go to <a
href="http://developer.android.com/resources/samples/index.html">List of Sample
Apps</a>.</strong></p>

Some files were not shown because too many files have changed in this diff Show More