From 50e990c64fa23ce94efa76b9e72df7f8ec3cee6a Mon Sep 17 00:00:00 2001
From: Scott Main This page provides data about the relative number of active devices
+running a given version of the Android platform. This can help you
+understand the landscape of device distribution and decide how to prioritize
+the development of your application features for the devices currently in
+the hands of users. For information about how to target your application to devices based on
+platform version, read about API levels. The following pie chart and table is based on the number of Android devices that have accessed
+Google Play within a 14-day period ending on the data collection date noted below. Data collected during a 14-day period ending on June 1, 2012 The following stacked line graph provides a history of the relative number of
+active Android devices running different versions of the Android platform. It also provides a
+valuable perspective of how many devices your application is compatible with, based on the
+platform version. Notice that the platform versions are stacked on top of each other with the oldest active
+version at the top. This format indicates the total percent of active devices that are compatible
+with a given version of Android. For example, if you develop your application for
+the version that is at the very top of the chart, then your application is
+compatible with 100% of active devices (and all future versions), because all Android APIs are
+forward compatible. Or, if you develop your application for a version lower on the chart,
+then it is currently compatible with the percentage of devices indicated on the y-axis, where the
+line for that version meets the y-axis on the right. Each dataset in the timeline is based on the number of Android devices that accessed
+Google Play within a 14-day period ending on the date indicated on the x-axis. Last historical dataset collected during a 14-day period ending on June 1, 2012 This section provides data about the relative number of active devices that have a particular
+screen configuration, defined by a combination of screen size and density. To simplify the way that
+you design your user interfaces for different screen configurations, Android divides the range of
+actual screen sizes and densities into: For information about how you can support multiple screen configurations in your
+application, see Supporting Multiple
+Screens. Note: This data is based on the number
+of Android devices that have accessed Google Play within a 7-day period
+ending on the data collection date noted below. Data collected during a 7-day period ending on May 1, 2012 This section provides data about the relative number of active devices that support a particular
+version of OpenGL ES. Note that support for one particular version of OpenGL ES also implies
+support for any lower version (for example, support for version 2.0 also implies support for
+1.1). To declare which version of OpenGL ES your application requires, you should use the {@code
+android:glEsVersion} attribute of the {@code <uses-feature>}
+element. You can also use the {@code
+<supports-gl-texture>} element to declare the GL compression formats that your application
+uses. Note: This data is based on the number
+of Android devices that have accessed Google Play within a 7-day period
+ending on the data collection date noted below. Data collected during a 7-day period ending on June 4, 2012 Android powers millions of devices around the world and in a variety of form-factors. The Android
+framework is specially built to run apps on more than just one screen size and hardware
+configuration. As an app developer, Android's scale and variety offers you the potential to quickly
+reach millions of users. Android apps are flexible and easily adapt to the device on which they are running. Although the
+system scales your assets when necessary, you can provide alternative app resources that are
+optimized for specific device categories, such as the screen size and density. Android applies the
+appropriate resources when running your app, based on the current device’s configuration. Some devices provide a different user experience when using apps, but you’re always in control of
+how your app behaves on each device. If you publish your app on Google Play, you also have
+control over which kinds of devices are allowed to install your app and you can closely control how
+your app is distributed. Every device that includes Google Play has been certified compatible. This means that
+the device has passed a rigorous test suite to ensure that the device uses a version of Android that
+supports all the platform APIs and will successfully run your app. Android powers hundreds of millions of mobile devices in more than 190
+countries around the world. It's the largest installed base of any mobile platform
+and growing fast—every day another 900,000 users power up their
+Android devices for the first time and start looking for apps, games,
+and other digital content. Android gives you a world-class platform for creating apps and games for
+Android users everywhere, as well as an open marketplace for distributing
+to them instantly. Building on the contributions of the open-source Linux community and more
+than 300 hardware, software, and carrier partners, Android has rapidly become
+the fastest-growing mobile OS. Android’s openness has made it a favorite for consumers and developers alike,
+driving strong growth in app consumption. Android users download more than
+1 billion apps and games from Google Play each month. With it's partners, Android is continuously pushing the boundaries of hardware and software
+forward to bring new capabilities to users and developers. For developers,
+Android innovation lets you build powerful, differentiated applications
+that use the latest mobile technologies. Android gives you everything you need to build best-in-class app experiences.
+It gives you a single application model that lets you deploy
+your apps broadly to hundreds of millions of users across a wide range of
+devices—from phones to tablets and beyond. Android also gives you tools for creating apps that look great and take
+advantage of the hardware capabilities available on each device. It
+automatically adapts your UI to look it's best on each device, while giving you
+as much control as you want over your UI on different device
+types. For example, you can create a single app binary that's optimized for
+both phone and tablet form factors. You declare your UI in lightweight sets of XML
+resources, one set for parts of the UI that are common to all form factors and
+other sets for optimzations specific to phones or tablets.
+At runtime, Android applies the correct resource sets based on its screen size,
+density, locale,
+and so on. To help you develop efficiently, the Android
+ Developer Tools
+offers a full Java IDE with advanced features for developing, debugging, and
+packaging Android apps. Using the IDE, you can develop on any available Android
+device or create virtual devices that emulate any hardware configuration. Google Play is the premier marketplace for selling and distributing Android apps.
+When you publish an app on Google Play, you reach the huge installed base of
+Android. As an open marketplace, Google Play puts you in control of how you sell your
+products. You can publish whenever you want, as often as you want, and to the
+customers you want. You can distribute broadly to all markets and
+devices or focus on specific segments, devices, or ranges of hardware
+capabilities. You can monetize in the way that works best for your business—priced or
+free, with in-app products or subscriptions—for highest engagement and
+revenues. You also have complete control of the pricing for your apps
+and in-app products and can set or change prices in any supported currency at
+any time.
+
+ Beyond growing your customer base, Google Play helps you build visibility and
+engagement across your apps and brand. As your apps rise in popularity, Google
+Play gives them higher placement in weekly "top" charts and rankings, and for
+the best apps promotional slots in curated collections.
+ Preinstalled on hundreds of millions of Android devices around the world,
+Google Play can be a growth engine for your business. Robot Invader chose
+ Android as the launch platform for their first game,
+ Wind-up
+ Knight.
+
+ Hear from the developers themselves how Android helped them reach more
+ than 100 devices with a single app binary, then iterate rapidly to ensure
+ a great experience for users.
+ Android offers an open distribution model, not a walled garden. Once you’ve developed an
+app for Android and want to distribute it, you have choice. Your final application is contained in an APK file that you can make available to users any
+way you want. For example, you can upload it to your own web site to allow visitors to
+install it onto their devices. More often, you’ll want to use a trusted
+marketplace where users can discover and search for your apps. How you choose to distribute your app affects precisely how many users your app will reach. Which
+distribution provider you choose also affects the kinds of services available to you as a publisher,
+such as licensing and in-app billing APIs, user bug reports, installation analytics, marketing
+services, and more. Among your choices is Google Play, the premier marketplace for selling and distributing apps
+to Android users around the world. When you publish an app on Google Play, you reach hundreds of
+millions of customers in over 130 countries. As an open marketplace, Google Play puts you in control of your business and makes it easy for
+you to manage how you sell your products. You can publish whenever you want, as often as you want,
+and to the exact set of customers you want. Beyond growing your customer base, Google Play helps you build visibility and engagement across
+your apps and brand. As your apps rise in popularity, Google Play gives you higher placement in
+weekly "top" lists and offers promotional slots in curated collections. You can engage customers
+using rich, colorful product pages that feature app screenshots, videos, and user reviews, as well
+as cross-marketing links to your other products. Google Play offers a choice of monetizing options to meet your business needs. You control the
+pricing of your apps and in-app products—you can set and change prices at any time, even
+individually in local currencies around the world. On purchase, Google Play handles transactions in
+the buyer’s currency and makes payouts in your own currency. After publishing, you can manage the distribution of your app. You can distribute broadly to all
+markets and devices or focus on specific segments, devices, or ranges of hardware capabilities.
+Google Play provides the tools for controlling distribution and ensures that your app is available
+only to the users who you are targeting. Everything you need to start developing apps for Android is available here on
+developer.android.com. You'll find everything from the developer SDK, API documentation, and design
+guidelines, to information about the current device landscape and how you can distribute and
+monetize your app. No two apps are built in the same way, but we've structured the information you need to build an
+app into the following three sections that represent the general order for app development.
+
+
+
+
+ Before you write a single line of code, you need to design the user interface and make it fit
+the Android user experience. Although you may know what a user will do with your app, you
+should pause to focus on how a user will interact with it. Your design should be sleek,
+simple, powereful, and tailored to the Android experience. So whether your a one-man shop or a large team, you should study the Design guidelines first. Once your design is finalized, all you need are the tools to turn your app ideas into reality.
+Android's framework provides you the APIs to build apps that take full advantage of
+device hardware, connected accessory devices, the Internet, software features, and more.
+With the power of Android, there's no limit to the power of your apps. Everything you need to learn about the app framework and developer tools is in the Develop documentation. Now your app is complete. You've built it to support a variety of screen sizes and
+densities, and tested it on the Android emulator and on real devices. You're ready to ship your app. How you proceed depends on a variety of factors, such as your monetization strategy and which
+types of devices your app supports. Everything you need to get started with this process is
+available in the Distribute section. Now that you know what's available, get started by installing the Android SDK.
+Date: February 2009 This document provides version notes for the Android 1.1 system image included in the SDK.
+
+Platform Versions
+
+Current Distribution
+
+
+
+
+
+
+
+Version
+ Codename
+ API Level
+ Distribution
+
+1.5 Cupcake 3 0.3%
+1.6 Donut 4 0.6%
+2.1 Eclair 7 5.2%
+2.2 Froyo 8 19.1%
+2.3 - 2.3.2
+ Gingerbread 9 0.4%
+2.3.3 - 2.3.7
+ 10 64.6%
+3.1
+ Honeycomb 12 0.7%
+3.2 13 2%
+4.0 - 4.0.2
+ Ice Cream Sandwich 14 0.4%
+4.0.3 - 4.0.4 15 6.7%
+
+
Historical Distribution
+
+
+
+
Screen Sizes and Densities
+
+
+
+
+
+
+
+
+
+
+
+ ldpi
+mdpi
+hdpi
+xhdpi
+
+small
+2.3%
+
+ 2.4%
+
+
+normal
+0.7%
+26.2%
+57.8%
+0.9%
+
+large
+0.3%
+2%
+
+
+
+xlarge
+
+ 7.4%
+
+
+
+
+
Open GL Version
+
+
+
+
+
+OpenGL ES Version
+Distribution
+
+
+1.1 only
+ 9.9%
+
+
+2.0 & 1.1
+ 90.1%
+
+
+
Android's flexible framework means it runs on more devices and reaches more
+users
+
+You're in control of which devices can install your app
+
+
+Global partnerships and large installed base
+
+Every day more than 900,000 new Android devices are activated worldwide.
+
+Powerful development framework
+
+Easily optimize a single binary for phones, tablets, and other devices.
+
+A billion downloads a month and growing. Get your apps in front
+of millions of users at Google's scale.
+
+Open marketplace for distributing your apps
+
+
+Developer Story: Robot Invader
+
+
Your business, your customers
+
+Google Play makes your apps available to your customers
+immediately
+
+Visibility for your apps
+
+Flexible monetizing and distribution
+
+You can distribute
+your apps free or priced and you can sell in-app products for additional revenue
+
+1. Design
+
+2. Develop
+3. Distribute
+
+API Level: 2
The Android 1.1 system image delivered in the SDK is the development +counterpart to the Android 1.1 production system image, deployable to +Android-powered handsets starting in February 2009.
+ +The Android 1.1 system image delivers an updated version of the framework +API. As with the Android 1.0 API, the Android 1.1 API +is assigned an integer identifier — 2 — that is +stored in the system itself. This identifier, called the "API Level", allows the +system to correctly determine whether an application is compatible with +the system, prior to installing the application.
+ +Applications indicate the lowest system API Level that they are compatible with by adding
+a value to the android:minSdkVersion attribute.
+The value of the attribute is an integer corresponding to an API Level
+identifier. Prior to installing an application, the system checks the value of
+android:minSdkVersion and allows the install only
+if the referenced integer is less than or equal to the API Level integer stored
+in the system itself.
If you use the Android 1.1 system image to build an application
+compatible with Android-powered devices running the Android 1.1
+platform, you must set the
+android:minSdkVersion attribute to "2" in order to specify that your application
+is compatible only with devices using the Android 1.1 (or greater) system image.
+
Specifically, you specify the android:minSdkVersion
+attribute in a <uses-sdk> element as a child of
+<manifest> in the manifest file. When set, the
+attribute looks like this:
<manifest>
+ ...
+ <uses-sdk android:minSdkVersion="2" />
+ ...
+</manifest>
+
+
+By setting android:minSdkVersion in this way, you ensure
+that users will only be able to install your application if their
+devices are running the Android 1.1 platform. In turn, this ensures that
+your application will function properly on their devices, especially if
+it uses APIs introduced in Android 1.1.
If your application uses APIs introduced in Android 1.1 but does not
+declare <uses-sdk android:minSdkVersion="2" />, then it will
+run properly on Android 1.1 devices but not on Android 1.0
+devices. In the latter case, the application will crash at runtime when
+it tries to use the Android 1.1 APIs.
If your application does not use any new APIs introduced in Android
+1.1, you can indicate Android 1.0 compatibility by removing
+android:minSdkVersion or setting the attribute to "1". However,
+before publishing your application, you must make sure to compile your
+application against the Android 1.0 system image (available in the
+Android 1.0 SDK), to ensure that it builds and functions properly for
+Android 1.0 devices. You should test the application against system
+images corresponding to the API Levels that the application is designed
+to be compatible with.
If you are sure your application is not using Android 1.1 APIs and +has no need to use them, you might find it easier to keep working in the +Android 1.0 SDK, rather than migrating to the Android 1.1 SDK and having +to do additional testing.
+ + +The system image includes these external libraries, which you can +access from your application by adding a +<uses-library>.
+The Android 1.1 system image was tested for compatability with the +Android-powered devices listed below:
+The system image includes these built-in applications:
+The system image provides localized UI strings for the languages +listed below.
+Localized UI strings match the locales that are displayable in +the emulator, accessible through the device Settings application.
+ +| Module or Feature | Change Description | +
|---|---|
| Annotations for test systems | |
| Added {@link android.test.suitebuilder.annotation.LargeTest LargeTest} annotation. | |
| Added {@link android.test.suitebuilder.annotation.MediumTest MediumTest} annotation. | |
| Added {@link android.test.suitebuilder.annotation.SmallTest SmallTest} annotation. | |
| Allow a process to easily know its UID. | |
| Added public method {@link android.os.Process#myUid} to class {@link android.os.Process android.os.Process} | |
| Padding in views | |
| Added public method {@link android.view.View#getBottomPaddingOffset} to class {@link android.view.View android.view.View}. | |
| Added public method {@link android.view.View#getLeftPaddingOffset} to class {@link android.view.View android.view.View}. | |
| Added public method {@link android.view.View#getRightPaddingOffset} to class {@link android.view.View android.view.View}. | |
| Added public method {@link android.view.View#getTopPaddingOffset} to class {@link android.view.View android.view.View}. | |
| Added public method {@link android.view.View#isPaddingOffsetRequired} to class {@link android.view.View android.view.View}. | |
| Marquee support | |
| Added public method {@link android.widget.TextView#setMarqueeRepeatLimit} to class {@link android.widget.TextView} | |
| Added public field {@link android.R.attr#marqueeRepeatLimit android.R.attr.marqueeRepeatLimit} | |
| New permissions | |
| Added public field {@link android.Manifest.permission#BROADCAST_SMS android.Manifest.permission.BROADCAST_SMS} | |
| Added public field {@link android.Manifest.permission#BROADCAST_WAP_PUSH android.Manifest.permission.BROADCAST_WAP_PUSH} | |
| API cleanup | |
| Removed protected constructor java.net.ServerSocket.ServerSocket(java.net.SocketImpl). |
+April 2009 +
+ + +The Android 1.5 platform introduces many new features for users and developers. +The list below provides an overview of the changes.
+ +Applications can now use a new element in their manifest files, <uses-
+configuration> to indicate to the Android system what hardware features
+they require in order to function properly. For example, an application might
+use the element to specify that it requires a physical keyboard or a particular
+navigation device, such as a trackball. Prior to installing the application, the
+Android system checks the attributes defined for the
+<uses-configuration> element and allows the installation to
+continue only if the required hardware is present.
+API Level: {@sdkPlatformApiLevel}
+ +Android {@sdkPlatformVersion} is a {@sdkPlatformMajorMinor} platform release +deployable to Android-powered handsets starting in May 2009. +The release includes new features for users and developers, as well as changes +in the Android framework API.
+ +For developers, the Android {@sdkPlatformVersion} platform is available as a +downloadable component for the Android SDK. The downloadable platform includes a +fully compliant Android library and system image, as well as a set of emulator +skins, sample applications, and more. The downloadable platform is fully +compliant and includes no external libraries.
+ +To get started developing or testing against the Android +{@sdkPlatformVersion} platform, use the Android SDK and AVD Manager tool to +download the platform into your Android 1.6 or later SDK. For more information, +see Exploring the +SDK.
+ + +For a list of new user features and platform highlights, see the Android +{@sdkPlatformVersion} Platform Highlights document.
+ +The sections below provide notes about successive releases of +the Android {@sdkPlatformVersion} platform component for the Android SDK, as denoted by +revision number. To determine what revision(s) of the Android +{@sdkPlatformVersion} platforms are installed in your SDK environment, refer to +the "Installed Packages" listing in the Android SDK and AVD Manager.
+ + + + +
+ Android 1.5, Revision 4 (May 2010)
+ Requires SDK Tools r6 or higher.
+
+ Android 1.5, Revision 3 (July 2009)
+ Requires SDK Tools r3 or higher.
+
+ Android 1.5, Revision 2 (May 2009)
+ Not available as an SDK component — please use Android 1.5, r3 instead.
+
+ Android 1.5, Revision 1 (April 2009)
+ Not available as an SDK component — please use Android 1.5, r3 instead.
+The Android {@sdkPlatformVersion} platform delivers an updated version of +the framework API. The Android {@sdkPlatformVersion} API +is assigned an integer identifier — +{@sdkPlatformApiLevel} — that is +stored in the system itself. This identifier, called the "API Level", allows the +system to correctly determine whether an application is compatible with +the system, prior to installing the application.
+ +To use APIs introduced in Android {@sdkPlatformVersion} in your
+application, you need to set the proper value, "{@sdkPlatformApiLevel}", in the
+android:minSdkVersion attributes of the <uses-sdk>
+element in your application's manifest.
For more information about how to use API Level, see the API Levels document.
+ + +The sections below provide information about the application framework API provided by the Android {@sdkPlatformVersion} platform.
+ +Applications can now use a new element in their manifest files, <uses-configuration>
+ to indicate to the Android system what hardware features
+they require in order to function properly. For example, an application might
+use the element to specify that it requires a physical keyboard or a particular
+navigation device, such as a trackball. Prior to installing the application, the
+Android system checks the attributes defined for the
+<uses-configuration> element and allows the installation to
+continue only if the required hardware is present.
For a detailed view of API changes in Android {@sdkPlatformVersion} (API Level {@sdkPlatformApiLevel}), as compared to +the previous version, see the API +Differences Report.
+ + +The system image included in the downloadable platform provides these +built-in applications:
+ +
+
|
+
+
|
+
The system image included in the downloadable platform provides a variety of +built-in locales. In some cases, region-specific strings are available for the +locales. In other cases, a default version of the language is used. The +languages that are available in the Android {@sdkPlatformVersion} system +image are listed below (with language_country/region +locale descriptor).
+ +
+
|
+
+ |
+
Localized UI strings match the locales that are accessible +through Settings.
+ +The downloadable platform includes a set of emulator skins that you can use for modeling your application in different screen sizes and resolutions. The emulator skins are:
+ +For more information about how to develop an application that displays and functions properly on all Android-powered devices, see Supporting Multiple Screens.
diff --git a/docs/html/about/versions/android-1.6-highlights.jd b/docs/html/about/versions/android-1.6-highlights.jd new file mode 100644 index 000000000000..2ee1d807029b --- /dev/null +++ b/docs/html/about/versions/android-1.6-highlights.jd @@ -0,0 +1,213 @@ +page.title=Android 1.6 Platform Highlights +sdk.date=September 2009 + +@jd:body + + + + +The Android 1.6 platform introduces new features for users and developers. +This page provides an overview of some new features and technologies.
+ + + + + +


Android 1.6 includes a redesigned search framework that provides a quick, +effective, and consistent way for users to search across multiple sources—such as +browser bookmarks & history, contacts, and the web—directly from +the home screen.
+ +The system constantly learns which search results are more relevant based on what is +clicked. So popular contacts or apps that have previously been picked will bubble up to +the top when a user types the first few letters of a relevant query.
+ +The search framework also provides developers a way to easily expose relevant +content from their applications in Quick Search Box.
+ +An updated user interface provides an integrated camera, camcorder, and gallery experience. +Users can quickly toggle between still and video capture modes. Additionally, the gallery +enables users to select multiple photos for deletion.
+ +Android 1.6 also provides a much faster camera experience. +Compared to the previous release, launching the camera is now 39% faster, +and there is a 28% improvement in the time from completing one shot to the next.
+ + +A new Virtual Private Network (VPN) control panel in Settings allows users +to configure and connect to the following types of VPNs:
+ +A new battery usage screen lets users see which apps and services are consuming +battery power. If the user determines that a particular service or application is +using too much power, they can take action to save the battery by +adjusting settings, stopping the application, or uninstalling the application.
+ + +Users will be able to download new accessibility services built +on the new accessibility framework and enable them in Settings.
+ + + + +
For devices with Google Play, the latest version improves the overall user experience and makes +it easier for users to discover great apps and games from developers.
+ +The Android search framework has been redesigned and expanded to provide +third-party applications the opportunity to surface +content from their applications in Quick Search Box, the global search tool. +To do this, developers will need to make their app "searchable" and provide +suggestions in response to user queries. +To enable application search suggestions, users simply select each application from which +they'd like to receive suggestions, under Searchable items in the Search settings.
+ + +Android 1.6 features a multi-lingual speech synthesis engine called Pico. +It allows any Android application to "speak" a string of text with an accent that matches the language. +The engine supports the following languages: English (American and British accents), French, +Italian, German and Spanish. If you're using a T-Mobile G1 or Dream device, you'll need to download the +SpeechSynthesis Data Installer from Google Play, which includes the "voices" needed by the +text-to-speech engine.
+ + +A new gestures framework provides application developers with a framework for creating, storing, +loading, and recognizing gestures and associating them with specific actions.
+ +Developers can use the new GestureBuilder tool included in the Android 1.6 SDK to generate libraries +of gestures to include with their application.
+ + +Android 1.6 provides a new accessibility framework. +With this framework, developers can create accessibility plugins that respond to user input, +such as making a sound when a new window is shown, vibrating when navigating to the top of +a list, and providing spoken feedback.
+ + +Android 1.6 adds screen support that enables applications to be rendered properly on different +display resolutions and densities. Developers can also specify the types of screens supported by their +application.
+ + +Android 1.6 includes support for CDMA in the telephony stack.
+ + +Android 1.6 includes the updated OpenCore 2 media engine, which has:
+ +Android 1.6 upgrades the Linux kernel from 2.6.27 to 2.6.29.
+ + +For a detailed overview of new APIs, see the +Version Notes. +For a complete report of all API changes, see the +API Differences Report. diff --git a/docs/html/about/versions/android-1.6.jd b/docs/html/about/versions/android-1.6.jd new file mode 100644 index 000000000000..2a66cd3e7e5a --- /dev/null +++ b/docs/html/about/versions/android-1.6.jd @@ -0,0 +1,505 @@ +page.title=Android 1.6 Platform +sdk.platform.version=1.6 +sdk.platform.apiLevel=4 +sdk.platform.majorMinor=minor + +@jd:body + +
+API Level: {@sdkPlatformApiLevel}
+ +Android {@sdkPlatformVersion} is a {@sdkPlatformMajorMinor} platform release +deployable to Android-powered handsets since October 2009. +The platform includes new features for users and developers, as well as changes +in the Android framework API.
+ +For developers, a new release of the Android {@sdkPlatformVersion} platform +is available as a downloadable component for the Android SDK. The platform +— Android 1.6 r2 — includes a fully compliant Android library and +system image, as well as a set of emulator skins, sample applications, and minor +development updates. The downloadable platform is fully compliant (API Level 4) +and includes no external libraries.
+ +To get started developing or testing against the Android +{@sdkPlatformVersion} platform, use the Android SDK and AVD Manager tool to +download the latest Android 1.6 platform into your Android 1.6 or later SDK. For +more information, see Exploring the +SDK.
+ + +For a list of new user features and platform highlights, see the Android +{@sdkPlatformVersion} Platform Highlights document.
+ + +The sections below provide notes about successive releases of +the Android {@sdkPlatformVersion} platform component for the Android SDK, as denoted by +revision number. To determine what revision(s) of the Android +{@sdkPlatformVersion} platforms are installed in your SDK environment, refer to +the "Installed Packages" listing in the Android SDK and AVD Manager.
+ + + + +
+ Android 1.6, Revision 3 (May 2010)
+ Requires SDK Tools r6 or higher.
+
+ Android 1.6, Revision 2 (December 2009)
+ Requires SDK Tools r4 or higher.
+android.telephony.TelephonyManager: DATA_ACTIVITY_DORMANT,
+PHONE_TYPE_CDMA, NETWORK_TYPE_CDMA,
+NETWORK_TYPE_EVDO_0, NETWORK_TYPE_EVDO_A, and
+NETWORK_TYPE_1xRTT.
+ Android 1.6, Revision 1 (September 2009)
+ Requires SDK Tools r3 or higher.
+The Android {@sdkPlatformVersion} platform delivers an updated version of +the framework API. The Android {@sdkPlatformVersion} API +is assigned an integer identifier — +{@sdkPlatformApiLevel} — that is +stored in the system itself. This identifier, called the "API Level", allows the +system to correctly determine whether an application is compatible with +the system, prior to installing the application.
+ +To use APIs introduced in Android {@sdkPlatformVersion} in your
+application, you need to set the proper value, "{@sdkPlatformApiLevel}", in the
+android:minSdkVersion attributes of the <uses-sdk>
+element in your application's manifest.
For more information about how to use API Level, see the API Levels document.
+ + +The sections below provide information about the application framework API provided by the Android {@sdkPlatformVersion} platform.
+ +AnticipateInterpolatorAnticipateOvershootInterpolatorBounceInterpolatorOvershootInterpolatorandroid:onClick to specify a View's
+View.OnClickListener
+from a layout file.
+ To use APIs introduced in Android {@sdkPlatformVersion} in your application, you need to
+set the proper value, "{@sdkPlatformApiLevel}", in the attributes of the <uses-sdk>
+element in your application's manifest.
<supports-screen> element, the system
+ displays the application in compatibility mode, which performs best-effort scaling
+ of the application UI to match the resolution and density of the screen.
+
+ The attributes available for defining an application's screen support are: + +
smallScreen: Boolean value that indicates whether the
+ application is designed to run on devices with small screens.
+ Examples: QVGA low density; VGA high density.
+ normalScreens: Boolean value that indicates whether
+ the application is designed to run on devices with normal screens.
+ Examples: WQVGA low density; HVGA medium density; WVGA high density.
+ largeScreens: Boolean value that indicates whether
+ the application is designed to run on devices with significantly
+ larger screens, such that special care may be required on
+ the application's part to make proper use of the screen area.
+ Examples: VGA medium density; WVGA medium density.
+ anyDensity: Boolean value that indicates whether
+ the application can accommodate any screen density.
+ resizable: Boolean value that indicates whether
+ the application can expand its layout to fit slightly larger screens.
+ name: The name of the feature required by the application. Currently accepts
+ "android.hardware.camera" and "android.hardware.camera.autofocus" values, which specify that a
+ camera and camera autofocus are required, respectively.glEsVersion: Indicates the minimum version of OpenGL ES required.targetSdkVersion: Indicates the API Level that the application is targeting.
+ It is able to run on older versions (down to minSdkVersion), but was explicitly tested to
+ work with the version specified here. Specifying this version allows the platform to
+ disable compatibility code that is not required or enable newer features that are not
+ available to older applications. maxSdkVersion: Indicates the maximum API Level on which an application is
+ designed to run. Important: Please read the <uses-sdk>
+ documentation before using this attribute. For a detailed view of API changes in Android {@sdkPlatformVersion} (API Level {@sdkPlatformApiLevel}), as compared to +the previous version, see the API +Differences Report.
+ +The system image included in the downloadable platform provides these +built-in applications:
+ +
+
|
+
+
|
+
The system image included in the downloadable platform provides a variety of +built-in locales. In some cases, region-specific strings are available for the +locales. In other cases, a default version of the language is used. The +languages that are available in the Android {@sdkPlatformVersion} system +image are listed below (with language_country/region +locale descriptor).
+ +
+
|
+
+ |
+
Localized UI strings match the locales that are accessible +through Settings.
+ +The downloadable platform includes a set of emulator skins that you can +use for modeling your application in different screen sizes and resolutions. +The emulator skins are:
+ +For more information about how to develop an application that displays and functions properly on all Android-powered devices, see Supporting Multiple Screens.
diff --git a/docs/html/about/versions/android-2.0-highlights.jd b/docs/html/about/versions/android-2.0-highlights.jd new file mode 100644 index 000000000000..2ba9ac76f6f9 --- /dev/null +++ b/docs/html/about/versions/android-2.0-highlights.jd @@ -0,0 +1,201 @@ +page.title=Android 2.0 Platform Highlights +sdk.date=October 2009 + +@jd:body + + + + +The Android 2.0 platform introduces many new and exciting features for +users and developers. This document provides a glimpse at some of the new features +and technologies in Android 2.0.
+ + + + + +




Revamped graphics architecture for improved performance that enables better +hardware acceleration.
+ + +Android 2.0 includes several new developer APIs. +For an overview of new APIs, see the +Android 2.0 version notes.
+ +For a complete report of all API changes, see the +API Differences Report.
+ + + diff --git a/docs/html/about/versions/android-2.0.1.jd b/docs/html/about/versions/android-2.0.1.jd new file mode 100644 index 000000000000..bcba7177b684 --- /dev/null +++ b/docs/html/about/versions/android-2.0.1.jd @@ -0,0 +1,361 @@ +page.title=Android 2.0.1, Release 1 +sdk.platform.version=2.0.1 +sdk.platform.apiLevel=6 +sdk.platform.majorMinor=minor + +@jd:body + ++ +API Level: {@sdkPlatformApiLevel}
+ +Android {@sdkPlatformVersion} is a {@sdkPlatformMajorMinor} platform release +deployable to Android-powered handsets starting in December 2009. +This release includes minor API +changes, bug fixes and framework behavioral changes. For information on changes +and fixes, see the Framework API section.
+ +For developers, the Android {@sdkPlatformVersion} platform is available as a +downloadable component for the Android SDK. The downloadable platform includes a +fully compliant Android library and system image, as well as a set of emulator +skins, sample applications, and more. The downloadable platform +includes no external libraries.
+ +To get started developing or testing against the Android +{@sdkPlatformVersion} platform, use the Android SDK and AVD Manager tool to +download the platform into your Android 1.6 or later SDK. For more information, +see Exploring the +SDK.
+ + +For a list of new user features and platform highlights, see the Android +2.0 Platform Highlights document.
+ +The sections below provide notes about successive releases of +the Android {@sdkPlatformVersion} platform component for the Android SDK, as denoted by +revision number. To determine what revision(s) of the Android +{@sdkPlatformVersion} platforms are installed in your SDK environment, refer to +the "Installed Packages" listing in the Android SDK and AVD Manager.
+ + + + +
+ Android 2.0.1, Revision 1 (December 2009)
+ Requires SDK Tools r4 or higher.
+The system image included in the downloadable platform provides these +built-in applications:
+ +
+
|
+
+
|
+
New with 2.0.1 The Dev Tools app now +includes a "Sync Tester" application to provide quick and easy testing of +third-party sync adapters.
+ +The system image included in the downloadable platform provides a variety of +built-in locales. In some cases, region-specific strings are available for the +locales. In other cases, a default version of the language is used. The +languages that are available in the Android {@sdkPlatformVersion} system +image are listed below (with language_country/region locale +descriptor).
+ +
+
|
+
+ |
+
Localized UI strings match the locales that are accessible +through Settings.
+ +The downloadable platform includes a set of emulator skins that you can use for modeling your application in different screen sizes and resolutions. The emulator skins are:
+ +For more information about how to develop an application that displays and functions properly on all Android-powered devices, see Supporting Multiple Screens.
+ +The sections below provide information about new developer features offered by the downloadable Android 2.0 platform component.
+ +zipalign optimization. For more information, see Signing Your Applications.The sections below provide information about changes made to the application +framework API provided by the Android {@sdkPlatformVersion} platform. Note, +however, that Android 2.0.1 is a minor release to Android 2.0, so for more +information about the changes made to in Android 2.0, please refer to the +Android 2.0 version notes.
+ + +The Android {@sdkPlatformVersion} platform delivers an updated version of the framework +API. The Android {@sdkPlatformVersion} API +is assigned an integer identifier — {@sdkPlatformApiLevel} — that is +stored in the system itself. This identifier, called the "API Level", allows the +system to correctly determine whether an application is compatible with +the system, prior to installing the application.
+ +To use APIs introduced in Android {@sdkPlatformVersion} in your application, you need to
+set the proper value, "{@sdkPlatformApiLevel}", in the attributes of the <uses-sdk>
+element in your application's manifest.
For more information about how to use API Level, see the API Levels document.
+ + +The following is a summary of changes to the framework APIs.
+ +The following is a summary of changes that affect the behavior of some +framework APIs but do not add or remove API functionality.
+ +Changes to the values returned by {@link +android.bluetooth.BluetoothAdapter#ACTION_REQUEST_ENABLE} and +{@link android.bluetooth.BluetoothAdapter#ACTION_REQUEST_DISCOVERABLE}:
+ +The {@link android.content.Intent#ACTION_INSERT} Intent now returns {@link +android.app.Activity#RESULT_CANCELED} in cases where the contact was not +persisted (for example, if the save was trimmed to a no-op).
+ + +The following is a summary of bug fixes that affect some framework APIs.
+ +The framework now correctly selects application resources in project +folders that use the API Level qualifier. For example, {@code drawable-v4/} is a +folder of drawable resources for API Level 4 (or higher) devices. This version +matching did not work properly and has been fixed.
+ +The {@link android.content.Intent#ACTION_INSERT} Intent now returns the +appropriate kind of URI when the request is made using the (now +deprecated) {@link android.provider.Contacts} APIs.
+ +For a detailed view of API changes in Android {@sdkPlatformVersion} (API Level {@sdkPlatformApiLevel}), as compared to +API Level 5, see the API +Differences Report. There are very few API changes in API Level 6, +so you might also be interested in reviewing the API +differences between 4 and 5.
+ diff --git a/docs/html/about/versions/android-2.0.jd b/docs/html/about/versions/android-2.0.jd new file mode 100644 index 000000000000..7a12e48672e3 --- /dev/null +++ b/docs/html/about/versions/android-2.0.jd @@ -0,0 +1,384 @@ +page.title=Android 2.0, Release 1 +sdk.platform.version=2.0 +sdk.platform.apiLevel=5 +sdk.platform.majorMinor=major + +@jd:body + ++API Level: {@sdkPlatformApiLevel}
+ +Android {@sdkPlatformVersion} is a {@sdkPlatformMajorMinor} platform release +deployable to Android-powered handsets starting in November 2009. +The release includes new features for users and developers, as well as changes +in the Android framework API.
+ +For developers, the Android {@sdkPlatformVersion} platform is available as a +downloadable component for the Android SDK. The downloadable platform includes a +fully compliant Android library and system image, as well as a set of emulator +skins, sample applications, and more. The downloadable platform is fully +compliant and includes no external libraries.
+ +To get started developing or testing against the Android +{@sdkPlatformVersion} platform, use the Android SDK and AVD Manager tool to +download the platform into your SDK. For more information, +see Exploring the +SDK.
+ + +For a list of new user features and platform highlights, see the Android +{@sdkPlatformVersion} Platform Highlights document.
+ +The sections below provide notes about successive releases of +the Android {@sdkPlatformVersion} platform component for the Android SDK, as denoted by +revision number. To determine what revision(s) of the Android +{@sdkPlatformVersion} platforms are installed in your SDK environment, refer to +the "Installed Packages" listing in the Android SDK and AVD Manager.
+ + + + +
+ Android 2.0, Revision 1 (October 2009)
+ Requires SDK Tools r3 or higher.
+The system image included in the downloadable platform provides these +built-in applications:
+ +
+
|
+
+
|
+
The system image included in the downloadable platform provides a variety of +built-in locales. In some cases, region-specific strings are available for the +locales. In other cases, a default version of the language is used. The +languages that are available in the Android {@sdkPlatformVersion} system +image are listed below (with language_country/region locale +descriptor).
+ +
+
|
+
+ |
+
Localized UI strings match the locales that are accessible +through Settings.
+ +The downloadable platform includes a set of emulator skins that you can use for modeling your application in different screen sizes and resolutions. The emulator skins are:
+ +For more information about how to develop an application that displays and functions properly on all Android-powered devices, see Supporting Multiple Screens.
+ +The sections below provide information about new developer features offered by the downloadable Android 2.0 platform component.
+ +zipalign optimization. For more information, see Signing Your Applications.The sections below provide information about the application framework API provided by the Android {@sdkPlatformVersion} platform.
+ + +The Android {@sdkPlatformVersion} platform delivers an updated version of the framework +API. As with previous versions, the Android {@sdkPlatformVersion} API +is assigned an integer identifier — {@sdkPlatformApiLevel} — that is +stored in the system itself. This identifier, called the "API Level", allows the +system to correctly determine whether an application is compatible with +the system, prior to installing the application.
+ +To use APIs introduced in Android {@sdkPlatformVersion} in your application, you need to
+set the proper value, "{@sdkPlatformApiLevel}", in the attributes of the <uses-sdk>
+element in your application's manifest.
For more information about how to use API Level, see the API Levels document.
+ + +Android 2.0 is designed to run on devices that use virtual keys for HOME, +MENU, BACK, and SEARCH, rather than physical keys. To support the best user +experience on those devices, the Android platform now executes these buttons at +key-up, for a key-down/key-up pair, rather than key-down. This helps prevent +accidental button events and lets the user press the button area and then drag +out of it without generating an event.
+ +This change in behavior should only affect your application if it is +intercepting button events and taking an action on key-down, rather than on +key-up. Especially if your application is intercepting the BACK key, you should +make sure that your application is handling the key events properly.
+ +In general, intercepting the BACK key in an application is not recommended, +however, if your application is doing so and it invokes some action on +key-down, rather than key-up, you should modify your code.
+ +If your application will use APIs introduced in Android 2.0 (API Level 5), +you can take advantage of new APIs for managing key-event pairs:
+ + public boolean onKeyDown(int keyCode, KeyEvent event) {
+ if (keyCode == KeyEvent.KEYCODE_BACK
+ && event.getRepeatCount() == 0) {
+ event.startTracking();
+ return true;
+ }
+ return super.onKeyDown(keyCode, event);
+ }
+
+ public boolean onKeyUp(int keyCode, KeyEvent event) {
+ if (keyCode == KeyEvent.KEYCODE_BACK && event.isTracking()
+ && !event.isCanceled()) {
+ // *** DO ACTION HERE ***
+ return true;
+ }
+ return super.onKeyUp(keyCode, event);
+ }
+
+
+
+If you want to update a legacy application so that its handling of the BACK +key works properly for both Android 2.0 and older platform versions, you +can use an approach similar to that shown above. Your code can catch the +target button event on key-down, set a flag to track the key event, and +then also catch the event on key-up, executing the desired action if the tracking +flag is set. You'll also want to watch for focus changes and clear the tracking +flag when gaining/losing focus.
+ +For a detailed view of API changes in Android {@sdkPlatformVersion} (API Level {@sdkPlatformApiLevel}), as compared to +the previous version, see the API Differences Report.
+ diff --git a/docs/html/about/versions/android-2.1.jd b/docs/html/about/versions/android-2.1.jd new file mode 100644 index 000000000000..3cb0708ec42a --- /dev/null +++ b/docs/html/about/versions/android-2.1.jd @@ -0,0 +1,373 @@ +page.title=Android 2.1 Platform +sdk.platform.version=2.1 +sdk.platform.apiLevel=7 +sdk.platform.majorMinor=minor + +@jd:body + ++API Level: {@sdkPlatformApiLevel}
+ +Android {@sdkPlatformVersion} is a {@sdkPlatformMajorMinor} platform release +deployable to Android-powered handsets starting in January 2010. +This release includes new API +changes and bug fixes. For information on changes, see the Framework API +section.
+ +For developers, the Android {@sdkPlatformVersion} platform is available as a +downloadable component for the Android SDK. The downloadable platform includes a +fully compliant Android library and system image, as well as a set of emulator +skins, sample applications, and more. The downloadable platform +includes no external libraries.
+ +To get started developing or testing against the Android +{@sdkPlatformVersion} platform, use the Android SDK and AVD Manager tool to +download the platform into your SDK. For more information, +see Exploring the +SDK.
+ + +Android {@sdkPlatformVersion} does not add significant user features, see the Android +2.0 Platform Highlights document for the latest user features.
+ +The sections below provide notes about successive releases of +the Android {@sdkPlatformVersion} platform component for the Android SDK, as denoted by +revision number. To determine what revision(s) of the Android +{@sdkPlatformVersion} platforms are installed in your SDK environment, refer to +the "Installed Packages" listing in the Android SDK and AVD Manager.
+ + +
+
+ Android {@sdkPlatformVersion}, Revision 3 (July 2011)
+
Requires SDK Tools r12 or +higher.
+Improvements to the platform's rendering library to support the visual layout editor in the ADT +Eclipse plugin. This revision allows for more drawing features in ADT and fixes several +bugs in the previous rendering library. It also unlocks several editor features that were added in +ADT 12.
+
+
+ Android {@sdkPlatformVersion}, Revision 2 (May 2010)
+
Requires SDK Tools r6 or higher.
+
+
+ Android {@sdkPlatformVersion}, Revision 1 (January 2010)
+
Requires SDK Tools r4 or higher.
+The Android {@sdkPlatformVersion} platform delivers an updated version of +the framework API. The Android {@sdkPlatformVersion} API +is assigned an integer identifier — +{@sdkPlatformApiLevel} — that is +stored in the system itself. This identifier, called the "API Level", allows the +system to correctly determine whether an application is compatible with +the system, prior to installing the application.
+ +To use APIs introduced in Android {@sdkPlatformVersion} in your
+application, you need to set the proper value, "{@sdkPlatformApiLevel}", in the
+android:minSdkVersion attributes of the <uses-sdk>
+element in your application's manifest.
For more information about how to use API Level, see the API Levels document.
+ + +The sections below provide information about changes made to the application +framework API provided by the Android {@sdkPlatformVersion} platform.
+ +The following additions provide APIs for you to develop animated wallpapers:
+Additionally, if your application uses or provides Live Wallpapers, you must
+remember to add a <uses-feature>
+ element to the application's manifest, declaring the attribute
+android:name="android.software.live_wallpaper". For example:
+<uses-feature android:name="android.software.live_wallpaper" /> ++ +
When you've published your application, Google Play checks for the +presence of this element and uses it as a filter, ensuring that your application +is not made available to users whose devices do not support Live Wallpapers. +
+ +For a detailed view of all API changes in Android {@sdkPlatformVersion} (API +Level {@sdkPlatformApiLevel}), as compared to API Level 6, see the API +Differences Report.
+ +The system image included in the downloadable platform provides these +built-in applications:
+ +
+
|
+
+
|
+
The system image included in the downloadable platform provides a variety of +built-in locales. In some cases, region-specific strings are available for the +locales. In other cases, a default version of the language is used. The +languages that are available in the Android {@sdkPlatformVersion} system +image are listed below (with language_country/region locale +descriptor).
+ +
+
|
+
+ |
+
Localized UI strings match the locales that are accessible +through Settings.
+ +The downloadable platform includes a set of emulator skins that you can use +for modeling your application in different screen sizes and resolutions. The +emulator skins are:
+ +For more information about how to develop an application that displays +and functions properly on all Android-powered devices, see Supporting Multiple +Screens.
diff --git a/docs/html/about/versions/android-2.2-highlights.jd b/docs/html/about/versions/android-2.2-highlights.jd new file mode 100644 index 000000000000..37a20d506512 --- /dev/null +++ b/docs/html/about/versions/android-2.2-highlights.jd @@ -0,0 +1,298 @@ +page.title=Android 2.2 Platform Highlights + +@jd:body + + + + + +The Android 2.2 platform introduces many new and exciting features for +users and developers. This document provides a glimpse at some of the new user features +and technologies in Android 2.2. For more information about the new developer APIs, see the Android 2.2 version notes.
+ + + + + +
+
+ |
+
+ New Home screen tips widget assists new users on +how to configure the +home screen with shortcuts and widgets and how to make use of multiple home screens. +The Phone, applications Launcher, and Browser now have dedicated +shortcuts on the Home screen, making it easy to access them from any of the 5 home screen +panels. + |
+
|
+ Improved security with the addition of numeric pin or alpha-numeric +password options to unlock device. Exchange administrators can enforce password policy across +devices. +Remote wipe: Exchange administrators can remotely reset the device to +factory defaults to secure data in case device is lost or stolen. +Exchange Calendars are now supported in the Calendar application. +Auto-discovery: you just need to know your user-name and password to +easily set up and sync an Exchange account (available for Exchange 2007 and higher). +Global Address Lists look-up is now available in the Email +application, enabling users to auto-complete recipient names from the directory. + |
+
+
+ |
+
+
+ |
+
+ Gallery allows you to peek into picture stacks using a zoom +gesture. +Camera onscreen buttons provide easy access to a new UI for +controling zoom, flash, white balance, geo-tagging, focus and exposure. Camcorder also provides +an easy way to set video size/quality for MMS and YouTube. +With the LED flash now enabled for the Camcorder, videos can be shot +at night or in low light settings. + |
+
|
+ Certain devices like the Nexus One can be turned into a portable Wi-Fi +hotspot that can be shared with up to 8 devices. +You can use your Android-powered phone as a 3G connection for a Windows or Linux laptop by +connecting their phone to the computer with a USB cable. The connection is then shared between the +two devices. + |
+
+
+ |
+
+
+ |
+
+ Multi-lingual users can add multiple languages to the keyboard and switch +between multiple Latin-based input languages by swiping across the space bar. This changes +the keys as well as the auto-suggest dictionary. + |
+
|
+ Performance of the browser has been enhanced using the V8 engine, +which enables faster loading of JavaScript-heavy pages. +Dalvik Performance Boost: 2x-5x performance speedup for CPU-heavy code +over Android 2.1 with Dalvik JIT. +The graph to the right shows the performance speedup from Android 2.1 +to Android 2.2 using various benchmark tests. For example, LinPack is now more than 5 times +faster. +Kernel Memory Management Boost: Improved memory reclaim by up to 20x, +which results in faster app switching and smoother performance on memory-constrained devices. + |
+
+
+ |
+
Apps can utilize Android Cloud to Device Messaging to enable mobile alert, send to phone, and +two-way push sync functionality.
+ + +New bug reporting feature for Google Play apps enables developers to receive crash and freeze +reports from their users. The reports will be available when they log into their publisher +account.
+ + + + +Applications can now request installation on the shared external storage (such as an SD +card).
+ + +Provides new APIs for audio focus, routing audio to SCO, and auto-scan of files to media +database. Also provides APIs to let applications detect completion of sound loading and auto-pause +and auto-resume audio playback.
+ + +New preview API doubles the frame rate from ~10FPS to ~20FPS. Camera now supports portrait +orientation, zoom controls, access to exposure data, and a thumbnail utility. A new camcorder +profile enables apps to determine device hardware capablities.
+ + +New APIs for OpenGL ES 2.0, working with YUV image format, and ETC1 for texture +compression.
+ + +Apps can participate in data backup and restore, to ensure that users maintain their data +after performing a factory reset or when switching devices.
+ + +New device policy management APIs allow developers to write "device administrator" applications +that can control security features on the device, such as the minimum password strength, data wipe, +and so on. Users can select the administrators that are enabled on their devices.
+ + +New "car mode" and "night mode" controls and configurations allow applications to adjust their UI +for these situations. A scale gesture detector API provides improved definition of multi-touch +events. Applications can now customize the bottom strip of a TabWidget.
+ + + +For more information about the new developer APIs, see the Android 2.2 version notes and the API Differences Report.
+ + + + + diff --git a/docs/html/about/versions/android-2.2.jd b/docs/html/about/versions/android-2.2.jd new file mode 100644 index 000000000000..361e8b695d55 --- /dev/null +++ b/docs/html/about/versions/android-2.2.jd @@ -0,0 +1,252 @@ +page.title=Android 2.2 Platform +sdk.platform.version=2.2 +sdk.platform.apiLevel=8 +sdk.platform.majorMinor=minor + +@jd:body + ++API Level: {@sdkPlatformApiLevel}
+ +Android {@sdkPlatformVersion} is a {@sdkPlatformMajorMinor} platform release including user +features, developer features, API changes, and bug +fixes. For information on developer features and API changes, see the +Framework API section.
+ +For developers, the Android {@sdkPlatformVersion} platform is available as a +downloadable component for the Android SDK. The downloadable platform includes +an Android library and system image, as well as a set of emulator skins and +more. To get started developing or testing against Android {@sdkPlatformVersion}, +use the Android SDK Manager to download the platform into your SDK.
+ + +For a list of new user features and platform highlights, see the Android +2.2 Platform Highlights document.
+ + +The Android {@sdkPlatformVersion} platform delivers an updated version of +the framework API. The Android {@sdkPlatformVersion} API +is assigned an integer identifier — +{@sdkPlatformApiLevel} — that is +stored in the system itself. This identifier, called the "API Level", allows the +system to correctly determine whether an application is compatible with +the system, prior to installing the application.
+ +To use APIs introduced in Android {@sdkPlatformVersion} in your
+application, you need to set the proper value, "{@sdkPlatformApiLevel}", in the
+android:minSdkVersion attributes of the <uses-sdk>
+element in your application's manifest.
For more information about how to use API Level, see the API Levels document.
+ + +The sections below provide information about changes made to the application +framework API provided by the Android {@sdkPlatformVersion} platform.
+ +The Android platform now allows applications to request installation onto the +device's external storage media (such as the SD card), as an alternative to +installation onto the device's internal memory.
+ +Application developers can express the preferred installation location for
+their applications by means of a new attribute of <manifest>
+in the manifest file,
+android:installLocation. The attribute supports three values:
+"internalOnly", "preferExternal", and
+"auto". At install time, the system checks the value of
+android:installLocation and installs the application
+.apk according to the preferred location, if possible. If the
+application has requested external installation, the system installs it into a
+private, encrypted partition in the external media. Once an application .apk is
+installed externally, the system lets the user change the storage location of
+the .apk and move it onto the device's internal memory if needed (and vice
+versa), through Manage Applications in the user settings.
By default, the system installs all applications onto the device's internal
+memory, except for those that explicitly request external installation. This
+means that the system will always install legacy applications onto internal
+memory, since they do not have access to the
+android:installLocation attribute. However, it is possible to
+configure and compile a legacy application such that it is installed internally
+on older versions of the platform and externally on Android 2.2 and later
+platforms, if necessary.
Note that requesting installation onto the device's external media is not +suitable for all applications, particularly because the external media may be +removable and unmounting/remounting may disrupt the user experience and system +settings.
+ +For more information about setting a preferred install location for your +application, including a discussion of what types of applications should and +should not request external installation, please read the App Install Location +document.
+ +The platform now provides a generalized backup service that +applications can use to backup and restore user data, to ensure that users can +maintain their data when switching devices or reinstalling the application. The +Backup Manager handles the work of transporting the application data to and from +the backup storage area in the cloud. The Backup Manager can store any type of +data, from arbitrary data to files, and manages backup and restore operations +in an atomic manner. For more information, see Data Backup.
+ +New device policy management APIs allow developers to write "device +administrator" applications that can control security features of the device, +such as the minimum password strength, data wipe, and so on. Users can select +the administrators that are enabled on their devices. For more information, see +the {@link android.app.admin android.app.admin} classees or the example +application code in DeviceAdminSample.java.
+ +fill_parent is renamed to match_parent. This affects both XML and Java code (see {@link android.view.ViewGroup.LayoutParams}). Note that the platform will continue to honor uses of fill_parent in legacy applications. android:installLocation attribute of the <manifest> element. Specifies the default install location defined by an application.android:backupAgent attribute of the
+<application> element. Specifies the component name of the
+BackupAgent subclass provided by the application to handle backup/restore
+operations, if any.android:restoreAnyVersion attribute of the
+<application> element. Boolean value that indicates whether
+the application is prepared to attempt a restore of any backed-up dataset, even
+if the backup is apparently from a newer version of the application than is
+currently installed on the device.android:vmSafeMode attribute of the <application> element. Boolean value that specifies whether to disable JIT compiler optimizations when running the application.android.permission.BIND_DEVICE_ADMIN — Any device administration broadcast receiver must require this permission, to ensure that only the system can interact with it.android.permission.KILL_BACKGROUND_PROCESSES — Allows an application to call {@link android.app.ActivityManager#killBackgroundProcesses(String)}.
+android.permission.BIND_WALLPAPER — Any {@link android.service.wallpaper.WallpaperService} must require this permission, to ensure that only the system can interact with it.android.permission.SET_TIME — Allows an application to set the system time.For a detailed view of all API changes in Android {@sdkPlatformVersion} (API +Level {@sdkPlatformApiLevel}), see the API +Differences Report.
+ + + diff --git a/docs/html/about/versions/android-2.3-highlights.jd b/docs/html/about/versions/android-2.3-highlights.jd new file mode 100644 index 000000000000..582bce9f81fd --- /dev/null +++ b/docs/html/about/versions/android-2.3-highlights.jd @@ -0,0 +1,444 @@ +page.title=Gingerbread + +@jd:body + + + + +The Android 2.3 platform introduces many new and exciting features for +users and developers. This document provides a glimpse at some of the new features +and technologies in Android 2.3. For detailed information about the new developer APIs, see the Android 2.3 version notes.
+ + + + +The user interface is refined in many ways across the system, making it +easier to learn, faster to use, and more power-efficient. A simplified +visual theme of colors against black brings vividness and contrast to the +notification bar, menus, and other parts of the UI. Changes in menus and +settings make it easier for the user to navigate and control the features +of the system and device.
+ +The Android soft keyboard is redesigned and optimized for faster text input +and editing. The keys themselves are reshaped and repositioned for improved +targeting, making them easier to see and press accurately, even at high speeds. +The keyboard also displays the current character and dictionary suggestions in a +larger, more vivid style that is easier to read.
+ +The keyboard adds the capability to correct entered words from suggestions in +the dictionary. As the user selects a word already entered, the keyboard +displays suggestions that the user can choose from, to replace the selection. +The user can also switch to voice input mode to replace the selection. Smart +suggestions let the user accept a suggestion and then return to correct it +later, if needed, from the original set of suggestions.
+ +New multitouch key-chording lets the user quickly enter numbers and symbols +by pressing Shift+<letter> and ?123+<symbol>, +without needing to manually switch input modes. From certain keys, users can +also access a popup menu of accented characters, numbers, and symbols by holding +the key and sliding to select a character.
+

When entering text or viewing a web page, the user can quickly select a word +by press-hold, then copy to the clipboard and paste. Pressing on a word enters a +free-selection mode — the user can adjust the selection area as needed by +dragging a set of bounding arrows to new positions, then copy the bounded area +by pressing anywhere in the selection area. For text entry, the user can +slide-press to enter a cursor mode, then reposition the cursor easily and +accurately by dragging the cursor arrow. With both the selection and cursor +modes, no use of a trackball is needed.
+ +The Android system takes a more active role in managing apps that are keeping +the device awake for too long or that are consuming CPU while running in the +background. By managing such apps — closing them if appropriate — +the system helps ensure best possible performance and maximum battery life.
+ +The system also gives the user more visibility over the power being consumed +by system components and running apps. The Application settings provides an +accurate overview of how the battery is being used, with details of the usage +and relative power consumed by each component or application.
+ +A shortcut to the Manage Applications control now appears in the Options Menu +in the Home screen and Launcher, making it much easier to check and manage +application activity. Once the user enters Manage Applications, a new Running +tab displays a list of active applications and the storage and memory being used +by each. The user can read further details about each application and if +necessary stop an application or report feedback to its developer.
+An updated set of standard applications lets the user take new approaches to +managing information and relationships.
+ +
+Internet calling
+ +The user can make voice calls over the internet to other users who have SIP +accounts. The user can add an internet calling number (a SIP address) to any +Contact and can initiate a call from Quick Contact or Dialer. To use internet +calling, the user must create an account at the SIP provider of their choice +— SIP accounts are not provided as part of the internet calling feature. +Additionally, support for the platform's SIP and internet calling features on +specific devices is determined by their manufacturers and associated carriers. +
+ +Near-field communications
+ +An NFC Reader application lets the user read and interact with near-field +communication (NFC) tags. For example, the user can “touch” or “swipe” an NFC +tag that might be embedded in a poster, sticker, or advertisement, then act on +the data read from the tag. A typical use would be to read a tag at a +restaurant, store, or event and then rate or register by jumping to a web site +whose URL is included in the tag data. NFC communication relies on wireless +technology in the device hardware, so support for the platform's NFC features on +specific devices is determined by their manufacturers. +
+Downloads management
+ +The Downloads application gives the user easy access to any file downloaded from +the browser, email, or another application. Downloads is built on an completely new +download manager facility in the system that any other applications can use, to +more easily manage and store their downloads.
+ +Camera
+ +The application now lets the user access multiple cameras on the device, +including a front-facing camera, if available.
+ + +Android 2.3 delivers a variety of features and APIs that +let developers bring new types of applications to the Android +platform.
+ + + +Performance
+ +Android 2.3 includes a variety of improvements across the system that make +common operations faster and more efficient for all applications. Of particular +interest to game developers are:
+ +Native input and +sensor events
+ +Applications that use native code can now receive and process input and +sensor events directly in their native code, which dramatically improves +efficiency and responsiveness.
+ +Native libraries exposed by the platform let applications handle the same +types of input events as those available through the framework. Applications +can receive events from all supported sensor types and can enable/disable +specific sensors and manage event delivery rate and queueing.
+ + +Gyroscope and other +new sensors, for improved 3D motion processing
+ +Android 2.3 adds API support for several new sensor types, including +gyroscope, rotation vector, linear acceleration, gravity, and barometer sensors. +Applications can use the new sensors in combination with any other sensors +available on the device, to track three-dimensional device motion and +orientation change with high precision and accuracy. For example, a game +application could use readings from a gyroscope and accelerometer on the device +to recognize complex user gestures and motions, such as tilt, spin, thrust, and +slice.
+ + +Open API for native +audio
+ +The platform provides a software implementation of Khronos OpenSL ES, a standard API +that gives applications access to powerful audio controls and effects from +native code. Applications can use the API to manage audio devices and control +audio input, output, and processing directly from native code.
+ +Native graphics +management
+ +The platform provides an interface to its Khronos EGL library, which lets +applications manage graphics contexts and create and manage OpenGL ES textures +and surfaces from native code.
+ + +Native access to +Activity lifecycle, window management
+ +Native applications can declare a new type of Activity class,
+NativeActivity whose lifecycle callbacks are implemented directly
+in native code. The NativeActivity and its underlying native code
+run in the system just as do other Activities — they run in the
+application's system process and execute on the application's main UI thread,
+and they receive the same lifecycle callbacks as do other Activities.
The platform also exposes native APIs for managing windows, including the +ability to lock/unlock the pixel buffer to draw directly into it. Through the +API, applications can obtain a native window object associated with a framework +Surface object and interact with it directly in native code.
+ + +Native access to +assets, storage
+ +Applications can now access a native Asset Manager API to retrieve
+application assets directly from native code without needing to go through JNI.
+If the assets are compressed, the platform does streaming decompression as the
+application reads the asset data. There is no longer a limit on the size of
+compressed .apk assets that can be read.
Additionally, applications can access a native Storage Manager API to work +directly with OBB files downloaded and managed by the system. Note that although +platform support for OBB is available in Android 2.3, development tools for +creating and managing OBB files will not be available until early 2011.
+ + +Robust native +development environment
+ +The Android NDK (r5 or higher) provides a complete set of tools, toolchains, +and libraries for developing applications that use the rich native environment +offered by the Android 2.3 platform. For more information or to download the +NDK, please see the Android NDK +page.
+ + +Internet +telephony
+ +Developers can now add SIP-based internet telephony features to their +applications. Android 2.3 includes a full SIP protocol stack and integrated call +management services that let applications easily set up outgoing and incoming +voice calls, without having to manage sessions, transport-level communication, +or audio record or playback directly.
+ +Support for the platform's SIP and internet calling features on specific +devices is determined by their manufacturers and associated carriers.
+ + +Near Field +Communications (NFC)
+ +The platform's support for Near Field Communications (NFC) lets developers +get started creating a whole new class of applications for Android. Developers +can create new applications that offer proximity-based information and services +to users, organizations, merchants, and advertisers.
+ +Using the NFC API, +applications can read and respond to NFC tags “discovered” as the user “touches” an +NFC-enabled device to elements embedded in stickers, smart posters, and even +other devices. When a tag of interest is collected, applications can respond to +the tag, read messages from it, and then store the messages, prompting +the user as needed.
+ +Starting from Android 2.3.3, applications can also write to tags and +set up peer-to-peer connections with other NFC devices.
+ +NFC communication relies on wireless technology in the device hardware, so +support for the platform's NFC features on specific devices is determined by +their manufacturers.
+ + +Mixable audio +effects
+ +A new audio effects API lets developers easily create rich audio environments +by adding equalization, bass boost, headphone virtualization (widened +soundstage), and reverb to audio tracks and sounds. Developers can mix multiple +audio effects in a local track or apply effects globally, across multiple +tracks.
+ +Support for new media +formats
+ +The platform now offers built-in support for the VP8 open video compression +format and the WebM open container format. The platform also adds support for +AAC encoding and AMR wideband encoding (in software), so that applications can +capture higher quality audio than narrowband.
+ +Access to multiple +cameras
+ +The Camera API now lets developers access any cameras that are available on a +device, including a front-facing camera. Applications can query the platform for +the number of cameras on the device and their types and characteristics, then +open the camera needed. For example, a video chat application might want to access a +front-facing camera that offers lower-resolution, while a photo application +might prefer a back-facing camera that offers higher-resolution.
+ + +For more information about the new developer APIs, see the Android 2.3 version notes and the API Differences Report.
diff --git a/docs/html/about/versions/android-2.3.3.jd b/docs/html/about/versions/android-2.3.3.jd new file mode 100644 index 000000000000..55ff346ac242 --- /dev/null +++ b/docs/html/about/versions/android-2.3.3.jd @@ -0,0 +1,192 @@ +page.title=Android 2.3.3 Platform +sdk.platform.version=2.3.3 +sdk.platform.apiLevel=10 + + +@jd:body + ++API Level: {@sdkPlatformApiLevel}
+ +Android 2.3.3 is a small feature release that adds several improvements +and APIs to the Android 2.3 platform.
+ +For developers, the Android {@sdkPlatformVersion} platform is available as a +downloadable component for the Android SDK. The downloadable platform includes +an Android library and system image, as well as a set of emulator skins and +more. To get started developing or testing against Android {@sdkPlatformVersion}, +use the Android SDK Manager to download the platform into your SDK.
+ + + +The sections below provide a technical overview of what's new for developers +in {@sdkPlatformVersion}, including new features and changes in the framework +API since the previous version.
+ +Android 2.3.3 provides improved and extended support for NFC, to allow +applications to interact with more types of tags in new ways.
+ +A new, comprehensive set of APIs give applications read and write access +to a wider range of standard tag technologies, including:
+ +The platform also provides a limited peer-to-peer communication protocol +and API. Foreground Activities can use the API to register an NDEF +message that will get pushed to other NFC devices when they connect.
+ +Advanced tag dispatching now gives applications more control over how and
+when they are launched, when an NFC tag is discovered. Previously, the platform
+used a single-step intent dispatch to notify interested applications that a tag
+was discovered. The platform now uses a four-step process that enables the
+foreground application to take control of a tag event before it is passed to any
+other applications (android.nfc.NfcAdapter.enableForegroundDispatch()).
+
+The new dispatch process also lets apps listen for specific tag content and
+tag technologies, based on two new intent actions —
+android.nfc.action.NDEF_DISCOVERED and
+android.nfc.action.TECH_DISCOVERED.
The NFC API is available in the {@link android.nfc} and +{@link android.nfc.tech} packages. The key classes are:
+ +NFC communication relies on wireless technology in the device hardware, and
+is not present in all Android devices. Android devices that do not support
+NFC will return a null object when
+{@link android.nfc.NfcAdapter#getDefaultAdapter(android.content.Context)
+getDefaultAdapter(Context)} is called, and
+context.getPackageManager().hasSystemFeature(PackageManager.FEATURE_NFC)
+will return false. The NFC API is always present, however, regardless of
+underlying hardware support.
To use the NFC API, applications must request permission from the user by
+declaring <uses-permission
+android:name="android.permission.NFC"> in their manifest files.
Additionally, developers can request filtering on Google Play, such that
+their applications are not discoverable to users whose devices do not support
+NFC. To request filtering, add
+<uses-feature android:name="android.hardware.nfc"
+android:required="true"> to the application's manifest.
To look at sample code for NFC, see +NFCDemo app, filtering by tag technology, using foreground dispatch, and foreground NDEF push (P2P).
+ +Android 2.3.3 adds platform and API support for Bluetooth nonsecure socket +connections. This lets applications communicate with simple devices that may not +offer a UI for authentication. See +{@link android.bluetooth.BluetoothDevice#createInsecureRfcommSocketToServiceRecord(java.util.UUID)} and +{@link android.bluetooth.BluetoothAdapter#listenUsingInsecureRfcommWithServiceRecord(java.lang.String, java.util.UUID)} +for more information.
+ +The speech-recognition API includes new constants to let you manage voice +search results in new ways. Although the new constants are not needed for normal +use of speech recognition, you could use them to offer a different view of voice +search results in your application. For information, see {@link +android.speech.RecognizerResultsIntent}.
+ + +The Android {@sdkPlatformVersion} platform delivers an updated version of +the framework API. The Android {@sdkPlatformVersion} API +is assigned an integer identifier — +{@sdkPlatformApiLevel} — that is +stored in the system itself. This identifier, called the "API Level", allows the +system to correctly determine whether an application is compatible with +the system, prior to installing the application.
+ +To use APIs introduced in Android {@sdkPlatformVersion} in your application,
+you need compile the application against the Android library that is provided in
+the Android {@sdkPlatformVersion} SDK platform. Depending on your needs, you might
+also need to add an android:minSdkVersion="{@sdkPlatformApiLevel}"
+attribute to the <uses-sdk> element in the application's
+manifest. If your application is designed to run only on Android 2.3 and higher,
+declaring the attribute prevents the application from being installed on earlier
+versions of the platform.
For more information, read What is API +Level?
\ No newline at end of file diff --git a/docs/html/about/versions/android-2.3.4.jd b/docs/html/about/versions/android-2.3.4.jd new file mode 100644 index 000000000000..bb4feecae287 --- /dev/null +++ b/docs/html/about/versions/android-2.3.4.jd @@ -0,0 +1,148 @@ +page.title=Android 2.3.4 Platform +sdk.platform.version=2.3.4 +sdk.platform.apiLevel=10 + + +@jd:body + ++API Level: {@sdkPlatformApiLevel}
+ +Android 2.3.4 is a maintenance release that adds several bug fixes and patches +to the Android 2.3 platform, without any API changes from Android 2.3.3. Additionally, +Android 2.3.4 brings support for the Open Accessory API to mobile devices, +through the optional Open Accessory Library.
+ +For developers, the Android {@sdkPlatformVersion} platform is available as a +downloadable component for the Android SDK. The downloadable platform includes +an Android library and system image, as well as a set of emulator skins and +more. To get started developing or testing against Android {@sdkPlatformVersion}, +use the Android SDK Manager to download the platform into your SDK.
+ + + +Android 2.3.4 provides the same framework API to applications as Android 2.3.3 +(API level 10). For a summary of the API, see the +Android 2.3.3 version notes.
+ + +Open Accessory is a new capability for integrating +connected peripherals with applications running on the platform. The capability +is based on a USB (Universal Serial Bus) stack built into the platform and an +API exposed to applications. Peripherals that attach to Android-powered devices +as accessories connect as USB hosts.
+ +Open Accessory is introduced in Android 3.1 (API level 12), but is +made available to devices running Android 2.3.4 by means of an optional external +library, the Open Accessory Library. The library exposes a framework API that +lets applications discover, communicate with, and manage a variety of device +types connected over USB. It also provides the implementation of the API against +parts of the Android platform that are not directly exposed to applications in +Android 2.3.4.
+ +The Open Accessory Library is optional on any given device. Device +manufacturers may choose whether to include the Open Accessory Library in their +products or exclude it. The library is forward-compatible with Android 3.1, so +applications developed against Android 2.3.4 will run properly on devices +running Android 3.1, if those devices support USB accessories.
+ +The API provided by the Open Accessory Library is based on the Open Accessory +API provided in Android 3.1. In most areas, you can use the same techniques and +APIs. However, developing for the Open Accessory Library on Android 2.3.4 differs +from the standard USB API in these ways: + +
getInstance() rather than {@link
+android.content.Context#getSystemService(java.lang.String) getSystemService()}
+For example:
+
+UsbManager manager = UsbManager.getInstance(this);
UsbAccessory accessory = UsbManager.getAccessory(intent)
To develop apps using the Open Accessory Library, you need:
+ +For a full discussion of how to develop applications that interact with USB +accessories, please see the related developer documentation.
+ +Additionally, developers can request filtering on Google Play, such that +their applications are not available to users whose devices do not provide the +appropriate accessory support. To request filtering, add the element below +to the application manifest:
+ +<uses-feature + android:name="android.hardware.usb.accessory" + android:required="true">+ + +
The Android 2.3.4 platform does not increment the API level — +it uses the same API level as Android 2.3.3, API level 10. + +
To use APIs introduced in API level 10 in your application, +you need compile the application against the Android library that is provided in +the latest version of the Google APIs Add-On, which also includes the Open +Accessory Library.
+ +Depending on your needs, you might
+also need to add an android:minSdkVersion="{@sdkPlatformApiLevel}"
+attribute to the <uses-sdk> element in the application's
+manifest. If your application is designed to run only on Android 2.3.3 and higher,
+declaring the attribute prevents the application from being installed on earlier
+versions of the platform.
For more information, read What is API +Level?
diff --git a/docs/html/about/versions/android-2.3.jd b/docs/html/about/versions/android-2.3.jd new file mode 100644 index 000000000000..2afa564ffc20 --- /dev/null +++ b/docs/html/about/versions/android-2.3.jd @@ -0,0 +1,710 @@ +page.title=Android 2.3 Platform +sdk.platform.version=2.3 +sdk.platform.apiLevel=9 + + +@jd:body + ++API Level: {@sdkPlatformApiLevel}
+ +For developers, the Android {@sdkPlatformVersion} platform is available as a +downloadable component for the Android SDK. The downloadable platform includes +an Android library and system image, as well as a set of emulator skins and +more. To get started developing or testing against Android {@sdkPlatformVersion}, +use the Android SDK Manager to download the platform into your SDK.
+ + + + +The sections below provide a technical overview of what's new for developers +in {@sdkPlatformVersion}, including new features and changes in the framework +API since the previous version.
+ + +The platform now includes a SIP protocol stack and framework API that lets +developers build internet telephony applications. Using the API, applications can offer +voice calling features without having to manage sessions, transport-level +communication, or audio — these are handled +transparently by the platform's SIP API and services.
+ +The SIP API is available in the {@link android.net.sip android.net.sip} +package. The key class is {@link android.net.sip.SipManager}, which applications +use to set up and manage SIP profiles, then initiate audio calls and receive +audio calls. Once an audio call is established, applications can mute calls, +turn on speaker mode, send DTMF tones, and more. Applications can also use the +{@link android.net.sip.SipManager} to create generic SIP connections.
+ +The platform’s underlying SIP stack and services are available on devices at +the discretion of the manufacturer and associated carrier. For this reason, +applications should use the {@link android.net.sip.SipManager#isApiSupported +isApiSupported()} method to check whether SIP support is available, before +exposing calling functionality to users.
+ +To use the SIP API, applications must request permission from the user by
+declaring <uses-permission
+android:name="android.permission.INTERNET"> and <uses-permission
+android:name="android.permission.USE_SIP"> in their manifest files.
Additionally, developers can request filtering on Google Play, such that
+their applications are not discoverable to users whose devices do not include
+the platform’s SIP stack and services. To request filtering, add <uses-feature
+android:name="android.software.sip"
+android:required="true"> and <uses-feature
+android:name="android.software.sip.voip"> to the application manifest.
To look at a sample application that uses the SIP API, see SIP Demo.
+ +Android 2.3 includes an NFC stack and framework API that lets developers +read NDEF tags that are discovered as a user touches an NFC-enabled device +to tag elements embedded in stickers, smart posters, and even other devices.
+ +The platform provides the underlying NFC services that work with the device +hardware to discover tags when they come into range. On discovering a tag, the +platform notifies applications by broadcasting an Intent, appending the tag's +NDEF messages to the Intent as extras. Applications can create Intent filters to +recognize and handle targeted tags and messages. For example, after receiving a +tag by Intent, applications extract the NDEF messages, store them, alert the +user, or handle them in other ways.
+ +The NFC API is available in the {@link android.nfc} package. The key classes are:
+ +NFC communication relies on wireless technology in the device hardware, so +support for the platform's NFC features on specific devices is determined by +their manufacturers. To determine the NFC support on the current device, +applications can call {@link android.nfc.NfcAdapter#isEnabled isEnabled()} to +query the {@link android.nfc.NfcAdapter}. The NFC API is always present, +however, regardless of underlying hardware support.
+ +To use the NFC API, applications must request permission from the user by
+declaring <uses-permission
+android:name="android.permission.NFC"> in their manifest files.
Additionally, developers can request filtering on Google Play, such that
+their applications are not discoverable to users whose devices do not support
+NFC. To request filtering, add
+<uses-feature android:name="android.hardware.nfc"
+android:required="true"> to the application's manifest.
To look at a sample application that uses the NFC API, see +NFCDemo.
+ +Android 2.3 adds platform and API support for several new sensor reading +types — gyroscope, rotation vector, linear acceleration, gravity, and barometer. +Developers can use the new sensor readings to create applications that respond +quickly and smoothly to precise changes in device position and motion. The +Sensor API reports gyroscope and other sensor changes to interested +applications, whether they are running on the application framework or in native +code.
+ +Note that the specific set of hardware sensors available on any given device +varies at the discretion of the device manufacturer.
+ +Developers can request filtering on Google Play, such that their
+applications are not discoverable to users whose devices do not offer a
+gyroscope sensor. To do so, add <uses-feature
+android:name="android.hardware.sensor.gyroscope"
+android:required="true"> to the application manifest.
For API details, see {@link android.hardware.Sensor}.
+ + +Applications can now make use of any cameras that are available on a device, +for either photo or video capture. The {@link android.hardware.Camera} lets +applications query for the number of cameras available and the unique +characteristics of each.
+ +To look at sample code for accessing a front-facing camera, see CameraPreview.java +in the ApiDemos sample application.
+ +The Camera API also adds:
+The platform's media framework adds support for new per-track or global audio effects, +including bass boost, headphone virtualization, equalization, and reverb.
+To look at sample code for audio effects, see +AudioFxDemo.java +in the ApiDemos sample application.
+ +The media framework also adds:
+The platform includes a new {@link android.app.DownloadManager} system service
+that handles long-running HTTP downloads. Applications can request that a URI be
+downloaded to a particular destination file. The DownloadManager
+will conduct the download in the background, taking care of HTTP interactions
+and retrying downloads after failures or across connectivity changes and system
+reboots.
To help developers monitor and improve the performance of their applications, +the platform offers a new system facility called {@link android.os.StrictMode}. +When implemented in an application, StrictMode catches and notifies the +developer of accidental disk or network activity that could degrade application +performance, such as activity taking place on the application's main thread +(where UI operations are received and animations are also taking place). +Developers can evaluate the network and disk usages issues raised in StrictMode +and correct them if needed, keeping the main thread more responsive and +preventing ANR dialogs from being shown to users. + +
For more information about how to use StrictMode to optimize your +application, see the class documentation and sample code at {@link +android.os.StrictMode android.os.StrictMode}.
+ +overScrollMode, overScrollFooter, and
+overScrollHeader attributes for <ListView> elements,
+for controlling overscroll behavior.filterTouchesWhenObscured attribute for view elements,
+which declares whether to filter touches when the view's window is obscured by
+another visible window. When set to "true", the view will not
+receive touches whenever a toast, dialog or other window appears above the
+view's window. Refer to View security
+documentation for details.To look at sample code for touch filtering, see +SecureView.java +in the ApiDemos sample application.
+setComposingRegion method lets an application mark a
+region of text as composing text, maintaining the current styling. A
+getSelectedText method returns the selected text to the
+application. The methods are available in {@link
+android.view.inputmethod.BaseInputConnection}, {@link
+android.view.inputmethod.InputConnection}, and {@link
+android.view.inputmethod.InputConnectionWrapper}.textSelectHandle, textSelectHandleLeft,
+textSelectHandleRight, and textSelectHandleWindowStyle
+attributes for <TextView>, for referencing drawables that will be
+used to display text-selection anchors and the style for the containing
+window.The platform now supports extra large screen sizes, such as those that might
+be found on tablet devices. Developers can indicate that their applications are
+designed to support extra large screen sizes by adding a <supports
+screens ... android:xlargeScreens="true"> element to their manifest
+files. Applications can use a new resource qualifier, xlarge, to
+tag resources that are specific to extra large screens. For
+details on how to support extra large and other screen sizes, see Supporting Multiple
+Screens.
ACTION_SET_ALARM Intent
+action and extras that can be used to start an Activity to set a new alarm in an
+alarm clock application. Applications that wish to receive the
+SET_ALARM Intent should create an activity that requires the
+the SET_ALARM permission. Applications that wish to create a new
+alarm should use {@link
+android.content.Context#startActivity(android.content.Intent)
+Context.startActivity()}, so that the user has the option of choosing
+which alarm clock application to use.The LocationManager keeps track
+of all clients requesting periodic updates, and tells its providers
+about them as a WorkSource parameter, when setting their minimum
+update times.
+The network location provider uses WorkSource to track the
+wake and wifi locks initiated by an application and adds it to the application's
+battery usage reported in Manage Applications.
Android 2.3 exposes a broad set of APIs to applications that use native +code. Framework classes of interest to such applications include:
+ +NativeActivity and its underlying native code run in the system
+just as do other Activities — specifically they run in the Android
+application's system process and execute on the application's main UI thread,
+and they receive the same lifecycle callbacks as do other Activities. For full information on working with native code or to download the NDK, +see the Android NDK page.
+ + +binarySearch(),
+ copyOf(), copyOfRange(), and others.xlargeScreens attribute for {@code
+<supports-screens>}
+element, to indicate whether the application supports
+extra large screen form-factors. For details, see Supporting Multiple
+Screens.android:screenOrientation attribute of
+<activity> element:
+"reverseLandscape" — The Activity would like to have the
+screen in landscape orientation, turned in the opposite direction from normal
+landscape."reversePortrait" — The Activity would like to have the
+screen in portrait orientation, turned in the opposite direction from normal
+portrait."sensorLandscape" — The Activity would like to have the
+screen in landscape orientation, but can use the sensor to change which
+direction the screen is facing."sensorPortrait" — The Activity would like to have the
+screen in portrait orientation, but can use the sensor to change which direction
+the screen is facing."fullSensor" — Orientation is determined by a physical
+orientation sensor: the display will rotate based on how the user moves the
+device. This allows any of the 4 possible rotations, regardless of what the
+device will normally do (for example some devices won't normally use 180 degree
+rotation).com.android.permission.SET_ALARM — Allows an application
+to broadcast an Intent to set an alarm for the user. An Activity that handles
+the {@link android.provider.AlarmClock#ACTION_SET_ALARM SET_ALARM} Intent action
+should require this permission.android.permission.USE_SIP — Allows an application to use
+the {@link android.net.sip SIP API} to make or receive internet calls.
+android.permission.NFC — Allows an application to use the
+{@link android.nfc NFC API} to read NFC tags.The platform adds several new hardware features that developers can declare +in their application manifests as being required by their applications. This +lets developers control how their application is filtered, when published on +Google Play.
+ +For full information about how to declare features and use them for
+filtering, see the documentation for <uses-feature>.
For a detailed view of all API changes in Android {@sdkPlatformVersion} (API +Level {@sdkPlatformApiLevel}), see the API +Differences Report.
+ + +The Android {@sdkPlatformVersion} platform delivers an updated version of +the framework API. The Android {@sdkPlatformVersion} API +is assigned an integer identifier — +{@sdkPlatformApiLevel} — that is +stored in the system itself. This identifier, called the "API Level", allows the +system to correctly determine whether an application is compatible with +the system, prior to installing the application.
+ +To use APIs introduced in Android {@sdkPlatformVersion} in your application,
+you need compile the application against the Android library that is provided in
+the Android {@sdkPlatformVersion} SDK platform. Depending on your needs, you might
+also need to add an android:minSdkVersion="{@sdkPlatformApiLevel}"
+attribute to the <uses-sdk> element in the application's
+manifest. If your application is designed to run only on Android 2.3 and higher,
+declaring the attribute prevents the application from being installed on earlier
+versions of the platform.
For more information, read What is API +Level?
\ No newline at end of file diff --git a/docs/html/about/versions/android-3.0-highlights.jd b/docs/html/about/versions/android-3.0-highlights.jd new file mode 100644 index 000000000000..21dbda6af4ce --- /dev/null +++ b/docs/html/about/versions/android-3.0-highlights.jd @@ -0,0 +1,261 @@ +page.title=Honeycomb + +@jd:body + + + + + +Welcome to Android 3.0!
+ +The Android 3.0 platform introduces many new and exciting features for users and developers. +This document provides a glimpse of some of the new features and technologies, as delivered in +Android 3.0. For a more detailed look at new developer APIs, see the Android 3.0 Platform document.
+ + + +Android 3.0 is a new version of the Android platform that is specifically optimized for devices with larger screen sizes, particularly tablets. It introduces a brand new, truly virtual and “holographic” UI design, as well as an elegant, content-focused interaction model.
+ +Android 3.0 builds on the things people love most about Android — refined multitasking, rich notifications, Home screen customization, widgets, and more — and transforms them with a vibrant, 3D experience and deeper interactivity, making them familiar but even better than before.
+ +The new UI brings fresh paradigms for interaction, navigation, and customization and makes them available to all applications — even those built for earlier versions of the platform. Applications written for Android 3.0 are able to use an extended set of UI objects, powerful graphics, and media capabilities to engage users in new ways.
+ +System Bar, for global status and notifications
+ +Across the system and in all applications, users have quick access to notifications, system status, and soft navigation buttons in a System Bar, available at the bottom of the screen. The System Bar is always present and is a key touchpoint for users, but in a new "lights out mode" can also be dimmed for full-screen viewing, such as for videos.
+ +Action Bar, for application control
+ +In every application, users have access to contextual options, navigation, widgets, or other types of content in an Action Bar, displayed at the top of the screen. The Action Bar is always present when an application is in use, although its content, theme, and other properties are managed by the application rather than the system. The Action Bar is another key touchpoint for users, especially with action items and an overflow dropdown menu, which users frequently access in a similar manner in most applications.
+ +Customizable Home screens
+ +Five customizable Home screens give users instant access to all parts of the system from any context. Each screen offers a large grid that maintains spatial arrangement in all orientations. Users can select and manipulate Home screen widgets, app shortcuts, and wallpapers using a dedicated visual layout mode. Visual cues and drop shadows improve visibility when adjusting the layout of shortcuts and widgets. Each Home screen also offers a familiar launcher for access to all installed applications, as well as a Search box for universal search of apps, contacts, media files, web content, and more.
+ +Recent Apps, for easy visual multitasking
+ +Multitasking is a key strength of Android and it is central to the Android 3.0 experience. As users launch applications to handle various tasks, they can use the Recent Apps list in the System Bar to see the tasks underway and quickly jump from one application context to another. To help users rapidly identify the task associated with each app, the list shows a snapshot of its actual state when the user last viewed it.
+ +The Android soft keyboard is redesigned to make entering text fast and accurate on larger screen sizes. The keys are reshaped and repositioned for improved targeting, and new keys have been added, such as a Tab key, to provide richer and more efficient text input. Users can touch-hold keys to access menus of special characters and switch text/voice input modes from a button in the System Bar.
+ +When entering or viewing text, a new UI lets users quickly select a word by press-hold and then adjust the selection area as needed by dragging a set of bounding arrows to new positions. Users can then select an action from the Action Bar, such as copy to the clipboard, share, paste, web search, or find.
+ + +Android 3.0 includes new connectivity features that add versatility and convenience for users. Built-in support for Media/Picture Transfer Protocol lets users instantly sync media files with a USB-connected camera or desktop computer, without needing to mount a USB mass-storage device. Users can also connect full keyboards over either USB or Bluetooth, for a familiar text-input environment. For improved wi-fi connectivity, a new combo scan reduces scan times across bands and filters. New support for Bluetooth tethering means that more types of devices can share the network connection of an Android-powered device.
+ + +The Android 3.0 platform includes an updated set of standard applications that are designed for use on larger screen devices. The sections below highlight some of the new features.
+ +Browser + +The browser includes new features that let users navigate and organize more efficiently. Multiple tabs replace browser windows and a new “incognito” mode allows anonymous browsing. Bookmarks and history are presented and managed in a single unified view. Users can now choose to automatically sign into Google sites on the browser with a supplied account and sync bookmarks with Google Chrome. New multitouch support is now available to JavaScript and plugins. Users can enjoy a better browsing experience at non-mobile sites through an improved zoom and viewport model, overflow scrolling, support for fixed positioning, and more.
+ +Camera and Gallery
+ +The Camera application has been redesigned to take advantage of a larger screen for quick access to exposure, focus, flash, zoom, front-facing camera, and more. To let users capture scenes in new ways, it adds built-in support for time-lapse video recording. The Gallery application lets users view albums and other collections in full-screen mode, with easy access to thumbnails for other photos in the collection.
+ +Contacts
+ +The Contacts app uses a new two-pane UI and Fast Scroll to let users easily organize and locate contacts. The application offers improved formatting of international phone numbers as user types, based on home country and an international number parsing library. Contact information is presented in a card-like UI, making it easier for users to read and edit contacts.
+ +The Email application uses a new two-pane UI to make viewing and organizing messages more efficient. The app lets users select one or more messages, then select an action from the Action Bar, such as moving them to a folder. Users can sync attachments for later viewing and keep track of email using a home screen Widget.
+ +The Android 3.0 platform is designed specially to meet the unique needs of applications on devices with larger screen sizes. It offers all of the tools developers need to create incredible visual and interaction experiences on these devices.
+ +Activity fragments, for greater control of content and design flexibility
+ +Starting with Android 3.0, developers can break the Activities of their applications into subcomponents called Fragments, then combine them in a variety of ways to create a richer, more interactive experience. For example, an application can use a set of Fragments to create a true multipane UI, with the user being able to interact with each pane independently. Fragments can be added, removed, replaced, and animated inside an Activity dynamically, and they are modular and reusable across multiple Activities. Because they are modular, Fragments also offer an efficient way for developers to write applications that can run properly on both larger screen as well as smaller screen devices.
+ +Redesigned UI widgets
+ +Android 3.0 offers an updated set of UI widgets that developers can use to quickly add new types of content to their applications. The new UI widgets are redesigned for use on larger screens such as tablets and incorporate the new holographic UI theme. Several new widget types are available, including a 3D stack, search box, a date/time picker, number picker, calendar, popup menu, and others. Most of the redesigned UI widgets can now be used as remote views in application widgets displayed on the home screen. Applications written for earlier versions can inherit the new Widget designs and themes.
+ + +Expanded Home screen widgets
+ +Home screen widgets are popular with users because they offer fast access to application-specific data directly from the home screen. Android 3.0 lets developers take home screen widgets to the next level, offering more types of content and new modes of interaction with users. Developers can now use more standard UI widget types home screen widgets, including widgets that let users flip through collections of content as 3D stacks, grids, or lists. Users can interact with the home screen widgets in new ways, such as by using touch gestures to scroll and flip the content displayed in a widget.
+ +Persistent Action Bar
+ +The platform provides each application with its own instance of the Action Bar at the top of the screen, which the application can use to give the user quick access to contextual options, widgets, status, navigation, and more. The application can also customize the display theme of its Action Bar instance. The Action Bar lets developers expose more features of their applications to users in a familiar location, while also unifying the experience of using an application that spans multiple Activities or states.
+ +Richer notifications
+ +Notifications are a key part of the Android user experience because they let applications show key updates and status information to users in real time. Android 3.0 extends this capability, letting developers include richer content and control more properties. A new builder class lets developers quickly create notifications that include large and small icons, a title, a priority flag, and any properties already available in previous versions. Notifications can offer more types of content by building on the expanded set of UI Widgets that are now available as remote Views.
+ +Multiselect, clipboard, and drag-and-drop
+ +The platform offers convenient new interaction modes that developers can use. For managing collections of items in lists or grids, developers can offer a new multiselect mode that lets users choose multiple items for an action. Developers can also use a new system-wide Clipboard to let users easily copy any type of data into and out of their applications. To make it easier for users to manage and organize files, developers can now add drag-and-drop interaction through a DragEvent framework.
+ +New animation framework
+ +The platform includes a flexible new animation framework that lets developers easily animate the properties of UI elements such as Views, Widgets, Fragments, Drawables, or any arbitrary object. Animations can create fades or movement between states, loop an animated image or an existing animation, change colors, and much more. Adding animation to UI elements can add visual interest to an application and refine the user experience, to keep users engaged.
+ +Hardware-accelerated 2D graphics
+ +Android 3.0 offers a new hardware-accelerated OpenGL renderer that gives a performance boost to many common graphics operations for applications running in the Android framework. When the renderer is enabled, most operations in Canvas, Paint, Xfermode, ColorFilter, Shader, and Camera are accelerated. Developers can control how hardware-acceleration is applied at every level, from enabling it globally in an application to enabling it in specific Activities and Views inside the application.
+ +Renderscript 3D graphics engine
+ +Renderscript is a runtime 3D framework that provides both an API for building 3D scenes as well as a special, platform-independent shader language for maximum performance. Using Renderscript, you can accelerate graphics operations and data processing. Renderscript is an ideal way to create high-performance 3D effects for applications, wallpapers, carousels, and more.
+ + +Android 3.0 is the first version of the platform designed to run on either single or multicore processor architectures. A variety of changes in the Dalvik VM, Bionic library, and elsewhere add support for symmetric multiprocessing in multicore environments. These optimizations can benefit all applications, even those that are single-threaded. For example, with two active cores, a single-threaded application might still see a performance boost if the Dalvik garbage collector runs on the second core. The system will arrange for this automatically.
+ + +HTTP Live streaming
+ +Applications can now pass an M3U playlist URL to the media framework to begin an HTTP Live streaming session. The media framework supports most of the HTTP Live streaming specification, including adaptive bit rate.
+ +Pluggable DRM framework
+ +Android 3.0 includes an extensible DRM framework that lets applications manage protected content according to a variety of DRM mechanisms that may be available on the device. For application developers, the framework API offers an consistent, unified API that simplifies the management of protected content, regardless of the underlying DRM engines.
+ +Digital media file transfer
+ +The platform includes built-in support for Media/Picture Transfer Protocol (MTP/PTP) over USB, which lets users easily transfer any type of media files between devices and to a host computer. Developers can build on this support, creating applications that let users create or manage media files that they may want to transfer or share across devices.
+ +More types of connectivity
+ +The platform offers new connectivity that developers can build on. API support for Bluetooth A2DP and HSP profiles lets applications query Bluetooth profiles for connected devices, audio state, and more, then notify the user. For example, a music application can check connectivity and status and let the user know that music is playing through a stereo headset. Applications can also register to receive system broadcasts of pre-defined vendor-specific AT commands, such as Platronics Xevent. For example, an application could receive broadcasts that indicate a connected device's battery level and could notify the user or take other action as needed. Applications can also take advantage of the platform's new support for full keyboards connected by USB or Bluetooth.
+ + +In Android 3.0, developers of device administration applications can support new types of policies, including policies for encrypted storage, password expiration, password history, and password complex characters required.
+ +Android 3.0 brings a new UI designed for tablets and other larger screen devices, but it also is fully compatible with applications developed for earlier versions of the platform, or for smaller screen sizes. Existing applications can seamlessly participate in the new holographic UI theme without code changes, by adding a single attribute in their manifest files. The platform emulates the Menu key, which is replaced by the overflow menu in the Action Bar in the new UI. Developers wanting to take fuller advantage of larger screen sizes can also create dedicated layouts and assets for larger screens and add them to their existing applications.
+ diff --git a/docs/html/about/versions/android-3.0.jd b/docs/html/about/versions/android-3.0.jd new file mode 100644 index 000000000000..76e07959135e --- /dev/null +++ b/docs/html/about/versions/android-3.0.jd @@ -0,0 +1,976 @@ +page.title=Android 3.0 Platform +sdk.platform.version=3.0 +sdk.platform.apiLevel=11 +@jd:body + +API Level: {@sdkPlatformApiLevel}
+ +For developers, the Android {@sdkPlatformVersion} platform is available as a downloadable +component for the Android SDK. The downloadable platform includes an Android library and system +image, as well as a set of emulator skins and more. The downloadable platform includes no external +libraries.
+ +For developers, the Android {@sdkPlatformVersion} platform is available as a +downloadable component for the Android SDK. The downloadable platform includes +an Android library and system image, as well as a set of emulator skins and +more. To get started developing or testing against Android {@sdkPlatformVersion}, +use the Android SDK Manager to download the platform into your SDK.
+ + + + + + +The sections below provide a technical overview of what's new for developers in Android 3.0, +including new features and changes in the framework API since the previous version.
+ + + + + +A fragment is a new framework component that allows you to separate distinct elements of an +activity into self-contained modules that define their own UI and lifecycle. To create a +fragment, you must extend the {@link android.app.Fragment} class and implement several lifecycle +callback methods, similar to an {@link android.app.Activity}. You can then combine multiple +fragments in a single activity to build a multi-pane UI in which each +pane manages its own lifecycle and user inputs.
+ +You can also use a fragment without providing a UI and instead use the fragment as a worker +for the activity, such as to manage the progress of a download that occurs only while the +activity is running.
+ +Additionally:
+ +To manage the fragments in your activity, you must use the {@link +android.app.FragmentManager}, which provides several APIs for interacting with fragments, such +as finding fragments in the activity and popping fragments off the back stack to restore their +previous state.
+ +To perform a transaction, such as add or remove a fragment, you must create a {@link +android.app.FragmentTransaction}. You can then call methods such as {@link +android.app.FragmentTransaction#add add()} {@link android.app.FragmentTransaction#remove +remove()}, or {@link android.app.FragmentTransaction#replace replace()}. Once you've applied all +the changes you want to perform for the transaction, you must call {@link +android.app.FragmentTransaction#commit commit()} and the system applies the fragment transaction to +the activity.
+ +For more information about using fragments, read the Fragments documentation. Several +samples are also available in the +API Demos application.
+ + + + +The Action Bar is a replacement for the traditional title bar at the top of the activity window. +It includes the application logo in the left corner and provides a new interface for items in the +Options Menu. Additionally, the +Action Bar allows you to:
+ +In your XML declaration for the menu item, include the {@code +android:showAsAction} attribute with a value of {@code "ifRoom"}. When there's enough room, the menu +item appears directly in the Action Bar. Otherwise, the item is placed in the +overflow menu, revealed by the menu icon on the right side of the Action Bar.
In the XML declaration for the menu item, add the {@code android:actionViewLayout} attribute +with a layout resource or the {@code android:actionViewClass} attribute with the class name of a +widget. (You must also declare the {@code android:showAsAction} attribute so that the item appears +in the Action Bar.) If there's not enough room in the Action Bar and the item appears in the +overflow menu, it behaves like a regular menu item and does not show the widget.
The application logo is automatically assigned the {@code android.R.id.home} ID, +which the system delivers to your activity's {@link android.app.Activity#onOptionsItemSelected +onOptionsItemSelected()} callback when touched. Simply respond to this ID in your callback +method to perform an action such as go to your application's "home" activity.
+To replace the icon with a logo, specify your application logo in the manifest file with the +{@code android:logo} +attribute, then call {@link android.app.ActionBar#setDisplayUseLogoEnabled +setDisplayUseLogoEnabled(true)} in your activity.
The Action Bar is standard for all applications that use the new holographic theme, which is +also standard when you set either the {@code +android:minSdkVersion} or {@code +android:targetSdkVersion} to {@code "11"}.
+ +For more information about the Action Bar, read the Action Bar documentation. Several +samples are also available in the +API Demos application.
+ + + + +Applications can now copy and paste data (beyond mere text) to and from the system-wide +clipboard. Clipped data can be plain text, a URI, or an intent.
+ +By providing the system access to the data you want the user to copy, through a content provider, +the user can copy complex content (such as an image or data structure) from your application and +paste it into another application that supports that type of content.
+ +To start using the clipboard, get the global {@link android.content.ClipboardManager} object +by calling {@link android.content.Context#getSystemService getSystemService(CLIPBOARD_SERVICE)}.
+ +To copy an item to the clipboard, you need to create a new {@link +android.content.ClipData} object, which holds one or more {@link android.content.ClipData.Item} +objects, each describing a single entity. To create a {@link android.content.ClipData} object +containing just one {@link android.content.ClipData.Item}, you can use one of the helper methods, +such as {@link android.content.ClipData#newPlainText newPlainText()}, {@link +android.content.ClipData#newUri newUri()}, and {@link android.content.ClipData#newIntent +newIntent()}, which each return a {@link android.content.ClipData} object pre-loaded with the +{@link android.content.ClipData.Item} you provide.
+ +To add the {@link android.content.ClipData} to the clipboard, pass it to {@link +android.content.ClipboardManager#setPrimaryClip setPrimaryClip()} for your instance of {@link +android.content.ClipboardManager}.
+ +You can then read a file from the clipboard (in order to paste it) by calling {@link +android.content.ClipboardManager#getPrimaryClip()} on the {@link +android.content.ClipboardManager}. Handling the {@link android.content.ClipData} you receive can +be complicated and you need to be sure you can actually handle the data type in the clipboard +before attempting to paste it.
+ +The clipboard holds only one piece of clipped data (a {@link android.content.ClipData} +object) at a time, but one {@link android.content.ClipData} can contain multiple {@link +android.content.ClipData.Item}s.
+ +For more information, read the Copy +and Paste documentation. You can also see a simple implementation of copy and paste in the API Demos +sample and a more complete implementation in the Note Pad sample.
+ + + + +New APIs simplify drag and drop operations in your application's user interface. A drag +operation is the transfer of some kind of data—carried in a {@link android.content.ClipData} +object—from one place to another. The start and end point for the drag operation is a {@link +android.view.View}, so the APIs that directly handle the drag and drop operations are +in the {@link android.view.View} class.
+ +A drag and drop operation has a lifecycle that's defined by several drag actions—each +defined by a {@link android.view.DragEvent} object—such as {@link +android.view.DragEvent#ACTION_DRAG_STARTED}, {@link android.view.DragEvent#ACTION_DRAG_ENTERED}, and +{@link android.view.DragEvent#ACTION_DROP}. Each view that wants to participate in a drag +operation can listen for these actions.
+ +To begin dragging content in your activity, call {@link android.view.View#startDrag startDrag()} +on a {@link android.view.View}, providing a {@link android.content.ClipData} object that represents +the data to drag, a {@link android.view.View.DragShadowBuilder} to facilitate the "shadow" +that users see under their fingers while dragging, and an {@link java.lang.Object} that can share +information about the drag object with views that may receive the object.
+ +To accept a drag object in a {@link android.view.View} (receive the "drop"), register the view +with an {@link android.view.View.OnDragListener OnDragListener} by calling {@link +android.view.View#setOnDragListener setOnDragListener()}. When a drag event occurs on the view, the +system calls {@link android.view.View.OnDragListener#onDrag onDrag()} for the {@link +android.view.View.OnDragListener OnDragListener}, which receives a {@link android.view.DragEvent} +describing the type of drag action has occurred (such as {@link +android.view.DragEvent#ACTION_DRAG_STARTED}, {@link android.view.DragEvent#ACTION_DRAG_ENTERED}, and +{@link android.view.DragEvent#ACTION_DROP}). During a drag, the system repeatedly calls {@link +android.view.View.OnDragListener#onDrag onDrag()} for the view underneath the drag, to deliver a +stream of drag events. The receiving view can inquire the event type delivered to {@link +android.view.View#onDragEvent onDragEvent()} by calling {@link android.view.DragEvent#getAction +getAction()} on the {@link android.view.DragEvent}.
+ +Note: Although a drag event may carry a {@link +android.content.ClipData} object, this is not related to the system clipboard. A drag and drop +operation should never put the dragged data in the system clipboard.
+ +For more information, read the Dragging and +Dropping documentation. You can also see an implementation of drag and drop in the +API Demos application and the Honeycomb Gallery +application.
+ + + +Android 3.0 supports several new widget classes for more interactive app widgets on the users +Home screen, including: {@link android.widget.GridView}, {@link android.widget.ListView}, {@link +android.widget.StackView}, {@link android.widget.ViewFlipper}, and {@link +android.widget.AdapterViewFlipper}.
+ +More importantly, you can use the new {@link android.widget.RemoteViewsService} to create app +widgets with collections, using widgets such as {@link android.widget.GridView}, {@link +android.widget.ListView}, and {@link android.widget.StackView} that are backed by remote data, +such as from a content provider.
+ +The {@link android.appwidget.AppWidgetProviderInfo} class (defined in XML with an {@code +<appwidget-provider>} element) also supports two new fields: {@link +android.appwidget.AppWidgetProviderInfo#autoAdvanceViewId} and {@link +android.appwidget.AppWidgetProviderInfo#previewImage}. The {@link +android.appwidget.AppWidgetProviderInfo#autoAdvanceViewId} field lets you specify the view ID of the +app widget subview that should be auto-advanced by the app widget’s host. The +{@link android.appwidget.AppWidgetProviderInfo#previewImage} field specifies a preview of what the +app widget looks like and is shown to the user from the widget picker. If this field is not +supplied, the app widget's icon is used for the preview.
+ +To help create a preview image for your app widget (to specify in the {@link +android.appwidget.AppWidgetProviderInfo#previewImage} field), the Android emulator includes an +application called "Widget Preview." To create a preview image, launch this application, select the +app widget for your application and set it up how you'd like your preview image to appear, then save +it and place it in your application's drawable resources.
+ +You can see an implementation of the new app widget features in the StackView App Widget and Weather List Widget +applications.
+ + + +The {@link android.app.Notification} APIs have been extended to support more content-rich status +bar notifications, plus a new {@link android.app.Notification.Builder} class allows you to easily +create {@link android.app.Notification} objects.
+New features include:
+New framework APIs facilitate asynchronous loading of data using the {@link +android.content.Loader} class. You can use it in combination with UI components such as views and +fragments to dynamically load data from worker threads. The {@link +android.content.CursorLoader} subclass is specially designed to help you do so for data backed by +a {@link android.content.ContentProvider}.
+ +All you need to do is implement the {@link android.app.LoaderManager.LoaderCallbacks +LoaderCallbacks} interface to receive callbacks when a new loader is requested or the data has +changed, then call {@link android.app.LoaderManager#initLoader initLoader()} to initialize the +loader for your activity or fragment.
+ +For more information, read the Loaders documentation. You can also see +example code using loaders in the LoaderCursor +and +LoaderThrottle samples.
+ + + +Android now includes APIs for applications to verify the state of connected Bluetooth A2DP and +headset profile devices. For example, applications can identify when a Bluetooth headset is +connected for listening to music and notify the user as appropriate. Applications can also receive +broadcasts for vendor specific AT commands and notify the user about the state of the connected +device, such as when the connected device's battery is low.
+ +You can initialize the respective {@link android.bluetooth.BluetoothProfile} by calling {@link +android.bluetooth.BluetoothAdapter#getProfileProxy getProfileProxy()} with either the {@link +android.bluetooth.BluetoothProfile#A2DP} or {@link android.bluetooth.BluetoothProfile#HEADSET} +profile constant and a {@link android.bluetooth.BluetoothProfile.ServiceListener} to receive +callbacks when the Bluetooth client is connected or disconnected.
+ + + + +An all new flexible animation framework allows you to animate arbitrary properties of any object +(View, Drawable, Fragment, Object, or anything else). It allows you to define several aspects of an +animation, such as:
+You can define these animation aspects, and others, for an object's int, float, and hexadecimal +color values, by default. That is, when an object has a property field for one of these types, you +can change its value over time to affect an animation. To animate any other type of value, you tell +the system how to calculate the values for that given type, by implementing the {@link +android.animation.TypeEvaluator} interface.
+ +There are two animators you can use to animate the values of a property: {@link +android.animation.ValueAnimator} and {@link android.animation.ObjectAnimator}. The {@link +android.animation.ValueAnimator} computes the animation values, but is not aware of the specific +object or property that is animated as a result. It simply performs the calculations, and you must +listen for the updates and process the data with your own logic. The {@link +android.animation.ObjectAnimator} is a subclass of {@link android.animation.ValueAnimator} and +allows you to set the object and property to animate, and it handles all animation work. +That is, you give the {@link android.animation.ObjectAnimator} the object to animate, the +property of the object to change over time, and a set of values to apply to the property over +time, then start the animation.
+ +Additionally, the {@link android.animation.LayoutTransition} class enables automatic transition +animations for changes you make to your activity layout. To enable transitions for part of the +layout, create a {@link android.animation.LayoutTransition} object and set it on +any {@link android.view.ViewGroup} by calling {@link +android.view.ViewGroup#setLayoutTransition setLayoutTransition()}. This causes default +animations to run whenever items are added to or removed from the group. To specify custom +animations, call {@link android.animation.LayoutTransition#setAnimator setAnimator()} on the {@link +android.animation.LayoutTransition} and provide a custom {@link android.animation.Animator}, +such as a {@link android.animation.ValueAnimator} or {@link android.animation.ObjectAnimator} +discussed above.
+ +For more information, see the Property Animation documentation. You can +also see several samples using the animation APIs in the API +Demos application.
+ + + + +New {@link android.widget.AbsListView#CHOICE_MODE_MULTIPLE_MODAL} mode for {@link +android.widget.AbsListView#setChoiceMode setChoiceMode()} allows users to select multiple items +from a {@link android.widget.ListView} or {@link android.widget.GridView}. When used in +conjunction with the Action Bar, users can select multiple items and then select the action to +perform from a list of options in the Action Bar (which has transformed into a Multi-choice +Action Mode).
+ +To enable multiple-choice selection, call {@link +android.widget.AbsListView#setChoiceMode setChoiceMode(CHOICE_MODE_MULTIPLE_MODAL)} and register a +{@link android.widget.AbsListView.MultiChoiceModeListener MultiChoiceModeListener} with {@link +android.widget.AbsListView#setMultiChoiceModeListener setMultiChoiceModeListener()}.
+ +When the user performs a long-press on an item, the Action Bar switches to the Multi-choice +Action Mode. The system notifies the {@link android.widget.AbsListView.MultiChoiceModeListener +MultiChoiceModeListener} when items are selected by calling {@link +android.widget.AbsListView.MultiChoiceModeListener#onItemCheckedStateChanged +onItemCheckedStateChanged()}.
+ +For an example of multiple-choice selection, see the List15. +java +class in the API Demos sample application.
+New APIs allow you to easily apply 2D and 3D transformations to views in your activity +layout. New transformations are made possible with a set of object properties that define the view's +layout position, orientation, transparency and more.
+New methods to set the view properties include: {@link android.view.View#setAlpha +setAlpha()}, {@link +android.view.View#setBottom setBottom()}, {@link android.view.View#setLeft setLeft()}, {@link +android.view.View#setRight setRight()}, {@link android.view.View#setBottom setBottom()}, {@link +android.view.View#setPivotX setPivotX()}, {@link android.view.View#setPivotY setPivotY()}, {@link +android.view.View#setRotationX setRotationX()}, {@link android.view.View#setRotationY +setRotationY()}, {@link android.view.View#setScaleX setScaleX()}, {@link android.view.View#setScaleY +setScaleY()}, {@link android.view.View#setAlpha setAlpha()}, and others.
+ +Some methods also have a corresponding XML attribute that you can specify in your layout +file, to apply a default transformation. Available attributes include: {@code translationX}, {@code +translationY}, {@code rotation}, +{@code rotationX}, {@code rotationY}, {@code scaleX}, {@code scaleY}, {@code transformPivotX}, +{@code transformPivotY}, and {@code alpha}.
+ +Using some of these new view properties in combination with the new animation framework (discussed +above), you can easily apply some fancy animations to your views. For example, to rotate a +view on its y-axis, supply {@link android.animation.ObjectAnimator} with the {@link +android.view.View}, the "rotationY" property, and the start and end values:
++ObjectAnimator animator = ObjectAnimator.ofFloat(myView, "rotationY", 0, 360); +animator.setDuration(2000); +animator.start(); ++
The standard system widgets and overall look have been redesigned and incorporate a new +"holographic" user interface theme. The system applies the new theme +using the standard style and theme system.
+ +Any application that targets the Android 3.0 platform—by setting either the {@code android:minSdkVersion} +or {@code +android:targetSdkVersion} value to {@code "11"}—inherits the holographic theme by default. +However, if your application also applies its own theme, then your theme will override the +holographic theme, unless you update your styles to inherit the holographic theme.
+ +To apply the holographic theme to individual activities or to inherit them in your own theme +definitions, use one of several new {@link android.R.style#Theme_Holo Theme.Holo} +themes. If your application is compatible with version of Android lower than 3.0 and applies +custom themes, then you should select a theme based on platform +version.
+ +Base class for an {@link android.widget.AdapterView} that performs animations when switching + between its views.
Simple {@link android.widget.ViewAnimator} that animates between two or more views that have + been added to it. Only one child is shown at a time. If requested, it can automatically flip + between + each child at a regular interval.
Allows users to select dates from a calendar by touching the date and can scroll or fling the +calendar to a desired date. You can configure the range of dates available in the widget.
Anchors itself to a host view and displays a list of choices, such as for a list of + suggestions when typing into an {@link android.widget.EditText} view.
Enables the user to select a number from a predefined range. The widget presents an input +field and up and down buttons for selecting a number. Touching the input field allows the user to +scroll through values or touch again to directly edit the current value. It also allows you to map +positions to strings, so that the corresponding string is displayed instead of the index +position.
Displays a {@link android.view.Menu} in a modal popup window that's anchored to a view. The +popup appears below the anchor view if there is room, or above it if there is not. If the IME (soft +keyboard) is visible, the popup does not overlap the IME it until the user touches the +menu.
Provides a search box that you can configure to deliver search queries to a specified +activity and display search suggestions (in the same manner as the traditional search dialog). This +widget is particularly useful for offering a search widget in the Action Bar. For more information, +see Creating a Search Interface.
A view that displays its children in a 3D stack and allows users to swipe through + views like a rolodex.
You can now enable the OpenGL renderer for your application by setting {@code +android:hardwareAccelerated="true"} in your manifest element's {@code <application>} +element or for individual {@code <activity>} +elements.
+ +This flag helps applications by making them draw faster. This results in smoother animations, +smoother scrolling, and overall better performance and response to user interaction.
By default, a {@link android.view.View} has no layer specified. You can specify that the +view be backed by either a hardware or software layer, specified by values {@link +android.view.View#LAYER_TYPE_HARDWARE} and {@link android.view.View#LAYER_TYPE_SOFTWARE}, using +{@link android.view.View#setLayerType setLayerType()} or the {@code layerType} +attribute.
+A hardware layer is backed by a hardware specific texture (generally Frame Buffer Objects or +FBO on OpenGL hardware) and causes the view to be rendered using Android's hardware rendering +pipeline, but only if hardware acceleration is turned on for the view hierarchy. When hardware +acceleration is turned off, hardware layers behave exactly as software layers.
+A software layer is backed by a bitmap and causes the view to be rendered using Android's +software rendering pipeline, even if hardware acceleration is enabled. Software layers should be +avoided when the affected view tree updates often. Every update will require to re-render the +software layer, which can potentially be slow.
+For more information, see the {@link android.view.View#LAYER_TYPE_HARDWARE} and {@link +android.view.View#LAYER_TYPE_SOFTWARE} documentation.
+Renderscript is a runtime 3D framework that provides both an API for building 3D scenes as well +as a special, platform-independent shader language for maximum performance. Using Renderscript, you +can accelerate graphics operations and data processing. Renderscript is an ideal way to create +high-performance 3D effects for applications, wallpapers, carousels, and more.
+For more information, see the 3D Rendering and Computation with +Renderscript documentation.
Camcorder APIs now support the ability to record time lapse video. The {@link +android.media.MediaRecorder#setCaptureRate setCaptureRate()} sets the rate at which frames +should be captured.
New {@link android.graphics.SurfaceTexture} allows you to capture an image stream as an OpenGL ES +texture. By calling {@link android.hardware.Camera#setPreviewTexture setPreviewTexture()} for your +{@link android.hardware.Camera} instance, you can specify the {@link +android.graphics.SurfaceTexture} upon which to draw video playback or preview frames from the +camera.
Applications can now pass an M3U playlist URL to the media framework to begin an HTTP Live +streaming session. The media framework supports most of the HTTP Live streaming specification, +including adaptive bit rate. See the Supported Media Formats document for +more information.
The {@link android.media.ExifInterface} includes new fields for photo aperture, ISO, and exposure +time.
New {@link android.media.CamcorderProfile#hasProfile hasProfile()} method and several video +quality profiles (such as {@link android.media.CamcorderProfile#QUALITY_1080P}, {@link +android.media.CamcorderProfile#QUALITY_720P}, {@link +android.media.CamcorderProfile#QUALITY_CIF}, and others) allow you to determine camcorder +quality options.
The platform includes built-in support for Media/Picture Transfer Protocol (MTP/PTP) over USB, +which lets users easily transfer any type of media files between devices and to a host computer. +Developers can build on this support, creating applications that let users create or manage rich +media files that they may want to transfer or share across devices.
New extensible digital rights management (DRM) framework for checking and enforcing digital +rights. It's implemented in two architectural layers:
+For application developers, the framework offers an abstract, unified API that simplifies the +management of protected content. The API hides the complexity of DRM operations and allows a +consistent operation mode for both protected and unprotected content, and across a variety of DRM +schemes.
+ +For device manufacturers, content owners, and Internet digital media providers the DRM +framework?s plugin API provides a means of adding support for a DRM scheme of choice into the +Android system, for secure enforcement of content protection.
+ +The preview release does not provide any native DRM plug-ins for checking and enforcing digital +rights. However, device manufacturers may ship DRM plug-ins with their devices.
+ +You can find all of the DRM APIs in the {@link android.drm} package.
Previously, only a single view could accept touch events at one time. Android 3.0 +adds support for splitting touch events across views and even windows, so different views can accept +simultaneous touch events.
+ +Split touch events is enabled by default when an application targets +Android 3.0. That is, when the application has set either the {@code android:minSdkVersion} +or {@code +android:targetSdkVersion} attribute's value to {@code "11"}.
+ +However, the following properties allow you to disable split touch events across views inside +specific view groups and across windows.
+ ++<LinearLayout android:splitMotionEvents="false" ... > + ... +</LinearLayout> ++
This way, child views in the linear layout cannot split touch events—only one view can +receive touch events at a time.
++<style name="NoSplitMotionEvents" parent="android:Theme.Holo"> + <item name="android:windowEnableSplitTouch">false</item> + ... +</style> ++
When this theme is applied to an {@code <activity>} or {@code <application>}, +only touch events within the current activity window are accepted. For example, by disabling split +touch events across windows, the system bar cannot receive touch events at the same time as the +activity. This does not affect whether views inside the activity can split touch +events—by default, the activity can still split touch events across views.
+ +For more information about creating a theme, read Applying Styles and Themes.
+The Browser application adds the following features to support web applications:
+ +As defined by the HTML Media Capture +specification, the Browser allows web applications to access audio, image and video capture +capabilities of the device. For example, the following HTML provides an input for the user to +capture a photo to upload:
++<input type="file" accept="image/*;capture=camera" /> ++
Or by excluding the {@code capture=camera} parameter, the user can choose to either capture a +new image with the camera or select one from the device (such as from the Gallery application).
+As defined by the Device Orientation Event +specification, the Browser allows web applications to listen to DOM events that provide information +about the physical orientation and motion of the device.
+The device orientation is expressed with the x, y, and z axes, in degrees and motion is +expressed with acceleration and rotation rate data. A web page can register for orientation +events by calling {@code window.addEventListener} with event type {@code "deviceorientation"} +and register for motion events by registering the {@code "devicemotion"} event type.
+As defined by the CSS 3D Transform +Module specification, the Browser allows elements rendered by CSS to be transformed in three +dimensions.
+New classes, {@link android.util.JsonReader} and {@link android.util.JsonWriter}, help you +read and write JSON streams. The new APIs complement the {@link org.json} classes, which manipulate +a document in memory.
+ +You can create an instance of {@link android.util.JsonReader} by calling +its constructor method and passing the {@link java.io.InputStreamReader} that feeds the JSON string. +Then begin reading an object by calling {@link android.util.JsonReader#beginObject()}, read a +key name with {@link android.util.JsonReader#nextName()}, read the value using methods +respective to the type, such as {@link android.util.JsonReader#nextString()} and {@link +android.util.JsonReader#nextInt()}, and continue doing so while {@link +android.util.JsonReader#hasNext()} is true.
+ +You can create an instance of {@link android.util.JsonWriter} by calling its constructor and +passing the appropriate {@link java.io.OutputStreamWriter}. Then write the JSON data in a manner +similar to the reader, using {@link android.util.JsonWriter#name name()} to add a property name +and an appropriate {@link android.util.JsonWriter#value value()} method to add the respective +value.
+ +These classes are strict by default. The {@link android.util.JsonReader#setLenient setLenient()} +method in each class configures them to be more liberal in what they accept. This lenient +parse mode is also compatible with the {@link org.json}'s default parser.
+ + + + +The {@code <uses-feature>} +manfest element should be used to inform external entities (such as Google Play) of the set of +hardware and software features on which your application depends. In this release, Android adds the +following new constants that applications can declare with this element:
+ +When declared, this indicates that the application is compatible with a device that offers an +emulated touchscreen (or better). A device that offers an emulated touchscreen provides a user input +system that can emulate a subset of touchscreen +capabilities. An example of such an input system is a mouse or remote control that drives an +on-screen cursor. Such input systems support basic touch events like click down, click up, and drag. +However, more complicated input types (such as gestures, flings, etc.) may be more difficult or +impossible on faketouch devices (and multitouch gestures are definitely not possible).
+If your application does not require complicated gestures and you do +not want your application filtered from devices with an emulated touchscreen, you +should declare {@link +android.content.pm.PackageManager#FEATURE_FAKETOUCH "android.hardware.faketouch"} with a {@code <uses-feature>} +element. This way, your application will be available to the greatest number of device types, +including those that provide only an emulated touchscreen input.
+All devices that include a touchscreen also support {@link +android.content.pm.PackageManager#FEATURE_FAKETOUCH "android.hardware.faketouch"}, because +touchscreen capabilities are a superset of faketouch capabilities. Thus, unless you actually require +a touchscreen, you should add a {@code <uses-feature>} +element for faketouch.
+This must be declared as a required permission in the {@code <service>} manifest +element for an implementation of {@link android.widget.RemoteViewsService}. For example, when +creating an App Widget that uses {@link android.widget.RemoteViewsService} to populate a +collection view, the manifest entry may look like this:
++<service android:name=".widget.WidgetService" + android:exported="false" + android:permission="android.permission.BIND_REMOTEVIEWS" /> ++
For a detailed view of all API changes in Android {@sdkPlatformVersion} (API Level +{@sdkPlatformApiLevel}), see the API Differences Report.
+ + + + + +The Android {@sdkPlatformVersion} platform delivers an updated version of +the framework API. The Android {@sdkPlatformVersion} API +is assigned an integer identifier — +{@sdkPlatformApiLevel} — that is +stored in the system itself. This identifier, called the "API Level", allows the +system to correctly determine whether an application is compatible with +the system, prior to installing the application.
+ +To use APIs introduced in Android {@sdkPlatformVersion} in your application,
+you need compile the application against the Android library that is provided in
+the Android {@sdkPlatformVersion} SDK platform. Depending on your needs, you might
+also need to add an android:minSdkVersion="{@sdkPlatformApiLevel}"
+attribute to the <uses-sdk> element in the application's
+manifest. If your application is designed to run only on Android 2.3 and higher,
+declaring the attribute prevents the application from being installed on earlier
+versions of the platform.
For more information, read What is API +Level?
diff --git a/docs/html/about/versions/android-3.1-highlights.jd b/docs/html/about/versions/android-3.1-highlights.jd new file mode 100644 index 000000000000..5283c2a45861 --- /dev/null +++ b/docs/html/about/versions/android-3.1-highlights.jd @@ -0,0 +1,381 @@ +page.title=Honeycomb MR1 + +@jd:body + + + + +Welcome to Android 3.1!
+ +Android 3.1 is an incremental platform release that refines many of the +features introduced in Android 3.0. It builds on the same tablet-optimized UI +and features offered in Android 3.0 and adds several new capabilities for +users and developers. This document provides an overview of the new features and +technologies introduced in Android 3.1. For a more detailed look at new +developer APIs, see the API +Overview document.
+ +For a high-level introduction to Android 3.0, please see the Android 3.0 Platform +Highlights.
+ + + +The Android 3.1 platform adds a variety of refinements to make the user +interface more intuitive and more efficient to use.
+ +UI transitions are improved throughout the system and across the standard +apps. The Launcher animation is optimized for faster, smoother transition to and +from the Apps list. Adjustments in color, positioning, and text make UI elements +easier to see, understand, and use. Accessibility is improved with consistent +audible feedback throughout the UI and a new setting to let users customize the +touch-hold interval to meet their needs.
+ +Navigation to and from the five home screens is now easier — touching +the Home button in the system bar now takes you to the home screen most recently +used. Settings offers an improved view of internal storage, +showing the storage used by a larger set of file types.
+ +Android 3.1 adds broad platform support for a variety of USB-connected +peripherals and accessories. Users can attach many types of input devices +(keyboards, mice, game controllers) and digital cameras. Applications can build +on the platform’s USB support to extend connectivity to almost any type of USB +device.
+ +The platform also adds new support for USB accessories — external +hardware devices designed to attach to Android-powered devices as USB hosts. When an +accessory is attached, the framework will look for a corresponding application +and offer to launch it for the user. The accessory can also present a URL +to the user, for downloading an appropriate application if one is not already +installed. Users can interact with the application to control powered accessories such +as robotics controllers; docking stations; diagnostic and musical equipment; +kiosks; card readers; and much more.
+ +The platform’s USB capabilities rely on components in device hardware, so +support for USB on specific devices may vary and is determined by device +manufacturers.
+ +
+For improved multitasking and instant visual access to a much larger number +of apps, the Recent Apps list is now expandable. Users can now scroll the list +of recent apps vertically to see thumbnail images all of the tasks in progress +and recently used apps, then touch a thumbnail to jump back into that task.
+ +For more flexible Home screen customization, users can now resize their Home +screen widgets using drag bars provided by the system. Users can expand widgets +both horizontally and/or vertically to include more content, where supported by +each widget.
+ + +Users can now attach almost any type of external keyboard or mouse to their +Android-powered devices, to create a familiar environment and work more +efficiently. One or more input devices can be attached to the system simultaneously +over USB and/or Bluetooth HID, in any combination. No special configuration or +driver is needed, in most cases. When multiple devices are connected, users can +conveniently manage the active keyboard and IME using the keyboard settings that +are available from the System bar.
+ +For pointing devices, the platform supports most types of mouse with a single +button and optionally a scroll wheel, as well as similar devices such as +trackballs. When these are connected, users can interact with the UI using +point, select, drag, scroll, hover, and other standard actions.
+ +To make the platform even better for gaming, Android 3.1 adds support for +most PC joysticks and gamepads that are connected over USB or Bluetooth HID.
+ +For example, users can connect PlayStation®3 and Xbox 360® +game controllers over USB (but not Bluetooth), Logitech Dual Action™ gamepads and +flight sticks, or a car racing controller. Game controllers that use proprietary +networking or pairing are not supported by default, but in general, the platform +supports most PC-connectible joysticks and gamepads.
+ +Android 3.1 adds robust Wi-Fi features, to make sure that users and their +apps can take full advantage of higher-speed Wi-Fi access at home, at work, and +while away.
+ +A new high-performance Wi-Fi lock lets applications maintain +high-performance Wi-Fi connections even when the device screen is off. Users can +take advantage of this to play continuous streamed music, video, and voice +services for long periods, even when the device is otherwise idle and the screen +is off.
+ +Users can now configure an HTTP proxy for each individual Wi-Fi access +point, by touch-hold of the access point in Settings. The browser uses the HTTP +proxy when communicating with the network over the access point and other apps +may also choose to do so. The platform also provides backup and restore of the +user-defined IP and proxy settings.
+The platform adds support for Preferred Network Offload (PNO), a background +scanning capability that conserves battery power savings in cases where Wi-Fi +needs to be available continuously for long periods of time.
+ +The Android 3.1 platform includes an updated set of standard applications +that are optimized for use on larger screen devices. The sections below +highlight some of the new features.
+ +
+Browser
+ +The Browser app includes a variety of new features and UI improvements that +make viewing web content simpler, faster, and more convenient.
+ +The Quick Controls UI, accessible from Browser Settings, is extended and +redesigned. Users can now use the controls to view thumbnails of open tabs and +close the active tab, as well as access the overflow menu for instant access to +Settings and other controls.
+ +To ensure a consistent viewing experience, the Browser extends it's support +for popular web standards such as CSS 3D, animations, and CSS fixed +positioning to all sites, mobile or desktop. It also adds support for embedded +playback of HTML5 video content. To make it easier to manage favorite +content, users can now save a web page locally for offline viewing, including +all styling and images. For convenience when visiting Google sites, an improved +auto-login UI lets users sign in quickly and manage access when multiple users +are sharing a device.
+ +For best performance, the Browser adds support for plugins that use hardware +accelerated rendering. Page zoom performance is also dramatically improved, +making it faster to navigate and view web pages.
+ +Gallery
+ +The Gallery app now supports Picture Transfer Protocol (PTP), so that users +can connect their cameras over USB and import their pictures to Gallery with a +single touch. The app also copies the pictures to local storage and provides an +indicator to let users see how much space is available.
+ +
+Calendar
+ +Calendar grids are larger, for better readability and more accurate +touch-targeting. Additionally, users can create a larger viewing area for grids +by hiding the calendar list controls. Controls in the date picker are +redesigned, making them easier to see and use. + + +
Contacts
+ +The Contacts app now lets you locate contacts more easily using full text +search. Search returns matching results from all fields that are stored for a +contact. +
+ +When replying or forwarding an HTML message, The Email app now sends both +plain text and HTML bodies as a multi-part mime message. This ensures that the +message will be formatted properly for all recipients. Folder prefixes for IMAP +accounts are now easier to define and manage. To conserve battery power and +minimize cell data usage, the application now prefetches email from the server +only when the device is connected to a Wi-Fi access point.
+ +An updated Home screen widget give users quick access to more email. Users +can touch Email icon at the top of the widget to cycle through labels such as +Inbox, Unread, and Starred. The widget itself is now resizable, both +horizontally and vertically.
+ +Users can now configure an HTTP proxy for each connected Wi-Fi access point. +This lets administrators work with users to set a proxy hostname, port, and any +bypass subdomains. This proxy configuration is automatically used by the Browser +when the Wi-Fi access point is connected, and may optionally be used by other +apps. The proxy and IP configuration is now backed up and restored across system +updates and resets.
+ +To meet the needs of tablet users, the platform now allows a "encrypted +storage card" device policy to be accepted on devices with emulated storage +cards and encrypted primary storage.
+ + +The Android 3.1 platform adds refinements and new capabilities that +developers can build on, to create powerful and engaging application experiences +on tablets and other large-screen devices.
+ +Android 3.1 introduces a new API for integrating hardware accessories with +applications running on the platform. The API provides a way to interact across +a wide range of peripherals, from robotics controllers to musical equipment, +exercise bicycles, and more.
+ +The API is based on a new USB (Universal Serial Bus) stack and services +that are built into the platform. The platform provides services for discovering +and identifying connected hardware, as well as for notifying interested +applications that the hardware is available.
+ +When a user plugs in a USB accessory, the platform receives +identifying information such as product name, accessory type, manufacturer, and +version. The platform sets up communication with the accessory and uses its +information to notify and launch a targeted app, if one is available. Optionally, +an accessory can provide a URL that lets users find and download an +app that works with the accessory. These discovery features make +first-time setup easier for the user and ensure that an appropriate application +is available for interacting with the connected hardware.
+ +For application developers and accessory manufacturers, accessory mode offers +many new ways to engage users and build powerful interaction experiences with +connected hardware.
+ +To learn more about how to develop applications that interact with +accessories, see the USB +Accessory documentation.
+ +Android 3.1 provides built-in platform support for USB host mode and exposes +an API that lets applications manage connected peripherals. On devices that +support host mode, applications can use the API to identify and communicate with +connected devices such as audio devices. input devices, communications devices, +hubs, cameras, and more.
+ +To learn more about how to develop applications that interact with +USB devices, see the USB +Host documentation.
+ +Android 3.1 extends the input event system to support a variety of new input +sources and motion events, across all views and windows. Developers can build on +these capabilities to let users interact with their applications using mice, +trackballs, joysticks, gamepads, and other devices, in addition to keyboards and +touchscreens.
+ +For mouse and trackball input, the platform supports two new motion event +actions: scroll (horizontal or vertical) such as from a scrollwheel; and hover, +which reports the location of the mouse when no buttons are pressed. +Applications can handle these events in any way needed.
+ +For joysticks and gamepads, the platform provides a large number of motion +axes that applications can use from a given input source, such as X, Y, Hat X, +Hat Y, rotation, throttle, pressure, size, touch, tool, orientation, and others. +Developers can also define custom axes if needed, to capture motion in +additional ways. The platform provides motion events to applications as a batch, +and applications can query the details of the movements included in the batch, +for more efficient and precise handling of events.
+ +Applications can query for the list of connected input devices and the motion +ranges (axes) supported by each device. Applications can also handle multiple +input and motion events from a single input device. For example, an application +can use mouse and joystick and mouse event sources from a single input +device.
+ +Developers can now create Home screen widgets that users can resize +horizontally, vertically, or both. By simply adding an attribute to the +declaration of a widget, the widget becomes resizable horizontally, vertically, +or both. This lets users customize the display of the widget content and display +more of it on their Home screens.
+ +In Android 3.1, a new MTP (Media Transfer Protocol) API lets developers write +apps that interact directly with connected cameras and other PTP devices. The +new API makes it easy for applications to receive notifications when devices are +attached and removed, manage files and storage on those devices, and transfer +files and metadata to and from them. The MTP API implements the PTP (Picture +Transfer Protocol) subset of the MTP specification.
+ +Android 3.1 exposes an API to its built-in RTP (Real-time Transport Protocol) +stack, which applications can use to directly manage on-demand or interactive +data streaming. In particular, apps that provide VOIP, push-to-talk, +conferencing, and audio streaming can use the API to initiate sessions and +transmit or receive data streams over any available network.
+ +Android 3.1 includes a variety of performance optimizations that help make +applications faster and more responsive. Some of the optimizations include:
+ +API Level: {@sdkPlatformApiLevel}
+ +For developers, the Android {@sdkPlatformVersion} platform is available as a +downloadable component for the Android SDK. The downloadable platform includes +an Android library and system image, as well as a set of emulator skins and +more. The downloadable platform includes no external libraries.
+ +For developers, the Android {@sdkPlatformVersion} platform is available as a +downloadable component for the Android SDK. The downloadable platform includes +an Android library and system image, as well as a set of emulator skins and +more. To get started developing or testing against Android {@sdkPlatformVersion}, +use the Android SDK Manager to download the platform into your SDK.
+ + + +The sections below provide a technical overview of what's new for developers +in Android 3.1, including new features and changes in the framework API since +the previous version.
+ +Android 3.1 introduces powerful new APIs for +integrating connected peripherals with applications running on the platform. +The APIs are based on a USB (Universal Serial Bus) stack and services that are +built into the platform, including support for both USB host and device +interactions. Using the APIs, developers can create applications that are able to +discover, communicate with, and manage a variety of device types connected over +USB.
+ +The stack and APIs distinguish two basic types of USB hardware, based on +whether the Android-powered device is acting as host or the external hardware +is acting as host:
+ +For both types — USB devices and USB accessories — the +platform's USB APIs support discovery by intent broadcast when attached or +detached, as well as standard interfaces, endpoints, and transfer modes +(control, bulk, and interrupt).
+ +The USB APIs are available in the package {@link android.hardware.usb}. The +central class is {@link android.hardware.usb.UsbManager}, which provides +helper methods for identifying and communicating with +both USB devices and USB accessories. Applications can acquire an instance of +{@link android.hardware.usb.UsbManager} and then query for the list of attached +devices or accessories and then communicate with or manage them. +{@link android.hardware.usb.UsbManager} also declares intent actions that the +system broadcasts, to announce when a USB device or accessory is attached or +detached.
+ +Other classes include:
+ +Note that although the USB stack is built into the platform, actual support +for USB host and open accessory modes on specific devices is determined by +their manufacturers. In particular, host mode relies on appropriate USB +controller hardware in the Android-powered device.
+ +Additionally, developers can request filtering on Google Play, such that +their applications are not availabe to users whose devices do not provide the +appropriate USB support. To request filtering, add one or both of the elements +below to the application manifest, as appropriate:
+ +<uses-feature
+ android:name="android.hardware.usb.host"
+ android:required="true">
<uses-feature
+ android:name="android.hardware.usb.accessory"
+ android:required="true">
For complete information about how to develop applications that interact with +USB accessories, please see the +developer documentation.
+ +To look at sample applications that use the USB host API, see ADB Test and Missile +Launcher
+ +Android 3.1 exposes a new MTP API that lets applications interact directly +with connected cameras and other PTP devices. The new API makes it easy for an +application to receive notifications when devices are attached and removed, +manage files and storage on those devices, and transfer files and metadata to +and from them. The MTP API implements the PTP (Picture Transfer Protocol) subset +of the MTP (Media Transfer Protocol) specification.
+ +The MTP API is available in the {@link android.mtp} package and provides +these classes:
+ +Android 3.1 extends the input subsystem to support new input devices and new +types of motion events, across all views and windows. Developers can build on +these capabilities to let users interact with their applications using mice, +trackballs, joysticks, gamepads, and other devices, in addition to keyboards and +touchscreens.
+ +For handling mouse, scrollwheel, and trackball input, the platform supports +two new motion event actions:
+HOVER_MOVE event. Hover enter and exit
+notifications are not yet supported.To support joysticks and gamepads, the {@link android.view.InputDevice} class +includes these new input device sources:
+To describe motion events from these new sources, as well as those from mice +and trackballs, the platform now defines axis codes on {@link +android.view.MotionEvent}, similar to how it defines key codes on {@link +android.view.KeyEvent}. New axis codes for joysticks +and game controllers include +{@link android.view.MotionEvent#AXIS_HAT_X}, {@link +android.view.MotionEvent#AXIS_HAT_Y}, {@link +android.view.MotionEvent#AXIS_RTRIGGER}, {@link +android.view.MotionEvent#AXIS_ORIENTATION}, {@link +android.view.MotionEvent#AXIS_THROTTLE}, and many others. +Existing {@link android.view.MotionEvent} axes are represented by {@link +android.view.MotionEvent#AXIS_X}, {@link android.view.MotionEvent#AXIS_Y}, +{@link android.view.MotionEvent#AXIS_PRESSURE}, {@link +android.view.MotionEvent#AXIS_SIZE}, {@link +android.view.MotionEvent#AXIS_TOUCH_MAJOR}, {@link +android.view.MotionEvent#AXIS_TOUCH_MINOR}, {@link +android.view.MotionEvent#AXIS_TOOL_MAJOR}, {@link +android.view.MotionEvent#AXIS_TOOL_MINOR}, and {@link +android.view.MotionEvent#AXIS_ORIENTATION}.
+ +Additionally, {@link android.view.MotionEvent} defines a number of generic +axis codes that are used when the framework does not know how to map a +particular axis. Specific devices can use the generic axis codes to pass custom +motion data to applications. For a full list of axes and their intended +interpretations, see the {@link android.view.MotionEvent} class documentation. +
+ +The platform provides motion events to applications in batches, so a single +event may contain a current position and multiple so-called historical movements. +Applications should use {@link android.view.MotionEvent#getHistorySize()} to get +the number of historical samples, then retrieve and process all historical +samples in order using {@link +android.view.MotionEvent#getHistoricalAxisValue(int, int, int) +getHistoricalAxisValue()}. After that, applications should process the current +sample using {@link android.view.MotionEvent#getAxisValue(int) getAxisValue()}. +
+ +Some axes can be retrieved using special accessor methods. For example, +instead of calling {@link android.view.MotionEvent#getAxisValue(int) +getAxisValue()}, applications can call {@link android.view.MotionEvent#getX(int) +getX()}. Axes that have built-in accessors include {@link +android.view.MotionEvent#AXIS_X}, {@link android.view.MotionEvent#AXIS_Y}, +{@link android.view.MotionEvent#AXIS_PRESSURE}, {@link +android.view.MotionEvent#AXIS_SIZE}, {@link +android.view.MotionEvent#AXIS_TOUCH_MAJOR}, {@link +android.view.MotionEvent#AXIS_TOUCH_MINOR}, {@link +android.view.MotionEvent#AXIS_TOOL_MAJOR}, {@link +android.view.MotionEvent#AXIS_TOOL_MINOR}, and {@link +android.view.MotionEvent#AXIS_ORIENTATION}.
+ +Each input device has a unique, system-assigned ID and may also provide +multiple sources. When a device provides multiple sources, more than one source +can provide axis data using the same axis. For example, a touch event coming +from the touch source uses the X axis for screen position data, while a joystick +event coming from the joystick source will use the X axis for the stick position +instead. For this reason, it's important for applications to interpret axis +values according to the source from which they originate. When handling a motion +event, applications should use methods on the {@link android.view.InputDevice} +class to determine the axes supported by a device or source. Specifically, +applications can use {@link android.view.InputDevice#getMotionRanges() +getMotionRanges()} to query for all axes of a device or all axes of a given +source of the device. In both cases, the range information for axes returned in +the {@link android.view.InputDevice.MotionRange} object specifies the source for +each axis value.
+ +Finally, since the motion events from joysticks, gamepads, mice, and +trackballs are not touch events, the platform adds a new callback method for +passing them to a {@link android.view.View} as "generic" motion events. +Specifically, it reports the non-touch motion events to +{@link android.view.View}s through a call to {@link +android.view.View#onGenericMotionEvent(android.view.MotionEvent) +onGenericMotionEvent()}, rather than to {@link +android.view.View#onTouchEvent(android.view.MotionEvent) +onTouchEvent()}.
+ +The platform dispatches generic motion events differently, depending on the +event source class. {@link android.view.InputDevice#SOURCE_CLASS_POINTER} events +go to the {@link android.view.View} under the pointer, similar to how touch +events work. All others go to the currently focused {@link android.view.View}. +For example, this means a {@link android.view.View} must take focus in order to +receive joystick events. If needed, applications can handle these events at the +level of Activity or Dialog by implementing {@link +android.view.View#onGenericMotionEvent(android.view.MotionEvent) +onGenericMotionEvent()} there instead.
+ +To look at a sample application that uses joystick motion +events, see GameControllerInput +and GameView.
+ +Android 3.1 exposes an API to its built-in RTP (Real-time Transport Protocol) +stack, which applications can use to manage on-demand or interactive data +streaming. In particular, apps that provide VOIP, push-to-talk, conferencing, +and audio streaming can use the API to initiate sessions and transmit or receive +data streams over any available network.
+ +The RTP API is available in the {@link android.net.rtp} package. Classes +include:
+To support audio conferencing and similar usages, an application instantiates +two classes as endpoints for the stream:
+ +The simplest usage involves a single remote endpoint and local endpoint. +For more complex usages, please refer to the limitations described for +{@link android.net.rtp.AudioGroup}.
+ +To use the RTP API, applications must request permission from the user by
+declaring <uses-permission
+android:name="android.permission.INTERNET">
+in their manifest files. To acquire the device microphone, the <uses-permission
+android:name="android.permission.RECORD_AUDIO"> permission is also required.
Starting in Android 3.1, developers can make their homescreen widgets +resizeable — horizontally, vertically, or on both axes. Users touch-hold a +widget to show its resize handles, then drag the horizontal and/or vertical +handles to change the size on the layout grid.
+ +Developers can make any Home screen widget resizeable by defining a
+resizeMode attribute in the widget's {@link
+android.appwidget.AppWidgetProviderInfo} metadata. Values for the
+resizeMode attribute include "horizontal", "vertical", and "none".
+To declare a widget as resizeable horizontally and vertically, supply the value
+"horizontal|vertical".
+
+
Here's an example:
+ +<appwidget-provider xmlns:android="http://schemas.android.com/apk/res/android" + android:minWidth="294dp" + android:minHeight="72dp" + android:updatePeriodMillis="86400000" + android:previewImage="@drawable/preview" + android:initialLayout="@layout/example_appwidget" + android:configure="com.example.android.ExampleAppWidgetConfigure" + android:resizeMode="horizontal|vertical" > +</appwidget-provider>+ +
For more information about Home screen widgets, see the App Widgets +documentation.
+ +Using the {@link android.view.ViewPropertyAnimator} is straightforward. To animate properties for
+a {@link android.view.View}, call {@link android.view.View#animate()} to
+construct a {@link android.view.ViewPropertyAnimator} object for that {@link android.view.View}. Use the
+methods on the {@link android.view.ViewPropertyAnimator} to specify what property to
+animate and how to animate it. For example, to fade the {@link android.view.View} to transparent,
+call alpha(0);. The {@link android.view.ViewPropertyAnimator} object
+handles the details of configuring the underlying {@link
+android.animation.Animator} class and starting it, then rendering the
+animation.
ViewAnimator
+ To create a high-performance lock, pass {@link +android.net.wifi.WifiManager#WIFI_MODE_FULL_HIGH_PERF} as the lock mode in a +call to {@link android.net.wifi.WifiManager#createWifiLock(int, +java.lang.String) createWifiLock()}.
Starting from Android 3.1, the system's package manager keeps track of +applications that are in a stopped state and provides a means of controlling +their launch from background processes and other applications.
+ +Note that an application's stopped state is not the same as an Activity's +stopped state. The system manages those two stopped states separately.
+ +The platform defines two new intent flags that let a sender specify +whether the Intent should be allowed to activate components in stopped +application.
+ +When neither or both of these flags is defined in an intent, the default +behavior is to include filters of stopped applications in the list of +potential targets.
+ +Note that the system adds {@link +android.content.Intent#FLAG_EXCLUDE_STOPPED_PACKAGES} to all broadcast +intents. It does this to prevent broadcasts from background services from +inadvertently or unnecessarily launching components of stoppped applications. +A background service or application can override this behavior by adding the +{@link android.content.Intent#FLAG_INCLUDE_STOPPED_PACKAGES} flag to broadcast +intents that should be allowed to activate stopped applications.
+ +Applications are in a stopped state when they are first installed but are not +yet launched and when they are manually stopped by the user (in Manage +Applications).
+ +The platform adds improved notification of application first launch and +upgrades through two new intent actions:
+ +This intent is sent directly to the application, but only if the application +was upgraded while it was in started state (not in a stopped state).
int
+ file: URI scheme. You can use {@link
+android.webkit.CookieManager#setAcceptFileSchemeCookies(boolean)
+setAcceptFileSchemeCookies()} to
+enable/disable support for file scheme cookies, before constructing an instance
+of WebView or CookieManager. In a
+CookieManager instance, you can check whether file scheme cookies
+is enabled by calling {@link
+android.webkit.CookieManager#allowFileSchemeCookies()}.The Browser application adds the following features to support web +applications:
+ +<video> tag. Playback is hardware-accelerated where possible.
+The platform adds new hardware feature constants that developers can declare +in their application manifests, to inform external entities such as Google +Play of the application's requirement for new hardware capabilities supported +in this version of the platform. Developers declare these and other feature +constants in {@code +<uses-feature>} manifest elements. + +
Google Play filters applications based on features declared in {@code +<uses-feature>} manifest elements. For more information about +declaring features in an application manifest, read Google Play +Filters.
+ + + +For a detailed view of all API changes in Android {@sdkPlatformVersion} (API +Level +{@sdkPlatformApiLevel}), see the API +Differences Report.
+ + + + + +The Android {@sdkPlatformVersion} platform delivers an updated version of +the framework API. The Android {@sdkPlatformVersion} API +is assigned an integer identifier — +{@sdkPlatformApiLevel} — that is +stored in the system itself. This identifier, called the "API Level", allows the +system to correctly determine whether an application is compatible with +the system, prior to installing the application.
+ +To use APIs introduced in Android {@sdkPlatformVersion} in your application,
+you need compile the application against the Android library that is provided in
+the Android {@sdkPlatformVersion} SDK platform. Depending on your needs, you
+might
+also need to add an android:minSdkVersion="{@sdkPlatformApiLevel}"
+attribute to the <uses-sdk> element in the application's
+manifest.
For more information, read What is API +Level?
diff --git a/docs/html/about/versions/android-3.2.jd b/docs/html/about/versions/android-3.2.jd new file mode 100644 index 000000000000..02111a058737 --- /dev/null +++ b/docs/html/about/versions/android-3.2.jd @@ -0,0 +1,556 @@ +page.title=Android 3.2 Platform +sdk.platform.version=3.2 +sdk.platform.apiLevel=13 +@jd:body + +API Level: {@sdkPlatformApiLevel}
+ +Android 3.2 is an incremental platform release that adds new +capabilities for users and developers. The sections below provide an overview +of the new features and developer APIs.
+ +For developers, the Android {@sdkPlatformVersion} platform is available as a +downloadable component for the Android SDK. The downloadable platform includes +an Android library and system image, as well as a set of emulator skins and +more. To get started developing or testing against Android {@sdkPlatformVersion}, +use the Android SDK Manager to download the platform into your SDK.
+ + + +Android 3.2 includes a variety of optimizations across the system +to ensure a great user experience on a wider range of tablet devices.
Android 3.2 introduces a new compatibility zoom mode that gives +users a new way to view fixed-sized apps on larger devices. The new mode provides a +pixel-scaled alternative to the standard UI stretching for apps that are not +designed to run on larger screen sizes, such as on tablets. The new mode is +accessible to users from a menu icon in the system bar, for apps that need +compatibility support.
On devices that support an SD card, users can now load media files directly +from the SD card to apps that use them. A system facility makes the files +accessible to apps from the system media store.
Android 3.2 introduces extensions to the platform's screen support API to +give developers additional ways to manage application UI across the range of +Android-powered devices. The API includes new resource qualifiers and new +manifest attributes that give you more precise control over how your +apps are displayed on different sizes, rather than relying on generalized +size categories.
+ +To ensure the best possible display for fixed-sized apps and apps with limited +support for various screen sizes, the platform also provides a new zoom +compatibility mode that renders the UI on a smaller screen area, then scales it +up to fill the space available on the display. For more information about the +screen support API and the controls it provides, see the sections below.
Android 3.2 introduces new screens support APIs that give you more +control over how their applications are displayed across different screen sizes. +The API builds on the existing screens-support API, including the platform's +generalized screen density model, but extends it with the ability to precisely +target specific screen ranges by their dimensions, measured in +density-independent pixel units (such as 600dp or 720dp wide), rather than +by their generalized screen sizes (such as large or xlarge)
+ +When designing an application's UI, you can still rely on the platform to +provide density abstraction, which means that applications do not need to +compensate for the differences in actual pixel density across devices. You +can design the application UI according to the amount of horizontal or vertical +space available. The platform expresses the amount of space available using three new +characteristics: smallestWidth, width, and +height.
+ +The new screens support API is designed to let you manage application UI +according to the smallestWidth of the current screen. You can also manage the +UI according to current width or height, as needed. For those purposes, the API +provides these tools:
+ +Additionally, applications can still query the system and manage UI and +resource loading at runtime, as in the previous versions of the platform.
+ +Since the new API lets you target screens more directly through smallestWidth, +width, and height, it's helpful to understand the typical +characteristics of the different screen types. The table below provides some +examples, measured in "dp" units.
+ +Table 1. Typical devices, with density +and size in dp.
+ +| Type | +Density (generalized) | +Dimensions (dp) | +smallestWidth (dp) | +
|---|---|---|---|
| Baseline phone | +mdpi | +320x480 | +320 | + +
| Small tablet/large phone | +mdpi | +480x800 | +480 | +
| 7-inch tablet | +mdpi | +600x1024 | +600 | +
| 10-inch tablet | +mdpi | +800x1280 | +800 | +
The sections below provide more information about the new screen qualifiers +and manifest attributes. For complete information about how to use the screen +support API, see Supporting Multiple +Screens.
+ +The new resource qualifiers in Android 3.2 let you better target your layouts +for ranges of screen sizes. Using the qualifiers, you can create resource +configurations designed for a specific minimum smallestWidth, current width, or +current height, measured in density-independent pixels.
+ +The new qualifiers are:
+swNNNdp — Specifies the minimum smallestWidth on which
+the resource should be used, measured in "dp" units. As mentioned above, a
+screen's smallestWidth is constant, regardless of orientation. Examples:
+sw320dp, sw720dp, sw720dp.wNNNdp and hNNNdp — Specifies the minimum
+width or height on which the resource should be used, measured in "dp" units. As
+mentioned above, a screen's width and height are relative to the orientation of
+the screen and change whenever the orientation changes. Examples:
+w320dp, w720dp, h1024dp.You can also create multiple overlapping resource configurations if needed. +For example, you could tag some resources for use on any screen wider than 480 +dp, others for wider than 600 dp, and others for wider than 720 dp. When +multiple resource configurations are qualified for a given screen, the system +selects the configuration that is the closest match. For precise control over +which resources are loaded on a given screen, you can tag resources with one +qualifier or combine several new or existing qualifiers. + +
Based on the typical dimensions listed earlier, here are some examples of how +you could use the new qualifiers:
+ +res/layout/main_activity.xml # For phones +res/layout-sw600dp/main_activity.xml # For 7” tablets +res/layout-sw720dp/main_activity.xml # For 10” tablets +res/layout-w600dp/main_activity.xml # Multi-pane when enough width +res/layout-sw600dp-w720dp/main_activity.xml # For large width+ +
Older versions of the platform will ignore the new qualifiers, so you can +mix them as needed to ensure that your app looks great on any device. Here +are some examples:
+ +res/layout/main_activity.xml # For phones +res/layout-xlarge/main_activity.xml # For pre-3.2 tablets +res/layout-sw600dp/main_activity.xml # For 3.2 and up tablets+ +
For complete information about how to use the new qualifiers, see Using new +size qualifiers.
+ +The framework offers a new set of <supports-screens> manifest attributes that let
+you manage your app's support for different screen sizess.
+Specifically, you can specify the largest and smallest screens on which your app
+is designed to run, as well as the largest screen on which it is designed run
+without needing the system's new screen
+compatibility mode. Like the resource qualifiers described above, the new
+manifest attributes specify the range of screens that the application supports,
+as specified by the smallestWidth.
The new manifest attributes for screen support are:
+ +android:compatibleWidthLimitDp="numDp" — This
+attribute lets you specify the maximum smallestWidth on which the application
+can run without needing compatibility mode. If the current screen is larger than
+the value specified, the system displays the application in normal mode but
+allows the user to optionally switch to compatibility mode through a setting in
+the system bar.android:largestWidthLimitDp="numDp" — This
+attribute lets you specify the maximum smallestWidth on which the application
+is designed to run. If the current screen is larger than the value specified,
+the system forces the application into screen compatibility mode, to ensure best
+display on the current screen.android:requiresSmallestWidthDp="numDp" — This
+attribute lets you specify the minimum smallestWidth on which the application
+can run. If the current screen is smaller than the value specified, the system
+considers the application incompatible with the device, but does not prevent it
+from being installed and run.Note: Google Play does not currently filter
+apps based on any of the attributes above. Support for filtering will be
+added in a later platform release. Applications that require
+filtering based on screen size can use the existing <supports-screens>
+attributes.
For complete information about how to use the new attributes, see Declaring +screen size support.
+ +Android 3.2 provides a new screen compatibility mode for applications +explicitly declaring that they do not support screens as large as the one on +which they are running. This new "zoom" mode is a pixel-scaled — it +renders the application in a smaller screen area and then scales the pixels to +fill the current screen.
+ +By default, the system offers screen compatibility mode as an user option, for apps +that require it. Users can turn the zoom mode on and off using a control available +in the system bar.
+ +Because the new screen compatibility mode may not be appropriate for all +applications, the platform allows the application to disable it using manifest +attributes. When disabled by the app, the system does not offer "zoom" compatibility +mode as an option for users when the app is running.
+ +Note: For important information about how +to control compatibility mode in your applications, please review the New Mode for Apps on Large Screens article on the Android +Developers Blog.
+ +To meet the needs of applications running on 720p televisions or similar with
+moderate density screens, Android 3.2 introduces a new generalized density,
+tvdpi, with an approximate dpi of 213. Applications can query for
+the new density in {@link android.util.DisplayMetrics#densityDpi} and can use
+the new tvdpi qualifier to tag resources for televisions and
+similar devices. For example:
res/drawable-tvdpi/my_icon.png # Bitmap for tv density+ +
In general, applications should not need to work with this density. For situations +where output is needed for a 720p screen, the UI elements can be scaled +automatically by the platform.
+ + +<supports-screens> attributes
+ in the application manifest file.The platform adds new hardware feature constants that you can declare +in their application manifests, to inform external entities such as Google +Play of required hardware and software capabilities. You declare these +and other feature constants in {@code +<uses-feature>} manifest elements. + +
Google Play filters applications based on their <uses-feature> attributes, to ensure that they are available only to devices on which their requirements are met.
Android 3.2 introduces new feature constants that let applications specify whether they require display in landscape orientation, portrait orientation, or both. Declaring these constants indicates that the application must not be installed on a device that doesn't offer the associated orientation. Conversely, if one or both of the constants are not declared, it indicates that the application does not have a preference for the undeclared orientations and may be installed on a device that doesn't offer them.
+ +A typical application that functions properly in both landscape and portrait orientations would not normally need to declare an orientation requirement. Rather, an application designed primarily for one orientation, such as an app designed for a television, could declare one of the constants to ensure that it isn't available to devices that don't provide that orientation.
+ +If any of activities declared in the manifest request that they run in a specific orientation, +using the {@code +android:screenOrientation} attribute, then this also declares that the application +requires that orientation.
+ +For a detailed view of all API changes in Android {@sdkPlatformVersion} (API +Level +{@sdkPlatformApiLevel}), see the API +Differences Report.
+ + + + + +The Android {@sdkPlatformVersion} platform delivers an updated version of +the framework API. The Android {@sdkPlatformVersion} API +is assigned an integer identifier — +{@sdkPlatformApiLevel} — that is +stored in the system itself. This identifier, called the "API Level", allows the +system to correctly determine whether an application is compatible with +the system, prior to installing the application.
+ +To use APIs introduced in Android {@sdkPlatformVersion} in your application,
+you need compile the application against the Android library that is provided in
+the Android {@sdkPlatformVersion} SDK platform. Depending on your needs, you
+might
+also need to add an android:minSdkVersion="{@sdkPlatformApiLevel}"
+attribute to the <uses-sdk> element in the application's
+manifest.
For more information, read What is API +Level?
+ + diff --git a/docs/html/about/versions/android-4.0-highlights.jd b/docs/html/about/versions/android-4.0-highlights.jd new file mode 100644 index 000000000000..9fdb02c8815b --- /dev/null +++ b/docs/html/about/versions/android-4.0-highlights.jd @@ -0,0 +1,1066 @@ +page.title=Ice Cream Sandwich + +@jd:body + + + + +Welcome to Android 4.0!
+ +Android 4.0 delivers a refined, unified UI for phones and tablets and +introduces innovative features for users and developers. This document provides +a glimpse of the many new features and technologies that make Android 4.0 +simple, beautiful, and beyond smart.
+ + + +Android 4.0 builds on the things people love most about Android — easy +multitasking, rich notifications, customizable home screens, resizable widgets, +and deep interactivity — and adds powerful new ways of communicating and +sharing.
+ +Refined, evolved UI
+ +Focused on bringing the power of Android to the surface, Android 4.0 makes +common actions more visible and lets users navigate with +simple, intuitive gestures. Refined animations and feedback +throughout the system make interactions engaging and interesting. An entirely +new typeface optimized for high-resolution screens improves +readability and brings a polished, modern feel to the user interface.
+ +Virtual buttons in the System Bar let users navigate instantly to Back, Home, +and Recent Apps. The System Bar and virtual buttons are present +across all apps, but can be dimmed by applications for full-screen viewing. +Users can access each application's contextual options in the Action +Bar, displayed at the top (and sometimes also at the bottom) of the +screen.
+ +Multitasking is a key strength of Android and it's made even +easier and more visual on Android 4.0. The Recent Apps button lets users jump +instantly from one task to another using the list in the System Bar. The list +pops up to show thumbnail images of apps used recently — tapping a +thumbnail switches to the app.
+ +Rich and interactive notifications let users keep in +constant touch with incoming messages, play music tracks, see real-time updates +from apps, and much more. On smaller-screen devices, notifications appear at the +top of the screen, while on larger-screen devices they appear in the System +Bar.
+ +Home screen folders and +favorites tray
+ +New home screen folders offer a new way for users to group +their apps and shortcuts logically, just by dragging one onto another. Also, +in All Apps launcher, users can now simply drag an app to get +information about it or immediately uninstall it, or disable a pre-installed app.
+ +On smaller-screen devices, the home screen now includes a customizable +favorites tray visible from all home screens. Users can drag +apps, shortcuts, folders, and other priority items in or out of the favorites +tray for instant access from any home screen.
+ + +Resizable +widgets
+ +Home screens in Android 4.0 are designed to be content-rich and customizable. +Users can do much more than add shortcuts — they can embed live +application content directly through interactive widgets. +Widgets let users check email, flip through a calendar, play music, check social +streams, and more — right from the home screen, without having to launch +apps. Widgets are resizable, so users can expand them to show more content or +shrink them to save space.
+ + +New lock screen +actions
+ +The lock screens now let users do more without unlocking. From the slide lock +screen, users can jump directly to the camera for a picture or +pull down the notifications window to check for messages. When +listening to music, users can even manage music tracks and see album art.
+ + +Quick responses for +incoming calls
+ +When an incoming call arrives, users can now quickly respond by text +message, without needing to pick up the call or unlock the device. On +the incoming call screen, users simply slide a control to see a list of text +responses and then tap to send and end the call. Users can add their own +responses and manage the list from the Settings app.
+ + +Swipe to dismiss +notifications, tasks, and browser tabs
+ +Android 4.0 makes managing notifications, recent apps, and browser tabs even +easier. Users can now dismiss individual notifications, apps from the Recent +Apps list, and browser tabs with a simple swipe of a finger.
+ +Improved text input and +spell-checking
+ +The soft keyboard in Android 4.0 makes text input even faster and more +accurate. Error correction and word suggestion are improved through a new set of +default dictionaries and more accurate heuristics for handling cases such as +double-typed characters, skipped letters, and omitted spaces. Word suggestion +is also improved and the suggestion strip is simplified to show only three +words at a time.
+ +To fix misspelled words more easily, Android 4.0 adds a +spell-checker that locates and underlines errors and suggests +replacement words. With one tap, users can choose from multiple spelling +suggestions, delete a word, or add it to the dictionary. Users can even tap to +see replacement suggestions for words that are spelled correctly. For +specialized features or additional languages, users can now download and install +third-party dictionaries, spell-checkers, and other text services.
+ + +Powerful voice input +engine
+ +Android 4.0 introduces a powerful new voice input engine that offers a +continuous "open microphone" experience and streaming voice recognition. The new +voice input engine lets users dictate the text they want, for as long as they +want, using the language they want. Users can speak continously for a prolonged +time, even pausing for intervals if needed, and dictate punctuation to create +correct sentences. As the voice input engine enters text, it underlines possible +dictation errors in gray. After dictating, users can tap the underlined words to +quickly replace them from a list of suggestions.
+ +Control over network +data
+ +Mobile devices can make extensive use of network data for streaming content, +synchronizing data, downloading apps, and more. To meet the needs of users with +tiered or metered data plans, Android 4.0 adds new controls for +managing network data usage.
+ +In the Settings app, colorful charts show the total data usage on each +network type (mobile or Wi-Fi), as well as amount of data used by each running +application. Based on their data plans, users can optionally set warning levels +or hard limits on data usage or disable mobile data altogether. Users can also +manage the background data used by individual applications as needed.
+ + +Designed for +accessibility
+ +A variety of new features greatly enhance the accessibility of Android 4.0 +for blind or visually impaired users. Most important is a new +explore-by-touch mode that lets users navigate without having +to see the screen. Touching the screen once triggers audible feedback that +identifies the UI component below; a second touch in the same component +activates it with a full touch event. The new mode is especially important to +support users on new devices that use virtual buttons in the System Bar, rather +than dedicated hardware buttons or trackballs. Also, standard apps are updated +to offer an improved accessibility experience. The Browser +supports a script-based screen reader for reading favorite web content and +navigating sites. For improved readability, users can also increase the default +font size used across the system.
+ +The accessibility experience begins at first setup — a simple +touch gesture during setup (clockwise square from upper left) +activates all accessibility features and loads a setup tutorial. Once +accessibility features are active, everything visible on the screen can be +spoken aloud by the standard screen reader.
+ + +Designed for the way people live, Android 4.0 integrates rich social +communication and sharing touchpoints across the system, making it easy to talk, +email, text, and share.
+ + +People and +profiles
+ +Throughout the system, a user’s social groups, profiles, and contacts are +linked together and integrated for easy accessibility. At the center is a new +People app that offers richer profile information, including a +large profile picture, phone numbers, addresses and accounts, status updates, +events, stream items, and a new button for connecting on integrated social networks.
+ +The user's own contact information is stored in a new "Me" +profile, allowing easier sharing with apps and people. All of the +user's integrated contacts are displayed in an easy to manage list, including +controls over which contacts are shown from any integrated account or social +network. Wherever the user navigates across the system, tapping a profile photo +displays Quick Contacts, with large profile pictures, shortcuts to phone numbers, +text messaging, and more.
+ + +Unified calendar, visual +voicemail
+ +To help organize appointments and events, an updated Calendar +app brings together personal, work, school, and social agendas. With +user permission, other applications can contribute events to the calendar and +manage reminders, for an integrated view across multiple calendar providers. The +app is redesigned to let users manage events more easily. Calendars are +color-coded and users can swipe left or right to change dates +and pinch to zoom in or out agendas.
+ +In the phone app, a new visual voicemail features integrates +incoming messages, voice transcriptions, and audio files from one or more +providers. Third-party applications can integrate with the Phone app to add +their own voice messages, transcriptions, and more to the visual voicemail +inbox.
+ + + +Rich and versatile camera +capabilities
+ +The Camera app includes many new features that let users capture special moments +with great photos and videos. After capturing images, they can edit and share +them easily with friends.
+ +When taking pictures, continuous focus, zero shutter +lag exposure, and decreased shot-to-shot speed help capture clear, +precise images. Stabilized image zoom lets users compose photos +and video in the way they want, including while video is recording. For new +flexibility and convenience while shooting video, users can now take +snapshots at full video resolution just by tapping the screen +as video continues to record.
+ +To make it easier to take great pictures of people, built-in face +detection locates faces in the frame and automatically sets focus. For +more control, users can tap to focus anywhere in the preview +image.
+ +For capturing larger scenes, the Camera introduces a single-motion +panorama mode. In this mode, the user starts an exposure and then +slowly turns the Camera to encompass as wide a perspective as needed. The Camera +assembles the full range of continuous imagery into a single panoramic +photo.
+ +After taking a picture or video, users can quickly share it by email, text +message, bluetooth, social networks, and more, just by tapping the thumbnail in +the camera controls.
+ + +
+Redesigned Gallery app +with photo editor
+ +The Gallery app now makes it easier to manage, show, and share photos and +videos. For managing collections, a redesigned album layout +shows many more albums and offers larger thumbnails. There are many ways to sort +albums, including by time, location, people, and tags. To help pictures look +their best, the Gallery now includes a powerful photo editor. +Users can crop and rotate pictures, set levels, remove red eyes, add effects, +and much more. After retouching, users can select one or multiple pictures or +videos to share instantly over email, text messaging, bluetooth, social +networks, or other apps.
+ +An improved Picture Gallery widget lets users look at +pictures directly on their home screen. The widget can display pictures from a +selected album, shuffle pictures from all albums, or show a single image. After +adding the widget to the home screen, users can flick through the photo stacks +to locate the image they want, then tap to load it in Gallery.
+ +
+Live Effects for transforming +video
+ +Live Effects is a collection of graphical transformations that add interest +and fun to videos captured in the Camera app. For example, users can +change the background behind them to any stock or custom image, +for just the right setting when shooting videeo. Also available for video is +Silly Faces, a set of morphing effects that use state-of-the-art face +recognition and GPU filters to transform facial features. For example, you can +use effects such as small eyes, big mouth, big nose, face squeeze, and more. +Outside of the Camera app, Live Effects is available during video chat in the +Google Talk app.
+ +
+Sharing with screenshots
+ +Users can now share what's on their screens more easily by taking +screenshots. Hardware buttons let them snap a screenshot and +store it locally. Afterward, they can view, edit, and share the screen shot in +Gallery or a similar app.
+ + +Android has always been cloud-connected, letting users browse the web and +sync photos, apps, games, email, and contacts — wherever they are and +across all of their devices. Android 4.0 adds new browsing and email +capabilities to let users take even more with them and keep communication +organized.
+ + +Powerful web +browsing
+ +The Android Browser offers an experience that’s as rich and convenient as a +desktop browser. It lets users instantly sync and manage Google Chrome +bookmarks from all of their accounts, jump to their favorite content +faster, and even save it for reading later in case there's no network +available.
+ +To get the most out of web content, users can now request full +desktop versions of web sites, rather than their mobile +versions. Users can set their preference for web sites separately for each +browser tab. For longer content, users can save a copy for +offline reading. To find and open saved pages, users can browse +a visual list that’s included with browser bookmarks and history. For better +readability and accessibility, users can increase the browser’s zoom +levels and override the system default text sizes.
+ +Across all types of content, the Android Browser offers dramatically improved +page rendering performance through updated versions of the +WebKit core and the V8 Crankshaft compilation engine for JavaScript. In +benchmarks run on a Nexus S device, the Android 4.0 browser showed an +improvement of nearly 220% over the Android 2.3 browser in the V8 Benchmark +Suite and more than 35% in the SunSpider 9.1 JavaScript Benchmark. When run on a +Galaxy Nexus device, the Android 4.0 browser showed improvement of nearly 550% +in the V8 benchmark and nearly 70% in the SunSpider benchmark.
+ + +Improved +email
+ +In Android 4.0, email is easier to send, read, and manage. For composing +email, improved auto-completion of recipients helps with +finding and adding frequent contacts more quickly. For easier input of frequent +text, users can now create quick responses and store them in +the app, then enter them from a convenient menu when composing. When replying to +a message, users can now toggle the message to Reply All and Forward without +changing screens.
+ +For easier browsing across accounts and labels, the app adds an +integrated menu of accounts and recent labels. To help users +locate and organize IMAP and Exchange email, the Email app now supports +nested mail subfolders, each with synchronization rules. Users +can also search across folders on the server, for faster results.
+ +For enterprises, the Email app supports EAS v14. It supports +EAS certificate authentication, provides ABQ strings for device type and mode, +and allows automatic sync to be disabled while roaming. Administrators can also +limit attachment size or disable attachments.
+ +For keeping track of incoming email more easily, a resizable Email +widget lets users flick through recent email right from the home +screen, then jump into the Email app to compose or reply.
+ + +
+Android is continously driving innovation forward, pushing the boundaries of +communication and sharing with new capabilities and interactions.
+ +Android Beam for +NFC-based sharing
+ +Android Beam is an innovative, convenient feature for sharing across two +NFC-enabled devices, It lets people instantly exchange favorite apps, contacts, +music, videos — almost anything. It’s incredibly simple and convenient to +use — there’s no menu to open, application to launch, or pairing needed. +Just touch one Android-powered phone to another, then tap to send.
+ +For sharing apps, Android Beam pushes a link to the app's details page in +Google Play. On the other device, the Google Play client app launches and loads the +details page, for easy downloading of the app. Individual apps can build on +Android Beam to add other types of interactions, such as passing game scores, +initiating a multiplayer game or chat, and more.
+ +
+Face Unlock
+ +Android 4.0 introduces a completely new approach to securing a device, making +each person's device even more personal — Face Unlock is a new screen-lock +option that lets users unlock their devices with their faces. It takes advantage +of the device front-facing camera and state-of-the-art facial recognition +technology to register a face during setup and then to recognize it again when +unlocking the device. Users just hold their devices in front of their faces to +unlock, or use a backup PIN or pattern.
+ + +Wi-Fi Direct and Bluetooth HDP
+ +Support for Wi-Fi Direct lets users connect directly to +nearby peer devices over Wi-Fi, for more reliable, higher-speed communication. +No internet connection or tethering is needed. Through third-party apps, users +can connect to compatible devices to take advantage of new features such as +instant sharing of files, photos, or other media; streaming video or audio from +another device; or connecting to compatible printers or other devices.
+ +Android 4.0 also introduces built-in support for connecting to Bluetooth Health Device Profile (HDP) devices. With support from third-party apps, users can connect to wireless medical devices and sensors in hospitals, fitness centers, homes, and elsewhere.
+ + +Android 4.0 brings a unified UI framework that lets developers create +elegant, innovative apps for phones, tablets, and more. It includes all of the +familiar Android 3.x interface elements and APIs — fragments, content +loaders, Action Bar, rich notifications, resizable home screen widgets, and more +— as well as new elements and APIs.
+ +For developers, the unified UI framework in Android 4.0 means new UI tools, +consistent design practices, simplified code and resources, and streamlined +development across the range of Android-powered devices.
+ +Core UI
+Graphics and animation
+Media and connectivity
+Enterprise
+Android 4.0 extends social and sharing features to any application on the +device. Applications can integrate contacts, profile data, stream items, +and calendar events from any of the user’s activities or social networks.
+ + +Social API
+ +A shared social provider and API provide a new unified store for contacts, +profile data, stream items, and photos. Any app or social network with user +permission can contribute raw contacts and make them accessible to other apps +and networks. Applications with user permission can also read profile data from +the provider and display it in their applications.
+ +The social API lets applications store standard contact data as well as new +types of content for any given contact, including large profile photos, stream +items, and recent activity feedback. Recent activity feedback is a standard way for +applications to “tag” a contact with common activity, such as when the user +calls the contact or sends an email or SMS message. The social provider uses the +recent activity feedback as a new signal in ranking, such as for name +auto-complete, to keep the most relevant contacts ranked closest to the top.
+ +Applications can also let users set up a social connection to a contact from +the People app. When the user touches Add Connection in a contact, the app +sends a public intent that other apps can handle, displaying any UI needed +to create the social connection.
+ +Building on the social API, developers can add powerful new interactions that +span multiple social networks and contacts sources.
+ + +Calendar API
+ +A shared calendar content provider and framework API make it easier for +developers to add calendar services to their apps.
+ +With user permission, any application can add events to the shared database +and manage dates, attendees, alerts, and reminders. Applications can also read +entries from the database, including events contributed by other applications, +and handle the display of event alerts and reminders. Using the calendar +provider, applications can take advantage of event data sourced from a variety +of apps and protocols, to offer innovative ways of viewing and managing a user’s +events. Apps can also use calendar data to improve the relevance of their +other content.
+ +For lighter-weight access to calendar services, the Calendar app defines a +set of public Intents for creating, viewing, and editing events. Rather than +needing to implement a calendar UI and integrate directly with the calendar +provider, applications can simply broadcast calendar Intents. When the Calendar +app receives the Intents, it launches the appropriate UI and stores any event +data entered. Using calendar Intents, for example, apps can let users add events +directly from lists, dialogs, or home screen widgets, such as for making +restaurant reservations or booking time with friends.
+ + +Visual voicemail +API
+ +A shared Voicemail provider and API allow developers to build applications +that contribute to a unified voicemail store. Voicemails are displayed and +played in the call log tab of the platform’s Phone app.
+ + +Android Beam
+ +Android Beam is an NFC-based feature that lets users instantly share +information about the apps they are using, just by touching two NFC-enabled +phones together. When the devices are in range — within a few centimeters +— the system sets up an NFC connection and displays a sharing UI. To share +whatever they are viewing with the other device, users just touch the screen. +
+ +For developers, Android Beam is a new way of triggering almost any type of +proximity-based interaction. For example, it can let users instantly exchange +contacts, set up multiplayer gaming, join a chat or video call, share a photo or +video, and more. The system provides the low-level NFC support and the sharing +UI, while the foreground app provides lightweight data to transfer to the other +device. Developers have complete control over the data that is shared and how it +is handled, so almost any interaction is possible. For larger payloads, +developers can even use Android Beam to initiate a connection and transfer the +data over Bluetooth, without the need for user-visible pairing.
+ +Even if developers do not add custom interactions based on Android Beam they +can still benefit from it being deeply integrated into Android. By default the +system shares the app’s Google Play URL, so it’s easy for the user to +download or purchase the app right away.
+ + +Modular sharing +widget
+ +The UI framework includes a new widget, ShareActionProvider, that lets +developers quickly embed standard share functionality and UI in the Action Bar +of their applications. Developers simply add ShareActionProvider to the menu and +set an intent that describes the desired sharing action. The system handles the +rest, building up the list of applications that can handle the share intent and +dispatching the intent when the user chooses from the menu.
+ + +Low-level streaming +multimedia
+ +Android 4.0 provides a direct, efficient path for low-level streaming +multimedia. The new path is ideal for applications that need to maintain +complete control over media data before passing it to the platform for +presentation. For example, media applications can now retrieve data from any +source, apply proprietary encryption/decryption, and then send the data to the +platform for display.
+ +Applications can now send processed data to the platform as a multiplexed +stream of audio/video content in MPEG-2 transport stream format. The platform +de-muxes, decodes, and renders the content. The audio track is rendered to the +active audio device, while the video track is rendered to either a Surface or a +SurfaceTexture. When rendering to a SurfaceTexture, the application can apply +subsequent graphics effects to each frame using OpenGL.
+ +To support this low-level streaming, the platform introduces a new native API +based on Khronos +OpenMAX AL 1.0.1. The API is implemented on the same underlying services as +the platform’s existing OpenSL ES API, so developers can make use of both APIs +together if needed. Tools support for low-level streaming multimedia will be +available in an upcoming release of the Android NDK.
+ + +New camera +capabilities
+ +Developers can take advantage of a variety of new camera features in Android +4.0. ZSL exposure, continuous focus, and image zoom let apps capture better +still and video images, including during video capture. Apps can even capture +full-resolution snapshots while shooting video. Apps can now set custom metering +regions in a camera preview, then manage white balance and exposure dynamically +for those regions. For easier focusing and image processing, a face-detection +service identifies and tracks faces in a preview and returns their screen +coordinates.
+ + +Media effects for +transforming images and video
+ +A set of high-performance transformation filters let developers apply rich +effects to any image passed as an OpenGL ES 2.0 texture. Developers can adjust +color levels and brightness, change backgrounds, sharpen, crop, rotate, add lens +distortion, and apply other effects. The transformations are processed by the +GPU, so they are fast enough for processing image frames loaded from disk, +camera, or video stream.
+ + +Audio remote +controls
+ +Android 4.0 adds a new audio remote control API that lets media applications +integrate with playback controls that are displayed in a remote view. Media +applications can integrate with a remote music playback control that’s built +into in the platform’s lock screen, allowing users to control song selection and +playback without having to unlock and navigate to the music app.
+ +Using the audio remote control API, any music or media app can register to +receive media button events from the remote control and then manage play state +accordingly. The application can also supply metadata to the remote control, +such as album art or image, play state, track number and description, duration, +genre, and more.
+ + +New media codecs and +containers
+ +Android 4.0 adds support for additional media types and containers to give +developers access to the formats they need. For high-quality compressed images, +the media framework adds support for WebP content. For video, the framework now +supports streaming VP8 content. For streaming multimedia, the framework supports +HTTP Live streaming protocol version 3 and encoding of ADTS-contained AAC +content. Additionally, developers can now use Matroska containers for Vorbis and +VP8 content.
+ + +Wi-Fi Direct
+ +Developers can use a framework API to discover and connect directly to nearby +devices over a high-performance, secure Wi-Fi Direct connection. No internet +connection or hotspot is needed.
+ +Wi-Fi Direct opens new opportunities for developers to add innovative +features to their applications. Applications can use Wi-Fi Direct to share +files, photos, or other media between devices or between a desktop computer and +an Android-powered device. Applications could also use Wi-Fi Direct to stream +media content from a peer device such as a digital television or audio player, +connect a group of users for gaming, print files, and more.
+ + +Bluetooth Health Device +Profile (HDP)
+ +Developers can now build powerful medical applications that use Bluetooth to +communicate with wireless devices and sensors in hospitals, fitness centers, +homes, and elsewhere. Applications can collect and manage data from HDP source +devices and transmit it to backend medical applications such as records systems, +data analysis services, and others.
+ +Using a framework API, applications can use Bluetooth to discover nearby +devices, establish reliable or streaming data channels, and manage data +transmission. Applications can supply any IEEE 11073 Manager to retrieve and +interpret health data from Continua-certified devices such as heart-rate +monitors, blood meters, thermometers, and scales.
+ + +Layout +enhancements
+ +A new layout, GridLayout, improves the performance of Android applications by +supporting flatter view hierarchies that are faster to layout and render. +Because hierarchies are flatter, developers can also manage alignments between +components that are visually related to each other even when they are not +logically related, for precise control over application UI. GridLayout is also +specifically designed to be configured by drag-and-drop design tools such as the +ADT Plug-in for Eclipse.
+ + +OpenGL ES texture +views
+ +A new TextureView object lets developers directly integrate OpenGL ES +textures as rendering targets in a UI hierarchy. The object lets developers +display and manipulate OpenGL ES rendering just as they would a normal view +object in the hierarchy, including moving, transforming, and animating the view +as needed. The TextureView object makes it easy for developers to embed camera +preview, decoded video, OpenGL game scenes, and more. TextureView can be viewed +as a more powerful version of the existing SurfaceView object, since it offers +the same benefits of access to a GL rendering surface, with the added advantage +of having that surface participate fully in the normal view hierarchy.
+ + +Hardware-accelerated 2D +drawing
+ +All Android-powered devices running Android 4.0 are required to support +hardware-accelerated 2D drawing. Developers can take advantage of this to add +great UI effects while maintaining optimal performance on high-resolution +screens, even on phones. For example, developers can rely on accelerated +scaling, rotation, and other 2D operations, as well as accelerated UI components +such as TextureView and compositing modes such as filtering, blending, and +opacity.
+ + +Stylus input, button +support, hover events
+ +Android 4.0 includes full support for stylus input events, including tilt and +distance axes, pressure, and related motion event properties. To help +applications distinguish motion events from different sources, the platform adds +distinct tool types for stylus, finger, mouse, and eraser. For improved input +from multi-button pointing devices, the platform now provides distinct primary, +secondary, and tertiary buttons, as well as back and forward buttons. +Hover-enter and hover-exit events are also added, for improved navigation and +accessibility. Developers can build on these new input features to add powerful +interactions to their apps, such as precise drawing and gesturing, handwriting +and shape recognition, improved mouse input, and others.
+ + +Text services API for +integrating spelling checkers
+ +Android 4.0 lets applications query available text services such as +dictionaries and spell checkers for word suggestions, corrections, and similar +data. The text services are external to the active IME, so developers can create +and distribute dictionaries and suggestion engines that plug into the platform. +When an application receives results from a text service — for example, +word suggestions — it can display them in a dedicated suggestion popup +window directly inside the text view, rather than relying on the IME to display +them.
+ + +Android 4.0 adds new accessibility features and an enhanced API to let +developers improve the user experience in their apps, especially on devices that +don’t have hardware buttons. For accessibility services such as screen readers +in particular, the platform offers new APIs to query window content, for easier +navigation, better feedback, and richer user interfaces.
+ + +Accessibility +API
+ +To let applications manage interactions more effectively when accessibility +features are enabled, the platform adds accessibility events for +explore-by-touch mode, scrolling, and text selection. For these and other +events, the platform can attach a new object called an accessibility record that +provides extra information about the event context.
+ +Using the accessibility record and related APIs, applications can now access +the view hierarchy associated with an event. Applications can query for key +properties such as parent and child nodes, available states, supported actions, +screen position, and more. Applications can also request changes to certain +properties to help manage focus and selected state. For example, an +accessibility service could use these new capabilities to add convenient +features such as screen-search by text.
+ + +Text-to-speech +API
+ +A new framework API lets developers write text-to-speech engines and make +them available to any app requesting TTS capabilities.
+ + +In Android 4.0, users can see how much network data their running apps are +using. They can also set limits on data usage by network type and disable +background data usage for specific applications. In this context, developers +need to design their apps to run efficiently and follow best practices for +checking the network connection. Android 4.0 provides network APIs to let +applications meet those goals.
+ +As users move between networks or set limits on network data, the platform +lets applications query for connection type and availability. Developers can use +this information to dynamically manage network requests to ensure the best +experience for users. Developers can also build custom network and data-usage +options into their apps, then expose them to users directly from Settings by +means of a new system Intent.
+ + +Secure management of +credentials
+ +Android 4.0 makes it easier for applications to manage authentication and +secure sessions. A new keychain API and underlying encrypted storage let +applications store and retrieve private keys and their corresponding certificate +chains. Any application can use the keychain API to install and store user +certificates and CAs securely.
+ + +Address Space Layout +Randomization
+ +Android 4.0 now provides address space layout randomization (ASLR) to help +protect system and third party applications from exploitation due to +memory-management issues.
+ + +VPN client +API
+ +Developers can now build or extend their own VPN solutions on the platform +using a new VPN API and underlying secure credential storage. With user +permission, applications can configure addresses and routing rules, process +outgoing and incoming packets, and establish secure tunnels to a remote server. +Enterprises can also take advantage of a standard VPN client built into the +platform that provides access to L2TP and IPSec protocols.
+ + +Device policy management +for camera
+ +The platform adds a new policy control for administrators who manage devices +using an installed Device Policy Manager. Administrators can now remotely +disable the camera on a managed device for users working in sensitive +environments.
+ + + + + diff --git a/docs/html/about/versions/android-4.0.3.jd b/docs/html/about/versions/android-4.0.3.jd new file mode 100644 index 000000000000..b7d4db3c5229 --- /dev/null +++ b/docs/html/about/versions/android-4.0.3.jd @@ -0,0 +1,304 @@ +page.title=Android 4.0.3 Platform +sdk.platform.version=4.0.3 +sdk.platform.apiLevel=15 +@jd:body + +API Level: {@sdkPlatformApiLevel}
+ +Android {@sdkPlatformVersion} is an incremental release of the Android 4.x +(Ice Cream Sandwich) platform family. This release includes new features for +users and developers, API changes, and various bug fixes.
+ +For developers, the Android {@sdkPlatformVersion} platform is available as a +downloadable component for the Android SDK. The downloadable platform includes +an Android library and system image, as well as a set of emulator skins and +more. To get started developing or testing against Android {@sdkPlatformVersion}, +use the Android SDK Manager to download the platform into your SDK.
+ + +The sections below provide a technical overview of new APIs in Android 4.0.3.
+ +Applications that use social stream data such as status updates and check-ins +can now sync that data with each of the user’s contacts, providing items in a +stream along with photos for each.
+ +The database table that contains an individual contact’s social stream is +defined by {@link android.provider.ContactsContract.StreamItems}, the Uri for +which is nested within the {@link android.provider.ContactsContract.RawContacts} +directory to which the stream items belong. Each social stream table includes +several columns for metadata about each stream item, such as an icon +representing the source (an avatar), a label for the item, the primary text +content, comments about the item (such as responses from other people), and +more. Photos associated with a stream are stored in another table, defined by +{@link android.provider.ContactsContract.StreamItemPhotos}, which is available +as a sub-directory of the {@link android.provider.ContactsContract.StreamItems} +Uri.
+ +See {@link android.provider.ContactsContract.StreamItems} and +{@link android.provider.ContactsContract.StreamItemPhotos} for more information.
+ +To read or write social stream items for a contact, an application must
+request permission from the user by declaring <uses-permission
+android:name="android.permission.READ_SOCIAL_STREAM"> and/or <uses-permission
+android:name="android.permission.WRITE_SOCIAL_STREAM"> in their manifest files.
Starting from Android 4.0, home screen widgets should no longer include their +own padding. Instead, the system now automatically adds padding for each widget, +based the characteristics of the current screen. This leads to a more uniform, +consistent presentation of widgets in a grid. To assist applications that host +home screen widgets, the platform provides a new method +{@link android.appwidget.AppWidgetHostView#getDefaultPaddingForWidget(android.content.Context, android.content.ComponentName, android.graphics.Rect) +getDefaultPaddingForWidget()}. Applications can call this method to get the +system-defined padding and account for it when computing the number of cells to +allocate to the widget.
+ +Apps connected to the spell-checker can use the {@link +android.view.textservice.SuggestionsInfo#RESULT_ATTR_HAS_RECOMMENDED_SUGGESTIONS} +flag in combination with other suggestion attributes, as well as the {@link +android.view.textservice.SuggestionsInfo#getSuggestionsAttributes()} and {@link +android.view.textservice.SuggestionsInfo#getSuggestionsCount()} methods, to +determine whether to mark input words as typos and offer suggestions.
New public methods {@link +android.bluetooth.BluetoothDevice#fetchUuidsWithSdp()} and {@link +android.bluetooth.BluetoothDevice#getUuids()} let apps determine the features +(UUIDs) supported by a remote device. In the case of {@link +android.bluetooth.BluetoothDevice#fetchUuidsWithSdp()}, the system performs a +service discovery on the remote device to get the UUIDs supported, then +broadcasts the result in an {@link +android.bluetooth.BluetoothDevice#ACTION_UUID} intent.
+ +New methods {@link android.app.Fragment#setUserVisibleHint(boolean) setUserVisibleHint()} and +{@link android.app.Fragment#getUserVisibleHint() getUserVisibleHint()} allow a +fragment to set a hint of whether or not it is currently user-visible. The +system defers the start of fragments that are not user-visible until the loaders +for visible fragments have run. The visibility hint is "true" by default. +
+ +The {@link android.database.CrossProcessCursorWrapper} class fixes common +performance issues and bugs that applications have encountered when +implementing content providers.
Adds new categories for targeting common types of applications on the +device, such as {@link android.content.Intent#CATEGORY_APP_BROWSER}, {@link +android.content.Intent#CATEGORY_APP_CALENDAR}, {@link +android.content.Intent#CATEGORY_APP_MAPS}, and more. + +
The following are new permissions:
+For a detailed view of all API changes in Android {@sdkPlatformVersion} (API Level +{@sdkPlatformApiLevel}), see the API Differences Report.
+The Android {@sdkPlatformVersion} API is assigned an integer +identifier—{@sdkPlatformApiLevel}—that is stored in the system itself. +This identifier, called the "API level", allows the system to correctly determine whether an +application is compatible with the system, prior to installing the application.
+ +To use APIs introduced in Android {@sdkPlatformVersion} in your application, you need compile the
+application against an Android platform that supports API level {@sdkPlatformApiLevel} or
+higher. Depending on your needs, you might also need to add an
+android:minSdkVersion="{@sdkPlatformApiLevel}" attribute to the
+{@code <uses-sdk>}
+element.
For more information, see the API Levels +document.
+ diff --git a/docs/html/about/versions/android-4.0.jd b/docs/html/about/versions/android-4.0.jd new file mode 100644 index 000000000000..bea07253c87b --- /dev/null +++ b/docs/html/about/versions/android-4.0.jd @@ -0,0 +1,1829 @@ +page.title=Android 4.0 Platform +sdk.platform.version=4.0 +sdk.platform.apiLevel=14 +@jd:body + +API Level: {@sdkPlatformApiLevel}
+ +Android 4.0 is a major platform release that adds a variety of new features for users and app +developers. Besides all the new features and APIs discussed below, Android 4.0 is an important +platform release because it brings the extensive set of APIs and Holographic themes from Android 3.x +to smaller screens. As an app developer, you now have a single platform and unified API framework +that enables you to develop and publish your application with a single APK that provides an +optimized user experience for handsets, tablets, and more, when running the same version of +Android—Android 4.0 (API level 14) or greater.
+ +For developers, the Android {@sdkPlatformVersion} platform is available as a +downloadable component for the Android SDK. The downloadable platform includes +an Android library and system image, as well as a set of emulator skins and +more. To get started developing or testing against Android {@sdkPlatformVersion}, +use the Android SDK Manager to download the platform into your SDK.
+ +The sections below provide a technical overview of new APIs in Android 4.0.
+ +The contact APIs defined by the {@link android.provider.ContactsContract} provider have been +extended to support new social-oriented features such as a personal profile for the device owner and +the ability for users to invite individual contacts to social networks that are installed on the +device.
+ + +Android now includes a personal profile that represents the device owner, as defined by the +{@link android.provider.ContactsContract.Profile} table. Social apps that maintain a user identity +can contribute to the user's profile data by creating a new {@link +android.provider.ContactsContract.RawContacts} entry within the {@link +android.provider.ContactsContract.Profile}. That is, raw contacts that represent the device user do +not belong in the traditional raw contacts table defined by the {@link +android.provider.ContactsContract.RawContacts} Uri; instead, you must add a profile raw contact in +the table at {@link android.provider.ContactsContract.Profile#CONTENT_RAW_CONTACTS_URI}. Raw +contacts in this table are then aggregated into the single user-visible profile labeled "Me".
+ +Adding a new raw contact for the profile requires the {@link +android.Manifest.permission#WRITE_PROFILE} permission. Likewise, in order to read from the profile +table, you must request the {@link android.Manifest.permission#READ_PROFILE} permission. However, +most apps should not need to read the user profile, even when contributing data to the +profile. Reading the user profile is a sensitive permission and you should expect users to be +skeptical of apps that request it.
+ + +The {@link android.provider.ContactsContract.Intents#INVITE_CONTACT} intent action allows an app +to invoke an action that indicates the user wants to add a contact to a social network. The app +receiving the app uses it to invite the specified contact to that +social network. Most apps will be on the receiving-end of this operation. For example, the +built-in People app invokes the invite intent when the user selects "Add connection" for a specific +social app that's listed in a person's contact details.
+ +To make your app visible as in the "Add connection" list, your app must provide a sync adapter to +sync contact information from your social network. You must then indicate to the system that your +app responds to the {@link android.provider.ContactsContract.Intents#INVITE_CONTACT} intent by +adding the {@code inviteContactActivity} attribute to your app’s sync configuration file, with a +fully-qualified name of the activity that the system should start when sending the invite intent. +The activity that starts can then retrieve the URI for the contact in question from the intent’s +data and perform the necessary work to invite that contact to the network or add the person to the +user’s connections.
+ +See the Sample Sync +Adapter app for an example (specifically, see the contacts.xml +file).
+ + +Android now supports high resolution photos for contacts. Now, when you push a photo into a +contact record, the system processes it into both a 96x96 thumbnail (as it has previously) and a +256x256 "display photo" that's stored in a new file-based photo store (the exact dimensions that the +system chooses may vary in the future). You can add a large photo to a contact by putting a large +photo in the usual {@link android.provider.ContactsContract.CommonDataKinds.Photo#PHOTO} column of a +data row, which the system will then process into the appropriate thumbnail and display photo +records.
+ + +The new {@link android.provider.ContactsContract.DataUsageFeedback} APIs allow you to help track +how often the user uses particular methods of contacting people, such as how often the user uses +each phone number or e-mail address. This information helps improve the ranking for each contact +method associated with each person and provide better suggestions for contacting each person.
+ + + + + +The new calendar APIs allow you to read, add, modify and delete calendars, events, attendees, +reminders and alerts, which are stored in the Calendar Provider.
+ +A variety of apps and widgets can use these APIs to read and modify calendar events. However, +some of the most compelling use cases are sync adapters that synchronize the user's calendar from +other calendar services with the Calendar Provider, in order to offer a unified location for all the +user's events. Google Calendar events, for example, are synchronized with the Calendar Provider by +the Google Calendar Sync Adapter, allowing these events to be viewed with Android's built-in +Calendar app.
+ +The data model for calendars and event-related information in the Calendar Provider is +defined by {@link android.provider.CalendarContract}. All the user’s calendar data is stored in a +number of tables defined by various subclasses of {@link android.provider.CalendarContract}:
+ +To access a user’s calendar data with the Calendar Provider, your application must request +the {@link android.Manifest.permission#READ_CALENDAR} permission (for read access) and +{@link android.Manifest.permission#WRITE_CALENDAR} (for write access).
+ + +If all you want to do is add an event to the user’s calendar, you can use an {@link +android.content.Intent#ACTION_INSERT} intent with the data defined by {@link +android.provider.CalendarContract.Events#CONTENT_URI Events.CONTENT_URI} in order to start an +activity in the Calendar app that creates new events. Using the intent does not require any +permission and you can specify event details with the following extras:
+ +The new Voicemail Provider allows applications to add voicemails to the +device, in order to present all the user's voicemails in a single visual presentation. For instance, +it’s possible that a user has multiple voicemail sources, such as +one from the phone’s service provider and others from VoIP or other alternative voice +services. These apps can use the Voicemail Provider APIs to add their voicemails to the device. The +built-in Phone application then presents all voicemails to the user in a unified presentation. +Although the system’s Phone application is the only application that can read all the voicemails, +each application that provides voicemails can read those that it has added to the system (but cannot +read voicemails from other services).
+ +Because the APIs currently do not allow third-party apps to read all the voicemails from the +system, the only third-party apps that should use the voicemail APIs are those that have voicemail +to deliver to the user.
+ +The {@link android.provider.VoicemailContract} class defines the content provider for the +Voicemail Provder. The subclasses {@link android.provider.VoicemailContract.Voicemails} and {@link +android.provider.VoicemailContract.Status} provide tables in which apps can +insert voicemail data for storage on the device. For an example of a voicemail provider app, see the +Voicemail Provider +Demo.
+ + + + + +Android 4.0 adds several new APIs for applications that interact with media such as photos, +videos, and music.
+ + +A new media effects framework allows you to apply a variety of visual effects to images and +videos. For example, image effects allow you to easily fix red-eye, convert an image to grayscale, +adjust brightness, adjust saturation, rotate an image, apply a fisheye effect, and much more. The +system performs all effects processing on the GPU to obtain maximum performance.
+ +For maximum performance, effects are applied directly to OpenGL textures, so your application +must have a valid OpenGL context before it can use the effects APIs. The textures to which you apply +effects may be from bitmaps, videos or even the camera. However, there are certain restrictions that +textures must meet:
+An {@link android.media.effect.Effect} object defines a single media effect that you can apply to +an image frame. The basic workflow to create an {@link android.media.effect.Effect} is:
+ +You can adjust an effect’s parameters by calling {@link android.media.effect.Effect#setParameter +setParameter()} and passing a parameter name and parameter value. Each type of effect accepts +different parameters, which are documented with the effect name. For example, {@link +android.media.effect.EffectFactory#EFFECT_FISHEYE} has one parameter for the {@code scale} of the +distortion.
+ +To apply an effect on a texture, call {@link android.media.effect.Effect#apply apply()} on the +{@link +android.media.effect.Effect} and pass in the input texture, it’s width and height, and the output +texture. The input texture must be bound to a {@link android.opengl.GLES20#GL_TEXTURE_2D} texture +image (usually done by calling the {@link android.opengl.GLES20#glTexImage2D glTexImage2D()} +function). You may provide multiple mipmap levels. If the output texture has not been bound to a +texture image, it will be automatically bound by the effect as a {@link +android.opengl.GLES20#GL_TEXTURE_2D} and with one mipmap level (0), which will have the same +size as the input.
+ +All effects listed in {@link android.media.effect.EffectFactory} are guaranteed to be supported. +However, some additional effects available from external libraries are not supported by all devices, +so you must first check if the desired effect from the external library is supported by calling +{@link android.media.effect.EffectFactory#isEffectSupported isEffectSupported()}.
+ + +The new {@link android.media.RemoteControlClient} allows media players to enable playback +controls from remote control clients such as the device lock screen. Media players can also expose +information about the media currently playing for display on the remote control, such as track +information and album art.
+ +To enable remote control clients for your media player, instantiate a {@link +android.media.RemoteControlClient} with its constructor, passing it a {@link +android.app.PendingIntent} that broadcasts {@link +android.content.Intent#ACTION_MEDIA_BUTTON}. The intent must also declare the explicit {@link +android.content.BroadcastReceiver} component in your app that handles the {@link +android.content.Intent#ACTION_MEDIA_BUTTON} event.
+ +To declare which media control inputs your player can handle, you must call {@link +android.media.RemoteControlClient#setTransportControlFlags setTransportControlFlags()} on your +{@link android.media.RemoteControlClient}, passing a set of {@code FLAG_KEY_MEDIA_*} flags, such as +{@link android.media.RemoteControlClient#FLAG_KEY_MEDIA_PREVIOUS} and {@link +android.media.RemoteControlClient#FLAG_KEY_MEDIA_NEXT}.
+ +You must then register your {@link android.media.RemoteControlClient} by passing it to {@link +android.media.AudioManager#registerRemoteControlClient MediaManager.registerRemoteControlClient()}. +Once registered, the broadcast receiver you declared when you instantiated the {@link +android.media.RemoteControlClient} will receive {@link android.content.Intent#ACTION_MEDIA_BUTTON} +events when a button is pressed from a remote control. The intent you receive includes the {@link +android.view.KeyEvent} for the media key pressed, which you can retrieve from the intent with {@link +android.content.Intent#getParcelableExtra getParcelableExtra(Intent.EXTRA_KEY_EVENT)}.
+ +To display information on the remote control about the media playing, call {@link +android.media.RemoteControlClient#editMetadata editMetaData()} and add metadata to the returned +{@link android.media.RemoteControlClient.MetadataEditor}. You can supply a bitmap for media artwork, +numerical information such as elapsed time, and text information such as the track title. For +information on available keys see the {@code METADATA_KEY_*} flags in {@link +android.media.MediaMetadataRetriever}.
+ +For a sample implementation, see the Random Music Player, which +provides compatibility logic such that it enables the remote control client on Android 4.0 +devices while continuing to support devices back to Android 2.1.
+ + +Android 4.0 adds support for:
+For more info, see Supported Media +Formats.
+ + + + + +The {@link android.hardware.Camera} class now includes APIs for detecting faces and controlling +focus and metering areas.
+ + +Camera apps can now enhance their abilities with Android’s face detection APIs, which not +only detect the face of a subject, but also specific facial features, such as the eyes and mouth. +
+ +To detect faces in your camera application, you must register a {@link +android.hardware.Camera.FaceDetectionListener} by calling {@link +android.hardware.Camera#setFaceDetectionListener setFaceDetectionListener()}. You can then start +your camera surface and start detecting faces by calling {@link +android.hardware.Camera#startFaceDetection}.
+ +When the system detects one or more faces in the camera scene, it calls the {@link +android.hardware.Camera.FaceDetectionListener#onFaceDetection onFaceDetection()} callback in your +implementation of {@link android.hardware.Camera.FaceDetectionListener}, including an array of +{@link android.hardware.Camera.Face} objects.
+ +An instance of the {@link android.hardware.Camera.Face} class provides various information about +the face detected, including:
+Note: Face detection may not be supported on some +devices, so you should check by calling {@link +android.hardware.Camera.Parameters#getMaxNumDetectedFaces()} and ensure the return +value is greater than zero. Also, some devices may not support identification of eyes and mouth, +in which case, those fields in the {@link android.hardware.Camera.Face} object will be null.
+ + +Camera apps can now control the areas that the camera uses for focus and for metering white +balance +and auto-exposure. Both features use the new {@link android.hardware.Camera.Area} class to specify +the region of the camera’s current view that should be focused or metered. An instance of the {@link +android.hardware.Camera.Area} class defines the bounds of the area with a {@link +android.graphics.Rect} and the area's weight—representing the level of importance of that +area, relative to other areas in consideration—with an integer.
+ +Before setting either a focus area or metering area, you should first call {@link +android.hardware.Camera.Parameters#getMaxNumFocusAreas} or {@link +android.hardware.Camera.Parameters#getMaxNumMeteringAreas}, respectively. If these return zero, then +the device does not support the corresponding feature.
+ +To specify the focus or metering areas to use, simply call {@link +android.hardware.Camera.Parameters#setFocusAreas setFocusAreas()} or {@link +android.hardware.Camera.Parameters#setMeteringAreas setMeteringAreas()}. Each take a {@link +java.util.List} of {@link android.hardware.Camera.Area} objects that indicate the areas to consider +for focus or metering. For example, you might implement a feature that allows the user to set the +focus area by touching an area of the preview, which you then translate to an {@link +android.hardware.Camera.Area} object and request that the camera focus on that area of the scene. +The focus or exposure in that area will continually update as the scene in the area changes.
+ + +You can now enable continuous auto focusing (CAF) when taking photos. To enable CAF in your +camera app, pass {@link android.hardware.Camera.Parameters#FOCUS_MODE_CONTINUOUS_PICTURE} +to {@link android.hardware.Camera.Parameters#setFocusMode setFocusMode()}. When ready to capture +a photo, call {@link android.hardware.Camera#autoFocus autoFocus()}. Your {@link +android.hardware.Camera.AutoFocusCallback} immediately receives a callback to indicate whether +focus was achieved. To resume CAF after receiving the callback, you must call {@link +android.hardware.Camera#cancelAutoFocus()}.
+ +Note: Continuous auto focus is also supported when capturing +video, using {@link android.hardware.Camera.Parameters#FOCUS_MODE_CONTINUOUS_VIDEO}, which was +added in API level 9.
+ + +Android Beam is a new NFC feature that allows you to send NDEF messages from one device to +another (a process also known as “NDEF Push"). The data transfer is initiated when two +Android-powered devices that support Android Beam are in close proximity (about 4 cm), usually with +their backs touching. The data inside the NDEF message can contain any data that you wish to share +between devices. For example, the People app shares contacts, YouTube shares videos, and Browser +shares URLs using Android Beam.
+ +To transmit data between devices using Android Beam, you need to create an {@link +android.nfc.NdefMessage} that contains the information you want to share while your activity is in +the foreground. You must then pass the {@link android.nfc.NdefMessage} to the system in one of two +ways:
+ +Call {@link android.nfc.NfcAdapter#setNdefPushMessage setNdefPushMessage()} at any time to set +the message you want to send. For instance, you might call this method and pass it your {@link +android.nfc.NdefMessage} during your activity’s {@link android.app.Activity#onCreate onCreate()} +method. Then, whenever Android Beam is activated with another device while the activity is in the +foreground, the system sends the {@link android.nfc.NdefMessage} to the other device.
Implement {@link android.nfc.NfcAdapter.CreateNdefMessageCallback}, in which your +implementation of the {@link +android.nfc.NfcAdapter.CreateNdefMessageCallback#createNdefMessage createNdefMessage()} +method returns the {@link android.nfc.NdefMessage} you want to send. Then pass the {@link +android.nfc.NfcAdapter.CreateNdefMessageCallback} implementation to {@link +android.nfc.NfcAdapter#setNdefPushMessageCallback setNdefPushMessageCallback()}.
+In this case, when Android Beam is activated with another device while your activity is in the +foreground, the system calls {@link +android.nfc.NfcAdapter.CreateNdefMessageCallback#createNdefMessage createNdefMessage()} to retrieve +the {@link android.nfc.NdefMessage} you want to send. This allows you to define the {@link +android.nfc.NdefMessage} to deliver only once Android Beam is initiated, in case the contents +of the message might vary throughout the life of the activity.
In case you want to run some specific code once the system has successfully delivered your NDEF +message to the other device, you can implement {@link +android.nfc.NfcAdapter.OnNdefPushCompleteCallback} and set it with {@link +android.nfc.NfcAdapter#setOnNdefPushCompleteCallback setNdefPushCompleteCallback()}. The system will +then call {@link android.nfc.NfcAdapter.OnNdefPushCompleteCallback#onNdefPushComplete +onNdefPushComplete()} when the message is delivered.
+ +On the receiving device, the system dispatches NDEF Push messages in a similar way to regular NFC +tags. The system invokes an intent with the {@link android.nfc.NfcAdapter#ACTION_NDEF_DISCOVERED} +action to start an activity, with either a URL or a MIME type set according to the first {@link +android.nfc.NdefRecord} in the {@link android.nfc.NdefMessage}. For the activity you want to +respond, you can declare intent filters for the URLs or MIME types your app cares about. For more +information about Tag Dispatch see the NFC developer guide.
+ +If you want your {@link android.nfc.NdefMessage} to carry a URI, you can now use the convenience +method {@link android.nfc.NdefRecord#createUri createUri} to construct a new {@link +android.nfc.NdefRecord} based on either a string or a {@link android.net.Uri} object. If the URI is +a special format that you want your application to also receive during an Android Beam event, you +should create an intent filter for your activity using the same URI scheme in order to receive the +incoming NDEF message.
+ +You should also pass an “Android application record" with your {@link android.nfc.NdefMessage} in +order to guarantee that your application handles the incoming NDEF message, even if other +applications filter for the same intent action. You can create an Android application record by +calling {@link android.nfc.NdefRecord#createApplicationRecord createApplicationRecord()}, passing it +your application’s package name. When the other device receives the NDEF message with the +application record and multiple applications contain activities that handle the specified intent, +the system always delivers the message to the activity in your application (based on the matching +application record). If the target device does not currently have your application installed, the +system uses the Android application record to launch Google Play and take the user to the +application in order to install it.
+ +If your application doesn’t use NFC APIs to perform NDEF Push messaging, then Android provides a +default behavior: When your application is in the foreground on one device and Android Beam is +invoked with another Android-powered device, then the other device receives an NDEF message with an +Android application record that identifies your application. If the receiving device has the +application installed, the system launches it; if it’s not installed, Google Play opens and takes +the user to your application in order to install it.
+ +You can read more about Android Beam and other NFC features in the NFC Basics developer guide. For some example code +using Android Beam, see the Android +Beam Demo.
+ + + + + +Android now supports Wi-Fi Direct for peer-to-peer (P2P) connections between Android-powered +devices and other device types without a hotspot or Internet connection. The Android framework +provides a set of Wi-Fi P2P APIs that allow you to discover and connect to other devices when each +device supports Wi-Fi Direct, then communicate over a speedy connection across distances much longer +than a Bluetooth connection.
+ +A new package, {@link android.net.wifi.p2p}, contains all the APIs for performing peer-to-peer +connections with Wi-Fi. The primary class you need to work with is {@link +android.net.wifi.p2p.WifiP2pManager}, which you can acquire by calling {@link +android.app.Activity#getSystemService getSystemService(WIFI_P2P_SERVICE)}. The {@link +android.net.wifi.p2p.WifiP2pManager} includes APIs that allow you to:
+Several other interfaces and classes are necessary as well, such as:
+In order to use the Wi-Fi P2P APIs, your app must request the following user permissions:
+The Android system also broadcasts several different actions during certain Wi-Fi P2P events:
+See the {@link android.net.wifi.p2p.WifiP2pManager} documentation for more information. Also +look at the Wi-Fi Direct Demo +sample application.
+ + + + + +Android now supports Bluetooth Health Profile devices, so you can create applications that use +Bluetooth to communicate with health devices that support Bluetooth, such as heart-rate monitors, +blood meters, thermometers, and scales.
+ +Similar to regular headset and A2DP profile devices, you must call {@link +android.bluetooth.BluetoothAdapter#getProfileProxy getProfileProxy()} with a {@link +android.bluetooth.BluetoothProfile.ServiceListener} and the {@link +android.bluetooth.BluetoothProfile#HEALTH} profile type to establish a connection with the profile +proxy object.
+ +Once you’ve acquired the Health Profile proxy (the {@link android.bluetooth.BluetoothHealth} +object), connecting to and communicating with paired health devices involves the following new +Bluetooth classes:
+For more information about using the Bluetooth Health Profile, see the documentation for {@link +android.bluetooth.BluetoothHealth}.
+ + + + + +Android 4.0 improves accessibility for sight-impaired users with new explore-by-touch mode +and extended APIs that allow you to provide more information about view content or +develop advanced accessibility services.
+ + +Users with vision loss can now explore the screen by touching and dragging a finger across the +screen to hear voice descriptions of the content. Because the explore-by-touch mode works like a +virtual cursor, it allows screen readers to identify the descriptive text the same way that screen +readers can when the user navigates with a d-pad or trackball—by reading information provided +by {@link android.R.attr#contentDescription android:contentDescription} and {@link +android.view.View#setContentDescription setContentDescription()} upon a simulated "hover" event. So, +consider this is a reminder that you should provide descriptive text for the views in your +application, especially for {@link android.widget.ImageButton}, {@link android.widget.EditText}, +{@link android.widget.ImageView} and other widgets that might not naturally contain descriptive +text.
+ + +To enhance the information available to accessibility services such as screen readers, you can +implement new callback methods for accessibility events in your custom {@link +android.view.View} components.
+ +It's important to first note that the behavior of the {@link +android.view.View#sendAccessibilityEvent sendAccessibilityEvent()} method has changed in Android +4.0. As with previous version of Android, when the user enables accessibility services on the device +and an input event such as a click or hover occurs, the respective view is notified with a call to +{@link android.view.View#sendAccessibilityEvent sendAccessibilityEvent()}. Previously, the +implementation of {@link android.view.View#sendAccessibilityEvent sendAccessibilityEvent()} would +initialize an {@link android.view.accessibility.AccessibilityEvent} and send it to {@link +android.view.accessibility.AccessibilityManager}. The new behavior involves some additional callback +methods that allow the view and its parents to add more contextual information to the event: +
Custom implementations of {@link android.view.View} might want to implement {@link +android.view.View#onInitializeAccessibilityEvent onInitializeAccessibilityEvent()} to +attach additional accessibility information to the {@link +android.view.accessibility.AccessibilityEvent}, but should also call the super implementation to +provide default information such as the standard content description, item index, and more. +However, you should not add additional text content in this callback—that happens +next.
Custom implementations of {@link android.view.View} should usually implement {@link +android.view.View#onPopulateAccessibilityEvent onPopulateAccessibilityEvent()} to add additional +text content to the {@link android.view.accessibility.AccessibilityEvent} if the {@link +android.R.attr#contentDescription android:contentDescription} text is missing or +insufficient. To add more text description to the +{@link android.view.accessibility.AccessibilityEvent}, call {@link +android.view.accessibility.AccessibilityEvent#getText()}.{@link java.util.List#add add()}.
+In addition to the new methods above, which are useful when extending the {@link +android.view.View} class, you can also intercept these event callbacks on any {@link +android.view.View} by extending {@link +android.view.View.AccessibilityDelegate AccessibilityDelegate} and setting it on the view with +{@link android.view.View#setAccessibilityDelegate setAccessibilityDelegate()}. +When you do, each accessibility method in the view defers the call to the corresponding method in +the delegate. For example, when the view receives a call to {@link +android.view.View#onPopulateAccessibilityEvent onPopulateAccessibilityEvent()}, it passes it to the +same method in the {@link android.view.View.AccessibilityDelegate}. Any methods not handled by +the delegate are given right back to the view for default behavior. This allows you to override only +the methods necessary for any given view without extending the {@link android.view.View} class.
+ + +If you want to maintain compatibility with Android versions prior to 4.0, while also supporting +the new the accessibility APIs, you can do so with the latest version of the v4 support +library (in Compatibility Package, r4) +using a set of utility classes that provide the new accessibility APIs in a backward-compatible +design.
+ + + + +If you're developing an accessibility service, the information about various accessibility events +has been significantly expanded to enable more advanced accessibility feedback for users. In +particular, events are generated based on view composition, providing better context information and +allowing accessibility services to traverse view hierarchies to get additional view information and +deal with special cases.
+ +If you're developing an accessibility service (such as a screen reader), you can access +additional content information and traverse view hierarchies with the following procedure:
+An {@link android.view.accessibility.AccessibilityNodeInfo} represents a single node +of the window content in a format that allows you to query accessibility information about that +node. The {@link android.view.accessibility.AccessibilityNodeInfo} object returned from {@link +android.view.accessibility.AccessibilityEvent} describes the event source, whereas the source from +an {@link android.view.accessibility.AccessibilityRecord} describes the predecessor of the event +source.
In order for your application to publish itself to the system as an accessibility service, it +must declare an XML configuration file that corresponds to {@link +android.accessibilityservice.AccessibilityServiceInfo}. For more information about creating an +accessibility service, see {@link +android.accessibilityservice.AccessibilityService} and {@link +android.accessibilityservice.AccessibilityService#SERVICE_META_DATA +SERVICE_META_DATA} for information about the XML configuration.
+ + +If you're interested in the device's accessibility state, the {@link +android.view.accessibility.AccessibilityManager} has some new APIs such as:
+A new spell checker framework allows apps to create spell checkers in a manner similar to the +input method framework (for IMEs). To create a new spell checker, you must implement a service that +extends +{@link android.service.textservice.SpellCheckerService} and extend the {@link +android.service.textservice.SpellCheckerService.Session} class to provide spelling suggestions based +on text provided by the interface's callback methods. In the {@link +android.service.textservice.SpellCheckerService.Session} callback methods, you must return the +spelling suggestions as {@link android.view.textservice.SuggestionsInfo} objects.
+ +Applications with a spell checker service must declare the {@link +android.Manifest.permission#BIND_TEXT_SERVICE} permission as required by the service. +The service must also declare an intent filter with {@code <action +android:name="android.service.textservice.SpellCheckerService" />} as the intent’s action and should +include a {@code <meta-data>} element that declares configuration information for the spell +checker.
+ +See the sample +Spell Checker Service app and +sample +Spell Checker Client app for example code.
+ + + + +Android’s text-to-speech (TTS) APIs have been significantly extended to allow applications to +more easily implement custom TTS engines, while applications that want to use a TTS engine have a +couple new APIs for selecting an engine.
+ + +In previous versions of Android, you could use the {@link android.speech.tts.TextToSpeech} class +to perform text-to-speech (TTS) operations using the TTS engine provided by the system or set a +custom engine using {@link android.speech.tts.TextToSpeech#setEngineByPackageName +setEngineByPackageName()}. In Android 4.0, the {@link +android.speech.tts.TextToSpeech#setEngineByPackageName setEngineByPackageName()} method has been +deprecated and you can now specify the engine to use with a new {@link +android.speech.tts.TextToSpeech} constructor that accepts the package name of a TTS engine.
+ +You can also query the available TTS engines with {@link +android.speech.tts.TextToSpeech#getEngines()}. This method returns a list of {@link +android.speech.tts.TextToSpeech.EngineInfo} objects, which include meta data such as the engine’s +icon, label, and package name.
+ + +Previously, custom engines required that the engine be built using an undocumented native header +file. In Android 4.0, there is a complete set of framework APIs for building TTS engines.
+ +The basic setup requires an implementation of {@link android.speech.tts.TextToSpeechService} that +responds to the {@link android.speech.tts.TextToSpeech.Engine#INTENT_ACTION_TTS_SERVICE} intent. The +primary work for a TTS engine happens during the {@link +android.speech.tts.TextToSpeechService#onSynthesizeText onSynthesizeText()} callback in a service +that extends {@link android.speech.tts.TextToSpeechService}. The system delivers this method two +objects:
+Now that the framework supports a true API for creating TTS engines, support for the native code +implementation has been removed. Look for a blog post about a compatibility layer +that you can use to convert your old TTS engines to the new framework.
+ +For an example TTS engine using the new APIs, see the Text To Speech Engine sample app.
+ + + + + + +Android 4.0 gives users precise visibility of how much network data their applications are using. +The Settings app provides controls that allow users to manage set limits for network data usage and +even disable the use of background data for individual apps. In order to avoid users disabling your +app’s access to data from the background, you should develop strategies to use the data +connection efficiently and adjust your usage depending on the type of connection available.
+ +If your application performs a lot of network transactions, you should provide user settings that +allow users to control your app’s data habits, such as how often your app syncs data, whether to +perform uploads/downloads only when on Wi-Fi, whether to use data while roaming, etc. With these +controls available to them, users are much less likely to disable your app’s access to data when +they approach their limits, because they can instead precisely control how much data your app uses. +If you provide a preference activity with these settings, you should include in its manifest +declaration an intent filter for the {@link android.content.Intent#ACTION_MANAGE_NETWORK_USAGE} +action. For example:
+ ++<activity android:name="DataPreferences" android:label="@string/title_preferences"> + <intent-filter> + <action android:name="android.intent.action.MANAGE_NETWORK_USAGE" /> + <category android:name="android.intent.category.DEFAULT" /> + </intent-filter> +</activity> ++ +
This intent filter indicates to the system that this is the activity that controls your +application’s data usage. Thus, when the user inspects how much data your app is using from the +Settings app, a “View application settings" button is available that launches your +preference activity so the user can refine how much data your app uses.
+ +Also beware that {@link android.net.ConnectivityManager#getBackgroundDataSetting()} is now +deprecated and always returns true—use {@link +android.net.ConnectivityManager#getActiveNetworkInfo()} instead. Before you attempt any network +transactions, you should always call {@link android.net.ConnectivityManager#getActiveNetworkInfo()} +to get the {@link android.net.NetworkInfo} that represents the current network and query {@link +android.net.NetworkInfo#isConnected()} to check whether the device has a +connection. You can then check other connection properties, such as whether the device is +roaming or connected to Wi-Fi.
+ + + + + + + + +Three major features have been added to RenderScript:
+ +The {@link android.renderscript.Allocation} class now supports a {@link +android.renderscript.Allocation#USAGE_GRAPHICS_RENDER_TARGET} memory space, which allows you to +render things directly into the {@link android.renderscript.Allocation} and use it as a framebuffer +object.
+ +{@link android.renderscript.RSTextureView} provides a means to display RenderScript graphics +inside of a {@link android.view.View}, unlike {@link android.renderscript.RSSurfaceView}, which +creates a separate window. This key difference allows you to do things such as move, transform, or +animate an {@link android.renderscript.RSTextureView} as well as draw RenderScript graphics inside +a view that lies within an activity layout.
+ +The {@link android.renderscript.Script#forEach Script.forEach()} method allows you to call +RenderScript compute scripts from the VM level and have them automatically delegated to available +cores on the device. You do not use this method directly, but any compute RenderScript that you +write will have a {@link android.renderscript.Script#forEach forEach()} method that you can call in +the reflected RenderScript class. You can call the reflected {@link +android.renderscript.Script#forEach forEach()} method by passing in an input {@link +android.renderscript.Allocation} to process, an output {@link android.renderscript.Allocation} to +write the result to, and a {@link android.renderscript.FieldPacker} data structure in case the +RenderScript needs more information. Only one of the {@link android.renderscript.Allocation}s is +necessary and the data structure is optional.
+ + + + + + + + + +Android 4.0 expands the capabilities for enterprise application with the following features.
+ +The new {@link android.net.VpnService} allows applications to build their own VPN (Virtual +Private Network), running as a {@link android.app.Service}. A VPN service creates an interface for a +virtual network with its own address and routing rules and performs all reading and writing with a +file descriptor.
+ +To create a VPN service, use {@link android.net.VpnService.Builder}, which allows you to specify +the network address, DNS server, network route, and more. When complete, you can establish the +interface by calling {@link android.net.VpnService.Builder#establish()}, which returns a {@link +android.os.ParcelFileDescriptor}.
+ +Because a VPN service can intercept packets, there are security implications. As such, if you +implement {@link android.net.VpnService}, then your service must require the {@link +android.Manifest.permission#BIND_VPN_SERVICE} to ensure that only the system can bind to it (only +the system is granted this permission—apps cannot request it). To then use your VPN service, +users must manually enable it in the system settings.
+ + +Applications that manage the device restrictions can now disable the camera using {@link +android.app.admin.DevicePolicyManager#setCameraDisabled setCameraDisabled()} and the {@link +android.app.admin.DeviceAdminInfo#USES_POLICY_DISABLE_CAMERA} property (applied with a {@code +<disable-camera />} element in the policy configuration file).
+ + +The new {@link android.security.KeyChain} class provides APIs that allow you to import and access +certificates in the system key store. Certificates streamline the installation of both client +certificates (to validate the identity of the user) and certificate authority certificates (to +verify server identity). Applications such as web browsers or email clients can access the installed +certificates to authenticate users to servers. See the {@link android.security.KeyChain} +documentation for more information.
+ + + + + + + +Two new sensor types have been added in Android 4.0:
+ +If a device has both {@link android.hardware.Sensor#TYPE_AMBIENT_TEMPERATURE} and {@link +android.hardware.Sensor#TYPE_RELATIVE_HUMIDITY} sensors, you can use them to calculate the dew point +and the absolute humidity.
+ +The previous temperature sensor, {@link android.hardware.Sensor#TYPE_TEMPERATURE}, has been +deprecated. You should use the {@link android.hardware.Sensor#TYPE_AMBIENT_TEMPERATURE} sensor +instead.
+ +Additionally, Android’s three synthetic sensors have been greatly improved so they now have lower +latency and smoother output. These sensors include the gravity sensor ({@link +android.hardware.Sensor#TYPE_GRAVITY}), rotation vector sensor ({@link +android.hardware.Sensor#TYPE_ROTATION_VECTOR}), and linear acceleration sensor ({@link +android.hardware.Sensor#TYPE_LINEAR_ACCELERATION}). The improved sensors rely on the gyroscope +sensor to improve their output, so the sensors appear only on devices that have a gyroscope.
+ + + + + +The {@link android.app.ActionBar} has been updated to support several new behaviors. Most +importantly, the system gracefully manages the action bar’s size and configuration when running on +smaller screens in order to provide an optimal user experience on all screen sizes. For example, +when the screen is narrow (such as when a handset is in portrait orientation), the action bar’s +navigation tabs appear in a “stacked bar," which appears directly below the main action bar. You can +also opt-in to a “split action bar," which places all action items in a separate bar at the bottom +of the screen when the screen is narrow.
+ + +If your action bar includes several action items, not all of them will fit into the action bar on +a narrow screen, so the system will place more of them into the overflow menu. However, Android 4.0 +allows you to enable “split action bar" so that more action items can appear on the screen in a +separate bar at the bottom of the screen. To enable split action bar, add {@link +android.R.attr#uiOptions android:uiOptions} with {@code "splitActionBarWhenNarrow"} to either your +{@code <application>} +tag or +individual {@code +<activity>} tags +in your manifest file. When enabled, the system will add an additional bar at the bottom of the +screen for all action items when the screen is narrow (no action items will appear in the primary +action bar).
+ +If you want to use the navigation tabs provided by the {@link android.app.ActionBar.Tab} APIs, +but don’t need the main action bar on top (you want only the tabs to appear at the top), then enable +the split action bar as described above and also call {@link +android.app.ActionBar#setDisplayShowHomeEnabled setDisplayShowHomeEnabled(false)} to disable the +application icon in the action bar. With nothing left in the main action bar, it +disappears—all that’s left are the navigation tabs at the top and the action items at the +bottom of the screen.
+ + +If you want to apply custom styling to the action bar, you can use new style properties {@link +android.R.attr#backgroundStacked} and {@link android.R.attr#backgroundSplit} to apply a background +drawable or color to the stacked bar and split bar, respectively. You can also set these styles at +runtime with {@link android.app.ActionBar#setStackedBackgroundDrawable +setStackedBackgroundDrawable()} and {@link android.app.ActionBar#setSplitBackgroundDrawable +setSplitBackgroundDrawable()}.
+ + +The new {@link android.view.ActionProvider} class allows you to create a specialized handler for +action items. An action provider can define an action view, a default action behavior, and a submenu +for each action item to which it is associated. When you want to create an action item that has +dynamic behaviors (such as a variable action view, default action, or submenu), extending {@link +android.view.ActionProvider} is a good solution in order to create a reusable component, rather than +handling the various action item transformations in your fragment or activity.
+ +For example, the {@link android.widget.ShareActionProvider} is an extension of {@link +android.view.ActionProvider} that facilitates a “share" action from the action bar. Instead of using +traditional action item that invokes the {@link android.content.Intent#ACTION_SEND} intent, you can +use this action provider to present an action view with a drop-down list of applications that handle +the {@link android.content.Intent#ACTION_SEND} intent. When the user selects an application to use +for the action, {@link android.widget.ShareActionProvider} remembers that selection and provides it +in the action view for faster access to sharing with that app.
+ +To declare an action provider for an action item, include the {@code android:actionProviderClass} +attribute in the {@code +<item>} element for your activity’s options menu, with the class name of the action +provider as the value. For example:
+ ++<item android:id="@+id/menu_share" + android:title="Share" + android:showAsAction="ifRoom" + android:actionProviderClass="android.widget.ShareActionProvider" /> ++ +
In your activity’s {@link android.app.Activity#onCreateOptionsMenu onCreateOptionsMenu()} +callback method, retrieve an instance of the action provider from the menu item and set the +intent:
+ +
+public boolean onCreateOptionsMenu(Menu menu) {
+ getMenuInflater().inflate(R.menu.options, menu);
+ ShareActionProvider shareActionProvider =
+ (ShareActionProvider) menu.findItem(R.id.menu_share).getActionProvider();
+ // Set the share intent of the share action provider.
+ shareActionProvider.setShareIntent(createShareIntent());
+ ...
+ return super.onCreateOptionsMenu(menu);
+}
+
+
+For an example using the {@link android.widget.ShareActionProvider}, see ActionBarShareActionProviderActivity in ApiDemos.
+ + +Action items that provide an action view can now toggle between their action view state and +traditional action item state. Previously only the {@link android.widget.SearchView} supported +collapsing when used as an action view, but now you can add an action view for any action item and +switch between the expanded state (action view is visible) and collapsed state (action item is +visible).
+ +To declare that an action item that contains an action view be collapsible, include the {@code +“collapseActionView"} flag in the {@code android:showAsAction} attribute for the {@code +<item>} element in the menu’s XML file.
+ +To receive callbacks when an action view switches between expanded and collapsed, register an +instance of {@link android.view.MenuItem.OnActionExpandListener} with the respective {@link +android.view.MenuItem} by calling {@link android.view.MenuItem#setOnActionExpandListener +setOnActionExpandListener()}. Typically, you should do so during the {@link +android.app.Activity#onCreateOptionsMenu onCreateOptionsMenu()} callback.
+ +To control a collapsible action view, you can call {@link +android.view.MenuItem#collapseActionView()} and {@link android.view.MenuItem#expandActionView()} on +the respective {@link android.view.MenuItem}.
+ +When creating a custom action view, you can also implement the new {@link +android.view.CollapsibleActionView} interface to receive callbacks when the view is expanded and +collapsed.
+ + +Android 4.0 introduces a variety of new views and other UI components.
+ + +{@link android.widget.GridLayout} is a new view group that places child views in a rectangular +grid. Unlike {@link android.widget.TableLayout}, {@link android.widget.GridLayout} relies on a flat +hierarchy and does not make use of intermediate views such as table rows for providing structure. +Instead, children specify which row(s) and column(s) they should occupy (cells can span multiple +rows and/or columns), and by default are laid out sequentially across the grid’s rows and columns. +The {@link android.widget.GridLayout} orientation determines whether sequential children are by +default laid out horizontally or vertically. Space between children may be specified either by using +instances of the new {@link android.widget.Space} view or by setting the relevant margin parameters +on children.
+ +See ApiDemos +for samples using {@link android.widget.GridLayout}.
+ + + +{@link android.view.TextureView} is a new view that allows you to display a content stream, such +as a video or an OpenGL scene. Although similar to {@link android.view.SurfaceView}, {@link +android.view.TextureView} is unique in that it behaves like a regular view, rather than creating a +separate window, so you can treat it like any other {@link android.view.View} object. For example, +you can apply transforms, animate it using {@link android.view.ViewPropertyAnimator}, or +adjust its opacity with {@link android.view.View#setAlpha setAlpha()}.
+ +Beware that {@link android.view.TextureView} works only within a hardware accelerated window.
+ +For more information, see the {@link android.view.TextureView} documentation.
+ + +The new {@link android.widget.Switch} widget is a two-state toggle that users can drag to one +side or the other (or simply tap) to toggle an option between two states.
+ +You can use the {@code android:textOn} and {@code android:textOff} attributes to specify the text +to appear on the switch when in the on and off setting. The {@code android:text} attribute also +allows you to place a label alongside the switch.
+ +For a sample using switches, see the switches.xml layout file +and respective Switches + activity.
+ + +Android 3.0 introduced {@link android.widget.PopupMenu} to create short contextual menus that pop +up at an anchor point you specify (usually at the point of the item selected). Android 4.0 extends +the {@link android.widget.PopupMenu} with a couple useful features:
+A new {@link android.preference.TwoStatePreference} abstract class serves as the basis for +preferences that provide a two-state selection option. The new {@link +android.preference.SwitchPreference} is an extension of {@link +android.preference.TwoStatePreference} that provides a {@link android.widget.Switch} widget in the +preference view to allow users to toggle a setting on or off without the need to open an additional +preference screen or dialog. For example, the Settings application uses a {@link +android.preference.SwitchPreference} for the Wi-Fi and Bluetooth settings.
+ + + +The default theme for all applications that target Android 4.0 (by setting either {@code targetSdkVersion} or +{@code minSdkVersion} to +{@code “14"} or higher) is now the +"device default" theme: {@link android.R.style#Theme_DeviceDefault Theme.DeviceDefault}. This may be +the dark Holo theme or a different dark theme defined by the specific device.
+ +The {@link android.R.style#Theme_Holo Theme.Holo} family of themes are guaranteed to not change +from one device to another when running the same version of Android. If you explicitly +apply any of the {@link android.R.style#Theme_Holo Theme.Holo} themes to your activities, you can +rest assured that these themes will not change character on different devices within the same +platform version.
+ +If you wish for your app to blend in with the overall device theme (such as when different OEMs +provide different default themes for the system), you should explicitly apply themes from the {@link +android.R.style#Theme_DeviceDefault Theme.DeviceDefault} family.
+ + +Beginning with Android 4.0, you'll notice that handsets no longer require a Menu hardware button. +However, there's no need for you to worry about this if your existing application provides an options menu and expects there to be a +Menu button. To ensure that existing apps continue to work as they expect, the system provides an +on-screen Menu button for apps that were designed for older versions of Android.
+ +For the best user experience, new and updated apps should instead use the {@link +android.app.ActionBar} to provide access to menu items and set {@code targetSdkVersion} to +{@code "14"} to take advantage of the latest framework default behaviors.
+ + + +Since the early days of Android, the system has managed a UI component known as the status +bar, which resides at the top of handset devices to deliver information such as the carrier +signal, time, notifications, and so on. Android 3.0 added the system bar for tablet +devices, which resides at the bottom of the screen to provide system navigation controls (Home, +Back, and so forth) and also an interface for elements traditionally provided by the status bar. In +Android 4.0, the system provides a new type of system UI called the navigation bar. You +might consider the navigation bar a re-tuned version of the system bar designed for +handsets—it provides navigation controls +for devices that don’t have hardware counterparts for navigating the system, but it leaves out the +system bar's notification UI and setting controls. As such, a device that provides the navigation +bar also has the status bar at the top.
+ +To this day, you can hide the status bar on handsets using the {@link +android.view.WindowManager.LayoutParams#FLAG_FULLSCREEN} flag. In Android 4.0, the APIs that control +the system bar’s visibility have been updated to better reflect the behavior of both the system bar +and navigation bar:
+You can set each of these flags for the system bar and navigation bar by calling {@link +android.view.View#setSystemUiVisibility setSystemUiVisibility()} on any view in your activity. The +window manager combines (OR-together) all flags from all views in your window and +apply them to the system UI as long as your window has input focus. When your window loses input +focus (the user navigates away from your app, or a dialog appears), your flags cease to have effect. +Similarly, if you remove those views from the view hierarchy their flags no longer apply.
+ +To synchronize other events in your activity with visibility changes to the system UI (for +example, hide the action bar or other UI controls when the system UI hides), you should register a +{@link android.view.View.OnSystemUiVisibilityChangeListener} to be notified when the visibility +of the system bar or navigation bar changes.
+ +See the +OverscanActivity class for a demonstration of different system UI options.
+ + + + + +Android 4.0 adds support for cursor hover events and new stylus and mouse button events.
+ +The {@link android.view.View} class now supports “hover" events to enable richer interactions +through the use of pointer devices (such as a mouse or other devices that drive an on-screen +cursor).
+ +To receive hover events on a view, implement the {@link android.view.View.OnHoverListener} and +register it with {@link android.view.View#setOnHoverListener setOnHoverListener()}. When a hover +event occurs on the view, your listener receives a call to {@link +android.view.View.OnHoverListener#onHover onHover()}, providing the {@link android.view.View} that +received the event and a {@link android.view.MotionEvent} that describes the type of hover event +that occurred. The hover event can be one of the following:
+Your {@link android.view.View.OnHoverListener} should return true from {@link +android.view.View.OnHoverListener#onHover onHover()} if it handles the hover event. If your +listener returns false, then the hover event will be dispatched to the parent view as usual.
+ +If your application uses buttons or other widgets that change their appearance based on the +current state, you can now use the {@code android:state_hovered} attribute in a state list drawable to +provide a different background drawable when a cursor hovers over the view.
+ +For a demonstration of the new hover events, see the Hover class in +ApiDemos.
+ + +Android now provides APIs for receiving input from a stylus input device such as a digitizer +tablet peripheral or a stylus-enabled touch screen.
+ +Stylus input operates in a similar manner to touch or mouse input. When the stylus is in contact +with the digitizer, applications receive touch events just like they would when a finger is used to +touch the display. When the stylus is hovering above the digitizer, applications receive hover +events just like they would when a mouse pointer was being moved across the display when no buttons +are pressed.
+ +Your application can distinguish between finger, mouse, stylus and eraser input by querying the +“tool type" associated with each pointer in a {@link android.view.MotionEvent} using {@link +android.view.MotionEvent#getToolType getToolType()}. The currently defined tool types are: {@link +android.view.MotionEvent#TOOL_TYPE_UNKNOWN}, {@link android.view.MotionEvent#TOOL_TYPE_FINGER}, +{@link android.view.MotionEvent#TOOL_TYPE_MOUSE}, {@link android.view.MotionEvent#TOOL_TYPE_STYLUS}, +and {@link android.view.MotionEvent#TOOL_TYPE_ERASER}. By querying the tool type, your application +can choose to handle stylus input in different ways from finger or mouse input.
+ +Your application can also query which mouse or stylus buttons are pressed by querying the “button +state" of a {@link android.view.MotionEvent} using {@link android.view.MotionEvent#getButtonState +getButtonState()}. The currently defined button states are: {@link +android.view.MotionEvent#BUTTON_PRIMARY}, {@link android.view.MotionEvent#BUTTON_SECONDARY}, {@link +android.view.MotionEvent#BUTTON_TERTIARY}, {@link android.view.MotionEvent#BUTTON_BACK}, and {@link +android.view.MotionEvent#BUTTON_FORWARD}. For convenience, the back and forward mouse buttons are +automatically mapped to the {@link android.view.KeyEvent#KEYCODE_BACK} and {@link +android.view.KeyEvent#KEYCODE_FORWARD} keys. Your application can handle these keys to support +mouse button based back and forward navigation.
+ +In addition to precisely measuring the position and pressure of a contact, some stylus input +devices also report the distance between the stylus tip and the digitizer, the stylus tilt angle, +and the stylus orientation angle. Your application can query this information using {@link +android.view.MotionEvent#getAxisValue getAxisValue()} with the axis codes {@link +android.view.MotionEvent#AXIS_DISTANCE}, {@link android.view.MotionEvent#AXIS_TILT}, and {@link +android.view.MotionEvent#AXIS_ORIENTATION}.
+ +For a demonstration of tool types, button states and the new axis codes, see the TouchPaint + class in ApiDemos.
+ + + + + + +The new {@link android.util.Property} class provides a fast, efficient, and easy way to specify a +property on any object that allows callers to generically set/get values on target objects. It also +allows the functionality of passing around field/method references and allows code to set/get values +of the property without knowing the details of what the fields/methods are.
+ +For example, if you want to set the value of field {@code bar} on object {@code foo}, you would +previously do this:
++foo.bar = value; ++ +
If you want to call the setter for an underlying private field {@code bar}, you would previously +do this:
++foo.setBar(value); ++ +
However, if you want to pass around the {@code foo} instance and have some other code set the +{@code bar} value, there is really no way to do it prior to Android 4.0.
+ +Using the {@link android.util.Property} class, you can declare a {@link android.util.Property} +object {@code BAR} on class {@code Foo} so that you can set the field on instance {@code foo} of +class {@code Foo} like this:
++BAR.set(foo, value); ++ +
The {@link android.view.View} class now leverages the {@link android.util.Property} class to +allow you to set various fields, such as transform properties that were added in Android 3.0 ({@link +android.view.View#ROTATION}, {@link android.view.View#ROTATION_X}, {@link +android.view.View#TRANSLATION_X}, etc.).
+ +The {@link android.animation.ObjectAnimator} class also uses the {@link android.util.Property} +class, so you can create an {@link android.animation.ObjectAnimator} with a {@link +android.util.Property}, which is faster, more efficient, and more type-safe than the string-based +approach.
+ + + + + + +Beginning with Android 4.0, hardware acceleration for all windows is enabled by default if your +application has set either {@code targetSdkVersion} or +{@code minSdkVersion} to +{@code “14"} or higher. Hardware acceleration generally results in smoother animations, smoother +scrolling, and overall better performance and response to user interaction.
+ +If necessary, you can manually disable hardware acceleration with the {@code hardwareAccelerated} +attribute for individual {@code +<activity>} elements or the {@code <application>} +element. You can alternatively disable hardware acceleration for individual views by calling {@link +android.view.View#setLayerType setLayerType(LAYER_TYPE_SOFTWARE)}.
+ +For more information about hardware acceleration, including a list of unsupported drawing +operations, see the Hardware +Acceleration document.
+ + + +In previous versions of Android, JNI local references weren’t indirect handles; Android used +direct pointers. This wasn't a problem as long as the garbage collector didn't move objects, but it +seemed to work because it made it possible to write buggy code. In Android 4.0, the system now uses +indirect references in order to detect these bugs.
+ +The ins and outs of JNI local references are described in “Local and Global References" in JNI Tips. In Android 4.0, +CheckJNI has been enhanced to detect these errors. Watch the Android Developers Blog for an upcoming post +about common errors with JNI references and how you can fix them.
+ +This change in the JNI implementation only affects apps that target Android 4.0 by setting either +the {@code +targetSdkVersion} or {@code +minSdkVersion} to {@code “14"} or higher. If you’ve set these attributes to any lower value, +then JNI local references behave the same as in previous versions.
+ + + + + +The Browser application adds the following features to support web applications:
+The following are new permissions:
+The following are new device features:
+For a detailed view of all API changes in Android {@sdkPlatformVersion} (API Level +{@sdkPlatformApiLevel}), see the API Differences Report.
+In addition to everything above, Android 4.0 naturally supports all APIs from previous releases. +Because the Android 3.x platform is available only for large-screen devices, if you've +been developing primarily for handsets, then you might not be aware of all the APIs added to Android +in these recent releases.
+ +Here's a look at some of the most notable APIs you might have missed that are now available +on handsets as well:
+ +<application>
+element or for individual <activity>
+elements. This results
+in smoother animations, smoother scrolling, and overall better performance and response to user
+interaction.
+ Note: If you set your application's {@code minSdkVersion} or {@code targetSdkVersion} to +{@code "14"} or higher, hardware acceleration is enabled by default.
The Android {@sdkPlatformVersion} API is assigned an integer +identifier—{@sdkPlatformApiLevel}—that is stored in the system itself. +This identifier, called the "API level", allows the system to correctly determine whether an +application is compatible with the system, prior to installing the application.
+ +To use APIs introduced in Android {@sdkPlatformVersion} in your application, you need compile the
+application against an Android platform that supports API level {@sdkPlatformApiLevel} or
+higher. Depending on your needs, you might also need to add an
+android:minSdkVersion="{@sdkPlatformApiLevel}" attribute to the
+{@code <uses-sdk>}
+element.
For more information, read What is API +Level?
diff --git a/docs/html/about/versions/api-levels.jd b/docs/html/about/versions/api-levels.jd new file mode 100644 index 000000000000..525e2cb5570a --- /dev/null +++ b/docs/html/about/versions/api-levels.jd @@ -0,0 +1,421 @@ +page.title=Android API Levels +@jd:body + +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.
+ +The sections below provide information about API Level and how it affects +your applications.
+ +For information about how to use the "Filter by API Level" control +available in the API reference documentation, see +Filtering the documentation at the +end of this document.
+ +API Level is an integer value that uniquely identifies the framework API +revision offered by a version of the Android platform.
+ +The Android platform provides a framework API that applications can use to +interact with the underlying Android system. The framework API consists of:
+ +Each successive version of the Android platform can include updates to the +Android application framework API that it delivers.
+ +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.
+ +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.
+ +The following table specifies the API Level supported by each version of the +Android platform.
+ +| Platform Version | API Level | VERSION_CODE | Notes |
|---|---|---|---|
| Android 4.0.3 | +15 | +{@link android.os.Build.VERSION_CODES#ICE_CREAM_SANDWICH_MR1} | +Platform +Highlights |
| Android 4.0, 4.0.1, 4.0.2 | +14 | +{@link android.os.Build.VERSION_CODES#ICE_CREAM_SANDWICH} | +|
| Android 3.2 | +13 | +{@link android.os.Build.VERSION_CODES#HONEYCOMB_MR2} | +|
| Android 3.1.x | +12 | +{@link android.os.Build.VERSION_CODES#HONEYCOMB_MR1} | +Platform Highlights |
| Android 3.0.x | +11 | +{@link android.os.Build.VERSION_CODES#HONEYCOMB} | +Platform Highlights |
| Android 2.3.4 Android 2.3.3 |
+ 10 | +{@link android.os.Build.VERSION_CODES#GINGERBREAD_MR1} | +Platform Highlights |
| Android 2.3.2 Android 2.3.1 Android 2.3 |
+ 9 | +{@link android.os.Build.VERSION_CODES#GINGERBREAD} | +|
| Android 2.2.x | +8 | +{@link android.os.Build.VERSION_CODES#FROYO} | +Platform Highlights |
| Android 2.1.x | +7 | +{@link android.os.Build.VERSION_CODES#ECLAIR_MR1} | +Platform Highlights |
| Android 2.0.1 | +6 | +{@link android.os.Build.VERSION_CODES#ECLAIR_0_1} | +|
| Android 2.0 | +5 | +{@link android.os.Build.VERSION_CODES#ECLAIR} | +|
| Android 1.6 | +4 | +{@link android.os.Build.VERSION_CODES#DONUT} | +Platform Highlights |
| Android 1.5 | +3 | +{@link android.os.Build.VERSION_CODES#CUPCAKE} | +Platform Highlights |
| Android 1.1 | +2 | +{@link android.os.Build.VERSION_CODES#BASE_1_1} | |
| Android 1.0 | +1 | +{@link android.os.Build.VERSION_CODES#BASE} | +
The API Level identifier serves a key role in ensuring the best possible +experience for users and application developers: + +
Each Android platform version stores its API Level identifier internally, in +the Android system itself.
+ +Applications can use a manifest element provided by the framework API —
+<uses-sdk> — 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:
android:minSdkVersion — Specifies the minimum API Level
+on which the application is able to run. The default value is "1".android:targetSdkVersion — Specifies the API Level
+on which the application is designed to run. In some cases, this allows the
+application to use manifest elements or behaviors defined in the target
+API Level, rather than being restricted to using only those defined
+for the minimum API Level.android:maxSdkVersion — Specifies the maximum API Level
+on which the application is able to run. Important: Please read the <uses-sdk>
+documentation before using this attribute. 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
+<uses-sdk> element with a android:minSdkVersion
+attribute. The value of android:minSdkVersion would be the integer
+corresponding to the API Level of the earliest version of the Android platform
+under which the application can run.
When the user attempts to install an application, or when revalidating an
+appplication after a system update, the Android system first checks the
+<uses-sdk> 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:
android:minSdkVersion 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. android:maxSdkVersion 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 <uses-sdk>
+documentation for more information about how the system handles this attribute.When declared in an application's manifest, a <uses-sdk>
+element might look like this:
<manifest> + <uses-sdk android:minSdkVersion="5" /> + ... +</manifest>+ +
The principal reason that an application would declare an API Level in
+android:minSdkVersion is to tell the Android system that it is
+using APIs that were introduced 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.
For example, the {@link android.appwidget} package was introduced with API
+Level 3. If an application uses that API, it must declare a
+android:minSdkVersion 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).
For more information about how to specify an application's API Level
+requirements, see the <uses-sdk>
+ section of the manifest file documentation.
The sections below provide information related to API level that you should +consider when developing your application.
+ +Android applications are generally forward-compatible with new versions of +the Android platform.
+ +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.
+ +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.
+ +In some cases, changes below 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.
+ +Android applications are not necessarily backward compatible with versions of +the Android platform older than the version against which they were compiled. +
+ +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.
+ +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.
+ +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. + +
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
+android:minSdkVersion attribute in the application's manifest and
+set its value to the API Level of the platform version.
If you build an application that uses APIs or system features introduced in
+the latest platform version, you should set the
+android:minSdkVersion 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.
If your application uses APIs introduced in the latest platform version but
+does not declare a android:minSdkVersion attribute, then
+it will run properly on devices running the latest version of the platform, but
+not 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.
After compiling your application, you should make sure to test it on the
+platform specified in the application's android:minSdkVersion
+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.
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.
+ +To access the updater, use the android command-line tool,
+located in the <sdk>/tools directory. You can launch the SDK updater by
+executing android sdk. 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
+Window > Android SDK
+Manager.
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 Creating and Managing Virtual Devices. 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.
+ +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 provisional API Level 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.
+ +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.
+ +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.
+ + +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 android:minSdkVersion attribute of its manifest file.
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.
+ +Filtering by API Level in the documentation does not provide a view +of what is new or introduced in each API Level — 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.
+ +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. +
+ +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 <api level>" 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.
diff --git a/docs/html/about/versions/index.jd b/docs/html/about/versions/index.jd new file mode 100644 index 000000000000..30826c085a0e --- /dev/null +++ b/docs/html/about/versions/index.jd @@ -0,0 +1,141 @@ +page.title=App Framework +@jd:body + +Android is a software stack for mobile devices that includes an operating +system, middleware and key applications. The Android SDK +provides the tools and APIs necessary to begin developing applications on the +Android platform using the Java programming language.
+ +The following diagram shows the major components of the Android operating +system. Each section is described in more detail below.
+ +
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.
+ + +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.
+ +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.
+ +Underlying all applications is a set of services and systems, including: +
For more details and a walkthrough of an application, see the Notepad Tutorial.
+ + +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:
+Android includes a set of core libraries that provides most of +the functionality available in the core libraries of the Java programming +language.
+ +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 "dx" tool.
+ +The Dalvik VM relies on the Linux kernel for underlying functionality such +as threading and low-level memory management.
+ + + +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.
diff --git a/docs/html/community/index.html b/docs/html/community/index.html deleted file mode 100644 index fb2a0d35bcc1..000000000000 --- a/docs/html/community/index.html +++ /dev/null @@ -1,10 +0,0 @@ - - - -You should have been redirected. Please click here.
- - \ No newline at end of file diff --git a/docs/html/design/building-blocks/index.jd b/docs/html/design/building-blocks/index.jd index 52b4915f2020..d915aae51abf 100644 --- a/docs/html/design/building-blocks/index.jd +++ b/docs/html/design/building-blocks/index.jd @@ -10,7 +10,7 @@ footer.hide=1 #text-overlay { position: absolute; - left: 10px; + left: 0; top: 472px; width: 450px; } diff --git a/docs/html/design/building-blocks/progress.jd b/docs/html/design/building-blocks/progress.jd index b18853871fce..03fc09c7302c 100644 --- a/docs/html/design/building-blocks/progress.jd +++ b/docs/html/design/building-blocks/progress.jd @@ -1,5 +1,4 @@ page.title=Progress and Activity -header.title=Feedback @jd:bodyWhen an operation of interest to the user is taking place over a relatively long period of time, diff --git a/docs/html/design/design_toc.cs b/docs/html/design/design_toc.cs index 6dd8d610418f..a31fdd322e93 100644 --- a/docs/html/design/design_toc.cs +++ b/docs/html/design/design_toc.cs @@ -63,8 +63,4 @@
-Action bar icons for phones should be 32x32 dp.
Today we’re thrilled to announce several significant improvements to the emulator, including a dramatic...
+In the upcoming weeks, some of the older Client + Login authentication keys will expire. If you generated the token you’re...
+We recently published some new resources to help developers make their Android applications more accessible...
+Over the past year we’ve been working to expand the list of + countries and currencies from which Android developers...
+In-app Billing is a Google Play service that lets you sell digital content from inside your applications. You can sell products as standard in-app products (one-time purchase) or with subscriptions (recurring...
+The Contacts Provider is a powerful and flexible Android component that manages the device's central repository of data about people. You can use it to build powerful social features...
+This training class demonstrates the best practices for scheduling and executing downloads using techniques such as caching, polling, and prefetching.
+This training class demonstrates how to use UI components and APIs available in newer versions of Android in a backward-compatible way, ensuring that your application still runs on previous versions...
+Deliver your apps to the users you want, on the devices you want, on your schedule.
+ +On Google Play, you can publish your products to customers instantly. Just +upload and configure your product in the Google Play Android Developer Console +and press the Publish button—your app appears in the store listings within +hours, not weeks. There are no delays for code or policy reviews, so you keep +complete control over your release schedule.
+ +Once your app is published, you can update it as often as you want. You can +change prices, configuration, and distribution options at any time through the +Google Play Android Developer Console, without needing to update your app +binary.
+ +Later, as you add features or address code issues, you can publish an updated +binary at any time. Google Play makes the new version available immediately and +notifies existing customers that an update is ready for download. To streamline +the rollout across your customer base, Google Play also lets users accept +automatic updates of your app, so that your updates are delivered and installed +s soon as you publish them.
+ +Google Play does more than connect your app with users—it helps you +reach the broadest possible distribution across the Android ecosystem, while +making sure that your app is only available to the audience that you want to +reach.
+ +
+You can use controls in the Google Play Android Developer Console to easily +manage the geographic distribution of your apps, without any changes in your +application binary. You can specify which countries and territories you want to +distribute to, and even which carriers (for some countries).
+ +When users visit the store, Google Play makes sure that they are in one of +your targeted countries before downloading your app. You can change your country +and carrier targeting at any time just by saving changes in the Google Play +Android Developer Console
+ +
+Google Play also lets you control distribution according to device features +or capabilities that your app depends on. There are several types of +dependencies that the app can define in its manifest, such as hardware features, +OpenGL texture compression formats, libraries, Android platform versions, and +others.
+ +When you upload your app, Google Play reads the dependencies and sets up any +necessary distribution rules. For technical information about declaring +dependencies, read Filters on +Google Play.
+ +For pinpoint control over distribution, Google Play lets you see all of the +devices your app is available to based on its dependencies (if any). From the +Google Play Android Developer Console, you can list the supported devices and +even exclude specific devices if needed.
+ +Once you’ve published your app, Google Play makes it easy to see how it’s +doing. The Google Play Android Developer Console gives you access to a variety +of anonymized metrics that show your app’s installation performance measured by +unique users and unique devices, across a variety of different dimensions such +as country, Android version, device, country, carrier, and app version.
+ +
+You can also view your installation data on timeline charts, for all metrics and +dimensions. At a glance, these charts highlight your app’s installation peaks +and longer-term trends, which you can correlate to promotions, app improvements, +or other factors. You can even focus in on data inside a dimension by +highlighting specific data points (such as individual platform versions or +languages) on the timeline.
+ +So that you can “take your data with you”, you can download all of your +installation data as a CSV file for viewing in the business program of your +choice.
+ + +Google Play offers convenient options for managing how your apps are +delivered to users.
+ +In most cases, it’s easy to create an app that supports all of your targeted +screen sizes and platform versions from a single APK. Distributing a single APK +to all of your users is a highly recommended approach, because it’s the easiest +way to manage and maintain the app. If you need to deliver a different APK to +devices, Google Play provides a way to do that.
+ +An option called Multiple APK support lets you create multiple APK packages +that use the same package name but differ in their OpenGL texture compression +formats, screen-size support, or Android platform versions supported. You can +upload all of the APKs to Google Play under a single product listing and Google +Play selects the best APK to deliver to users, based on the characteristics of +their devices.
+ +The APK Expansion Files option lets you upload up to two secondary downloads +for each published APK, including multiple APKs. Each of the two expansion files +can be up to 2GB each and can contain any type of code or assets. When you +upload the expansion files, Google Play hosts them for free and handles the +download of the files as part of the normal APK installation.
+ +To help you protect your application against piracy, Google Play offers a +licensing service that you can implement in your app. It’s a network-based +service that lets an application query a trusted Google Play licensing server to +determine whether the application is licensed to the current device user.
diff --git a/docs/html/distribute/googleplay/about/monetizing.jd b/docs/html/distribute/googleplay/about/monetizing.jd new file mode 100644 index 000000000000..1e3437b266a2 --- /dev/null +++ b/docs/html/distribute/googleplay/about/monetizing.jd @@ -0,0 +1,152 @@ +page.title=Flexible Monetizing and Business Tools +page.metaDescription= + +@jd:body + +
+
+Sell your app in more than 130 countries. Flexible monetization options with +in-app purchase, subscriptions, and more.
+ +When users find your app, they can purchase it instantly with a streamlined, +consistent purchasing process and convenient payment methods.
+ +Google Play makes it fast and easy for your customers to buy your products, +whether from a phone, a tablet, or a desktop computer. When users find an app or +game that they want to buy, they can purchase it in as few as two steps—one +to initiate the purchase and another to accept purchase details and permissions +and complete the transaction.
+ +Google Play's convenient purchase experience is the same familiar process for +all products everywhere across Google Play—apps, games, in-app products and +subscriptions, and other digital content.
+ +Purchasing is even more convenient on Google Play because it’s +cloud-connected. Users can find and purchase your products from anywhere—from +their Android phones or using any web browser on any host computer.
+ +When users find an app or game they want to buy, they purchase it and download +it instantly to their devices over-the-air. Users who sign in to the Google Play web site can also buy apps and games +and push them instantly to their phones, tablets, or other devices. Google Play +manages the application download.
+ +Users can purchase your products on Google Play using several convenient +payment methods—credit card, Direct Carrier Billing, and Google Play balance.
+ +Credit card is the most common method of payment. Users can pay using any credit card +that they’ve registered in Google Play. To make it easy for users to get started, +registration is offered as a part of initial device setup process.
+ +Subscribers on many popular carrier networks worldwide can charge purchases +to their monthly mobile phone bills through Direct +Carrier Billing. This form of payment is convenient and simple and is +extremely popular in regions where credit cards are less common. More than 75 +million users in key markets around the world can purchase +your products through Direct Carrier Billing. Many more will get the option in +the months ahead.
+ +The payment methods available to users worldwide may vary, based on +location, carrier network, and other factors.
+ +
+Google Play gives you a choice of billing models to let you monetize your +products.
+ +You can offer apps to all users for free, or +you can set an initial price for the app, paid before download. You can also +sell one-time purchases and auto-renewing subscriptions from inside the app, and +you can take advantage of AdMob integration to monetize your app through +targeted advertising.
+ +You can combine these billing models in different ways, based on your business +needs or market conditions.
+ +For example, you can use a freemium or ad-supported model by distributing +your app for free and selling in-app products or advertising. Alternatively you +could set a nominal price for your app at download and sell value add-ons, +gameplay levels, and upgrades as in-app products. The only restriction is that +free apps must remain free (to download) for the life of the app.
+ +
+Google Play gives you complete control over how you price your products. You +can set prices in more than 130 countries, for millions of +users around the world. When users browse your app’s product page or initiate a +purchase, Google Play shows them the price they will be charged in +their local currency.
+ +You can set and adjust your prices at any time, in any available currency. +Your prices in available currencies are independent, so you can adjust one +price without affecting others. This gives you the ability to run +short-term promotions and discounts in specific countries and more easily +manage shifts in exchange rates.
+ +You can set and manage prices for your apps and in-app products from the +Google Play Android Developer Console.
+ +To sell products in Google Play, all you have to do is register for a Google +Checkout merchant account and link it to your Google Play Android Developer +Console account (see Get Started with +Publishing for details). Once you’ve set up your account and published your +apps, Google Play makes monthly payouts of sales proceeds to your merchant +account, in your local currency.
+ +When you sell priced apps or in-app products on Google Play, you get a +variety of financial reports to help you track and project sales, optimize your +marketing campaigns, and support your customers.
+ +To help you keep up-to-date with the current activity, you can download daily +reports summarizing recent purchases of your products. The reports include +estimated sales amounts and include a variety of other data for each +transaction.
+ +At the close of the month, you can download a complete sales report that +gives you the final details of all transactions that closed in the month, +including the payout amounts and other data. Additional financial reports are +available in your Google Checkout merchant account.
diff --git a/docs/html/distribute/googleplay/about/visibility.jd b/docs/html/distribute/googleplay/about/visibility.jd new file mode 100644 index 000000000000..2c5dbe522055 --- /dev/null +++ b/docs/html/distribute/googleplay/about/visibility.jd @@ -0,0 +1,247 @@ +page.title=Visibility for Your Apps +page.metaDescription= + +@jd:body + +
+A billion downloads a month and growing. Get your apps in front of millions +of users at Google's scale.
+ + +Google Play is the premier store for distributing Android apps. It’s +preinstalled on more than 300 million devices worldwide, a number growing by +almost a million every day. Android users have downloaded +more than 15 billion apps from Google +Play, growing at a rate of more than 1 billion per month.
+ +When you publish on Google Play, you put your apps in front of Android's huge +base of active customers, in more than 130 countries and territories across the +world.
+ +Google Play is a central part of the Android experience. New users +personalize their devices with apps, games, and other Google Play content. +Existing users return regularly to see what's trending and new. Downloading new +apps is extremely convenient and fast— Google Play pushes apps to the +user's devices instantly, over the air. No cable or sync is ever needed.
+ +
+Growth in app consumption: Users download more than +1 billion apps from Google Play each month.
+Google Play is also a top destination for visitors from the the web. Anyone +with a browser can explore everything that Google Play has to offer from its web site. Android users can even buy and +install the apps they want and Google Play pushes them automatically to their +devices over the air.
+ +The accessiblility and convenience of the Google Play web +site give you new ways to drive traffic to your products from online ads, web +search, cross-linking, and more.
+Google Play is designed to connect users with great apps and games. It +provides key channels to help your app get noticed and gain traction in the +marketplace.
+ +When you develop a great app, Android users show their appreciation through +ratings and reviews. They rate your app (out of 5 stars) after downloading it +and can post a short description of their experience. When other users are +considering your app, they look at the ratings and reviews as key benchmarks of +the app’s quality.
+ +Your app’s rating is one of the most important factors influencing its +ranking in the various lists and search results in Google Play. It's also one of +the key signals that the editorial staff looks for, when curating apps and games +for promotion in the store.
+ +
+When you publish an app in Google Play, you pick the category in which you +want users to find your app. More than 30 categories are available. Inside each +category, apps are ranked based on a combination of ratings, reviews, downloads, +country, and other factors. Many popular categories also start with a collection +of featured apps selected by the Google Play editorial staff.
+ +
+
+
+Featuring in +categories: Most app and game categories include a featured list curated +by the editorial team.
+Search on Google Play lets users pinpoint an app or game quickly. Search uses +powerful heuristics to suggest terms as the user types, and it offers direct +links to apps as suggestions. In results, users find the most relevant, most +popular apps at the top.
+ +
+Top charts keep users in touch with what’s popular and trending with Android +users, right from the Apps and Games home pages. The charts are generated +several times each day based on recent download activity, keeping them fresh and +allowing new apps to move upward in the charts. To make the charts as relevant +as possible for users across the world, they are also country-specific.
+ +As your apps get traction and build momentum in downloads and ratings, +they’ll climb one or more of the top charts and gain even more exposure.
+ +| Top Free | Free apps and games | Top Paid | Priced apps and games | +Top New Free | Less than 30 days old | +Top New Paid | Less than 30 days old | +Top Grossing | Gross proceeds, free or priced | +Best Selling | Popular priced games | +Trending | New arrivals growing quickly in installs | + +
+
+The Google Play editorial team is dedicated to bringing the best apps to the +attention of users. It constantly reviews apps from across Google Play to find +not only the biggest apps and games, but also the “diamonds in the rough” that +they want more people to see.
+ +When the team finds great apps and games they use the Featured, +Staff Picks, and other collections to promote them. Any one of those +can give your apps dramatically higher visibility and market penetration.
+ +You can’t nominate your app for featuring or pay for a promotional slot, +because the editorial team wants to show the best apps and give the same chances +to all developers. However, if you build an app that users love and that looks +great on Android devices, the editorial team will notice. +
Each week the the Google Play editorial staff selects a new set of apps to +promote in its popular Featured and Staff Picks collections. +
+ +The Featured collections highlight the latest and greatest app and game +titles available for Android. Category featuring highlights the best and most +popular apps in the top categories. + +Staff Picks collects all recently featured apps and games on Google +Play. To better reach tablet users, there’s a special Staff Picks +collection that highlights the best apps for Android tablets. + +
+
+From time to time the editorial staff puts together a collection of apps and +games based on a theme or seasonal event. The collections are popular with +customers because they are timely and relevant, and they provide a new way to +showcase great Android apps to users.
+ +The editorial staff chooses apps for collection promotions in a similar way +as for featuring—high-quality apps that show the best of Android on phones +and tablets. For collections the staff also looks for apps that can make an +interesting or unique contribution to the collection as a whole.
+ +Editors’ Choice is a curated collection of apps that highlights some +of the very best apps available on Android. These apps are chosen for high +quality and great UI, long-term popularity, and innovative use of Android +features.
+ +Apps chosen for Editors’ Choice also receive a badge that is +displayed wherever the app name is seen in Google Play.
+ +Top Developer is a badge recognizing established, respected developers for +their commitment to launching high-quality and innovative apps on +Android. The Google Play editorial staff selects developers awards a Top +Developer badge from time to time, based on the cumulative work of the +developer.
+ +The Top Developer badge appears next to the developer name wherever it is +displayed in Google Play. For a developer, the badge means long-term recognition +of all of your apps. For users, the badge signifies an additional level of trust +and confidence in your products.
+ +In Google Play, your app’s storefront is its product details page +— a rich and colorful page that lets you promote your app, highlight its +ratings and reviews, and show what your app can do. + +
Your product details page is the one page where your users come to find out +everything about your app. When they see your app listed in search results, top +charts, category listings, and collections, one tap takes them directly to your +product details page.
+ +
+You can manage your product details page through the Google Play Android Develeper Console, from any +web browser. Just sign in, upload or update your brand assets, and enter your +product details in the languages of your markets.
+ +When you publish, Google Play adds your app’s ratings, reviews, links to your +other products, and more, and makes sure your product details page looks great +on phones, tablets, or in a web browser.
+ +You can link web users directly to your product details page from outside +Google Play, such as from your web site, an ad campaign, reviews, social media +posts, and more. See Linking +to Your Products to find out how.
+ +To learn more about how to create your product details page, see +Publishing on Google Play.
diff --git a/docs/html/distribute/googleplay/index.html b/docs/html/distribute/googleplay/index.html new file mode 100644 index 000000000000..46a8ce2c3b67 --- /dev/null +++ b/docs/html/distribute/googleplay/index.html @@ -0,0 +1,10 @@ + + + +You should have been redirected. Please click here.
+ + \ No newline at end of file diff --git a/docs/html/distribute/googleplay/promote/badges.jd b/docs/html/distribute/googleplay/promote/badges.jd new file mode 100644 index 000000000000..de12e2a962c0 --- /dev/null +++ b/docs/html/distribute/googleplay/promote/badges.jd @@ -0,0 +1,203 @@ +page.title=Google Play Badges +@jd:body + +Google Play badges give you an officially branded way of promoting your app to Android users. Use the form below to quickly create badges to link users to your products from web pages, ads, reviews, and more. See Linking to your products for more ways to bring users to your apps.
+ +Input your app's package or your publisher name, choose the style, size, and language, and click "Build my badge". The form will generate code for an embbeded button that links to your app's product page or a list of your apps.
+ +Note that you should not modify the Google Play badges after generating them, including colors, size, text, and logo. See Android Brand Guidelines for more information.
+ + + + + + + + diff --git a/docs/html/distribute/googleplay/promote/brand.jd b/docs/html/distribute/googleplay/promote/brand.jd new file mode 100644 index 000000000000..8aafc48fe3dd --- /dev/null +++ b/docs/html/distribute/googleplay/promote/brand.jd @@ -0,0 +1,174 @@ +page.title=Brand Assets, Icons, and Guidelines +@jd:body + +We encourage you to use the Android and Google Play brands in your +promotional materials. You can use the icons and other assets on this page in +any way you want, provided that you follow the guidelines described below.
+ +
+ Can be used, reproduced, and modified freely in marketing + communications. Our standard color value for print is PMS 376C. Our online hex + color is #A4C639.
+ +When using the Android Robot or any modification of it, proper attribution is + required under the terms of the Creative Commons Attribution license. For more + details on proper attribution, please see the Content License document.
+
+ The Android logo may not be used.
+
+ The custom typeface may not be used.
+
+ Any name with 'Android' alone may not be used in a name without permission. Any name + with 'Droid' alone may not be used in a name.
+ +The word 'Android' may be used only as a descriptor, 'for Android'. If used with your + logo, 'for Android' needs to be smaller in size than your logo. First instance of this + use should be followed by a TM symbol, 'for Android™'.
+ +If you are not sure you meet these criteria, please contact us.
+
+ + May be used in text as a descriptor, as long as it is followed by a proper generic term + (e.g. "Android™ application"). First instance of this use should be followed by a TM + symbol. +
+Note: Any usage of #04 or #05 needs to include footer attribution in your
+ communication:
+ "Android is a trademark of Google Inc."
+
+ The "Get it on Google Play" and "Android App on Google Play" logos are badges that you + can use on your web site and promotional materials, to point to your products on Google + Play. +
++ The logos are available in two sizes: +
++ Guidelines for usage: +
+For details on all the ways that you can link to your product details page in Google Play, + see Linking to your products
+ +For convenience, if you are using the logos online, you can use the + badge generator + to create the appropriate markup and link to your apps.
+ +Any other brands or icons depicted on this site are not are the property of their +repective owners and usage is reserved. You must seek the developer for appropriate permission to use them.
diff --git a/docs/html/distribute/googleplay/promote/index.jd b/docs/html/distribute/googleplay/promote/index.jd new file mode 100644 index 000000000000..68829907fe22 --- /dev/null +++ b/docs/html/distribute/googleplay/promote/index.jd @@ -0,0 +1,43 @@ +page.title=Promoting Your Apps +page.metaDescription=Raise the visibility of your apps in Google Play through deep links and Google Play badges. +header.hide=0 +footer.hide=0 +@jd:body + + + +After you publish your app, you can bring Android users to your app's product details page by +providing links in your social network posts, ad campaigns, app reviews and articles, your +web site, and more.
+ +You can use the resources in this section to create deep links for your online placements. +Google Play badges are an especially great way let Android users know that your app is available +and link them directly to your download page. With the badge generator, they're also easy to make.
+ + + + diff --git a/docs/html/distribute/googleplay/promote/linking.jd b/docs/html/distribute/googleplay/promote/linking.jd new file mode 100644 index 000000000000..4a1b19834f3f --- /dev/null +++ b/docs/html/distribute/googleplay/promote/linking.jd @@ -0,0 +1,213 @@ +page.title=Linking to Your Products +@jd:body + + + +Google Play provides several link formats that let you bring users to your +products in the way you want, from Android apps, web pages, ads, reviews, +articles, social media posts, and more.
+ +The link formats let you:
+If you are linking from an Android app, you can also control whether the link +launches the Play Store application or the browser, which takes the user +to the Google Play web site.
+ +Use the format below to deep-link users directly to a specific app's product +details page. At the product details page, users can see the app description, +screenshots, reviews and more, and then install it.
+ +To create the link, you need to know the app's fully qualified package +name, which is declared in the app's manifest +file. The package name is also visible in the Developer Console.
+ +http://play.google.com/store/apps/details?id=<package_name>+
market://details?id=<package_name>+
Here's an example:
+ +http://play.google.com/store/apps/details?id=com.google.android.apps
For details on how to send the link in an Android app, see Linking from an Android App.
+ + + +Use the format below to link users to a list of apps published by you. The +product list lets users see all of the apps from a specific publisher, with +ratings, editorial badges, and an Install button for each.
+ +To create the link, you need to know your publisher name, which is +available from the Developer Console.
+ +http://play.google.com/store/search?q=pub:<publisher_name>+
market://search?q=pub:<publisher_name>+
Here's an example:
+ +http://play.google.com/store/search?q=pub:Google Inc.
For details on how to send the link in an Android app, see Linking from an Android App.
+ + +Use the format below to link users to a search query result on Google Play. +The search result page shows a list of apps (and optionally other content) that +match the query, with ratings, badges, and an Install button for each.
+ +To create the link, you just need a search query string. If you want the
+query to search outside of the Google Play Apps listings, you can remove the
+&c=apps part of the link URL.
http://play.google.com/store/search?q=<search_query>&c=apps+
market://search?q=<seach_query>&c=apps+
Here's an example:
+ +http://play.google.com/store/search?q=maps&c=apps
For details on how to send the link in an Android app, see Linking from an Android App.
+ + + +If your app is featured or appears in one of the Google Play Top charts or +collections, you can use the format below to link users directly to the +collection. The collection shows a ranked list of apps in the collection, with +ratings, short descriptions, and an Install button.
+ +http://play.google.com/store/apps/collection/<collection_name>+
market://apps/collection/<collection_name>+
Here's an example:
+ +http://play.google.com/store/apps/collection/editors_choice
For details on how to send the link in an Android app, see Linking from an Android App.
+ +Table 1. Collections on Google Play.
+ +| Collection | collection_name | +
|---|---|
| Staff Picks (Featured) | featured |
| Editor's Choice | editors_choice |
| Top Paid | topselling_paid |
| Top Free | topselling_free |
| Top New Free | topselling_new_free |
| Top New Paid | topselling_new_paid |
| Top Grossing | topgrossing |
| Trending | movers_shakers |
| Best Selling in Games | topselling_paid_game |
There are two general formats for links that are accessible to users on +Android devices, The two formats trigger slightly different behaviors on the +device:
+ +market:// Launches the Play Store app to load the
+target page.http:// Lets the user choose whether to launch the
+Play Store app or the browser to handle the request. If the browser handles the
+request, it loads the target page on the Google Play web site.In general, you should use http:// format for links on web pages
+and market:// for links in Android apps.
If you want to link to your products from an Android app, create an {@link +android.content.Intent} that opens an Google Play URL, as shown in the example +below.
+ +
+Intent intent = new Intent(Intent.ACTION_VIEW);
+intent.setData(Uri.parse("market://details?id=com.example.android"));
+startActivity(intent);
+
+
+
+The table below provides a summary of the URIs currently supported by the Google Play (both on +the web and in an Android application), as discussed in the previous sections.
+ +| For this result | +Web page link | +Android app link | +
|---|---|---|
| Show the product details page for a specific app | +http://play.google.com/store/apps/details?id=<package_name>
+ | market://details?id=<package_name> |
+
| Show apps by a specific publisher | +http://play.google.com/store/search?q=pub:<publisher_name> |
+market://search?q=pub:<publisher_name> |
+
| Search for apps using a general string query. | +http://play.google.com/store/search?q=<query> |
+market://search?q=<query> |
+
Placeholder...
\ No newline at end of file diff --git a/docs/html/distribute/googleplay/publish/console.jd b/docs/html/distribute/googleplay/publish/console.jd new file mode 100644 index 000000000000..72b97abb7473 --- /dev/null +++ b/docs/html/distribute/googleplay/publish/console.jd @@ -0,0 +1,201 @@ +page.title=The Developer Console +@jd:body + + +Once you've registered and +received verification by email, you can sign in to your Google Play Android +Developer Console, which will be the home for your app publishing operations and +tools on Google Play. This sections below introduce a few of the key areas +you'll find in the Developer Console.
+ +
+Developer Console home page: Gives you a quick +overview of your apps, lets you jump to stats, reviews, or product details, or +upload a new app.
+
+Developer profile: Specifies your developer +identity and contact information, stores your developer key, and more.
+Your developer profile identifies you to Google Play and to your customers. +During registration you can provide information for your profile, but you can go +back at any time to edit the information and change your settings.
+ +Your developer profile contains:
+If you are working with a team, you can set up multiple user accounts to +access different parts of your Developer Console. The first account registered +is the account owner, with full access to all parts of the Console. The +owner can add user accounts and manage what parts of the Console they +have access to. For example, an owner can grant users access to publishing and +app configuration, but not access to financial reports.
+ +If you want to sell apps or in-app products, you can link your Google +Checkout Merchant account to your developer profile. Google Play uses the linked +Checkout account for financial and tax identification and monthly payouts of +sales.
+ +
+Product details page: Lets you upload your +graphic assets, description, support information, and other information to +create the product details page for a specific app.
+The Developer Console lets you set up a colorful storefront page for your app +called the product details page. Your product details page is the home +for your app in Google Play — it's the page users see on their mobile +phones or on the web when they want to learn about your app and download it. +
+ +You can upload custom brand assets, screen shots, and videos to highlight +what's great about your app, and you can provide a localized description, add +notes about the latest version, and more. You can update your store listing at +any time, even if you don’t have a new version of your application.
+ +From the Developer Console you can quickly upload a release-ready APK and +publish it when you're ready. The app is a draft until you publish it, +at which time Google Play makes your product details page and app available to +users. You can unpublish the app at any time.
+ +In the Developer Console you can manage what countries and territories the +app is distributed to and, for some countries, you can choose what carriers you +want to target.
+ +You can also see the list of devices that your app is currently available to, +based on any distribution rules declared in its manifest file.
+ +The Developer Console gives you tools to set prices for your apps and in-app +products. Your app can either be free to download or priced (charged before +download).
+ +See Supported locations for distributing applications for a list of countries where you can distribute or sell your app,
+In addition, you can sell in-app products and subscriptions in your app, +whether it is free or priced. You can set prices separately for priced apps, +in-app products, and subscriptions.
+ +If you are selling a priced app or in-app products or subscriptions, the +Developer Console lets you set prices in a large number of different currencies. +When users around the world visit your product details page, they see the price +of your app in their own currency. For most countries, the price you set is the +final price charged to users, inclusive of taxes.
+ +To help you manage your prices, the Developer Console provides an autofill +capability that uses recent exchange rates to populate the prices in all +supported currencies. You can change prices for apps and in-app products at any +time, just by saving changes in the Develoer Console.
+ +For details on how to implement In-app Billing, see the +In-app Billing +developer documentation.
In-app Billing is a Google Play service that lets you monetize your apps in more ways by selling in-app products and subscriptions. In-app products are one-time purchases, while subscriptions are recurring charges on an monthly or annual basis.
+ +From the Developer Console you can create product lists for in-app +products and subscriptions, set prices, and publish.
+ +
+User +reviews page: Gives you access to user reviews for a specific app. +You can filter reviews in a number of ways to locate issues more easily +and support your customers more effectively.
+Google Play makes it easy for users to submit reviews of your app for the +benefit of other users. The reviews are also extremely important to you, since +they give you usability feedback, support requests, and important functionality +issues direct from your customers.
+ +The Developer console also lets you see error reports, with stack trace and +other data, submitted automatically from Android devices, for debugging and +improving your app.
+ +The Developer Console gives you detailed statistics on the install +performance of your app.
+ +You can view installations of your app measured by unique users, as well as +by unique devices. For user installations, you can view active installs, total +installs, and daily installs and uninstalls. For devices, you can see active +installs as well as daily installs, uninstalls, and upgrades.
+ +You can zoom into the installation numbers along several dimensions, +including Android platform version, device, country, language, app version, and +carrier (mobile operator). You can see the installation data for each dimension +on a timeline charts.
+ +At a glance, these charts highlight your app’s installation peaks and +longer-term trends, which you can correlate to promotions, app improvements, or +other factors. You can even focus in on data inside a dimension by adding +specific points (such as individual platform versions or languages) to the +timeline.
+ +
+App +installation statistics page: Shows you a variety of statistics about a +specific app's installation performance over time.
+
+Upload apps, build your product pages, configure prices and + distribution, and publish. You can manage all phases of publishing + on Google Play through the Developer Console, from any web browser.
+ + +Before you publish your app on Google Play and distribute it to users, you +need to get the app ready, test it, and prepare your promotional materials.
+ +This document helps you understand the publishing process and get ready for a +successful product launch on Google Play. It summarizes some of the +tasks you'll need to complete before publishing your app on Google Play, such as +creating a signed, release-ready APK, understanding the requirements of the app, +and creating the product page and graphic assets for your app.
+ +The preparation and publishing tasks are numbered to give you a rough idea of +sequence. However, you can handle the tasks in any sequence that works for you +or you can skip steps as appropriate.
+ +As you move toward publishing, a variety of support resources are available to +you. Relevant links are provided in each step.
+ + +Before you begin the steps in this checklist, you should take a moment to +read and understand the overall publishing workflow and become familiar with how +the process works. In particular, you or your development team will need to +prepare your app for release using a process common to all Android apps. +The Publishing +Workflow documents provide the details on how publishing works and how to +get an APK ready for release.
+ +Once you are familiar with publishing in general, read this document to +understand the issues that you should consider when publishing an app on Google +Play.
+ +Related resources: +
|
+
Make sure that you understand and follow the Google Play program policies +that you accepted when registering. Google Play actively enforces the policies +and any violations can lead to suspension of your app or, for repeated +violations, termination of your developer account.
+ +Related resources: +
|
+
Google Play requires you to set a content rating for your app, which informs +Google Play users of its maturity level. Before you publish, you should confirm +what rating level you want to use. The available content rating levels are:
+ +On their Android devices, Android users can set the desired maturity level +for browsing. Google Play then filters apps based on the setting, so the content +rating you select can affect the app's distribution to users. You can assign (or +change) the content rating for your app in the Developer Console, so no changes +are required in your app binary.
+ +Related resources: +
|
+
Google Play lets you control what countries and territories your app is +distributed to. For widest reach and the largest potential customer base, you +would normally want to distribute to all available countries and territories. +However, because of business needs, app requirements, or launch dependencies, +you might want to exclude one or more countries from your distribution.
+ +It's important to determine the exact country distribution early, because it +can affect:
+With your country targeting in mind, you should assess what +your localization needs are, both in your app and in its Google Play listing +details, and start the work of localization well in advance of your +launch target date.
+ +Related resources: +
|
+
The overall size of your app can affect its design and how you publish it on +Google Play. Currently, the maximum size for an APK published on Google Play is +50 MB. If your app exceeds that size, or if you want to offer a +secondary download, you can use APK Expansion Files, +which Google Play will host for free on its server infrastructure and +automatically handle the download to devices.
+ +Using APK Expansion files is a convenient, cost-effective method of +distributing large apps. However, the use of APK Expansion Files requires some +changes in your app binary, so you will need to make those changes before +creating your release-ready APK.
+ +Related resources: +
|
+
Before publishing, it's important to make sure that your app is designed to +run properly on the Android platform versions and device screen sizes that you +want to target. + +
From an app-compatibility perspective, Android platform versions are defined
+by API level. You should
+confirm the minimum version that your app is compatible with (<minSdkVersion>),
+as that will affect its distribution to Android
+devices once it is published.
For screen sizes, you should confirm that the app runs properly and looks
+good on the range of screen sizes and densities that you want to support. You
+should confirm the minimum screen-size and density support that your app
+declares (<supports-screens>),
+since that can affect its distribution to
+Android devices once it is published.
To get a better understanding of the current device penetration of Android +platform versions and screen sizes across all Android devices, see the Device Dashboard +charts.
+ +Related resources: +
|
+
On Google Play, you can publish apps as free to download or priced. Free apps +can be downloaded by any Android user in Google Play. +Paid apps can be downloaded only by users who have registered a form of payment +in Google Play, such as a credit card or Direct Carrier Billing.
+ +Deciding whether you app will be free or paid is important because, on Google +Play, free apps must remain free.
+ +If your app is be priced, or if you'll be selling in-app products, +you need set up a Checkout Merchant Account before you can publish.
+ +Related resources: +
|
+
Google Play In-app +Billing 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. +In-app Billing service lets you sell one-time purchases and subscriptions from +inside your app. This can help you to monetize the app over its installed +lifetime.
+ +If your are looking for more ways to monetize your app and build engagement, +you should consider In-app Billing. The service has become very popular with +both users and developers. To use In-app Billing, you need to make changes to +your app binary, so you will need to complete and test your implementation +before creating your release-ready APK.
+ +Related resources: +
|
+
If your app is priced or you will sell in-app products, Google Play lets you +set prices for your products in a variety of currencies, for users in markets +around the world. You can set prices individually in different currencies, so +you have the flexibility to adjust your price according to market conditions and +exchange rates.
+ +Before you publish, consider how you will price your products +and what your prices will be in various currencies. Later, you can set prices +in all available currencies through the Developer Console.
+ +Related resources: +
|
+
With your country targeting in mind, it's a good idea to assess your localization +needs and start the work of localizing well in advance of your target +launch date.
+ +There are at least two aspects of localization to consider:
+ +To get started localizing your app, work with your development team to extract +any resource or coded strings for translation. Also identify images, icons, or +other assets that should be language- or locale-specific. Hand these off to +a translator.
+ +To localize your store listing, first create and finalize your app title, description, +and promotional text. Collect and send all of these for localization. You can optionally +translate the "Recent Changes" text for app updates as well.
+ +When your translations are complete, move them into your app resources as needed and test +that they are loaded properly. Save your app's translated listing details for later, +when you upload assets and configure your product details.
+ +Related resources: +
|
+
When you publish on Google Play, you can supply a variety of high-quality +graphic assets to showcase your app or brand. After you publish, these appear on +your product details page, in store listings and search results, and elsewhere. +These graphic assets are key parts of a successful product details page that +attracts and engages users, so you should consider having a professional produce +them for you. Screen shots and videos are also very important, because they show +what your app looks like, how it's used or played, and what makes it different. + +
All of your graphic assets should be designed so that they are easy to see +and highlight your app or brand in a colorful, interesting way. The assets +should reference the same logo and icon as users will actually find in the All +Apps launcher once they have downloaded the app. Your graphic assets should also +fit in well with the graphic assets of other apps published by you, which will +be also be displayed to users on your product details page.
+ +Because these assets are so important, you should get started on them well in +advance of your target publishing date.
+ +Related resources: +
|
+
When you are satisfied that your app meets your UI, compatibility, and +quality requirements, you can build the release-ready version of the app. The +release-ready APK is what you you will upload to the Developer Console and +distribute to users. + +
The process for preparing a release-ready APK is the same for all apps, +regardless of how they are distributed. Generally the process includes basic code cleanup +and optimization, building and signing with your release key, and final testing. +When you are finished preparing your application for release, you'll have a signed +APK file that you can upload to the Developer Console for distribution to +users.
+ +For complete details on how to create a release-ready version of your app, +read Preparing for +Release.
+ +Once you have the release-ready APK in hand, you can upload it to +the Developer Console. If necessary, you can replace the APK with a more +recent version before publishing.
+ +Related resources: +
|
+
On Google Play, your app's product information is shown to users on its +product details page, the page that users visit to learn more about your app and +the page from which they will decide to purchase or download your app, on their +Android devices or on the web.
+ +Google Play gives you a variety of ways to promote your app and engage with +users on your product details page, from colorful graphics, screenshots, and +videos to localized descriptions, release details, and links to your other apps. +As you prepare to publish your app, make sure that you take advantage of all +that your product details page can offer, making your app as compelling as +possible to users.
+ +You should begin planning your product page in advance of your target launch +date, arranging for localized description, high-quality graphic assets, +screenshots and video, and so on.
+ +As you get near your target publishing date, you should become familiar with +all the fields, options, and assets associated with the product details configuration +page in the Developer Console. As you collect the information and assets for the +page, make sure that you can enter or upload it to the Developer Console, until +the page is complete and ready for publishing.
+ +Related resources: +
|
+
Google Play badges give you an officially branded way of promoting your app +to Android users. Use the Google Play Badge +generator to quickly create badges to link users to your products from web +pages, ads, reviews, and more. You can also use special link formats +to link directly to your product details page, to a list of your products, or to +search results.
+ +To help your app get traction after launch, it's strongly recommended that you support +launch with a promotional campaign that announces your product through many channels as +possible, in as many countries as possible. For example, you can promote the launch +using ad placements, social network or blog posts, video and other media, interviews +and reviews, or any other channel available.
+ +Related resources: +
|
+
When you think you are ready to publish, sign in to the Developer Console and take a few moments for a few +final checks:
+ +Make sure that:
+ +Your app is now ready to publish!
+ +If you are releasing an update, make sure to read the requirements for publishing updates.
+ +When you are ready, click the Publish button in the Developer Console. Within a few hours, your app will become available to users and your product page will be appear in Google Play for browsing, searching, or linking from your promotional campaigns.
+ +Related resources: +
|
+
After you publish an app or an app update, it's crucial for you to support +your customers. Prompt and courteous support can provide a better experience for +users that results in better ratings and more positive reviews for your +products. Users are likely to be more engaged with your app and recommend it if +you are responsive to their needs and feedback. This is especially true after +publishing if you are using a coordinated promotional campaign.
+ +There are a number of ways that you can keep in touch with users and offer +them support. The most fundamental is to provide your support email +address on your product details page. Beyond that, you can provide support +in any way you choose, such as a forum, mailing list or a Google+ page. The +Google Play team does provide user support for downloading, installing and +payments issues, but issues that fall outside of these topics will fall under +your domain. Examples of issues you can support include: feature requests, +questions about using the app and questions about compatibility settings.
+ +After publishing, plan to:
+Related resources: +
|
+
You can set up to start publishing on Google Play in only a few minutes. Here's how you do it:
+ +The first step is to visit the Google Play Android Developer Console and register for a publisher account.
+ +Here's what you will do during registration:
+ +When your registration is verified, you’ll be notified at the email address you specified during registration.
+ +If you want to sell products on Google Play — priced apps, in-app products, or subscriptions — you will also need to set up a Google Checkout Merchant Account. You can do that at any time, but make sure to first review the list of merchant countries.
+ +To set up a Merchant account from the Developer Console:
+ +This will take you to the Google Checkout site to sign up as a Merchant; you'll need to have information about your business handy to complete this step.
+ +When your registration is verified, you can sign in to your Android Developer Console, which will be the home for your app publishing operations and tools on Google Play.
diff --git a/docs/html/distribute/googleplay/strategies/app-quality.jd b/docs/html/distribute/googleplay/strategies/app-quality.jd new file mode 100644 index 000000000000..26d71d751bf0 --- /dev/null +++ b/docs/html/distribute/googleplay/strategies/app-quality.jd @@ -0,0 +1,116 @@ +page.title=Improving App Quality +@jd:body + ++With thousands of new apps being published in Google Play every week, it's important to look for any available way to get the most visibility and the highest ratings possible. One way of improving your app's visibility in the ecosystem is by deploying well-targeted mobile advertising campaigns and cross-app promotions. Another time-tested method of fueling the impression-install-ranking cycle is simply: improve the product!
++A better app can go a very long way: a higher quality app will translate to higher user ratings, generally better rankings, more downloads, and higher retention (longer install periods). High-quality apps also have a much higher likelihood of getting some unanticipated positive publicity such as being featured in Google Play or getting social media buzz.
++The upside to having a higher-quality app is obvious. However, it's not always clear how to make an app "better". The path to improving app quality isn't always well-lit. The term "quality" — along with "polish" and "fit and finish" — aren't always well-defined. Here we'll light the path by looking at some of the key factors in app quality and ways of improving your app along these dimensions.
+ ++Most ways of measuring the "success" of an app are dependent on user behavior. User-related metrics such as number of downloads, daily active installs, retention rates, and so on highlight the importance of users. If you aren't doing so already, it's a good idea to start thinking of your app's quality as it relates to your users.
++The most obvious way to listen to users is by reading and addressing comments on your app in Google Play. Although the comments aren't always productive or constructive, some will provide valuable insight on aspects of your app that you may not have consciously considered before. It's important to remember that users have the opportunity to change their ratings and comments about an app as much as they'd like.
++One way to reach users and help them address their concerns is to set up your own support and discussion destination(s). There are some great support tools out there that can put you in touch with your users directly such as Google Groups, Zoho Discussions, getsatisfaction.com and uservoice.com. Once you get set up with such a tool, make sure to fill in the support link in your Google Play product details page — users do click through to these.
++Another way to better listen to your users is by having a public beta or trusted tester program. It's crucial to have some amount of real user testing before releasing something in Google Play. Fortunately, you can distribute your apps to users outside of Google Play via a website; this website can require a login or be publicly accessible — it's entirely up to you. Take advantage of this opportunity by offering your next planned update to some early adopters, before submitting to Google Play. You'll be surprised by how many little, yet impactful, improvements can come out of crowd-sourced, real-user testing.
+ + ++The effect of overall app stability of ratings and user satisfaction is very well-known and there are many tools and techniques for testing and profiling your app on different devices and user scenarios.
++One noteworthy and yet relatively underused tool for catching stability issues such as crashes is the UI/Application Exerciser Monkey (Monkey). Monkey will send random UI events to your app's activities, allowing you to trigger user flows that can uncover stability problems.
++Also, with the Google error-reporting features built into most Android devices, users now have a way to report application crashes to developers. The error reports show up in aggregate in the Google Play Developer Console. Make sure to read these reports often and act on them appropriately.
++Last, keep an external bug and feature request tracker and let users know how to find it. This will enable them to engage with the app at a closer level, by following features and bugs that affect them. User frustration with app problems can be effectively managed with diligent issue tracking and communication. Some of the community support tools listed above offer issue tracking features, and if your project is open source, most popular repository hosting sites such as Google Code and GitHub will offer this as well.
+ ++One sure-fire way to lose your users is to give them a slow, unresponsive UI. Research has shown that speed matters... for any interface, be it desktop, web, or mobile. In fact, the importance of speed is amplified on mobile devices since users often need their information on the go and in a hurry.
++You can improve your apps's UI responsiveness by moving long-running operations off the main thread to worker threads. Android offers built-in debugging facilities such as StrictMode for analyzing your app's performance and activities on the main thread. You can see more recommendations in Writing Zippy Android Apps, a developer session from Google I/O 2010,
+ + ++A great way to improve UI performance is to minimize the complexity of your layouts. If you open up hierarchyviewer and see that your layouts are more than 5 levels deep, it may be time to simplify your layout. Consider refactoring those deeply nested LinearLayouts into RelativeLayout. The impact of View objects is cumulative — each one costs about 1 to 2 KB of memory, so large view hierarchies can be a recipe for disaster, causing frequent VM garbage collection passes which block the main (UI) thread. You can learn more in World of ListView, another session at Google I/O.
++Lastly, pointed out in the blog post Traceview War Story, tools like traceview and ddms can be your best friends in improving your app by profiling method calls and monitoring VM memory allocations, respectively.
+ + ++In usability and in app design too, you should listen carefully to your users. Ask a handful of real Android device users (friends, family, etc.) to try out your app and observe them as they interact with it. Look for cases where they get confused, are unsure of how to proceed, or are surprised by certain behaviors. Minimize these cases by rethinking some of the interactions in your app, perhaps working in some of the user interface patterns the Android UI team discussed at Google I/O.
++In the same vein, two problems that can plague some Android user interfaces are small tap targets and excessively small font sizes. These are generally easy to fix and can make a big impact on usability and user satisfaction. As a general rule, optimize for ease of use and legibility, while minimizing, or at least carefully balancing, information density.
+ ++Another way to incrementally improve usability, based on real-world data, is to implement Analytics throughout your app to log usage of particular sections. Consider demoting infrequently used sections to the overflow menu in the Action bar, or removing them altogether. For often-used sections and UI elements, make sure they're immediately obvious and easily accessible in your app's UI so that users can get to them quickly.
++Lastly, usability is an extensive and well-documented subject, with close ties to interface design, cognitive science, and other disciplines.
+ ++There's no substitute for a real user interface designer — ideally one who's well-versed in mobile and Android, and ideally handy with both interaction and visual design. One popular venue to post openings for designers is jobs.smashingmagazine.com, and leveraging social connections on Twitter and LinkedIn can surface great talent.
++If you don't have the luxury of working with a UI designer, there are some ways in which you can improve your app's appearance yourself. First, get familiar with Adobe Photoshop, Adobe Fireworks, or some other raster image editing tool. Mastering the art of the pixel in these apps takes time, but honing this skill can help build polish across your interface designs. Also, master the resources framework by studying the framework UI assets and layouts and reading through the new resources documentation. Techniques such as 9-patches and resource directory qualifiers are somewhat unique to Android, and are crucial in building flexible yet aesthetic UIs.
++Before you get too far in designing your app and writing the code, make sure to visit the Android Design site and learn about the vision, the building blocks, and the tools of designing beautiful and inspiring user interfaces.
+ ++Having the right set of features in your app is important. It's often easy to fall into the trap of feature-creep, building as much functionality into your app as possible. Providing instant gratification by immediately showing the most important or relevant information is crucial on mobile devices. Providing too much information can be as frustrating (or even more so) than not providing enough of it.
++Again, listen to your users by collecting and responding to feature requests. Be careful, though, to take feature requests with a grain of salt. Requests can be very useful in aggregate, to get a sense of what kinds of functionality you should be working on, but not every feature request needs to be implemented.
+ ++A great way to deliver a delightful user experience is to integrate tightly with the operating system. Features like Home screen widgets, rich notifications, global search integration, and {@link android.widget.QuickContactBadge Quick Contacts} are fairly low-hanging fruit in this regard.
+ +For some app categories, basic features like home screen widgets are par for the course. Not including them is a sure-fire way to tarnish an otherwise positive user experience. Some apps can achieve even tighter OS integration with Android's contacts, accounts, and sync APIs.
++Third-party integrations can provide even more user delight and give the user a feeling of device cohesiveness. It's also a really nice way of adding functionality to your app without writing any extra code (by leveraging other apps' functionalities). For example, if you're creating a camera app, you can allow users to edit their photos in Photoshop Express before saving them to their collection, if they have that third-party application installed. More information on this subject is available in the class, Interacting with Other Apps.
+ ++One particular detail to pay close attention to is your app's icon quality and consistency. Make sure your app icons (especially your launcher icon) are crisp and pixel-perfect at all resolutions, and follow the icon guidelines as much as possible. If you're having trouble or don't have the resources to design the icons yourself, consider using the new Android Asset Studio tool to generate a set.
diff --git a/docs/html/distribute/googleplay/strategies/featuring.jd b/docs/html/distribute/googleplay/strategies/featuring.jd new file mode 100644 index 000000000000..4c4e67e1dc4f --- /dev/null +++ b/docs/html/distribute/googleplay/strategies/featuring.jd @@ -0,0 +1,4 @@ +page.title=Preparing for Featuring +@jd:body + +Placeholder...
\ No newline at end of file diff --git a/docs/html/distribute/googleplay/strategies/index.jd b/docs/html/distribute/googleplay/strategies/index.jd new file mode 100644 index 000000000000..3794bbfcac2a --- /dev/null +++ b/docs/html/distribute/googleplay/strategies/index.jd @@ -0,0 +1,33 @@ +page.title=Success Strategies +page.metaDescription= +header.hide=1 +footer.hide=1 + +@jd:body + + + + + +
+
+
+ The most visited store in the world for Android apps. Cloud-connected and always synced, it's never been easier for users to find and download your apps.
+ + +As an open platform, Android offers choice. You +distribute your Android apps to users in any way you want, using any +distribution approach or combination of approaches that meets your needs. +From publishing in an app marketplace to serving your apps from a web site or +emailing them directly users, you are never locked into any +particular distribution platform.
+ +The process for building and packaging your app for distribution is the same, +regardless of how you will distribute your app. This saves you time and lets you +automate parts of the process as needed. You can read Preparing +for Release for more information.
+ +The sections below highlight some of the alternatives for distributing +your apps to users.
+ +Usually, to reach the broadest possible audience, you would distribute your +apps through a marketplace, such as Google Play.
+ +Google Play is the premier marketplace for Android apps and is particularly +useful if you want to distribute your applications to a large global audience. +However, you can distribute your apps through any app marketplace you want or +you can use multiple marketplaces.
+ +
+ + Figure 1. Users can simply click Install when you send them + an application via email. +
+The easiest and quickest way to release your application is to send it to users through +email. To do this, you prepare your application for release and then attach it to an email +and send it to a user. When users open your email message on their Android-powered device, +the Android system will recognize the APK and display an Install Now +button in the email message (see figure 1). Users can install your application by touching the +button.
+ +Note: The Install Now button +shown in Figure 1 appears only if users have configured their device to allow +installation from unknown sources and have opened your +email with the native Gmail application.
+ +Distributing applications through email is convenient if you are sending your application to +only a few trusted users, but it provides few protections from piracy and unauthorized +distribution; that is, anyone you send your application to can simply forward it to someone else.
+ +If you do not want to release your app on a marketplace like Google Play, you +can make the app available for download on your own website or server, including +on a private or enterprise server. To do this, you must first prepare your +application for release in the normal way. Then all you need to do is host the +release-ready APK file on your website and provide a download link to users. +
+ +When users browse to the download link from their Android-powered devices, +the file is downloaded and Android system automatically starts installing it on +the device. However, the installation process will start automatically only if +users have configured their Settings to allow the installation of apps from +unknown sources.
+ +Although it is relatively easy to release your application on your own +website, it can be inefficient. For example, if you want to monetize your +application you will have to process and track all financial transactions +yourself and you will not be able to use Google Play's In-app Billing service +to sell in-app products. In addition, you will not be able to use the Licensing service to +help prevent unauthorized installation and use of your application.
+ + +
+ + Figure 2. Users must enable the Unknown sources + setting before they can install apps not downloaded from Google Play. +
+Android protects users from inadvertent download and install of apps from +locations other than Google Play (which is trusted). It blocks such installs +until the user opts-in Unknown sources in +Settings > Security, shown in Figure 2. To allow +the installation of applications from other sources, users need to enable the +Unknown sources setting on their devices, and they need to make this +configuration change before they download your application to their +devices.
+ +Note that some network providers do not allow users to install +applications from unknown sources.
+ + diff --git a/docs/html/favicon-a.ico b/docs/html/favicon-a.ico new file mode 100644 index 000000000000..d8884b792b29 Binary files /dev/null and b/docs/html/favicon-a.ico differ diff --git a/docs/html/favicon.ico b/docs/html/favicon.ico index d8884b792b29..c1076aab60a3 100644 Binary files a/docs/html/favicon.ico and b/docs/html/favicon.ico differ diff --git a/docs/html/guide/appendix/api-levels.jd b/docs/html/guide/appendix/api-levels.jd deleted file mode 100644 index bc7d83b6db1b..000000000000 --- a/docs/html/guide/appendix/api-levels.jd +++ /dev/null @@ -1,421 +0,0 @@ -page.title=Android API Levels -@jd:body - -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.
- -The sections below provide information about API Level and how it affects -your applications.
- -For information about how to use the "Filter by API Level" control -available in the API reference documentation, see -Filtering the documentation at the -end of this document.
- -API Level is an integer value that uniquely identifies the framework API -revision offered by a version of the Android platform.
- -The Android platform provides a framework API that applications can use to -interact with the underlying Android system. The framework API consists of:
- -Each successive version of the Android platform can include updates to the -Android application framework API that it delivers.
- -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.
- -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.
- -The following table specifies the API Level supported by each version of the -Android platform.
- -| Platform Version | API Level | VERSION_CODE | Notes |
|---|---|---|---|
| Android 4.0.3 | -15 | -{@link android.os.Build.VERSION_CODES#ICE_CREAM_SANDWICH_MR1} | -Platform -Highlights |
| Android 4.0, 4.0.1, 4.0.2 | -14 | -{@link android.os.Build.VERSION_CODES#ICE_CREAM_SANDWICH} | -|
| Android 3.2 | -13 | -{@link android.os.Build.VERSION_CODES#HONEYCOMB_MR2} | -|
| Android 3.1.x | -12 | -{@link android.os.Build.VERSION_CODES#HONEYCOMB_MR1} | -Platform Highlights |
| Android 3.0.x | -11 | -{@link android.os.Build.VERSION_CODES#HONEYCOMB} | -Platform Highlights |
| Android 2.3.4 Android 2.3.3 |
- 10 | -{@link android.os.Build.VERSION_CODES#GINGERBREAD_MR1} | -Platform Highlights |
| Android 2.3.2 Android 2.3.1 Android 2.3 |
- 9 | -{@link android.os.Build.VERSION_CODES#GINGERBREAD} | -|
| Android 2.2.x | -8 | -{@link android.os.Build.VERSION_CODES#FROYO} | -Platform Highlights |
| Android 2.1.x | -7 | -{@link android.os.Build.VERSION_CODES#ECLAIR_MR1} | -Platform Highlights |
| Android 2.0.1 | -6 | -{@link android.os.Build.VERSION_CODES#ECLAIR_0_1} | -|
| Android 2.0 | -5 | -{@link android.os.Build.VERSION_CODES#ECLAIR} | -|
| Android 1.6 | -4 | -{@link android.os.Build.VERSION_CODES#DONUT} | -Platform Highlights |
| Android 1.5 | -3 | -{@link android.os.Build.VERSION_CODES#CUPCAKE} | -Platform Highlights |
| Android 1.1 | -2 | -{@link android.os.Build.VERSION_CODES#BASE_1_1} | |
| Android 1.0 | -1 | -{@link android.os.Build.VERSION_CODES#BASE} | -
The API Level identifier serves a key role in ensuring the best possible -experience for users and application developers: - -
Each Android platform version stores its API Level identifier internally, in -the Android system itself.
- -Applications can use a manifest element provided by the framework API —
-<uses-sdk> — 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:
android:minSdkVersion — Specifies the minimum API Level
-on which the application is able to run. The default value is "1".android:targetSdkVersion — Specifies the API Level
-on which the application is designed to run. In some cases, this allows the
-application to use manifest elements or behaviors defined in the target
-API Level, rather than being restricted to using only those defined
-for the minimum API Level.android:maxSdkVersion — Specifies the maximum API Level
-on which the application is able to run. Important: Please read the <uses-sdk>
-documentation before using this attribute. 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
-<uses-sdk> element with a android:minSdkVersion
-attribute. The value of android:minSdkVersion would be the integer
-corresponding to the API Level of the earliest version of the Android platform
-under which the application can run.
When the user attempts to install an application, or when revalidating an
-appplication after a system update, the Android system first checks the
-<uses-sdk> 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:
android:minSdkVersion 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. android:maxSdkVersion 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 <uses-sdk>
-documentation for more information about how the system handles this attribute.When declared in an application's manifest, a <uses-sdk>
-element might look like this:
<manifest> - <uses-sdk android:minSdkVersion="5" /> - ... -</manifest>- -
The principal reason that an application would declare an API Level in
-android:minSdkVersion is to tell the Android system that it is
-using APIs that were introduced 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.
For example, the {@link android.appwidget} package was introduced with API
-Level 3. If an application uses that API, it must declare a
-android:minSdkVersion 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).
For more information about how to specify an application's API Level
-requirements, see the <uses-sdk>
- section of the manifest file documentation.
The sections below provide information related to API level that you should -consider when developing your application.
- -Android applications are generally forward-compatible with new versions of -the Android platform.
- -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.
- -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.
- -In some cases, changes below 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.
- -Android applications are not necessarily backward compatible with versions of -the Android platform older than the version against which they were compiled. -
- -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.
- -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.
- -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. - -
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
-android:minSdkVersion attribute in the application's manifest and
-set its value to the API Level of the platform version.
If you build an application that uses APIs or system features introduced in
-the latest platform version, you should set the
-android:minSdkVersion 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.
If your application uses APIs introduced in the latest platform version but
-does not declare a android:minSdkVersion attribute, then
-it will run properly on devices running the latest version of the platform, but
-not 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.
After compiling your application, you should make sure to test it on the
-platform specified in the application's android:minSdkVersion
-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.
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.
- -To access the updater, use the android command-line tool,
-located in the <sdk>/tools directory. You can launch the SDK updater by
-executing android sdk. 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
-Window > Android SDK
-Manager.
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 Creating and Managing Virtual Devices. 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.
- -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 provisional API Level 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.
- -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.
- -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.
- - -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 android:minSdkVersion attribute of its manifest file.
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.
- -Filtering by API Level in the documentation does not provide a view -of what is new or introduced in each API Level — 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.
- -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. -
- -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 <api level>" 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.
diff --git a/docs/html/guide/appendix/g-app-intents.jd b/docs/html/guide/appendix/g-app-intents.jd index df9d29bd72ff..10ec01e038f9 100644 --- a/docs/html/guide/appendix/g-app-intents.jd +++ b/docs/html/guide/appendix/g-app-intents.jd @@ -4,7 +4,7 @@ page.title=Intents List: Invoking Google Applications on Android DevicesRelated: Intent Filter, Broadcast Receiver.
Related: Intent, Broadcast Receiver.
diff --git a/docs/html/guide/appendix/install-location.jd b/docs/html/guide/appendix/install-location.jd index 63a3817e7c9f..19c4b3900ef1 100644 --- a/docs/html/guide/appendix/install-location.jd +++ b/docs/html/guide/appendix/install-location.jd @@ -174,7 +174,7 @@ external storage, it can never receive this broadcast.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 diff --git a/docs/html/guide/appendix/market-filters.jd b/docs/html/guide/appendix/market-filters.jd deleted file mode 100644 index 3e502d7d5f19..000000000000 --- a/docs/html/guide/appendix/market-filters.jd +++ /dev/null @@ -1,454 +0,0 @@ -page.title=Filters on Google Play -@jd:body - -
<supports-gl-texture><supports-screens><uses-configuration><uses-feature><uses-library><uses-permission><uses-sdk>
- Go to Google Play to create a publisher -account and upload your app.
When a user searches or browses on Google Play on an Android device, the results are filtered -based on which applications are compatible with that device. For example, if an application -requires a camera (as specified in the application manifest file), then Google Play will not show -the app on any device that does not have a camera.
- -Declarations in the manifest file that are compared to the device's configuration is not the -only part of how applications are filtered. Filtering might also occur due to the user's country and -carrier, the presence or absence of a SIM card, and other factors.
- -Changes to the Google Play filters are independent of changes to the Android platform itself. -This document is updated periodically to reflect any changes that affect the way Google Play -filters applications.
- - -Google Play uses the filter restrictions described below to determine -whether to show your application to a user who is browsing or searching for -applications from the Google Play app. When determining whether to display your app, -Google Play checks the device's hardware and software configuration, as well as it's -carrier, location, and other characteristics. It then compares those against the -restrictions and dependencies expressed by the application's -manifest file and publishing details. If the application is -compatible with the device according to the filter rules, Google Play displays the -application to the user. Otherwise, Google Play hides your application from search -results and category browsing, even if a user specifically requests -the app by clicking a deep link that points directly to the app's ID within Google Play..
- -Note: When users browse the Google Play web site, they can see all published -applications. The Google Play web site compares the application requirements to each of the -user's registered devices for compatibility, though, and only allows them to install the application -if it's compatible with their device.
- -You can use any combination of the available filters for your app. For example, you can set a
-minSdkVersion requirement of "4" and set smallScreens="false"
-in the app, then when uploading the app to Google Play you could target European countries (carriers)
-only. Google Play's filters will thus prevent the application from being available on any device
-that does not match all three of these requirements.
All filtering restrictions are associated with an application's version and can -change between versions. For example, if a user has installed your application and you publish an -update that makes the app invisible to the user, the user will not see that an update is -available.
- - -Most filters are triggered by elements within an application's -manifest file, AndroidManifest.xml -(although not everything in the manifest file can trigger filtering). -Table 1 lists the manifest elements that you should use to trigger -filtering, and explains how the filtering for each element works.
- -Table 1. Manifest elements that -trigger filtering on Google Play.
-| Manifest Element | -Filter Name | -How It Works | -
|---|---|---|
<supports-screens>
- |
- Screen Size | -
-
- An application indicates the screen sizes that it is capable of supporting by
-setting attributes of the As a general rule, Google Play 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, -Google Play 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. - -If an application does not declare attributes for
-
Example 1 Example 2 Example 3 For more information on how to declare support for screen sizes in your
- application, see |
-
<uses-configuration>
- |
- Device
- Configuration: - keyboard, navigation, touch screen |
- An application can - request certain hardware features, and Google Play will show the app only on devices that have the required hardware. -Example 1 Example 2 For more details, see |
-
<uses-feature>
-
- |
- Device Features - ( name) |
- An application can require certain device features to be -present on the device. This functionality was introduced in Android 2.0 (API -Level 5). -Example 1 Example 2 For complete information, see Filtering based on implied features: In some cases, Google
-Play interprets permissions requested through
- |
-
| OpenGL-ES
- Version -( openGlEsVersion) |
- An application can require that the device support a specific
- OpenGL-ES version using the Example 1 Example 2 Example 3 Example 4 For more details, see |
- |
<uses-library> |
- Software Libraries | -An application can require specific - shared libraries to be present on the device. -Example 1 Example 2 For more details, see |
-
<uses-permission> |
- - | Strictly, Google Play does not filter based on
-<uses-permission> elements. However, it does read the
-elements to determine whether the application has hardware feature requirements
-that may not have been properly declared in <uses-feature>
-elements. For example, if an application requests the CAMERA
-permission but does not declare a <uses-feature> element for
-android.hardware.camera, Google Play considers that the
-application requires a camera and should not be shown to users whose devices do
-not offer a camera.
- In general, if an application requests hardware-related permissions,
-Google Play assumes that the application requires the underlying hardware
-features, even though there might be no corresponding to
- For a list of permissions that imply hardware features, see
-the documentation for the |
-
<uses-sdk> |
- Minimum Framework Version (minSdkVersion) |
- An application can require a minimum API level. -Example 1 Example 2 Because you want to avoid this second scenario, we recommend that you always declare a |
-
Maximum Framework Version (maxSdkVersion) |
- Deprecated. Android
- 2.1 and later do not check or enforce the Declaring |
-
In addition to the manifest elements in table 1, Google Play can also -filter applications based on the advanced manifest elements in table 2.
- -These manifest elements and the filtering they trigger are for exceptional use-cases -only. These are designed for certain types of high-performance games and similar applications that -require strict controls on application distribution. Most applications should never use -these filters.
- -Table 2. Advanced manifest elements for -Google Play filtering.
-| Manifest Element | Summary |
|---|---|
|
- Google Play filters the application if the device screen size and density does not match -any of the screen configurations (declared by a {@code <screen>} element) in the {@code -<compatible-screens>} element. -Caution: Normally, you should not use -this manifest element. Using this element can dramatically -reduce the potential user base for your application, by excluding all combinations of screen size -and density that you have not listed. You should instead use the {@code -<supports-screens>} manifest element (described above in table -1) to enable screen compatibility mode for screen configurations you have not accounted for -with alternative resources. - |
- |
|
- Google Play filters the application unless one or more of the GL texture compression -formats supported by the application are also supported by the device. - |
-
Google Play 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.
- -Table 3. Application and publishing -characteristics that affect filtering on Google Play.
-| Filter Name | How It Works |
|---|---|
| Publishing Status | Only published applications will appear in - searches and browsing within Google Play. 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. If an application has been - suspended, users will not be able to reinstall or update it, even if it appears in their Downloads. |
| Priced - Status | 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. |
-
| Country / Carrier Targeting | When you upload your app to - Google Play, you can select specific countries to target. The app will only - be visible to the countries (carriers) that you select, as follows: -
|
| Native Platform | An application that includes native - libraries that target a specific platform (ARM EABI v7 or x86, for example) are - visible only on devices that support that platform. For details about the NDK and using - native libraries, see What is the - Android NDK? |
| Copy-Protected Applications | To - copy protect an application, set copy protection to "On" when you configure publishing -options for your application. Google Play will not show copy-protected applications on -developer devices or unreleased devices. |
Some specific Google Play filters allow you to publish multiple APKs for the same -application in order to provide a different APK to different device configurations. For example, if -you're creating a video game that uses high-fidelity graphic assets, you might want to create -two APKs that each support different texture compression formats. This way, you can reduce the -size of the APK file by including only the textures that are required for each device -configuration. Depending on each device's support for your texture compression formats, Google -Play will deliver it the APK that you've declared to support that device.
- -Currently, Google Play allows you to publish multiple APKs for the same application only -when each APK provides different filters based on the following configurations:
-By using the {@code -<supports-gl-texture>} element.
-By using the {@code -<supports-screens>} or {@code -<compatible-screens>} element.
-By using the {@code -<uses-sdk>} element.
-All other filters still work the same as usual, but these three are the only filters that can -distinguish one APK from another within the same application listing on Google Play. For example, -you cannot publish multiple APKs for the same application if the APKs differ only based on -whether the device has a camera.
- -Caution: Publishing multiple APKs for the same application is -considered an advanced feature and most application should publish only one -APK that supports a wide range of device configurations. Publishing multiple APKs -requires that you follow specific rules within your filters and that you pay extra attention to the -version codes for each APK to ensure proper update paths for each configuration.
- -If you need more information about how to publish multiple APKs on Google Play, read Multiple APK Support.
diff --git a/docs/html/guide/appendix/media-formats.jd b/docs/html/guide/appendix/media-formats.jd index 137f13811d11..93e813662249 100644 --- a/docs/html/guide/appendix/media-formats.jd +++ b/docs/html/guide/appendix/media-formats.jd @@ -268,9 +268,9 @@ no dither applied for 24-bit.Android is a software stack for mobile devices that includes an operating -system, middleware and key applications. The Android SDK -provides the tools and APIs necessary to begin developing applications on the -Android platform using the Java programming language.
- -The following diagram shows the major components of the Android operating -system. Each section is described in more detail below.
- -
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.
- - -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.
- -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.
- -Underlying all applications is a set of services and systems, including: -
For more details and a walkthrough of an application, see the Notepad Tutorial.
- - -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:
-Android includes a set of core libraries that provides most of -the functionality available in the core libraries of the Java programming -language.
- -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 "dx" tool.
- -The Dalvik VM relies on the Linux kernel for underlying functionality such -as threading and low-level memory management.
- - - -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.
diff --git a/docs/html/guide/components/activities.jd b/docs/html/guide/components/activities.jd new file mode 100644 index 000000000000..36f651f04c03 --- /dev/null +++ b/docs/html/guide/components/activities.jd @@ -0,0 +1,776 @@ +page.title=Activities +@jd:body + +An {@link android.app.Activity} is an application component that provides a screen with which +users can interact in order to do something, such as dial the phone, take a photo, send an email, or +view a map. Each activity is given a window in which to draw its user interface. The window +typically fills the screen, but may be smaller than the screen and float on top of other +windows.
+ +An application usually consists of multiple activities that are loosely bound +to each other. Typically, one activity in an application is specified as the "main" activity, which +is presented to the user when launching the application for the first time. Each +activity can then start another activity in order to perform different actions. Each time a new +activity starts, the previous activity is stopped, but the system preserves the activity +in a stack (the "back stack"). When a new activity starts, it is pushed onto the back stack and +takes user focus. The back stack abides to the basic "last in, first out" stack mechanism, +so, when the user is done with the current activity and presses the Back button, it +is popped from the stack (and destroyed) and the previous activity resumes. (The back stack is +discussed more in the Tasks +and Back Stack document.)
+ +When an activity is stopped because a new activity starts, it is notified of this change in state +through the activity's lifecycle callback methods. +There are several callback methods that an activity might receive, due to a change in its +state—whether the system is creating it, stopping it, resuming it, or destroying it—and +each callback provides you the opportunity to perform specific work that's +appropriate to that state change. For instance, when stopped, your activity should release any +large objects, such as network or database connections. When the activity resumes, you can +reacquire the necessary resources and resume actions that were interrupted. These state transitions +are all part of the activity lifecycle.
+ +The rest of this document discusses the basics of how to build and use an activity, +including a complete discussion of how the activity lifecycle works, so you can properly manage +the transition between various activity states.
+ + + +To create an activity, you must create a subclass of {@link android.app.Activity} (or +an existing subclass of it). In your subclass, you need to implement callback methods that the +system calls when the activity transitions between various states of its lifecycle, such as when +the activity is being created, stopped, resumed, or destroyed. The two most important callback +methods are:
+ +There are several other lifecycle callback methods that you should use in order to provide a +fluid user experience between activities and handle unexpected interuptions that cause your activity +to be stopped and even destroyed. All of the lifecycle callback methods are discussed later, in +the section about Managing the Activity Lifecycle.
+ + + +The user interface for an activity is provided by a hierarchy of views—objects derived +from the {@link android.view.View} class. Each view controls a particular rectangular space +within the activity's window and can respond to user interaction. For example, a view might be a +button that initiates an action when the user touches it.
+ +Android provides a number of ready-made views that you can use to design and organize your +layout. "Widgets" are views that provide a visual (and interactive) elements for the screen, such +as a button, text field, checkbox, or just an image. "Layouts" are views derived from {@link +android.view.ViewGroup} that provide a unique layout model for its child views, such as a linear +layout, a grid layout, or relative layout. You can also subclass the {@link android.view.View} and +{@link android.view.ViewGroup} classes (or existing subclasses) to create your own widgets and +layouts and apply them to your activity layout.
+ +The most common way to define a layout using views is with an XML layout file saved in your +application resources. This way, you can maintain the design of your user interface separately from +the source code that defines the activity's behavior. You can set the layout as the UI for your +activity with {@link android.app.Activity#setContentView(int) setContentView()}, passing the +resource ID for the layout. However, you can also create new {@link android.view.View}s in your +activity code and build a view hierarchy by inserting new {@link +android.view.View}s into a {@link android.view.ViewGroup}, then use that layout by passing the root +{@link android.view.ViewGroup} to {@link android.app.Activity#setContentView(View) +setContentView()}.
+ +For information about creating a user interface, see the User Interface documentation.
+ + + +You must declare your activity in the manifest file in order for it to +be accessible to the system. To declare your activity, open your manifest file and add an {@code <activity>} element +as a child of the {@code <application>} +element. For example:
+ ++<manifest ... > + <application ... > + <activity android:name=".ExampleActivity" /> + ... + </application ... > + ... +</manifest > ++ +
There are several other attributes that you can include in this element, to define properties +such as the label for the activity, an icon for the activity, or a theme to style the activity's +UI. The {@code android:name} +attribute is the only required attribute—it specifies the class name of the activity. Once +you publish your application, you should not change this name, because if you do, you might break +some functionality, such as application shortcuts (read the blog post, Things +That Cannot Change).
+ +See the {@code <activity>} element +reference for more information about declaring your activity in the manifest.
+ + +An {@code +<activity>} element can also specify various intent filters—using the {@code +<intent-filter>} element—in order to declare how other application components may +activate it.
+ +When you create a new application using the Android SDK tools, the stub activity +that's created for you automatically includes an intent filter that declares the activity +responds to the "main" action and should be placed in the "launcher" category. The intent filter +looks like this:
+ ++<activity android:name=".ExampleActivity" android:icon="@drawable/app_icon"> + <intent-filter> + <action android:name="android.intent.action.MAIN" /> + <category android:name="android.intent.category.LAUNCHER" /> + </intent-filter> +</activity> ++ +
The {@code +<action>} element specifies that this is the "main" entry point to the application. The {@code +<category>} element specifies that this activity should be listed in the +system's application launcher (to allow users to launch this activity).
+ +If you intend for your application to be self-contained and not allow other applications to +activate its activities, then you don't need any other intent filters. Only one activity should +have the "main" action and "launcher" category, as in the previous example. Activities that +you don't want to make available to other applications should have no intent filters and you can +start them yourself using explicit intents (as discussed in the following section).
+ +However, if you want your activity to respond to implicit intents that are delivered from +other applications (and your own), then you must define additional intent filters for your +activity. For each type of intent to which you want to respond, you must include an {@code +<intent-filter>} that includes an +{@code +<action>} element and, optionally, a {@code +<category>} element and/or a {@code +<data>} element. These elements specify the type of intent to which your activity can +respond.
+ +For more information about how your activities can respond to intents, see the Intents and Intent Filters +document.
+ + + +You can start another activity by calling {@link android.app.Activity#startActivity + startActivity()}, passing it an {@link android.content.Intent} that describes the activity you + want to start. The intent specifies either the exact activity you want to start or describes the + type of action you want to perform (and the system selects the appropriate activity for you, +which + can even be from a different application). An intent can also carry small amounts of data to be + used by the activity that is started.
+ +When working within your own application, you'll often need to simply launch a known activity. + You can do so by creating an intent that explicitly defines the activity you want to start, +using the class name. For example, here's how one activity starts another activity named {@code +SignInActivity}:
+ ++Intent intent = new Intent(this, SignInActivity.class); +startActivity(intent); ++ +
However, your application might also want to perform some action, such as send an email, text + message, or status update, using data from your activity. In this case, your application might + not have its own activities to perform such actions, so you can instead leverage the activities + provided by other applications on the device, which can perform the actions for you. This is where +intents are really valuable—you can create an intent that describes an action you want to +perform and the system + launches the appropriate activity from another application. If there are + multiple activities that can handle the intent, then the user can select which one to use. For + example, if you want to allow the user to send an email message, you can create the + following intent:
+ ++Intent intent = new Intent(Intent.ACTION_SEND); +intent.putExtra(Intent.EXTRA_EMAIL, recipientArray); +startActivity(intent); ++ +
The {@link android.content.Intent#EXTRA_EMAIL} extra added to the intent is a string array of + email addresses to which the email should be sent. When an email application responds to this + intent, it reads the string array provided in the extra and places them in the "to" field of the + email composition form. In this situation, the email application's activity starts and when the + user is done, your activity resumes.
+ + + + +Sometimes, you might want to receive a result from the activity that you start. In that case, + start the activity by calling {@link android.app.Activity#startActivityForResult + startActivityForResult()} (instead of {@link android.app.Activity#startActivity + startActivity()}). To then receive the result from the subsequent +activity, implement the {@link android.app.Activity#onActivityResult onActivityResult()} callback + method. When the subsequent activity is done, it returns a result in an {@link +android.content.Intent} to your {@link android.app.Activity#onActivityResult onActivityResult()} +method.
+ +For example, perhaps you want the user to pick one of their contacts, so your activity can +do something with the information in that contact. Here's how you can create such an intent and +handle the result:
+ +
+private void pickContact() {
+ // Create an intent to "pick" a contact, as defined by the content provider URI
+ Intent intent = new Intent(Intent.ACTION_PICK, Contacts.CONTENT_URI);
+ startActivityForResult(intent, PICK_CONTACT_REQUEST);
+}
+
+@Override
+protected void onActivityResult(int requestCode, int resultCode, Intent data) {
+ // If the request went well (OK) and the request was PICK_CONTACT_REQUEST
+ if (resultCode == Activity.RESULT_OK && requestCode == PICK_CONTACT_REQUEST) {
+ // Perform a query to the contact's content provider for the contact's name
+ Cursor cursor = getContentResolver().query(data.getData(),
+ new String[] {Contacts.DISPLAY_NAME}, null, null, null);
+ if (cursor.moveToFirst()) { // True if the cursor is not empty
+ int columnIndex = cursor.getColumnIndex(Contacts.DISPLAY_NAME);
+ String name = cursor.getString(columnIndex);
+ // Do something with the selected contact's name...
+ }
+ }
+}
+
+
+This example shows the basic logic you should use in your {@link +android.app.Activity#onActivityResult onActivityResult()} method in order to handle an +activity result. The first condition checks whether the request was successful—if it was, then +the {@code resultCode} will be {@link android.app.Activity#RESULT_OK}—and whether the request +to which this result is responding is known—in this case, the {@code requestCode} matches the +second parameter sent with {@link android.app.Activity#startActivityForResult +startActivityForResult()}. From there, the code handles the activity result by querying the +data returned in an {@link android.content.Intent} (the {@code data} parameter).
+ +What happens is, a {@link +android.content.ContentResolver} performs a query against a content provider, which returns a +{@link android.database.Cursor} that allows the queried data to be read. For more information, see +the Content Providers document.
+ +For more information about using intents, see the Intents and Intent +Filters document.
+ + +You can shut down an activity by calling its {@link android.app.Activity#finish +finish()} method. You can also shut down a separate activity that you previously started by calling +{@link android.app.Activity#finishActivity finishActivity()}.
+ +Note: In most cases, you should not explicitly finish an activity +using these methods. As discussed in the following section about the activity lifecycle, the +Android system manages the life of an activity for you, so you do not need to finish your own +activities. Calling these methods could adversely affect the expected user +experience and should only be used when you absolutely do not want the user to return to this +instance of the activity.
+ + +Managing the lifecycle of your activities by implementing callback methods is +crucial to developing a strong +and flexible application. The lifecycle of an activity is directly affected by its association with +other activities, its task and back stack.
+ +An activity can exist in essentially three states:
+ +If an activity is paused or stopped, the system can drop it from memory either by asking it to +finish (calling its {@link android.app.Activity#finish finish()} method), or simply killing its +process. When the activity is opened again (after being finished or killed), it must be created all +over.
+ + + +When an activity transitions into and out of the different states described above, it is notified +through various callback methods. All of the callback methods are hooks that you +can override to do appropriate work when the state of your activity changes. The following skeleton +activity includes each of the fundamental lifecycle methods:
+ + +
+public class ExampleActivity extends Activity {
+ @Override
+ public void {@link android.app.Activity#onCreate onCreate}(Bundle savedInstanceState) {
+ super.onCreate(savedInstanceState);
+ // The activity is being created.
+ }
+ @Override
+ protected void {@link android.app.Activity#onStart onStart()} {
+ super.onStart();
+ // The activity is about to become visible.
+ }
+ @Override
+ protected void {@link android.app.Activity#onResume onResume()} {
+ super.onResume();
+ // The activity has become visible (it is now "resumed").
+ }
+ @Override
+ protected void {@link android.app.Activity#onPause onPause()} {
+ super.onPause();
+ // Another activity is taking focus (this activity is about to be "paused").
+ }
+ @Override
+ protected void {@link android.app.Activity#onStop onStop()} {
+ super.onStop();
+ // The activity is no longer visible (it is now "stopped")
+ }
+ @Override
+ protected void {@link android.app.Activity#onDestroy onDestroy()} {
+ super.onDestroy();
+ // The activity is about to be destroyed.
+ }
+}
+
+
+Note: Your implementation of these lifecycle methods must +always call the superclass implementation before doing any work, as shown in the examples above.
+ +Taken together, these methods define the entire lifecycle of an activity. By implementing these +methods, you can monitor three nested loops in the activity lifecycle:
+ +The visible lifetime of an activity happens between the call to {@link +android.app.Activity#onStart onStart()} and the call to {@link +android.app.Activity#onStop onStop()}. During this time, the user can see the activity +on-screen and interact with it. For example, {@link android.app.Activity#onStop onStop()} is called +when a new activity starts and this one is no longer visible. Between these two methods, you can +maintain resources that are needed to show the activity to the user. For example, you can register a +{@link android.content.BroadcastReceiver} in {@link +android.app.Activity#onStart onStart()} to monitor changes that impact your UI, and unregister +it in {@link android.app.Activity#onStop onStop()} when the user can no longer see what you are +displaying. The system might call {@link android.app.Activity#onStart onStart()} and {@link +android.app.Activity#onStop onStop()} multiple times during the entire lifetime of the activity, as +the activity alternates between being visible and hidden to the user.
The foreground lifetime of an activity happens between the call to {@link +android.app.Activity#onResume onResume()} and the call to {@link android.app.Activity#onPause +onPause()}. During this time, the activity is in front of all other activities on screen and has +user input focus. An activity can frequently transition in and out of the foreground—for +example, {@link android.app.Activity#onPause onPause()} is called when the device goes to sleep or +when a dialog appears. Because this state can transition often, the code in these two methods should +be fairly lightweight in order to avoid slow transitions that make the user wait.
Figure 1 illustrates these loops and the paths an activity might take between states. +The rectangles represent the callback methods you can implement to perform operations when +the activity transitions between states.
+
+
+
Figure 1. The activity lifecycle.
+ +The same lifecycle callback methods are listed in table 1, which describes each of the callback +methods in more detail and locates each one within the +activity's overall lifecycle, including whether the system can kill the activity after the +callback method completes.
+ +Table 1. A summary of the activity lifecycle's +callback methods.
+ +| Method | Description | Killable after? | Next | ||
|---|---|---|---|---|---|
{@link android.app.Activity#onCreate onCreate()} |
+ Called when the activity is first created.
+ This is where you should do all of your normal static set up —
+ create views, bind data to lists, and so on. This method is passed
+ a Bundle object containing the activity's previous state, if that
+ state was captured (see Saving Activity State,
+ later).
+ Always followed by {@code onStart()}. |
+ No | +{@code onStart()} | +||
| + | {@link android.app.Activity#onRestart
+onRestart()} |
+ Called after the activity has been stopped, just prior to it being
+ started again.
+ Always followed by {@code onStart()} |
+ No | +{@code onStart()} | +|
{@link android.app.Activity#onStart onStart()} |
+ Called just before the activity becomes visible to the user.
+ Followed by {@code onResume()} if the activity comes + to the foreground, or {@code onStop()} if it becomes hidden. |
+ No | +{@code onResume()} or {@code onStop()} |
+||
| + | {@link android.app.Activity#onResume onResume()} |
+ Called just before the activity starts
+ interacting with the user. At this point the activity is at
+ the top of the activity stack, with user input going to it.
+ Always followed by {@code onPause()}. |
+ No | +{@code onPause()} | +|
{@link android.app.Activity#onPause onPause()} |
+ Called when the system is about to start resuming another
+ activity. This method is typically used to commit unsaved changes to
+ persistent data, stop animations and other things that may be consuming
+ CPU, and so on. It should do whatever it does very quickly, because
+ the next activity will not be resumed until it returns.
+ Followed either by {@code onResume()} if the activity + returns back to the front, or by {@code onStop()} if it becomes + invisible to the user. |
+ Yes | +{@code onResume()} or {@code onStop()} |
+||
{@link android.app.Activity#onStop onStop()} |
+ Called when the activity is no longer visible to the user. This
+ may happen because it is being destroyed, or because another activity
+ (either an existing one or a new one) has been resumed and is covering it.
+ Followed either by {@code onRestart()} if + the activity is coming back to interact with the user, or by + {@code onDestroy()} if this activity is going away. |
+ Yes | +{@code onRestart()} or {@code onDestroy()} |
+||
{@link android.app.Activity#onDestroy
+onDestroy()} |
+ Called before the activity is destroyed. This is the final call
+ that the activity will receive. It could be called either because the
+ activity is finishing (someone called {@link android.app.Activity#finish
+ finish()} on it), or because the system is temporarily destroying this
+ instance of the activity to save space. You can distinguish
+ between these two scenarios with the {@link
+ android.app.Activity#isFinishing isFinishing()} method. |
+ Yes | +nothing | +||
The column labeled "Killable after?" indicates whether or not the system can +kill the process hosting the activity at any time after the method returns, without +executing another line of the activity's code. Three methods are marked "yes": ({@link +android.app.Activity#onPause +onPause()}, {@link android.app.Activity#onStop onStop()}, and {@link android.app.Activity#onDestroy +onDestroy()}). Because {@link android.app.Activity#onPause onPause()} is the first +of the three, once the activity is created, {@link android.app.Activity#onPause onPause()} is the +last method that's guaranteed to be called before the process can be killed—if +the system must recover memory in an emergency, then {@link +android.app.Activity#onStop onStop()} and {@link android.app.Activity#onDestroy onDestroy()} might +not be called. Therefore, you should use {@link android.app.Activity#onPause onPause()} to write +crucial persistent data (such as user edits) to storage. However, you should be selective about +what information must be retained during {@link android.app.Activity#onPause onPause()}, because any +blocking procedures in this method block the transition to the next activity and slow the user +experience.
+ +Methods that are marked "No" in the Killable column protect the process hosting the +activity from being killed from the moment they are called. Thus, an activity is killable +from the time {@link android.app.Activity#onPause onPause()} returns to the time +{@link android.app.Activity#onResume onResume()} is called. It will not again be killable until +{@link android.app.Activity#onPause onPause()} is again called and returns.
+ +Note: An activity that's not technically "killable" by this +definition in table 1 might still be killed by the system—but that would happen only in +extreme circumstances when there is no other recourse. When an activity might be killed is +discussed more in the Processes and +Threading document.
+ + +The introduction to Managing the Activity Lifecycle briefly mentions +that +when an activity is paused or stopped, the state of the activity is retained. This is true because +the {@link android.app.Activity} object is still held in memory when it is paused or +stopped—all information about its members and current state is still alive. Thus, any changes +the user made within the activity are retained so that when the activity returns to the +foreground (when it "resumes"), those changes are still there.
+ +However, when the system destroys an activity in order to recover memory, the {@link +android.app.Activity} object is destroyed, so the system cannot simply resume it with its state +intact. Instead, the system must recreate the {@link android.app.Activity} object if the user +navigates back to it. Yet, the user is unaware +that the system destroyed the activity and recreated it and, thus, probably +expects the activity to be exactly as it was. In this situation, you can ensure that +important information about the activity state is preserved by implementing an additional +callback method that allows you to save information about the state of your activity: {@link +android.app.Activity#onSaveInstanceState onSaveInstanceState()}.
+ +The system calls {@link android.app.Activity#onSaveInstanceState onSaveInstanceState()} +before making the activity vulnerable to destruction. The system passes this method +a {@link android.os.Bundle} in which you can save +state information about the activity as name-value pairs, using methods such as {@link +android.os.Bundle#putString putString()} and {@link +android.os.Bundle#putInt putInt()}. Then, if the system kills your application +process and the user navigates back to your activity, the system recreates the activity and passes +the {@link android.os.Bundle} to both {@link android.app.Activity#onCreate onCreate()} and {@link +android.app.Activity#onRestoreInstanceState onRestoreInstanceState()}. Using either of these +methods, you can extract your saved state from the {@link android.os.Bundle} and restore the +activity state. If there is no state information to restore, then the {@link +android.os.Bundle} passed to you is null (which is the case when the activity is created for +the first time).
+ +
+Figure 2. The two ways in which an activity returns to user +focus with its state intact: either the activity is destroyed, then recreated and the activity must restore +the previously saved state, or the activity is stopped, then resumed and the activity state +remains intact.
+ +Note: There's no guarantee that {@link +android.app.Activity#onSaveInstanceState onSaveInstanceState()} will be called before your +activity is destroyed, because there are cases in which it won't be necessary to save the state +(such as when the user leaves your activity using the Back button, because the user is +explicitly +closing the activity). If the system calls {@link android.app.Activity#onSaveInstanceState +onSaveInstanceState()}, it does so before {@link +android.app.Activity#onStop onStop()} and possibly before {@link android.app.Activity#onPause +onPause()}.
+ +However, even if you do nothing and do not implement {@link +android.app.Activity#onSaveInstanceState onSaveInstanceState()}, some of the activity state is +restored by the {@link android.app.Activity} class's default implementation of {@link +android.app.Activity#onSaveInstanceState onSaveInstanceState()}. Specifically, the default +implementation calls the corresponding {@link +android.view.View#onSaveInstanceState onSaveInstanceState()} method for every {@link +android.view.View} in the layout, which allows each view to provide information about itself +that should be saved. Almost every widget in the Android framework implements this method as +appropriate, such that any visible changes to the UI are automatically saved and restored when your +activity is recreated. For example, the {@link android.widget.EditText} widget saves any text +entered by the user and the {@link android.widget.CheckBox} widget saves whether it's checked or +not. The only work required by you is to provide a unique ID (with the {@code android:id} +attribute) for each widget you want to save its state. If a widget does not have an ID, then the +system cannot save its state.
+ +You can also explicitly stop a view in your layout from saving its state by setting the +{@link android.R.attr#saveEnabled android:saveEnabled} attribute to {@code "false"} or by calling +the {@link android.view.View#setSaveEnabled setSaveEnabled()} method. Usually, you should not +disable this, but you might if you want to restore the state of the activity UI differently.
+Although the default implementation of {@link +android.app.Activity#onSaveInstanceState onSaveInstanceState()} saves useful information about +your activity's UI, you still might need to override it to save additional information. +For example, you might need to save member values that changed during the activity's life (which +might correlate to values restored in the UI, but the members that hold those UI values are not +restored, by default).
+ +Because the default implementation of {@link +android.app.Activity#onSaveInstanceState onSaveInstanceState()} helps save the state of the UI, if +you override the method in order to save additional state information, you should always call the +superclass implementation of {@link android.app.Activity#onSaveInstanceState onSaveInstanceState()} +before doing any work. Likewise, you should also call the supercall implementation of {@link +android.app.Activity#onRestoreInstanceState onRestoreInstanceState()} if you override it, so the +default implementation can restore view states.
+ +Note: Because {@link android.app.Activity#onSaveInstanceState +onSaveInstanceState()} is not guaranteed +to be called, you should use it only to record the transient state of the activity (the state of +the UI)—you should never use it to store persistent data. Instead, you should use {@link +android.app.Activity#onPause onPause()} to store persistent data (such as data that should be saved +to a database) when the user leaves the activity.
+ +A good way to test your application's ability to restore its state is to simply rotate the +device so that the screen orientation changes. When the screen orientation changes, the system +destroys and recreates the activity in order to apply alternative resources that might be available +for the new screen configuration. For this reason alone, it's very important that your activity +completely restores its state when it is recreated, because users regularly rotate the screen while +using applications.
+ + +Some device configurations can change during runtime (such as screen orientation, keyboard +availability, and language). When such a change occurs, Android recreates the running activity +(the system calls {@link android.app.Activity#onDestroy}, then immediately calls {@link +android.app.Activity#onCreate onCreate()}). This behavior is +designed to help your application adapt to new configurations by automatically reloading your +application with alternative resources that you've provided (such as different layouts for +different screen orientations and sizes).
+ +If you properly design your activity to handle a restart due to a screen orientation change and +restore the activity state as described above, your application will be more resilient to other +unexpected events in the activity lifecycle.
+ +The best way to handle such a restart is + to save and restore the state of your activity using {@link + android.app.Activity#onSaveInstanceState onSaveInstanceState()} and {@link +android.app.Activity#onRestoreInstanceState onRestoreInstanceState()} (or {@link +android.app.Activity#onCreate onCreate()}), as discussed in the previous section.
+ +For more information about configuration changes that happen at runtime and how you can handle +them, read the guide to Handling +Runtime Changes.
+ + + +When one activity starts another, they both experience lifecycle transitions. The first activity +pauses and stops (though, it won't stop if it's still visible in the background), while the other +activity is created. In case these activities share data saved to disc or elsewhere, it's important +to understand that the first activity is not completely stopped before the second one is created. +Rather, the process of starting the second one overlaps with the process of stopping the first +one.
+ +The order of lifecycle callbacks is well defined, particularly when the two activities are in the +same process and one is starting the other. Here's the order of operations that occur when Activity +A starts Acivity B:
+ +This predictable sequence of lifecycle callbacks allows you to manage the transition of +information from one activity to another. For example, if you must write to a database when the +first activity stops so that the following activity can read it, then you should write to the +database during {@link android.app.Activity#onPause onPause()} instead of during {@link +android.app.Activity#onStop onStop()}.
+ + \ No newline at end of file diff --git a/docs/html/guide/components/bound-services.jd b/docs/html/guide/components/bound-services.jd new file mode 100644 index 000000000000..b6a251286c05 --- /dev/null +++ b/docs/html/guide/components/bound-services.jd @@ -0,0 +1,675 @@ +page.title=Bound Services +parent.title=Services +parent.link=services.html +@jd:body + + +A bound service is the server in a client-server interface. A bound service allows components +(such as activities) to bind to the service, send requests, receive responses, and even perform +interprocess communication (IPC). A bound service typically lives only while it serves another +application component and does not run in the background indefinitely.
+ +This document shows you how to create a bound service, including how to bind +to the service from other application components. However, you should also refer to the Services document for additional +information about services in general, such as how to deliver notifications from a service, set +the service to run in the foreground, and more.
+ + +A bound service is an implementation of the {@link android.app.Service} class that allows +other applications to bind to it and interact with it. To provide binding for a +service, you must implement the {@link android.app.Service#onBind onBind()} callback method. This +method returns an {@link android.os.IBinder} object that defines the programming interface that +clients can use to interact with the service.
+ +As discussed in the Services +document, you can create a service that is both started and bound. That is, the service can be +started by calling {@link android.content.Context#startService startService()}, which allows the +service to run indefinitely, and also allow a client to bind to the service by calling {@link +android.content.Context#bindService bindService()}. +
If you do allow your service to be started and bound, then when the service has been +started, the system does not destroy the service when all clients unbind. Instead, you must +explicitly stop the service, by calling {@link android.app.Service#stopSelf stopSelf()} or {@link +android.content.Context#stopService stopService()}.
+ +Although you should usually implement either {@link android.app.Service#onBind onBind()} +or {@link android.app.Service#onStartCommand onStartCommand()}, it's sometimes necessary to +implement both. For example, a music player might find it useful to allow its service to run +indefinitely and also provide binding. This way, an activity can start the service to play some +music and the music continues to play even if the user leaves the application. Then, when the user +returns to the application, the activity can bind to the service to regain control of playback.
+ +Be sure to read the section about Managing the Lifecycle of a Bound +Service, for more information about the service lifecycle when adding binding to a +started service.
+A client can bind to the service by calling {@link android.content.Context#bindService +bindService()}. When it does, it must provide an implementation of {@link +android.content.ServiceConnection}, which monitors the connection with the service. The {@link +android.content.Context#bindService bindService()} method returns immediately without a value, but +when the Android system creates the connection between the +client and service, it calls {@link +android.content.ServiceConnection#onServiceConnected onServiceConnected()} on the {@link +android.content.ServiceConnection}, to deliver the {@link android.os.IBinder} that +the client can use to communicate with the service.
+ +Multiple clients can connect to the service at once. However, the system calls your service's +{@link android.app.Service#onBind onBind()} method to retrieve the {@link android.os.IBinder} only +when the first client binds. The system then delivers the same {@link android.os.IBinder} to any +additional clients that bind, without calling {@link android.app.Service#onBind onBind()} again.
+ +When the last client unbinds from the service, the system destroys the service (unless the +service was also started by {@link android.content.Context#startService startService()}).
+ +When you implement your bound service, the most important part is defining the interface +that your {@link android.app.Service#onBind onBind()} callback method returns. There are a few +different ways you can define your service's {@link android.os.IBinder} interface and the following +section discusses each technique.
+ + + +When creating a service that provides binding, you must provide an {@link android.os.IBinder} +that provides the programming interface that clients can use to interact with the service. There +are three ways you can define the interface:
+ +This is the preferred technique when your service is merely a background worker for your own +application. The only reason you would not create your interface this way is because +your service is used by other applications or across separate processes.
This is the simplest way to perform interprocess communication (IPC), because the {@link +android.os.Messenger} queues all requests into a single thread so that you don't have to design +your service to be thread-safe.
+To use AIDL directly, you must +create an {@code .aidl} file that defines the programming interface. The Android SDK tools use +this file to generate an abstract class that implements the interface and handles IPC, which you +can then extend within your service.
+Note: Most applications should not use AIDL to +create a bound service, because it may require multithreading capabilities and +can result in a more complicated implementation. As such, AIDL is not suitable for most applications +and this document does not discuss how to use it for your service. If you're certain that you need +to use AIDL directly, see the AIDL +document.
+ + + + +If your service is used only by the local application and does not need to work across processes, +then you can implement your own {@link android.os.Binder} class that provides your client direct +access to public methods in the service.
+ +Note: This works only if the client and service are in the same +application and process, which is most common. For example, this would work well for a music +application that needs to bind an activity to its own service that's playing music in the +background.
+ +Here's how to set it up:
+Note: The reason the service and client must be in the same +application is so the client can cast the returned object and properly call its APIs. The service +and client must also be in the same process, because this technique does not perform any +marshalling across processes.
+ +For example, here's a service that provides clients access to methods in the service through +a {@link android.os.Binder} implementation:
+ +
+public class LocalService extends Service {
+ // Binder given to clients
+ private final IBinder mBinder = new LocalBinder();
+ // Random number generator
+ private final Random mGenerator = new Random();
+
+ /**
+ * Class used for the client Binder. Because we know this service always
+ * runs in the same process as its clients, we don't need to deal with IPC.
+ */
+ public class LocalBinder extends Binder {
+ LocalService getService() {
+ // Return this instance of LocalService so clients can call public methods
+ return LocalService.this;
+ }
+ }
+
+ @Override
+ public IBinder onBind(Intent intent) {
+ return mBinder;
+ }
+
+ /** method for clients */
+ public int getRandomNumber() {
+ return mGenerator.nextInt(100);
+ }
+}
+
+
+The {@code LocalBinder} provides the {@code getService()} method for clients to retrieve the +current instance of {@code LocalService}. This allows clients to call public methods in the +service. For example, clients can call {@code getRandomNumber()} from the service.
+ +Here's an activity that binds to {@code LocalService} and calls {@code getRandomNumber()} +when a button is clicked:
+ +
+public class BindingActivity extends Activity {
+ LocalService mService;
+ boolean mBound = false;
+
+ @Override
+ protected void onCreate(Bundle savedInstanceState) {
+ super.onCreate(savedInstanceState);
+ setContentView(R.layout.main);
+ }
+
+ @Override
+ protected void onStart() {
+ super.onStart();
+ // Bind to LocalService
+ Intent intent = new Intent(this, LocalService.class);
+ bindService(intent, mConnection, Context.BIND_AUTO_CREATE);
+ }
+
+ @Override
+ protected void onStop() {
+ super.onStop();
+ // Unbind from the service
+ if (mBound) {
+ unbindService(mConnection);
+ mBound = false;
+ }
+ }
+
+ /** Called when a button is clicked (the button in the layout file attaches to
+ * this method with the android:onClick attribute) */
+ public void onButtonClick(View v) {
+ if (mBound) {
+ // Call a method from the LocalService.
+ // However, if this call were something that might hang, then this request should
+ // occur in a separate thread to avoid slowing down the activity performance.
+ int num = mService.getRandomNumber();
+ Toast.makeText(this, "number: " + num, Toast.LENGTH_SHORT).show();
+ }
+ }
+
+ /** Defines callbacks for service binding, passed to bindService() */
+ private ServiceConnection mConnection = new ServiceConnection() {
+
+ @Override
+ public void onServiceConnected(ComponentName className,
+ IBinder service) {
+ // We've bound to LocalService, cast the IBinder and get LocalService instance
+ LocalBinder binder = (LocalBinder) service;
+ mService = binder.getService();
+ mBound = true;
+ }
+
+ @Override
+ public void onServiceDisconnected(ComponentName arg0) {
+ mBound = false;
+ }
+ };
+}
+
+
+The above sample shows how the client binds to the service using an implementation of +{@link android.content.ServiceConnection} and the {@link +android.content.ServiceConnection#onServiceConnected onServiceConnected()} callback. The next +section provides more information about this process of binding to the service.
+ +Note: The example above doesn't explicitly unbind from the service, +but all clients should unbind at an appropriate time (such as when the activity pauses).
+ +For more sample code, see the {@code +LocalService.java} class and the {@code +LocalServiceActivities.java} class in ApiDemos.
+ + + + + +When you need to perform IPC, using a {@link android.os.Messenger} for your interface is +simpler than implementing it with AIDL, because {@link android.os.Messenger} queues +all calls to the service, whereas, a pure AIDL interface sends simultaneous requests to the +service, which must then handle multi-threading.
+For most applications, the service doesn't need to perform multi-threading, so using a {@link +android.os.Messenger} allows the service to handle one call at a time. If it's important +that your service be multi-threaded, then you should use AIDL to define your interface.
+If you need your service to communicate with remote processes, then you can use a +{@link android.os.Messenger} to provide the interface for your service. This technique allows +you to perform interprocess communication (IPC) without the need to use AIDL.
+ +Here's a summary of how to use a {@link android.os.Messenger}:
+ +In this way, there are no "methods" for the client to call on the service. Instead, the +client delivers "messages" ({@link android.os.Message} objects) that the service receives in +its {@link android.os.Handler}.
+ +Here's a simple example service that uses a {@link android.os.Messenger} interface:
+ +
+public class MessengerService extends Service {
+ /** Command to the service to display a message */
+ static final int MSG_SAY_HELLO = 1;
+
+ /**
+ * Handler of incoming messages from clients.
+ */
+ class IncomingHandler extends Handler {
+ @Override
+ public void handleMessage(Message msg) {
+ switch (msg.what) {
+ case MSG_SAY_HELLO:
+ Toast.makeText(getApplicationContext(), "hello!", Toast.LENGTH_SHORT).show();
+ break;
+ default:
+ super.handleMessage(msg);
+ }
+ }
+ }
+
+ /**
+ * Target we publish for clients to send messages to IncomingHandler.
+ */
+ final Messenger mMessenger = new Messenger(new IncomingHandler());
+
+ /**
+ * When binding to the service, we return an interface to our messenger
+ * for sending messages to the service.
+ */
+ @Override
+ public IBinder onBind(Intent intent) {
+ Toast.makeText(getApplicationContext(), "binding", Toast.LENGTH_SHORT).show();
+ return mMessenger.getBinder();
+ }
+}
+
+
+Notice that the {@link android.os.Handler#handleMessage handleMessage()} method in the +{@link android.os.Handler} is where the service receives the incoming {@link android.os.Message} +and decides what to do, based on the {@link android.os.Message#what} member.
+ +All that a client needs to do is create a {@link android.os.Messenger} based on the {@link +android.os.IBinder} returned by the service and send a message using {@link +android.os.Messenger#send send()}. For example, here's a simple activity that binds to the +service and delivers the {@code MSG_SAY_HELLO} message to the service:
+ +
+public class ActivityMessenger extends Activity {
+ /** Messenger for communicating with the service. */
+ Messenger mService = null;
+
+ /** Flag indicating whether we have called bind on the service. */
+ boolean mBound;
+
+ /**
+ * Class for interacting with the main interface of the service.
+ */
+ private ServiceConnection mConnection = new ServiceConnection() {
+ public void onServiceConnected(ComponentName className, IBinder service) {
+ // This is called when the connection with the service has been
+ // established, giving us the object we can use to
+ // interact with the service. We are communicating with the
+ // service using a Messenger, so here we get a client-side
+ // representation of that from the raw IBinder object.
+ mService = new Messenger(service);
+ mBound = true;
+ }
+
+ public void onServiceDisconnected(ComponentName className) {
+ // This is called when the connection with the service has been
+ // unexpectedly disconnected -- that is, its process crashed.
+ mService = null;
+ mBound = false;
+ }
+ };
+
+ public void sayHello(View v) {
+ if (!mBound) return;
+ // Create and send a message to the service, using a supported 'what' value
+ Message msg = Message.obtain(null, MessengerService.MSG_SAY_HELLO, 0, 0);
+ try {
+ mService.send(msg);
+ } catch (RemoteException e) {
+ e.printStackTrace();
+ }
+ }
+
+ @Override
+ protected void onCreate(Bundle savedInstanceState) {
+ super.onCreate(savedInstanceState);
+ setContentView(R.layout.main);
+ }
+
+ @Override
+ protected void onStart() {
+ super.onStart();
+ // Bind to the service
+ bindService(new Intent(this, MessengerService.class), mConnection,
+ Context.BIND_AUTO_CREATE);
+ }
+
+ @Override
+ protected void onStop() {
+ super.onStop();
+ // Unbind from the service
+ if (mBound) {
+ unbindService(mConnection);
+ mBound = false;
+ }
+ }
+}
+
+
+Notice that this example does not show how the service can respond to the client. If you want the +service to respond, then you need to also create a {@link android.os.Messenger} in the client. Then +when the client receives the {@link android.content.ServiceConnection#onServiceConnected +onServiceConnected()} callback, it sends a {@link android.os.Message} to the service that includes +the client's {@link android.os.Messenger} in the {@link android.os.Message#replyTo} parameter +of the {@link android.os.Messenger#send send()} method.
+ +You can see an example of how to provide two-way messaging in the {@code +MessengerService.java} (service) and {@code +MessengerServiceActivities.java} (client) samples.
+ + + + + +Application components (clients) can bind to a service by calling +{@link android.content.Context#bindService bindService()}. The Android +system then calls the service's {@link android.app.Service#onBind +onBind()} method, which returns an {@link android.os.IBinder} for interacting with the service.
+ +The binding is asynchronous. {@link android.content.Context#bindService +bindService()} returns immediately and does not return the {@link android.os.IBinder} to +the client. To receive the {@link android.os.IBinder}, the client must create an instance of {@link +android.content.ServiceConnection} and pass it to {@link android.content.Context#bindService +bindService()}. The {@link android.content.ServiceConnection} includes a callback method that the +system calls to deliver the {@link android.os.IBinder}.
+ +Note: Only activities, services, and content providers can bind +to a service—you cannot bind to a service from a broadcast receiver.
+ +So, to bind to a service from your client, you must:
+Your implementation must override two callback methods:
+When your client is destroyed, it will unbind from the service, but you should always unbind +when you're done interacting with the service or when your activity pauses so that the service can +shutdown while its not being used. (Appropriate times to bind and unbind is discussed +more below.)
+For example, the following snippet connects the client to the service created above by +extending the Binder class, so all it must do is cast the returned +{@link android.os.IBinder} to the {@code LocalService} class and request the {@code +LocalService} instance:
+ +
+LocalService mService;
+private ServiceConnection mConnection = new ServiceConnection() {
+ // Called when the connection with the service is established
+ public void onServiceConnected(ComponentName className, IBinder service) {
+ // Because we have bound to an explicit
+ // service that is running in our own process, we can
+ // cast its IBinder to a concrete class and directly access it.
+ LocalBinder binder = (LocalBinder) service;
+ mService = binder.getService();
+ mBound = true;
+ }
+
+ // Called when the connection with the service disconnects unexpectedly
+ public void onServiceDisconnected(ComponentName className) {
+ Log.e(TAG, "onServiceDisconnected");
+ mBound = false;
+ }
+};
+
+
+With this {@link android.content.ServiceConnection}, the client can bind to a service by passing +this it to {@link android.content.Context#bindService bindService()}. For example:
+ ++Intent intent = new Intent(this, LocalService.class); +bindService(intent, mConnection, Context.BIND_AUTO_CREATE); ++ +
Here are some important notes about binding to a service:
+Note: You should usually not bind and unbind +during your activity's {@link android.app.Activity#onResume onResume()} and {@link +android.app.Activity#onPause onPause()}, because these callbacks occur at every lifecycle transition +and you should keep the processing that occurs at these transitions to a minimum. Also, if +multiple activities in your application bind to the same service and there is a transition between +two of those activities, the service may be destroyed and recreated as the current activity unbinds +(during pause) before the next one binds (during resume). (This activity transition for how +activities coordinate their lifecycles is described in the Activities +document.)
+For more sample code, showing how to bind to a service, see the {@code +RemoteService.java} class in ApiDemos.
+ + + + + +
+Figure 1. The lifecycle for a service that is started +and also allows binding.
+When a service is unbound from all clients, the Android system destroys it (unless it was also +started with {@link android.app.Service#onStartCommand onStartCommand()}). As such, you don't have +to manage the lifecycle of your service if it's purely a bound +service—the Android system manages it for you based on whether it is bound to any clients.
+ +However, if you choose to implement the {@link android.app.Service#onStartCommand +onStartCommand()} callback method, then you must explicitly stop the service, because the +service is now considered to be started. In this case, the service runs until the service +stops itself with {@link android.app.Service#stopSelf()} or another component calls {@link +android.content.Context#stopService stopService()}, regardless of whether it is bound to any +clients.
+ +Additionally, if your service is started and accepts binding, then when the system calls +your {@link android.app.Service#onUnbind onUnbind()} method, you can optionally return +{@code true} if you would like to receive a call to {@link android.app.Service#onRebind +onRebind()} the next time a client binds to the service (instead of receiving a call to {@link +android.app.Service#onBind onBind()}). {@link android.app.Service#onRebind +onRebind()} returns void, but the client still receives the {@link android.os.IBinder} in its +{@link android.content.ServiceConnection#onServiceConnected onServiceConnected()} callback. +Below, figure 1 illustrates the logic for this kind of lifecycle.
+ +For more information about the lifecycle of an started service, see the Services document.
+ + + + diff --git a/docs/html/guide/components/fragments.jd b/docs/html/guide/components/fragments.jd new file mode 100644 index 000000000000..938e0ab02ea6 --- /dev/null +++ b/docs/html/guide/components/fragments.jd @@ -0,0 +1,836 @@ +page.title=Fragments +parent.title=Activities +parent.link=activities.html +@jd:body + +A {@link android.app.Fragment} represents a behavior or a portion of user interface in an +{@link android.app.Activity}. You can combine multiple fragments in a single activity to build a +multi-pane UI and reuse a fragment in multiple activities. You can think of a fragment as a +modular section of an activity, which has its own lifecycle, receives its own input events, and +which you can add or remove while the activity is running (sort of like a "sub activity" that +you can reuse in different activities).
+ +A fragment must always be embedded in an activity and the fragment's lifecycle is directly +affected by the host activity's lifecycle. For example, when the activity is paused, so are all +fragments in it, and when the activity is destroyed, so are all fragments. However, while an +activity is running (it is in the resumed lifecycle state), you can +manipulate each fragment independently, such as add or remove them. When you perform such a +fragment transaction, you can also add it to a back stack that's managed by the +activity—each back stack entry in the activity is a record of the fragment transaction that +occurred. The back stack allows the user to reverse a fragment transaction (navigate backwards), +by pressing the Back button.
+ +When you add a fragment as a part of your activity layout, it lives in a {@link +android.view.ViewGroup} inside the activity's view hierarchy and the fragment defines its own view +layout. +You can insert a fragment into your activity layout by declaring the fragment in the activity's +layout file, as a {@code <fragment>} element, or from your application code by adding it to an +existing {@link android.view.ViewGroup}. However, a fragment is not required to be a part of the +activity layout; you may also use a fragment without its own UI as an invisible worker for the +activity.
+ +This document describes how to build your application to use fragments, including +how fragments can maintain their state when added to the activity's back stack, share +events with the activity and other fragments in the activity, contribute to the activity's action +bar, and more.
+ + +Android introduced fragments in Android 3.0 (API level 11), primarily to support more +dynamic and flexible UI designs on large screens, such as tablets. Because a +tablet's screen is much larger than that of a handset, there's more room to combine and +interchange UI components. Fragments allow such designs without the need for you to manage complex +changes to the view hierarchy. By dividing the layout of an activity into fragments, you become able +to modify the activity's appearance at runtime and preserve those changes in a back stack +that's managed by the activity.
+ +For example, a news application can use one fragment to show a list of articles on the +left and another fragment to display an article on the right—both fragments appear in one +activity, side by side, and each fragment has its own set of lifecycle callback methods and handle +their own user input events. Thus, instead of using one activity to select an article and another +activity to read the article, the user can select an article and read it all within the same +activity, as illustrated in the tablet layout in figure 1.
+ +You should design each fragment as a modular and reusable activity component. That is, because +each fragment defines its own layout and its own behavior with its own lifecycle callbacks, you can +include one fragment in multiple activities, so you should design for reuse and avoid directly +manipulating one fragment from another fragment. This is especially important because a modular +fragment allows you to change your fragment combinations for different screen sizes. When designing +your application to support both tablets and handsets, you can reuse your fragments in different +layout configurations to optimize the user experience based on the available screen space. For +example, on a handset, it might be necessary to separate fragments to provide a single-pane UI when +more than one cannot fit within the same activity.
+ +
+Figure 1. An example of how two UI modules defined by +fragments can be combined into one activity for a tablet design, but separated for a +handset design.
+ +For example—to continue with the news application example—the application can embed +two fragments in Activity A, when running on a tablet-sized device. However, on a +handset-sized screen, there's not enough room for both fragments, so Activity A includes +only the fragment for the list of articles, and when the user selects an article, it starts +Activity B, which includes the second fragment to read the article. Thus, the application +supports both tablets and handsets by reusing fragments in different combinations, as illustrated in +figure 1.
+ +For more information about designing your application with different fragment combinations for +different screen configurations, see the guide to Supporting Tablets and Handsets.
+ + + +
+Figure 2. The lifecycle of a fragment (while its +activity is running).
+To create a fragment, you must create a subclass of {@link android.app.Fragment} (or an existing +subclass of it). The {@link android.app.Fragment} class has code that looks a lot like +an {@link android.app.Activity}. It contains callback methods similar to an activity, such +as {@link android.app.Fragment#onCreate onCreate()}, {@link android.app.Fragment#onStart onStart()}, +{@link android.app.Fragment#onPause onPause()}, and {@link android.app.Fragment#onStop onStop()}. In +fact, if you're converting an existing Android application to use fragments, you might simply move +code from your activity's callback methods into the respective callback methods of your +fragment.
+ +Usually, you should implement at least the following lifecycle methods:
+ +Most applications should implement at least these three methods for every fragment, but there are +several other callback methods you should also use to handle various stages of the +fragment lifecycle. All the lifecycle callback methods are discussed more later, in the section +about Handling the Fragment Lifecycle.
+ + +There are also a few subclasses that you might want to extend, instead of the base {@link +android.app.Fragment} class:
+ +A fragment is usually used as part of an activity's user interface and contributes its own +layout to the activity.
+ +To provide a layout for a fragment, you must implement the {@link +android.app.Fragment#onCreateView onCreateView()} callback method, which the Android system calls +when it's time for the fragment to draw its layout. Your implementation of this method must return a +{@link android.view.View} that is the root of your fragment's layout.
+ +Note: If your fragment is a subclass of {@link +android.app.ListFragment}, the default implementation returns a {@link android.widget.ListView} from +{@link android.app.Fragment#onCreateView onCreateView()}, so you don't need to implement it.
+ +To return a layout from {@link +android.app.Fragment#onCreateView onCreateView()}, you can inflate it from a layout resource defined in XML. To +help you do so, {@link android.app.Fragment#onCreateView onCreateView()} provides a +{@link android.view.LayoutInflater} object.
+ +For example, here's a subclass of {@link android.app.Fragment} that loads a layout from the +{@code example_fragment.xml} file:
+ +
+public static class ExampleFragment extends Fragment {
+ @Override
+ public View onCreateView(LayoutInflater inflater, ViewGroup container,
+ Bundle savedInstanceState) {
+ // Inflate the layout for this fragment
+ return inflater.inflate(R.layout.example_fragment, container, false);
+ }
+}
+
+
+In the sample above, {@code R.layout.example_fragment} is a reference to a layout resource +named {@code example_fragment.xml} saved in the application resources. For information about how to +create a layout in XML, see the User Interface +documentation.
+The {@code container} parameter passed to {@link android.app.Fragment#onCreateView +onCreateView()} is the parent {@link android.view.ViewGroup} (from the activity's layout) in which +your fragment layout +will be inserted. The {@code savedInstanceState} parameter is a {@link android.os.Bundle} that +provides data about the previous instance of the fragment, if the fragment is being resumed +(restoring state is discussed more in the section about Handling the +Fragment Lifecycle).
+ +The {@link android.view.LayoutInflater#inflate(int,ViewGroup,boolean) inflate()} method takes +three arguments:
+Now you've seen how to create a fragment that provides a layout. Next, you need to add +the fragment to your activity.
+ + + +Usually, a fragment contributes a portion of UI to the host activity, which is embedded as a part +of the activity's overall view hierarchy. There are two ways you can add a fragment to the activity +layout:
+ +In this case, you can +specify layout properties for the fragment as if it were a view. For example, here's the layout +file for an activity with two fragments:
++<?xml version="1.0" encoding="utf-8"?> +<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" + android:orientation="horizontal" + android:layout_width="match_parent" + android:layout_height="match_parent"> + <fragment android:name="com.example.news.ArticleListFragment" + android:id="@+id/list" + android:layout_weight="1" + android:layout_width="0dp" + android:layout_height="match_parent" /> + <fragment android:name="com.example.news.ArticleReaderFragment" + android:id="@+id/viewer" + android:layout_weight="2" + android:layout_width="0dp" + android:layout_height="match_parent" /> +</LinearLayout> ++
The {@code android:name} attribute in the {@code <fragment>} specifies the {@link +android.app.Fragment} class to instantiate in the layout.
+ +When the system creates this activity layout, it instantiates each fragment specified in the +layout and calls the {@link android.app.Fragment#onCreateView onCreateView()} method for each one, +to retrieve each fragment's layout. The system inserts the {@link android.view.View} returned by the +fragment directly in place of the {@code <fragment>} element.
+ +Note: Each fragment requires a unique identifier that +the system can use to restore the fragment if the activity is restarted (and which you can use to +capture the fragment to perform transactions, such as remove it). There are three ways to provide an +ID for a fragment:
+At any time while your activity is running, you can add fragments to your activity layout. You +simply need to specify a {@link +android.view.ViewGroup} in which to place the fragment.
+To make fragment transactions in your activity (such as add, remove, or replace a +fragment), you must use APIs from {@link android.app.FragmentTransaction}. You can get an instance +of {@link android.app.FragmentTransaction} from your {@link android.app.Activity} like this:
+ +
+FragmentManager fragmentManager = {@link android.app.Activity#getFragmentManager()}
+FragmentTransaction fragmentTransaction = fragmentManager.{@link android.app.FragmentManager#beginTransaction()};
+
+
+You can then add a fragment using the {@link +android.app.FragmentTransaction#add(int,Fragment) add()} method, specifying the fragment to add and +the view in which to insert it. For example:
+ ++ExampleFragment fragment = new ExampleFragment(); +fragmentTransaction.add(R.id.fragment_container, fragment); +fragmentTransaction.commit(); ++ +
The first argument passed to {@link android.app.FragmentTransaction#add(int,Fragment) add()} +is the {@link android.view.ViewGroup} in which the fragment should be placed, specified by +resource ID, and the second parameter is the fragment to add.
+Once you've made your changes with +{@link android.app.FragmentTransaction}, you must +call {@link android.app.FragmentTransaction#commit} for the changes to take effect.
+The examples above show how to add a fragment to your activity in order to provide a UI. However, +you can also use a fragment to provide a background behavior for the activity without presenting +additional UI.
+ +To add a fragment without a UI, add the fragment from the activity using {@link +android.app.FragmentTransaction#add(Fragment,String)} (supplying a unique string "tag" for the +fragment, rather than a view ID). This adds the fragment, but, because it's not associated with a +view in the activity layout, it does not receive a call to {@link +android.app.Fragment#onCreateView onCreateView()}. So you don't need to implement that method.
+ +Supplying a string tag for the fragment isn't strictly for non-UI fragments—you can also +supply string tags to fragments that do have a UI—but if the fragment does not have a +UI, then the string tag is the only way to identify it. If you want to get the fragment from the +activity later, you need to use {@link android.app.FragmentManager#findFragmentByTag +findFragmentByTag()}.
+ +For an example activity that uses a fragment as a background worker, without a UI, see the {@code +FragmentRetainInstance.java} sample.
+ + + +To manage the fragments in your activity, you need to use {@link android.app.FragmentManager}. To +get it, call {@link android.app.Activity#getFragmentManager()} from your activity.
+ +Some things that you can do with {@link android.app.FragmentManager} include:
+ +For more information about these methods and others, refer to the {@link +android.app.FragmentManager} class documentation.
+ +As demonstrated in the previous section, you can also use {@link android.app.FragmentManager} +to open a {@link android.app.FragmentTransaction}, which allows you to perform transactions, such as +add and remove fragments.
+ + +A great feature about using fragments in your activity is the ability to add, remove, replace, +and perform other actions with them, in response to user interaction. Each set of changes that you +commit to the activity is called a transaction and you can perform one using APIs in {@link +android.app.FragmentTransaction}. You can also save each transaction to a back stack managed by the +activity, allowing the user to navigate backward through the fragment changes (similar to navigating +backward through activities).
+ +You can acquire an instance of {@link android.app.FragmentTransaction} from the {@link +android.app.FragmentManager} like this:
+ +
+FragmentManager fragmentManager = {@link android.app.Activity#getFragmentManager()};
+FragmentTransaction fragmentTransaction = fragmentManager.{@link android.app.FragmentManager#beginTransaction()};
+
+
+Each transaction is a set of changes that you want to perform at the same time. You can set +up all the changes you want to perform for a given transaction using methods such as {@link +android.app.FragmentTransaction#add add()}, {@link android.app.FragmentTransaction#remove remove()}, +and {@link android.app.FragmentTransaction#replace replace()}. Then, to apply the transaction +to the activity, you must call {@link android.app.FragmentTransaction#commit()}.
+ + +Before you call {@link +android.app.FragmentTransaction#commit()}, however, you might want to call {@link +android.app.FragmentTransaction#addToBackStack addToBackStack()}, in order to add the transaction +to a back stack of fragment transactions. This back stack is managed by the activity and allows +the user to return to the previous fragment state, by pressing the Back button.
+ +For example, here's how you can replace one fragment with another, and preserve the previous +state in the back stack:
+ ++// Create new fragment and transaction +Fragment newFragment = new ExampleFragment(); +FragmentTransaction transaction = getFragmentManager().beginTransaction(); + +// Replace whatever is in the fragment_container view with this fragment, +// and add the transaction to the back stack +transaction.replace(R.id.fragment_container, newFragment); +transaction.addToBackStack(null); + +// Commit the transaction +transaction.commit(); ++ +
In this example, {@code newFragment} replaces whatever fragment (if any) is currently in the +layout container identified by the {@code R.id.fragment_container} ID. By calling {@link +android.app.FragmentTransaction#addToBackStack addToBackStack()}, the replace transaction is +saved to the back stack so the user can reverse the transaction and bring back the +previous fragment by pressing the Back button.
+ +If you add multiple changes to the transaction (such as another {@link +android.app.FragmentTransaction#add add()} or {@link android.app.FragmentTransaction#remove +remove()}) and call {@link +android.app.FragmentTransaction#addToBackStack addToBackStack()}, then all changes applied +before you call {@link android.app.FragmentTransaction#commit commit()} are added to the +back stack as a single transaction and the Back button will reverse them all together.
+ +The order in which you add changes to a {@link android.app.FragmentTransaction} doesn't matter, +except:
+If you do not call {@link android.app.FragmentTransaction#addToBackStack(String) +addToBackStack()} when you perform a transaction that removes a fragment, then that fragment is +destroyed when the transaction is committed and the user cannot navigate back to it. Whereas, if you +do call {@link android.app.FragmentTransaction#addToBackStack(String) addToBackStack()} when +removing a fragment, then the fragment is stopped and will be resumed if the user navigates +back.
+ +Tip: For each fragment transaction, you can apply a transition +animation, by calling {@link android.app.FragmentTransaction#setTransition setTransition()} before +you commit.
+ +Calling {@link android.app.FragmentTransaction#commit()} does not perform the transaction +immediately. Rather, it schedules it to run on the activity's UI thread (the "main" thread) as soon +as the thread is able to do so. If necessary, however, you may call {@link +android.app.FragmentManager#executePendingTransactions()} from your UI thread to immediately execute +transactions submitted by {@link android.app.FragmentTransaction#commit()}. Doing so is +usually not necessary unless the transaction is a dependency for jobs in other threads.
+ +Caution: You can commit a transaction using {@link +android.app.FragmentTransaction#commit commit()} only prior to the activity saving its +state (when the user leaves the activity). If you attempt to commit after that point, an +exception will be thrown. This is because the state after the commit can be lost if the activity +needs to be restored. For situations in which its okay that you lose the commit, use {@link +android.app.FragmentTransaction#commitAllowingStateLoss()}.
+ + + + +Although a {@link android.app.Fragment} is implemented as an object that's independent from an +{@link android.app.Activity} and can be used inside multiple activities, a given instance of +a fragment is directly tied to the activity that contains it.
+ +Specifically, the fragment can access the {@link android.app.Activity} instance with {@link +android.app.Fragment#getActivity()} and easily perform tasks such as find a view in the +activity layout:
+ +
+View listView = {@link android.app.Fragment#getActivity()}.{@link android.app.Activity#findViewById findViewById}(R.id.list);
+
+
+Likewise, your activity can call methods in the fragment by acquiring a reference to the +{@link android.app.Fragment} from {@link android.app.FragmentManager}, using {@link +android.app.FragmentManager#findFragmentById findFragmentById()} or {@link +android.app.FragmentManager#findFragmentByTag findFragmentByTag()}. For example:
+ ++ExampleFragment fragment = (ExampleFragment) getFragmentManager().findFragmentById(R.id.example_fragment); ++ + +
In some cases, you might need a fragment to share events with the activity. A good way to do that +is to define a callback interface inside the fragment and require that the host activity implement +it. When the activity receives a callback through the interface, it can share the information with +other fragments in the layout as necessary.
+ +For example, if a news application has two fragments in an activity—one to show a list of +articles (fragment A) and another to display an article (fragment B)—then fragment A must tell +the activity when a list item is selected so that it can tell fragment B to display the article. In +this case, the {@code OnArticleSelectedListener} interface is declared inside fragment A:
+ +
+public static class FragmentA extends ListFragment {
+ ...
+ // Container Activity must implement this interface
+ public interface OnArticleSelectedListener {
+ public void onArticleSelected(Uri articleUri);
+ }
+ ...
+}
+
+
+Then the activity that hosts the fragment implements the {@code OnArticleSelectedListener} +interface and +overrides {@code onArticleSelected()} to notify fragment B of the event from fragment A. To ensure +that the host activity implements this interface, fragment A's {@link +android.app.Fragment#onAttach onAttach()} callback method (which the system calls when adding +the fragment to the activity) instantiates an instance of {@code OnArticleSelectedListener} by +casting the {@link android.app.Activity} that is passed into {@link android.app.Fragment#onAttach +onAttach()}:
+ +
+public static class FragmentA extends ListFragment {
+ OnArticleSelectedListener mListener;
+ ...
+ @Override
+ public void onAttach(Activity activity) {
+ super.onAttach(activity);
+ try {
+ mListener = (OnArticleSelectedListener) activity;
+ } catch (ClassCastException e) {
+ throw new ClassCastException(activity.toString() + " must implement OnArticleSelectedListener");
+ }
+ }
+ ...
+}
+
+
+If the activity has not implemented the interface, then the fragment throws a +{@link java.lang.ClassCastException}. +On success, the {@code mListener} member holds a reference to activity's implementation of +{@code OnArticleSelectedListener}, so that fragment A can share events with the activity by calling +methods defined by the {@code OnArticleSelectedListener} interface. For example, if fragment A is an +extension of {@link android.app.ListFragment}, each time +the user clicks a list item, the system calls {@link android.app.ListFragment#onListItemClick +onListItemClick()} in the fragment, which then calls {@code onArticleSelected()} to share +the event with the activity:
+ +
+public static class FragmentA extends ListFragment {
+ OnArticleSelectedListener mListener;
+ ...
+ @Override
+ public void onListItemClick(ListView l, View v, int position, long id) {
+ // Append the clicked item's row ID with the content provider Uri
+ Uri noteUri = ContentUris.{@link android.content.ContentUris#withAppendedId withAppendedId}(ArticleColumns.CONTENT_URI, id);
+ // Send the event and Uri to the host activity
+ mListener.onArticleSelected(noteUri);
+ }
+ ...
+}
+
+
+The {@code id} parameter passed to {@link +android.app.ListFragment#onListItemClick onListItemClick()} is the row ID of the clicked item, +which the activity (or other fragment) uses to fetch the article from the application's {@link +android.content.ContentProvider}.
+ +More information about +using a content provider is available in the Content Providers document.
+ + + +Your fragments can contribute menu items to the activity's Options Menu (and, consequently, the Action Bar) by implementing +{@link android.app.Fragment#onCreateOptionsMenu(Menu,MenuInflater) onCreateOptionsMenu()}. In order +for this method to receive calls, however, you must call {@link +android.app.Fragment#setHasOptionsMenu(boolean) setHasOptionsMenu()} during {@link +android.app.Fragment#onCreate(Bundle) onCreate()}, to indicate that the fragment +would like to add items to the Options Menu (otherwise, the fragment will not receive a call to +{@link android.app.Fragment#onCreateOptionsMenu onCreateOptionsMenu()}).
+ +Any items that you then add to the Options Menu from the fragment are appended to the existing +menu items. The fragment also receives callbacks to {@link +android.app.Fragment#onOptionsItemSelected(MenuItem) onOptionsItemSelected()} when a menu item +is selected.
+ +You can also register a view in your fragment layout to provide a context menu by calling {@link +android.app.Fragment#registerForContextMenu(View) registerForContextMenu()}. When the user opens +the context menu, the fragment receives a call to {@link +android.app.Fragment#onCreateContextMenu(ContextMenu,View,ContextMenu.ContextMenuInfo) +onCreateContextMenu()}. When the user selects an item, the fragment receives a call to {@link +android.app.Fragment#onContextItemSelected(MenuItem) onContextItemSelected()}.
+ +Note: Although your fragment receives an on-item-selected callback +for each menu item it adds, the activity is first to receive the respective callback when the user +selects a menu item. If the activity's implementation of the on-item-selected callback does not +handle the selected item, then the event is passed to the fragment's callback. This is true for +the Options Menu and context menus.
+ +For more information about menus, see the Menus and Action Bar developer guides.
+ + + + +
+Figure 3. The effect of the activity lifecycle on the fragment +lifecycle.
+Managing the lifecycle of a fragment is a lot like managing the lifecycle of an activity. Like +an activity, a fragment can exist in three states:
+ +Also like an activity, you can retain the state of a fragment using a {@link +android.os.Bundle}, in case the activity's process is killed and you need to restore the +fragment state when the activity is recreated. You can save the state during the fragment's {@link +android.app.Fragment#onSaveInstanceState onSaveInstanceState()} callback and restore it during +either {@link android.app.Fragment#onCreate onCreate()}, {@link +android.app.Fragment#onCreateView onCreateView()}, or {@link +android.app.Fragment#onActivityCreated onActivityCreated()}. For more information about saving +state, see the Activities +document.
+ +The most significant difference in lifecycle between an activity and a fragment is how one is +stored in its respective back stack. An activity is placed into a back stack of activities +that's managed by the system when it's stopped, by default (so that the user can navigate back +to it with the Back button, as discussed in Tasks and Back Stack). +However, a fragment is placed into a back stack managed by the host activity only when you +explicitly request that the instance be saved by calling {@link +android.app.FragmentTransaction#addToBackStack(String) addToBackStack()} during a transaction that +removes the fragment.
+ +Otherwise, managing the fragment lifecycle is very similar to managing the activity +lifecycle. So, the same practices for managing the activity +lifecycle also apply to fragments. What you also need to understand, though, is how the life +of the activity affects the life of the fragment.
+ + +The lifecycle of the activity in which the fragment lives directly affects the lifecycle of the +fragment, such that each lifecycle callback for the activity results in a similar callback for each +fragment. For example, when the activity receives {@link android.app.Activity#onPause}, each +fragment in the activity receives {@link android.app.Fragment#onPause}.
+ +Fragments have a few extra lifecycle callbacks, however, that handle unique interaction with the +activity in order to perform actions such as build and destroy the fragment's UI. These additional +callback methods are:
+ +The flow of a fragment's lifecycle, as it is affected by its host activity, is illustrated +by figure 3. In this figure, you can see how each successive state of the activity determines which +callback methods a fragment may receive. For example, when the activity has received its {@link +android.app.Activity#onCreate onCreate()} callback, a fragment in the activity receives no more than +the {@link android.app.Fragment#onActivityCreated onActivityCreated()} callback.
+ +Once the activity reaches the resumed state, you can freely add and remove fragments to the +activity. Thus, only while the activity is in the resumed state can the lifecycle of a fragment +change independently.
+ +However, when the activity leaves the resumed state, the fragment again is pushed through its +lifecycle by the activity.
+ + + + +To bring everything discussed in this document together, here's an example of an activity +using two fragments to create a two-pane layout. The activity below includes one fragment to +show a list of Shakespeare play titles and another to show a summary of the play when selected +from the list. It also demonstrates how to provide different configurations of the fragments, +based on the screen configuration.
+ +Note: The complete source code for this activity is available in +{@code +FragmentLayout.java}.
+ +The main activity applies a layout in the usual way, during {@link +android.app.Activity#onCreate onCreate()}:
+ +{@sample development/samples/ApiDemos/src/com/example/android/apis/app/FragmentLayout.java main} + +The layout applied is {@code fragment_layout.xml}:
+ +{@sample development/samples/ApiDemos/res/layout-land/fragment_layout.xml layout} + +Using this layout, the system instantiates the {@code TitlesFragment} (which lists the play +titles) as soon as the activity loads the layout, while the {@link android.widget.FrameLayout} +(where the fragment for showing the play summary will go) consumes space on the right side of the +screen, but remains empty at first. As you'll see below, it's not until the user selects an item +from the list that a fragment is placed into the {@link android.widget.FrameLayout}.
+ +However, not all screen configurations are wide enough to show both the list of +plays and the summary, side by side. So, the layout above is used only for the landscape +screen configuration, by saving it at {@code res/layout-land/fragment_layout.xml}.
+ +Thus, when the screen is in portrait orientation, the system applies the following layout, which +is saved at {@code res/layout/fragment_layout.xml}:
+ +{@sample development/samples/ApiDemos/res/layout/fragment_layout.xml layout} + +This layout includes only {@code TitlesFragment}. This means that, when the device is in +portrait orientation, only the list of play titles is visible. So, when the user clicks a list +item in this configuration, the application will start a new activity to show the summary, +instead of loading a second fragment.
+ +Next, you can see how this is accomplished in the fragment classes. First is {@code +TitlesFragment}, which shows the list of Shakespeare play titles. This fragment extends {@link +android.app.ListFragment} and relies on it to handle most of the list view work.
+ +As you inspect this code, notice that there are two possible behaviors when the user clicks a +list item: depending on which of the two layouts is active, it can either create and display a new +fragment to show the details in the same activity (adding the fragment to the {@link +android.widget.FrameLayout}), or start a new activity (where the fragment can be shown).
+ +{@sample development/samples/ApiDemos/src/com/example/android/apis/app/FragmentLayout.java titles} + +The second fragment, {@code DetailsFragment} shows the play summary for the item selected from +the list from {@code TitlesFragment}:
+ +{@sample development/samples/ApiDemos/src/com/example/android/apis/app/FragmentLayout.java details} + +Recall from the {@code TitlesFragment} class, that, if the user clicks a list item and the +current layout does not include the {@code R.id.details} view (which is where the +{@code DetailsFragment} belongs), then the application starts the {@code DetailsActivity} +activity to display the content of the item.
+ +Here is the {@code DetailsActivity}, which simply embeds the {@code DetailsFragment} to display +the selected play summary when the screen is in portrait orientation:
+ +{@sample development/samples/ApiDemos/src/com/example/android/apis/app/FragmentLayout.java +details_activity} + +Notice that this activity finishes itself if the configuration is landscape, so that the main +activity can take over and display the {@code DetailsFragment} alongside the {@code TitlesFragment}. +This can happen if the user begins the {@code DetailsActivity} while in portrait orientation, but +then rotates to landscape (which restarts the current activity).
+ + +For more samples using fragments (and complete source files for this example), +see the sample code available in +ApiDemos (available for download from the Samples SDK component).
+ + diff --git a/docs/html/guide/components/fundamentals.jd b/docs/html/guide/components/fundamentals.jd new file mode 100644 index 000000000000..1717782129b4 --- /dev/null +++ b/docs/html/guide/components/fundamentals.jd @@ -0,0 +1,518 @@ +page.title=Application Fundamentals +@jd:body + +Android applications are written in the Java programming language. The Android SDK tools compile +the code—along with any data and resource files—into an Android package, an +archive file with an {@code .apk} suffix. All the code in a single {@code .apk} file is considered +to be one application and is the file that Android-powered devices use to install the +application.
+ +Once installed on a device, each Android application lives in its own security sandbox:
+ +In this way, the Android system implements the principle of least privilege. That is, +each application, by default, has access only to the components that it requires to do its work and +no more. This creates a very secure environment in which an application cannot access parts of +the system for which it is not given permission.
+ +However, there are ways for an application to share data with other applications and for an +application to access system services:
+ +That covers the basics regarding how an Android application exists within the system. The rest of +this document introduces you to:
+Application components are the essential building blocks of an Android application. Each +component is a different point through which the system can enter your application. Not all +components are actual entry points for the user and some depend on each other, but each one exists +as its own entity and plays a specific role—each one is a unique building block that +helps define your application's overall behavior.
+ +There are four different types of application components. Each type serves a distinct purpose +and has a distinct lifecycle that defines how the component is created and destroyed.
+ +Here are the four types of application components:
+ +An activity is implemented as a subclass of {@link android.app.Activity} and you can learn more +about it in the Activities +developer guide.
+A service is implemented as a subclass of {@link android.app.Service} and you can learn more +about it in the Services developer +guide.
+Content providers are also useful for reading and writing data that is private to your +application and not shared. For example, the Note Pad sample application uses a +content provider to save notes.
+ +A content provider is implemented as a subclass of {@link android.content.ContentProvider} +and must implement a standard set of APIs that enable other applications to perform +transactions. For more information, see the Content Providers developer +guide.
+A broadcast receiver is implemented as a subclass of {@link android.content.BroadcastReceiver} +and each broadcast is delivered as an {@link android.content.Intent} object. For more information, +see the {@link android.content.BroadcastReceiver} class.
+A unique aspect of the Android system design is that any application can start another +application’s component. For example, if you want the user to capture a +photo with the device camera, there's probably another application that does that and your +application can use it, instead of developing an activity to capture a photo yourself. You don't +need to incorporate or even link to the code from the camera application. +Instead, you can simply start the activity in the camera application that captures a +photo. When complete, the photo is even returned to your application so you can use it. To the user, +it seems as if the camera is actually a part of your application.
+ +When the system starts a component, it starts the process for that application (if it's not +already running) and instantiates the classes needed for the component. For example, if your +application starts the activity in the camera application that captures a photo, that activity +runs in the process that belongs to the camera application, not in your application's process. +Therefore, unlike applications on most other systems, Android applications don't have a single entry +point (there's no {@code main()} function, for example).
+ +Because the system runs each application in a separate process with file permissions that +restrict access to other applications, your application cannot directly activate a component from +another application. The Android system, however, can. So, to activate a component in +another application, you must deliver a message to the system that specifies your intent to +start a particular component. The system then activates the component for you.
+ + +Three of the four component types—activities, services, and +broadcast receivers—are activated by an asynchronous message called an intent. +Intents bind individual components to each other at runtime (you can think of them +as the messengers that request an action from other components), whether the component belongs +to your application or another.
+ +An intent is created with an {@link android.content.Intent} object, which defines a message to +activate either a specific component or a specific type of component—an intent +can be either explicit or implicit, respectively.
+ +For activities and services, an intent defines the action to perform (for example, to "view" or +"send" something) and may specify the URI of the data to act on (among other things that the +component being started might need to know). For example, an intent might convey a request for an +activity to show an image or to open a web page. In some cases, you can start an +activity to receive a result, in which case, the activity also returns +the result in an {@link android.content.Intent} (for example, you can issue an intent to let +the user pick a personal contact and have it returned to you—the return intent includes a +URI pointing to the chosen contact).
+ +For broadcast receivers, the intent simply defines the +announcement being broadcast (for example, a broadcast to indicate the device battery is low +includes only a known action string that indicates "battery is low").
+ +The other component type, content provider, is not activated by intents. Rather, it is +activated when targeted by a request from a {@link android.content.ContentResolver}. The content +resolver handles all direct transactions with the content provider so that the component that's +performing transactions with the provider doesn't need to and instead calls methods on the {@link +android.content.ContentResolver} object. This leaves a layer of abstraction between the content +provider and the component requesting information (for security).
+ +There are separate methods for activating each type of component:
+For more information about using intents, see the Intents and +Intent Filters document. More information about activating specific components is also provided +in the following documents: Activities, Services, {@link +android.content.BroadcastReceiver} and Content Providers.
+ + +Before the Android system can start an application component, the system must know that the +component exists by reading the application's {@code AndroidManifest.xml} file (the "manifest" +file). Your application must declare all its components in this file, which must be at the root of +the application project directory.
+ +The manifest does a number of things in addition to declaring the application's components, +such as:
+The primary task of the manifest is to inform the system about the application's components. For +example, a manifest file can declare an activity as follows:
+ ++<?xml version="1.0" encoding="utf-8"?> +<manifest ... > + <application android:icon="@drawable/app_icon.png" ... > + <activity android:name="com.example.project.ExampleActivity" + android:label="@string/example_label" ... > + </activity> + ... + </application> +</manifest>+ +
In the <application>
+element, the {@code android:icon} attribute points to resources for an icon that identifies the
+application.
In the <activity> element,
+the {@code android:name} attribute specifies the fully qualified class name of the {@link
+android.app.Activity} subclass and the {@code android:label} attributes specifies a string
+to use as the user-visible label for the activity.
You must declare all application components this way:
+<activity> elements
+for activities<service> elements for
+services<receiver> elements
+for broadcast receivers<provider> elements
+for content providersActivities, services, and content providers that you include in your source but do not declare +in the manifest are not visible to the system and, consequently, can never run. However, +broadcast +receivers can be either declared in the manifest or created dynamically in code (as +{@link android.content.BroadcastReceiver} objects) and registered with the system by calling +{@link android.content.Context#registerReceiver registerReceiver()}.
+ +For more about how to structure the manifest file for your application, see the The AndroidManifest.xml File +documentation.
+ + + +As discussed above, in Activating Components, you can use an +{@link android.content.Intent} to start activities, services, and broadcast receivers. You can do so +by explicitly naming the target component (using the component class name) in the intent. However, +the real power of intents lies in the concept of intent actions. With intent actions, you simply +describe the type of action you want to perform (and optionally, the data upon which you’d like to +perform the action) and allow the system to find a component on the device that can perform the +action and start it. If there are multiple components that can perform the action described by the +intent, then the user selects which one to use.
+ +The way the system identifies the components that can respond to an intent is by comparing the +intent received to the intent filters provided in the manifest file of other applications on +the device.
+ +When you declare a component in your application's manifest, you can optionally include +intent filters that declare the capabilities of the component so it can respond to intents +from other applications. You can declare an intent filter for your component by +adding an {@code +<intent-filter>} element as a child of the component's declaration element.
+ +For example, an email application with an activity for composing a new email might declare an +intent filter in its manifest entry to respond to "send" intents (in order to send email). An +activity in your application can then create an intent with the “send” action ({@link +android.content.Intent#ACTION_SEND}), which the system matches to the email application’s “send” +activity and launches it when you invoke the intent with {@link android.app.Activity#startActivity +startActivity()}.
+ +For more about creating intent filters, see the Intents and Intent Filters document. +
+ + + +There are a variety of devices powered by Android and not all of them provide the +same features and capabilities. In order to prevent your application from being installed on devices +that lack features needed by your application, it's important that you clearly define a profile for +the types of devices your application supports by declaring device and software requirements in your +manifest file. Most of these declarations are informational only and the system does not read +them, but external services such as Google Play do read them in order to provide filtering +for users when they search for applications from their device.
+ +For example, if your application requires a camera and uses APIs introduced in Android 2.1 (API Level 7), you should declare these as +requirements in your manifest file. That way, devices that do not have a camera and have an +Android version lower than 2.1 cannot install your application from Google Play.
+ +However, you can also declare that your application uses the camera, but does not +require it. In that case, your application must perform a check at runtime to determine +if the device has a camera and disable any features that use the camera if one is not available.
+ +Here are some of the important device characteristics that you should consider as you design and +develop your application:
+ +The screen sizes are: small, normal, large, and extra large.
+The screen densities are: low density, medium density, high density, and extra high density.
By default, your application is compatible with all screen sizes and densities, +because the Android system makes the appropriate adjustments to your UI layout and image +resources. However, you should create specialized layouts for certain screen sizes and provide +specialized images for certain densities, using alternative layout resources, and by declaring in +your manifest exactly which screen sizes your application supports with the {@code +<supports-screens>} element.
+For more information, see the Supporting Multiple Screens +document.
It's important that you declare all such requirements for your application, because, when you +distribute your application on Google Play, the store uses these declarations to filter which +applications are available on each device. As such, your application should be available only to +devices that meet all your application requirements.
+ +For more information about how Google Play filters applications based on these (and other) +requirements, see the Filters on Google Play +document.
+ + + +An Android application is composed of more than just code—it requires resources that are +separate from the source code, such as images, audio files, and anything relating to the visual +presentation of the application. For example, you should define animations, menus, styles, colors, +and the layout of activity user interfaces with XML files. Using application resources makes it easy +to update various characteristics of your application without modifying code and—by providing +sets of alternative resources—enables you to optimize your application for a variety of +device configurations (such as different languages and screen sizes).
+ +For every resource that you include in your Android project, the SDK build tools define a unique +integer ID, which you can use to reference the resource from your application code or from +other resources defined in XML. For example, if your application contains an image file named {@code +logo.png} (saved in the {@code res/drawable/} directory), the SDK tools generate a resource ID +named {@code R.drawable.logo}, which you can use to reference the image and insert it in your +user interface.
+ +One of the most important aspects of providing resources separate from your source code +is the ability for you to provide alternative resources for different device +configurations. For example, by defining UI strings in XML, you can translate the strings into other +languages and save those strings in separate files. Then, based on a language qualifier +that you append to the resource directory's name (such as {@code res/values-fr/} for French string +values) and the user's language setting, the Android system applies the appropriate language strings +to your UI.
+ +Android supports many different qualifiers for your alternative resources. The +qualifier is a short string that you include in the name of your resource directories in order to +define the device configuration for which those resources should be used. As another +example, you should often create different layouts for your activities, depending on the +device's screen orientation and size. For example, when the device screen is in portrait +orientation (tall), you might want a layout with buttons to be vertical, but when the screen is in +landscape orientation (wide), the buttons should be aligned horizontally. To change the layout +depending on the orientation, you can define two different layouts and apply the appropriate +qualifier to each layout's directory name. Then, the system automatically applies the appropriate +layout depending on the current device orientation.
+ +For more about the different kinds of resources you can include in your application and how +to create alternative resources for various device configurations, see the Application Resources developer guide.
+ + + diff --git a/docs/html/guide/components/index.jd b/docs/html/guide/components/index.jd new file mode 100644 index 000000000000..87bae53bf22a --- /dev/null +++ b/docs/html/guide/components/index.jd @@ -0,0 +1,56 @@ +page.title=App Components +page.landing=true +page.landing.intro=Android's application framework lets you create extremely rich and innovative apps using a set of reusable components. This section explains how Android apps work and how you use components to build them. +page.landing.image=images/develop/app_components.png + +@jd:body + +In this post, I’ll show how to use DialogFragments with the v4 support library (for backward compatibility on pre-Honeycomb devices) to show a simple edit dialog and return a result to the calling Activity using an interface.
+ + + +Today we’ve released a static library that exposes the same Fragments API (as well as the new LoaderManager and a few other classes) so that applications compatible with Android 1.6 or later can use fragments to create tablet-compatible user interfaces.
+ + + +A good practice in creating responsive applications is to make sure your main UI thread +does the minimum amount of work. Any potentially long task that may hang your application should be +handled in a different thread.
+ +This class explains important lifecycle callback methods that each Activity + instance receives and how you can use them so your activity does what the user expects and does not consume system + resources when your activity doesn't need them.
+ + + +This class shows you how to create a dynamic user experience with fragments and optimize +your app's user experience for devices with different screen sizes, all while continuing to support +devices running versions as old as Android 1.6.
+ + + +This class covers some common ways you can send and receive content between + applications using Intent APIs and the ActionProvider object.
+ ++Three of the core components of an application — activities, services, and +broadcast receivers — are activated through messages, called intents. +Intent messaging is a facility for late run-time binding between components in the same +or different applications. The intent itself, an {@link android.content.Intent} +object, is a passive data structure holding an abstract description of an operation +to be performed — or, often in the case of broadcasts, a description of something +that has happened and is being announced. There are separate mechanisms for +delivering intents to each type of component: +
+ +{@link android.content.Context#startActivity
+Context.startActivity()} or {@link android.app.Activity#startActivityForResult
+Activity.startActivityForResult()} to launch an activity or get an existing
+activity to do something new. (It can also be passed to
+{@link android.app.Activity#setResult(int, Intent) Activity.setResult()}
+to return information to the activity that called {@code startActivityForResult()}.)An Intent object is passed to {@link android.content.Context#startService
+Context.startService()} to initiate a service or deliver new instructions to an
+ongoing service. Similarly, an intent can be passed to {@link
+android.content.Context#bindService Context.bindService()} to establish a
+connection between the calling component and a target service. It can optionally
+initiate the service if it's not already running.
Intent objects passed to any of the broadcast methods (such as {@link
+android.content.Context#sendBroadcast(Intent) Context.sendBroadcast()},
+{@link android.content.Context#sendOrderedBroadcast(Intent, String)
+Context.sendOrderedBroadcast()}, or {@link
+android.content.Context#sendStickyBroadcast Context.sendStickyBroadcast()})
+are delivered to all interested broadcast receivers. Many kinds of broadcasts
+originate in system code.
+In each case, the Android system finds the appropriate activity, service, or set +of broadcast receivers to respond to the intent, instantiating them if necessary. +There is no overlap within these messaging systems: Broadcast intents are delivered +only to broadcast receivers, never to activities or services. An intent passed to +{@code startActivity()} is delivered only to an activity, never to a service or +broadcast receiver, and so on. +
+ ++This document begins with a description of Intent objects. It then describes the +rules Android uses to map intents to components — how it resolves which +component should receive an intent message. For intents that don't explicitly +name a target component, this process involves testing the Intent object against +intent filters associated with potential targets. +
+ + ++An {@link android.content.Intent} object is a bundle of information. It +contains information of interest to the component that receives the intent +(such as the action to be taken and the data to act on) plus information +of interest to the Android system (such as the category of component that +should handle the intent and instructions on how to launch a target activity). +Principally, it can contain the following: +
+ ++The component name is optional. If it is set, the Intent object is +delivered to an instance of the designated class. If it is not set, +Android uses other information in the Intent object to locate a suitable +target — see Intent Resolution, later in this +document. +
+ +
+The component name is set by {@link android.content.Intent#setComponent
+setComponent()}, {@link android.content.Intent#setClass
+setClass()}, or {@link android.content.Intent#setClassName(String, String)
+setClassName()} and read by {@link android.content.Intent#getComponent
+getComponent()}.
+
| Constant | +Target component | +Action | +
|---|---|---|
| {@code ACTION_CALL} + | activity + | Initiate a phone call. + |
| {@code ACTION_EDIT} + | activity + | Display data for the user to edit. + |
| {@code ACTION_MAIN} + | activity + | Start up as the initial activity of a task, with no data input and no returned output. + |
| {@code ACTION_SYNC} + | activity + | Synchronize data on a server with data on the mobile device. + |
| {@code ACTION_BATTERY_LOW} + | broadcast receiver + | A warning that the battery is low. + |
| {@code ACTION_HEADSET_PLUG} + | broadcast receiver + | A headset has been plugged into the device, or unplugged from it. + |
| {@code ACTION_SCREEN_ON} + | broadcast receiver + | The screen has been turned on. + |
| {@code ACTION_TIMEZONE_CHANGED} + | broadcast receiver + | The setting for the time zone has changed. + |
+See the {@link android.content.Intent} class description for a list of
+pre-defined constants for generic actions. Other actions are defined
+elsewhere in the Android API.
+You can also define your own action strings for activating the components
+in your application. Those you invent should include the application
+package as a prefix — for example:
+"com.example.project.SHOW_COLOR".
+
+The action largely determines how the rest of the intent is structured +— particularly the data and +extras fields — +much as a method name determines a set of arguments and a return value. +For this reason, it's a good idea to use action names that are +as specific as possible, and to couple them tightly to the other fields of +the intent. In other words, instead of defining an action in isolation, +define an entire protocol for the Intent objects your components can handle. +
+ +
+The action in an Intent object is set by the
+{@link android.content.Intent#setAction setAction()}
+method and read by
+{@link android.content.Intent#getAction getAction()}.
+
+When matching an intent to a component that is capable of handling the data, +it's often important to know the type of data (its MIME type) in addition to its URI. +For example, a component able to display image data should not be called +upon to play an audio file. +
+ +
+In many cases, the data type can be inferred from the URI — particularly
+{@code content:} URIs, which indicate that the data is located on the device and
+controlled by a content provider (see the
+separate
+discussion on content providers). But the type can also be explicitly set
+in the Intent object.
+The {@link android.content.Intent#setData setData()} method specifies
+data only as a URI, {@link android.content.Intent#setType setType()}
+specifies it only as a MIME type, and {@link
+android.content.Intent#setDataAndType setDataAndType()} specifies it as both
+a URI and a MIME type. The URI is read by {@link
+android.content.Intent#getData getData()} and the type by {@link
+android.content.Intent#getType getType()}.
+
| Constant | +Meaning | +
|---|---|
| {@code CATEGORY_BROWSABLE} + | The target activity can be safely invoked by the browser to display data + referenced by a link — for example, an image or an e-mail message. + |
| {@code CATEGORY_GADGET} + | The activity can be embedded inside of another activity that hosts gadgets. + |
| {@code CATEGORY_HOME} + | The activity displays the home screen, the first screen the user sees when + the device is turned on or when the Home button is pressed. + |
| {@code CATEGORY_LAUNCHER} + | The activity can be the initial activity of a task and is listed in + the top-level application launcher. + |
| {@code CATEGORY_PREFERENCE} + | The target activity is a preference panel. + |
+See the {@link android.content.Intent} class description for the full list of +categories. +
+ +
+The {@link android.content.Intent#addCategory addCategory()} method
+places a category in an Intent object, {@link android.content.Intent#removeCategory
+removeCategory()} deletes a category previously added, and {@link android.content.Intent#getCategories getCategories()} gets the set of all
+categories currently in the object.
+
+The Intent object has a series of {@code put...()} methods for inserting various
+types of extra data and a similar set of {@code get...()} methods for reading
+the data. These methods parallel those for {@link android.os.Bundle} objects.
+In fact, the extras can be installed and read as a Bundle using the {@link
+android.content.Intent#putExtras putExtras()} and {@link
+android.content.Intent#getExtras getExtras()} methods.
+
+The Android system and the applications that come with the platform employ +Intent objects both to send out system-originated broadcasts and to activate +system-defined components. To see how to structure an intent to activate a +system component, consult the +list of intents +in the reference. +
+ + ++Intents can be divided into two groups: +
+ +Implicit intents do not name a target (the field for +the component name is blank). Implicit intents are often used to +activate components in other applications.
+Android delivers an explicit intent to an instance of the designated +target class. Nothing in the Intent object other than the component +name matters for determining which component should get the intent. +
+ ++A different strategy is needed for implicit intents. In the absence of a +designated target, the Android system must find the best component (or +components) to handle the intent — a single activity or service to +perform the requested action or the set of broadcast receivers to respond +to the broadcast announcement. It does so by comparing the contents of +the Intent object to intent filters, structures associated with +components that can potentially receive intents. Filters advertise the +capabilities of a component and delimit the intents it can handle. They +open the component to the possibility of receiving implicit intents of +the advertised type. If a component does not have any intent filters, +it can receive only explicit intents. A component with filters can +receive both explicit and implicit intents. +
+ ++Only three aspects of an Intent object are consulted when the object +is tested against an intent filter: +
+ +action
+
data (both URI and data type)
+
category
+The extras and flags play no part in resolving which component receives +an intent. +
+ + ++To inform the system which implicit intents they can handle, activities, +services, and broadcast receivers can have one or more intent filters. +Each filter describes a capability of the component, a set of intents that +the component is willing to receive. It, in effect, filters in +intents of a desired type, while filtering out unwanted +intents — but only unwanted implicit intents (those that don't name +a target class). An explicit intent is always delivered to its target, +no matter what it contains; the filter is not consulted. But an implicit +intent is delivered to a component only if it can pass through one of the +component's filters. +
+ ++A component has separate filters for each job it can do, each face it can +present to the user. For example, the NoteEditor activity of the sample +Note Pad application has two filters — one for starting up with a +specific note that the user can view or edit, and another for starting +with a new, blank note that the user can fill in and save. (All of Note +Pad's filters are described in the Note Pad Example +section, later.) +
+ +An intent filter cannot be relied on for security. While it opens a +component to receiving only certain kinds of implicit intents, it does +nothing to prevent explicit intents from targeting the component. Even +though a filter restricts the intents a component will be asked to handle +to certain actions and data sources, someone could always put +together an explicit intent with a different action and data source, and +name the component as the target. +
+
+An intent filter is an instance of the {@link android.content.IntentFilter} class.
+However, since the Android system must know about the capabilities of a component
+before it can launch that component, intent filters are generally not set up in
+Java code, but in the application's manifest file (AndroidManifest.xml) as
+<intent-filter>
+elements. (The one exception would be filters for
+broadcast receivers that are registered dynamically by calling {@link android.content.Context#registerReceiver(BroadcastReceiver, IntentFilter, String,
+Handler) Context.registerReceiver()}; they are directly created as
+IntentFilter objects.)
+
+A filter has fields that parallel the action, data, and category fields of an +Intent object. An implicit intent is tested against the filter in all three areas. +To be delivered to the component that owns the filter, it must pass all three tests. +If it fails even one of them, the Android system won't deliver it to the +component — at least not on the basis of that filter. However, since a +component can have multiple intent filters, an intent that does not pass +through one of a component's filters might make it through on another. +
+ ++Each of the three tests is described in detail below: +
+ +<intent-filter>
+element in the manifest file lists actions as
+<action>
+subelements. For example:
+
+<intent-filter . . . > + <action android:name="com.example.project.SHOW_CURRENT" /> + <action android:name="com.example.project.SHOW_RECENT" /> + <action android:name="com.example.project.SHOW_PENDING" /> + . . . +</intent-filter>+ +
+As the example shows, while an Intent object names just a single action, +a filter may list more than one. The list cannot be empty; a filter must +contain at least one {@code <action>} element, or it +will block all intents. +
+ ++To pass this test, the action specified in the Intent object must match +one of the actions listed in the filter. If the object or the filter +does not specify an action, the results are as follows: +
+ +On the other hand, an Intent object that doesn't specify an +action automatically passes the test — as long as the filter +contains at least one action.
<intent-filter>
+element also lists categories as subelements. For example:
+
+<intent-filter . . . > + <category android:name="android.intent.category.DEFAULT" /> + <category android:name="android.intent.category.BROWSABLE" /> + . . . +</intent-filter>+ +
+Note that the constants described earlier for actions and categories are not +used in the manifest file. The full string values are used instead. For +instance, the "{@code android.intent.category.BROWSABLE}" string in the example +above corresponds to the {@code CATEGORY_BROWSABLE} constant mentioned earlier +in this document. Similarly, the string "{@code android.intent.action.EDIT}" +corresponds to the {@code ACTION_EDIT} constant. +
+ ++For an intent to pass the category test, every category in the Intent object +must match a category in the filter. The filter can list additional categories, +but it cannot omit any that are in the intent. +
+ ++In principle, therefore, an Intent object with no categories should always pass +this test, regardless of what's in the filter. That's mostly true. However, +with one exception, Android treats all implicit intents passed to {@link +android.content.Context#startActivity startActivity()} as if they contained +at least one category: "{@code android.intent.category.DEFAULT}" (the +{@code CATEGORY_DEFAULT} constant). +Therefore, activities that are willing to receive implicit intents must +include "{@code android.intent.category.DEFAULT}" in their intent filters. +(Filters with "{@code android.intent.action.MAIN}" and +"{@code android.intent.category.LAUNCHER}" settings are the exception. +They mark activities that begin new tasks and that are represented on the +launcher screen. They can include "{@code android.intent.category.DEFAULT}" +in the list of categories, but don't need to.) See Using +intent matching, later, for more on these filters.) +
+<intent-filter . . . > + <data android:mimeType="video/mpeg" android:scheme="http" . . . /> + <data android:mimeType="audio/mpeg" android:scheme="http" . . . /> + . . . +</intent-filter>+ +
+Each
+<data>
+element can specify a URI and a data type (MIME media type). There are separate
+attributes — {@code scheme}, {@code host}, {@code port},
+and {@code path} — for each part of the URI:
+
{@code scheme://host:port/path}
+ ++For example, in the following URI, +
+ +{@code content://com.example.project:200/folder/subfolder/etc}
+ +the scheme is "{@code content}", the host is "{@code com.example.project}", +the port is "{@code 200}", and the path is "{@code folder/subfolder/etc}". +The host and port together constitute the URI authority; if a host is +not specified, the port is ignored. +
+ ++Each of these attributes is optional, but they are not independent of each other: +For an authority to be meaningful, a scheme must also be specified. +For a path to be meaningful, both a scheme and an authority must be specified. +
+ ++When the URI in an Intent object is compared to a URI specification in a filter, +it's compared only to the parts of the URI actually mentioned in the filter. +For example, if a filter specifies only a scheme, all URIs with that scheme match +the filter. If a filter specifies a scheme and an authority but no path, all URIs +with the same scheme and authority match, regardless of their paths. If a filter +specifies a scheme, an authority, and a path, only URIs with the same scheme, +authority, and path match. However, a path specification in the filter can +contain wildcards to require only a partial match of the path. +
+ ++The {@code type} attribute of a {@code <data>} element specifies the MIME type +of the data. It's more common in filters than a URI. Both the Intent object and +the filter can use a "*" wildcard for the subtype field — for example, +"{@code text/*}" or "{@code audio/*}" — indicating any subtype matches. +
+ ++The data test compares both the URI and the data type in the Intent object to a URI +and data type specified in the filter. The rules are as follows: +
+ +An Intent object that contains a URI but no data type (and a type cannot +be inferred from the URI) passes the test only if its URI matches a URI in the +filter and the filter likewise does not specify a type. This will be the case +only for URIs like {@code mailto:} and {@code tel:} that do not refer to actual data.
An Intent object that contains a data type but not a URI passes the test +only if the filter lists the same data type and similarly does not specify a URI.
An Intent object that contains both a URI and a data type (or a data type +can be inferred from the URI) passes the data type part of the test only if its +type matches a type listed in the filter. It passes the URI part of the test +either if its URI matches a URI in the filter or if it has a {@code content:} +or {@code file:} URI and the filter does not specify a URI. In other words, +a component is presumed to support {@code content:} and {@code file:} data if +its filter lists only a data type.
+If an intent can pass through the filters of more than one activity or service, +the user may be asked which component to activate. An exception is raised if +no target can be found. +
+ + ++The last rule shown above for the data test, rule (d), reflects the expectation +that components are able to get local data from a file or content provider. +Therefore, their filters can list just a data type and do not need to explicitly +name the {@code content:} and {@code file:} schemes. +This is a typical case. A {@code <data>} element like the following, +for example, tells Android that the component can get image data from a content +provider and display it: +
+ +<data android:mimeType="image/*" />+ +
+Since most available data is dispensed by content providers, filters that +specify a data type but not a URI are perhaps the most common. +
+ ++Another common configuration is filters with a scheme and a data type. For +example, a {@code <data>} element like the following tells Android that +the component can get video data from the network and display it: +
+ +<data android:scheme="http" android:type="video/*" />+ +
+Consider, for example, what the browser application does when +the user follows a link on a web page. It first tries to display the data +(as it could if the link was to an HTML page). If it can't display the data, +it puts together an implicit intent with the scheme and data type and tries +to start an activity that can do the job. If there are no takers, it asks the +download manager to download the data. That puts it under the control +of a content provider, so a potentially larger pool of activities +(those with filters that just name a data type) can respond. +
+ ++Most applications also have a way to start fresh, without a reference +to any particular data. Activities that can initiate applications +have filters with "{@code android.intent.action.MAIN}" specified as +the action. If they are to be represented in the application launcher, +they also specify the "{@code android.intent.category.LAUNCHER}" +category: +
+ +<intent-filter . . . > + <action android:name="code android.intent.action.MAIN" /> + <category android:name="code android.intent.category.LAUNCHER" /> +</intent-filter>+ + +
+Intents are matched against intent filters not only to discover a target +component to activate, but also to discover something about the set of +components on the device. For example, the Android system populates the +application launcher, the top-level screen that shows the applications +that are available for the user to launch, by finding all the activities + with intent filters that specify the "{@code android.intent.action.MAIN}" +action and "{@code android.intent.category.LAUNCHER}" category +(as illustrated in the previous section). It then displays the icons and +labels of those activities in the launcher. Similarly, it discovers the +home screen by looking for the activity with +"{@code android.intent.category.HOME}" in its filter. +
+ ++Your application can use intent matching is a similar way. +The {@link android.content.pm.PackageManager} has a set of {@code query...()} +methods that return all components that can accept a particular intent, and +a similar series of {@code resolve...()} methods that determine the best +component to respond to an intent. For example, +{@link android.content.pm.PackageManager#queryIntentActivities +queryIntentActivities()} returns a list of all activities that can perform +the intent passed as an argument, and {@link +android.content.pm.PackageManager#queryIntentServices +queryIntentServices()} returns a similar list of services. +Neither method activates the components; they just list the ones that +can respond. There's a similar method, +{@link android.content.pm.PackageManager#queryBroadcastReceivers +queryBroadcastReceivers()}, for broadcast receivers. +
+ ++The Note Pad sample application enables users to browse through a list +of notes, view details about individual items in the list, edit the items, +and add a new item to the list. This section looks at the intent filters +declared in its manifest file. (If you're working offline in the SDK, you +can find all the source files for this sample application, including its +manifest file, at {@code <sdk>/samples/NotePad/index.html}. +If you're viewing the documentation online, the source files are in the +Tutorials and Sample Code +section here.) +
+ ++In its manifest file, the Note Pad application declares three activities, +each with at least one intent filter. It also declares a content provider +that manages the note data. Here is the manifest file in its entirety: +
+ +<manifest xmlns:android="http://schemas.android.com/apk/res/android" + package="com.example.android.notepad"> + <application android:icon="@drawable/app_notes" + android:label="@string/app_name" > + + <provider android:name="NotePadProvider" + android:authorities="com.google.provider.NotePad" /> + + <activity android:name="NotesList" android:label="@string/title_notes_list"> + <intent-filter> + <action android:name="android.intent.action.MAIN" /> + <category android:name="android.intent.category.LAUNCHER" /> + </intent-filter> + <intent-filter> + <action android:name="android.intent.action.VIEW" /> + <action android:name="android.intent.action.EDIT" /> + <action android:name="android.intent.action.PICK" /> + <category android:name="android.intent.category.DEFAULT" /> + <data android:mimeType="vnd.android.cursor.dir/vnd.google.note" /> + </intent-filter> + <intent-filter> + <action android:name="android.intent.action.GET_CONTENT" /> + <category android:name="android.intent.category.DEFAULT" /> + <data android:mimeType="vnd.android.cursor.item/vnd.google.note" /> + </intent-filter> + </activity> + + <activity android:name="NoteEditor" + android:theme="@android:style/Theme.Light" + android:label="@string/title_note" > + <intent-filter android:label="@string/resolve_edit"> + <action android:name="android.intent.action.VIEW" /> + <action android:name="android.intent.action.EDIT" /> + <action android:name="com.android.notepad.action.EDIT_NOTE" /> + <category android:name="android.intent.category.DEFAULT" /> + <data android:mimeType="vnd.android.cursor.item/vnd.google.note" /> + </intent-filter> + <intent-filter> + <action android:name="android.intent.action.INSERT" /> + <category android:name="android.intent.category.DEFAULT" /> + <data android:mimeType="vnd.android.cursor.dir/vnd.google.note" /> + </intent-filter> + </activity> + + <activity android:name="TitleEditor" + android:label="@string/title_edit_title" + android:theme="@android:style/Theme.Dialog"> + <intent-filter android:label="@string/resolve_title"> + <action android:name="com.android.notepad.action.EDIT_TITLE" /> + <category android:name="android.intent.category.DEFAULT" /> + <category android:name="android.intent.category.ALTERNATIVE" /> + <category android:name="android.intent.category.SELECTED_ALTERNATIVE" /> + <data android:mimeType="vnd.android.cursor.item/vnd.google.note" /> + </intent-filter> + </activity> + + </application> +</manifest>+ +
+The first activity, NotesList, is +distinguished from the other activities by the fact that it operates +on a directory of notes (the note list) rather than on a single note. +It would generally serve as the initial user interface into the +application. It can do three things as described by its three intent +filters: +
+ +<intent-filter> + <action android:name="android.intent.action.MAIN" /> + <category android:name="android.intent.category.LAUNCHER" /> +</intent-filter>+ +
+This filter declares the main entry point into the Note Pad application. +The standard {@code MAIN} action is an entry point that does not require +any other information in the Intent (no data specification, for example), +and the {@code LAUNCHER} category says that this entry point should be +listed in the application launcher. +
<intent-filter> + <action android:name="android.intent.action.VIEW" /> + <action android:name="android.intent.action.EDIT" /> + <action android:name="android.intent.action.PICK" /> + <category android:name="android.intent.category.DEFAULT" /> + <data android:mimeType="vnd.android.cursor.dir/vnd.google.note" /> +</intent-filter>+ +
+This filter declares the things that the activity can do on a directory +of notes. It can allow the user to view or edit the directory (via +the {@code VIEW} and {@code EDIT} actions), or to pick a particular note +from the directory (via the {@code PICK} action). +
+ +
+The {@code mimeType} attribute of the
+<data>
+element specifies the kind of data that these actions operate on. It
+indicates that the activity can get a Cursor over zero or more items
+({@code vnd.android.cursor.dir}) from a content provider that holds
+Note Pad data ({@code vnd.google.note}). The Intent object that launches
+the activity would include a {@code content:} URI specifying the exact
+data of this type that the activity should open.
+
+Note also the {@code DEFAULT} category supplied in this filter. It's
+there because the {@link android.content.Context#startActivity
+Context.startActivity()} and
+{@link android.app.Activity#startActivityForResult
+Activity.startActivityForResult()} methods treat all intents
+as if they contained the {@code DEFAULT} category — with just
+two exceptions:
+
+Therefore, the {@code DEFAULT} category is required for all +filters — except for those with the {@code MAIN} action and +{@code LAUNCHER} category. (Intent filters are not consulted for +explicit intents.) +
<intent-filter> + <action android:name="android.intent.action.GET_CONTENT" /> + <category android:name="android.intent.category.DEFAULT" /> + <data android:mimeType="vnd.android.cursor.item/vnd.google.note" /> +</intent-filter>+ +
+This filter describes the activity's ability to return a note selected by
+the user without requiring any specification of the directory the user should
+choose from. The {@code GET_CONTENT} action is similar to the {@code PICK}
+action. In both cases, the activity returns the URI for a note selected by
+the user. (In each case, it's returned to the activity that called
+{@link android.app.Activity#startActivityForResult
+startActivityForResult()} to start the NoteList activity.) Here,
+however, the caller specifies the type of data desired instead of the
+directory of data the user will be picking from.
+
+The data type, vnd.android.cursor.item/vnd.google.note,
+indicates the type of data the activity can return — a URI for
+a single note. From the returned URI, the caller can get a Cursor for
+exactly one item ({@code vnd.android.cursor.item}) from the content
+provider that holds Note Pad data ({@code vnd.google.note}).
+
+In other words, for the {@code PICK} action in the previous filter, +the data type indicates the type of data the activity could display to the +user. For the {@code GET_CONTENT} filter, it indicates the type of data +the activity can return to the caller. +
+Given these capabilities, the following intents will resolve to the +NotesList activity: +
+ +android.intent.action.MAINandroid.intent.action.MAIN
+android.intent.category.LAUNCHERandroid.intent.action.VIEW
+content://com.google.provider.NotePad/notescontent://com.google.provider.NotePad/notes. The user can then
+browse through the list and get information about the items in it.android.intent.action.PICK
+content://com.google.provider.NotePad/notescontent://com.google.provider.NotePad/notes.
+The user can then pick a note from the list, and the activity will return
+the URI for that item back to the activity that started the NoteList activity.android.intent.action.GET_CONTENT
+vnd.android.cursor.item/vnd.google.note+The second activity, NoteEditor, shows +users a single note entry and allows them to edit it. It can do two things +as described by its two intent filters: + +
<intent-filter android:label="@string/resolve_edit"> + <action android:name="android.intent.action.VIEW" /> + <action android:name="android.intent.action.EDIT" /> + <action android:name="com.android.notepad.action.EDIT_NOTE" /> + <category android:name="android.intent.category.DEFAULT" /> + <data android:mimeType="vnd.android.cursor.item/vnd.google.note" /> +</intent-filter>+ +
+The first, primary, purpose of this activity is to enable the user to
+interact with a single note — to either {@code VIEW} the note or
+{@code EDIT} it. (The {@code EDIT_NOTE} category is a synonym for
+{@code EDIT}.) The intent would contain the URI for data matching the
+MIME type vnd.android.cursor.item/vnd.google.note —
+that is, the URI for a single, specific note. It would typically be a
+URI that was returned by the {@code PICK} or {@code GET_CONTENT}
+actions of the NoteList activity.
+
+As before, this filter lists the {@code DEFAULT} category so that the +activity can be launched by intents that don't explicitly specify the +NoteEditor class. +
<intent-filter> + <action android:name="android.intent.action.INSERT" /> + <category android:name="android.intent.category.DEFAULT" /> + <data android:mimeType="vnd.android.cursor.dir/vnd.google.note" /> +</intent-filter>+ +
+The secondary purpose of this activity is to enable the user to create a new
+note, which it will {@code INSERT} into an existing directory of notes. The
+intent would contain the URI for data matching the MIME type
+vnd.android.cursor.dir/vnd.google.note — that
+is, the URI for the directory where the note should be placed.
+
+Given these capabilities, the following intents will resolve to the +NoteEditor activity: +
+ +android.intent.action.VIEW
+content://com.google.provider.NotePad/notes/IDandroid.intent.action.EDIT
+content://com.google.provider.NotePad/notes/IDandroid.intent.action.INSERT
+content://com.google.provider.NotePad/notescontent://com.google.provider.NotePad/notes
+and allow the user to edit it. If the user saves the note, its URI
+is returned to the caller.
+The last activity, TitleEditor, +enables the user to edit the title of a note. This could be implemented +by directly invoking the activity (by explicitly setting its component +name in the Intent), without using an intent filter. But here we take +the opportunity to show how to publish alternative operations on existing +data: +
+ +<intent-filter android:label="@string/resolve_title"> + <action android:name="com.android.notepad.action.EDIT_TITLE" /> + <category android:name="android.intent.category.DEFAULT" /> + <category android:name="android.intent.category.ALTERNATIVE" /> + <category android:name="android.intent.category.SELECTED_ALTERNATIVE" /> + <data android:mimeType="vnd.android.cursor.item/vnd.google.note" /> +</intent-filter>+ +
+The single intent filter for this activity uses a custom action called
+"com.android.notepad.action.EDIT_TITLE". It must be invoked on
+a specific note (data type vnd.android.cursor.item/vnd.google.note),
+like the previous {@code VIEW} and {@code EDIT} actions. However, here the
+activity displays the title contained in the note data, not the content of
+the note itself.
+
+In addition to supporting the usual {@code DEFAULT} category, the title
+editor also supports two other standard categories:
+{@link android.content.Intent#CATEGORY_ALTERNATIVE ALTERNATIVE}
+and {@link android.content.Intent#CATEGORY_SELECTED_ALTERNATIVE
+SELECTED_ALTERNATIVE}.
+These categories identify activities that can be presented to users in
+a menu of options (much as the {@code LAUNCHER} category identifies
+activities that should be presented to user in the application launcher).
+Note that the filter also supplies an explicit label (via
+android:label="@string/resolve_title") to better control
+what users see when presented with this activity as an alternative
+action to the data they are currently viewing. (For more information
+on these categories and building options menus, see the
+{@link android.content.pm.PackageManager#queryIntentActivityOptions
+PackageManager.queryIntentActivityOptions()} and
+{@link android.view.Menu#addIntentOptions Menu.addIntentOptions()}
+methods.)
+
+Given these capabilities, the following intent will resolve to the +TitleEditor activity: +
+ +com.android.notepad.action.EDIT_TITLE
+content://com.google.provider.NotePad/notes/IDIntroduced in Android 3.0, loaders make it easy to asynchronously load data +in an activity or fragment. Loaders have these characteristics:
+There are multiple classes and interfaces that may be involved in using +loaders in an application. They are summarized in this table:
+ +| Class/Interface | +Description | +
|---|---|
| {@link android.app.LoaderManager} | +An abstract class associated with an {@link android.app.Activity} or
+{@link android.app.Fragment} for managing one or more {@link
+android.content.Loader} instances. This helps an application manage
+longer-running operations in conjunction with the {@link android.app.Activity}
+or {@link android.app.Fragment} lifecycle; the most common use of this is with a
+{@link android.content.CursorLoader}, however applications are free to write
+their own loaders for loading other types of data.
+ + + There is only one {@link android.app.LoaderManager} per activity or fragment. But a {@link android.app.LoaderManager} can have +multiple loaders. |
+
| {@link android.app.LoaderManager.LoaderCallbacks} | +A callback interface for a client to interact with the {@link +android.app.LoaderManager}. For example, you use the {@link +android.app.LoaderManager.LoaderCallbacks#onCreateLoader onCreateLoader()} +callback method to create a new loader. | +
| {@link android.content.Loader} | +An abstract class that performs asynchronous loading of data. This is +the base class for a loader. You would typically use {@link +android.content.CursorLoader}, but you can implement your own subclass. While +loaders are active they should monitor the source of their data and deliver new +results when the contents change. | +
| {@link android.content.AsyncTaskLoader} | +Abstract loader that provides an {@link android.os.AsyncTask} to do the work. | +
| {@link android.content.CursorLoader} | +A subclass of {@link android.content.AsyncTaskLoader} that queries the +{@link android.content.ContentResolver} and returns a {@link +android.database.Cursor}. This class implements the {@link +android.content.Loader} protocol in a standard way for querying cursors, +building on {@link android.content.AsyncTaskLoader} to perform the cursor query +on a background thread so that it does not block the application's UI. Using +this loader is the best way to asynchronously load data from a {@link +android.content.ContentProvider}, instead of performing a managed query through +the fragment or activity's APIs. | +
The classes and interfaces in the above table are the essential components +you'll use to implement a loader in your application. You won't need all of them +for each loader you create, but you'll always need a reference to the {@link +android.app.LoaderManager} in order to initialize a loader and an implementation +of a {@link android.content.Loader} class such as {@link +android.content.CursorLoader}. The following sections show you how to use these +classes and interfaces in an application.
+ +This section describes how to use loaders in an Android application. An +application that uses loaders typically includes the following:
+The {@link android.app.LoaderManager} manages one or more {@link +android.content.Loader} instances within an {@link android.app.Activity} or +{@link android.app.Fragment}. There is only one {@link +android.app.LoaderManager} per activity or fragment.
+ +You typically +initialize a {@link android.content.Loader} within the activity's {@link +android.app.Activity#onCreate onCreate()} method, or within the fragment's +{@link android.app.Fragment#onActivityCreated onActivityCreated()} method. You +do this as follows:
+ +// Prepare the loader. Either re-connect with an existing one, +// or start a new one. +getLoaderManager().initLoader(0, null, this);+ +
The {@link android.app.LoaderManager#initLoader initLoader()} method takes +the following parameters:
+null in this example).The {@link android.app.LoaderManager#initLoader initLoader()} call ensures that a loader +is initialized and active. It has two possible outcomes:
+In either case, the given {@link android.app.LoaderManager.LoaderCallbacks} +implementation is associated with the loader, and will be called when the +loader state changes. If at the point of this call the caller is in its +started state, and the requested loader already exists and has generated its +data, then the system calls {@link +android.app.LoaderManager.LoaderCallbacks#onLoadFinished onLoadFinished()} +immediately (during {@link android.app.LoaderManager#initLoader initLoader()}), +so you must be prepared for this to happen. See +onLoadFinished for more discussion of this callback
+ +Note that the {@link android.app.LoaderManager#initLoader initLoader()} +method returns the {@link android.content.Loader} that is created, but you don't +need to capture a reference to it. The {@link android.app.LoaderManager} manages +the life of the loader automatically. The {@link android.app.LoaderManager} +starts and stops loading when necessary, and maintains the state of the loader +and its associated content. As this implies, you rarely interact with loaders +directly (though for an example of using loader methods to fine-tune a loader's +behavior, see the LoaderThrottle sample). +You most commonly use the {@link +android.app.LoaderManager.LoaderCallbacks} methods to intervene in the loading +process when particular events occur. For more discussion of this topic, see Using the LoaderManager Callbacks.
+ +When you use {@link android.app.LoaderManager#initLoader initLoader()}, as +shown above, it uses an existing loader with the specified ID if there is one. +If there isn't, it creates one. But sometimes you want to discard your old data +and start over.
+ +To discard your old data, you use {@link +android.app.LoaderManager#restartLoader restartLoader()}. For example, this +implementation of {@link android.widget.SearchView.OnQueryTextListener} restarts +the loader when the user's query changes. The loader needs to be restarted so +that it can use the revised search filter to do a new query:
+ +
+public boolean onQueryTextChanged(String newText) {
+ // Called when the action bar search text has changed. Update
+ // the search filter, and restart the loader to do a new query
+ // with this filter.
+ mCurFilter = !TextUtils.isEmpty(newText) ? newText : null;
+ getLoaderManager().restartLoader(0, null, this);
+ return true;
+}
+
+{@link android.app.LoaderManager.LoaderCallbacks} is a callback interface +that lets a client interact with the {@link android.app.LoaderManager}.
+Loaders, in particular {@link android.content.CursorLoader}, are expected to +retain their data after being stopped. This allows applications to keep their +data across the activity or fragment's {@link android.app.Activity#onStop +onStop()} and {@link android.app.Activity#onStart onStart()} methods, so that +when users return to an application, they don't have to wait for the data to +reload. You use the {@link android.app.LoaderManager.LoaderCallbacks} methods +when to know when to create a new loader, and to tell the application when it is + time to stop using a loader's data.
+ +{@link android.app.LoaderManager.LoaderCallbacks} includes these +methods:
+These methods are described in more detail in the following sections.
+ +When you attempt to access a loader (for example, through {@link +android.app.LoaderManager#initLoader initLoader()}), it checks to see whether +the loader specified by the ID exists. If it doesn't, it triggers the {@link +android.app.LoaderManager.LoaderCallbacks} method {@link +android.app.LoaderManager.LoaderCallbacks#onCreateLoader onCreateLoader()}. This +is where you create a new loader. Typically this will be a {@link +android.content.CursorLoader}, but you can implement your own {@link +android.content.Loader} subclass.
+ +In this example, the {@link +android.app.LoaderManager.LoaderCallbacks#onCreateLoader onCreateLoader()} +callback method creates a {@link android.content.CursorLoader}. You must build +the {@link android.content.CursorLoader} using its constructor method, which +requires the complete set of information needed to perform a query to the {@link +android.content.ContentProvider}. Specifically, it needs:
+null will return all columns, which is inefficient. null will return all rows for the given URI. null will
+use the default sort order, which may be unordered.For example:
+
+ // If non-null, this is the current filter the user has provided.
+String mCurFilter;
+...
+public Loader<Cursor> onCreateLoader(int id, Bundle args) {
+ // This is called when a new Loader needs to be created. This
+ // sample only has one Loader, so we don't care about the ID.
+ // First, pick the base URI to use depending on whether we are
+ // currently filtering.
+ Uri baseUri;
+ if (mCurFilter != null) {
+ baseUri = Uri.withAppendedPath(Contacts.CONTENT_FILTER_URI,
+ Uri.encode(mCurFilter));
+ } else {
+ baseUri = Contacts.CONTENT_URI;
+ }
+
+ // Now create and return a CursorLoader that will take care of
+ // creating a Cursor for the data being displayed.
+ String select = "((" + Contacts.DISPLAY_NAME + " NOTNULL) AND ("
+ + Contacts.HAS_PHONE_NUMBER + "=1) AND ("
+ + Contacts.DISPLAY_NAME + " != '' ))";
+ return new CursorLoader(getActivity(), baseUri,
+ CONTACTS_SUMMARY_PROJECTION, select, null,
+ Contacts.DISPLAY_NAME + " COLLATE LOCALIZED ASC");
+}
+This method is called when a previously created loader has finished its load. +This method is guaranteed to be called prior to the release of the last data +that was supplied for this loader. At this point you should remove all use of +the old data (since it will be released soon), but should not do your own +release of the data since its loader owns it and will take care of that.
+ + +The loader will release the data once it knows the application is no longer +using it. For example, if the data is a cursor from a {@link +android.content.CursorLoader}, you should not call {@link +android.database.Cursor#close close()} on it yourself. If the cursor is being +placed in a {@link android.widget.CursorAdapter}, you should use the {@link +android.widget.SimpleCursorAdapter#swapCursor swapCursor()} method so that the +old {@link android.database.Cursor} is not closed. For example:
+ ++// This is the Adapter being used to display the list's data.+ +
SimpleCursorAdapter mAdapter; +... + +public void onLoadFinished(Loader<Cursor> loader, Cursor data) { + // Swap the new cursor in. (The framework will take care of closing the + // old cursor once we return.) + mAdapter.swapCursor(data); +}
This method is called when a previously created loader is being reset, thus +making its data unavailable. This callback lets you find out when the data is +about to be released so you can remove your reference to it.
+This implementation calls
+{@link android.widget.SimpleCursorAdapter#swapCursor swapCursor()}
+with a value of null:
+// This is the Adapter being used to display the list's data.
+SimpleCursorAdapter mAdapter;
+...
+
+public void onLoaderReset(Loader<Cursor> loader) {
+ // This is called when the last Cursor provided to onLoadFinished()
+ // above is about to be closed. We need to make sure we are no
+ // longer using it.
+ mAdapter.swapCursor(null);
+}
+
+
+As an example, here is the full implementation of a {@link +android.app.Fragment} that displays a {@link android.widget.ListView} containing +the results of a query against the contacts content provider. It uses a {@link +android.content.CursorLoader} to manage the query on the provider.
+ +For an application to access a user's contacts, as shown in this example, its +manifest must include the permission +{@link android.Manifest.permission#READ_CONTACTS READ_CONTACTS}.
+ +
+public static class CursorLoaderListFragment extends ListFragment
+ implements OnQueryTextListener, LoaderManager.LoaderCallbacks<Cursor> {
+
+ // This is the Adapter being used to display the list's data.
+ SimpleCursorAdapter mAdapter;
+
+ // If non-null, this is the current filter the user has provided.
+ String mCurFilter;
+
+ @Override public void onActivityCreated(Bundle savedInstanceState) {
+ super.onActivityCreated(savedInstanceState);
+
+ // Give some text to display if there is no data. In a real
+ // application this would come from a resource.
+ setEmptyText("No phone numbers");
+
+ // We have a menu item to show in action bar.
+ setHasOptionsMenu(true);
+
+ // Create an empty adapter we will use to display the loaded data.
+ mAdapter = new SimpleCursorAdapter(getActivity(),
+ android.R.layout.simple_list_item_2, null,
+ new String[] { Contacts.DISPLAY_NAME, Contacts.CONTACT_STATUS },
+ new int[] { android.R.id.text1, android.R.id.text2 }, 0);
+ setListAdapter(mAdapter);
+
+ // Prepare the loader. Either re-connect with an existing one,
+ // or start a new one.
+ getLoaderManager().initLoader(0, null, this);
+ }
+
+ @Override public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
+ // Place an action bar item for searching.
+ MenuItem item = menu.add("Search");
+ item.setIcon(android.R.drawable.ic_menu_search);
+ item.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
+ SearchView sv = new SearchView(getActivity());
+ sv.setOnQueryTextListener(this);
+ item.setActionView(sv);
+ }
+
+ public boolean onQueryTextChange(String newText) {
+ // Called when the action bar search text has changed. Update
+ // the search filter, and restart the loader to do a new query
+ // with this filter.
+ mCurFilter = !TextUtils.isEmpty(newText) ? newText : null;
+ getLoaderManager().restartLoader(0, null, this);
+ return true;
+ }
+
+ @Override public boolean onQueryTextSubmit(String query) {
+ // Don't care about this.
+ return true;
+ }
+
+ @Override public void onListItemClick(ListView l, View v, int position, long id) {
+ // Insert desired behavior here.
+ Log.i("FragmentComplexList", "Item clicked: " + id);
+ }
+
+ // These are the Contacts rows that we will retrieve.
+ static final String[] CONTACTS_SUMMARY_PROJECTION = new String[] {
+ Contacts._ID,
+ Contacts.DISPLAY_NAME,
+ Contacts.CONTACT_STATUS,
+ Contacts.CONTACT_PRESENCE,
+ Contacts.PHOTO_ID,
+ Contacts.LOOKUP_KEY,
+ };
+ public Loader<Cursor> onCreateLoader(int id, Bundle args) {
+ // This is called when a new Loader needs to be created. This
+ // sample only has one Loader, so we don't care about the ID.
+ // First, pick the base URI to use depending on whether we are
+ // currently filtering.
+ Uri baseUri;
+ if (mCurFilter != null) {
+ baseUri = Uri.withAppendedPath(Contacts.CONTENT_FILTER_URI,
+ Uri.encode(mCurFilter));
+ } else {
+ baseUri = Contacts.CONTENT_URI;
+ }
+
+ // Now create and return a CursorLoader that will take care of
+ // creating a Cursor for the data being displayed.
+ String select = "((" + Contacts.DISPLAY_NAME + " NOTNULL) AND ("
+ + Contacts.HAS_PHONE_NUMBER + "=1) AND ("
+ + Contacts.DISPLAY_NAME + " != '' ))";
+ return new CursorLoader(getActivity(), baseUri,
+ CONTACTS_SUMMARY_PROJECTION, select, null,
+ Contacts.DISPLAY_NAME + " COLLATE LOCALIZED ASC");
+ }
+
+ public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
+ // Swap the new cursor in. (The framework will take care of closing the
+ // old cursor once we return.)
+ mAdapter.swapCursor(data);
+ }
+
+ public void onLoaderReset(Loader<Cursor> loader) {
+ // This is called when the last Cursor provided to onLoadFinished()
+ // above is about to be closed. We need to make sure we are no
+ // longer using it.
+ mAdapter.swapCursor(null);
+ }
+}
+There are a few different samples in ApiDemos that +illustrate how to use loaders:
+For information on downloading and installing the SDK samples, see Getting the +Samples.
+ diff --git a/docs/html/guide/components/processes-and-threads.jd b/docs/html/guide/components/processes-and-threads.jd new file mode 100644 index 000000000000..07a2667dc73f --- /dev/null +++ b/docs/html/guide/components/processes-and-threads.jd @@ -0,0 +1,424 @@ +page.title=Processes and Threads +@jd:body + +When an application component starts and the application does not have any other components +running, the Android system starts a new Linux process for the application with a single thread of +execution. By default, all components of the same application run in the same process and thread +(called the "main" thread). If an application component starts and there already exists a process +for that application (because another component from the application exists), then the component is +started within that process and uses the same thread of execution. However, you can arrange for +different components in your application to run in separate processes, and you can create additional +threads for any process.
+ +This document discusses how processes and threads work in an Android application.
+ + +By default, all components of the same application run in the same process and most applications +should not change this. However, if you find that you need to control which process a certain +component belongs to, you can do so in the manifest file.
+ +The manifest entry for each type of component element—{@code +<activity>}, {@code +<service>}, {@code +<receiver>}, and {@code +<provider>}—supports an {@code android:process} attribute that can specify a +process in which that component should run. You can set this attribute so that each component runs +in its own process or so that some components share a process while others do not. You can also set +{@code android:process} so that components of different applications run in the same +process—provided that the applications share the same Linux user ID and are signed with the +same certificates.
+ +The {@code +<application>} element also supports an {@code android:process} attribute, to set a +default value that applies to all components.
+ +Android might decide to shut down a process at some point, when memory is low and required by +other processes that are more immediately serving the user. Application +components running in the process that's killed are consequently destroyed. A process is started +again for those components when there's again work for them to do.
+ +When deciding which processes to kill, the Android system weighs their relative importance to +the user. For example, it more readily shuts down a process hosting activities that are no longer +visible on screen, compared to a process hosting visible activities. The decision whether to +terminate a process, therefore, depends on the state of the components running in that process. The +rules used to decide which processes to terminate is discussed below.
+ + +The Android system tries to maintain an application process for as long as possible, but +eventually needs to remove old processes to reclaim memory for new or more important processes. To +determine which processes to keep +and which to kill, the system places each process into an "importance hierarchy" based on the +components running in the process and the state of those components. Processes with the lowest +importance are eliminated first, then those with the next lowest importance, and so on, as necessary +to recover system resources.
+ +There are five levels in the importance hierarchy. The following list presents the different +types of processes in order of importance (the first process is most important and is +killed last):
+ +A process that is required for what the user is currently doing. A + process is considered to be in the foreground if any of the following conditions are true:
+ +Generally, only a few foreground processes exist at any given time. They are killed only as +a last resort—if memory is so low that they cannot all continue to run. Generally, at that +point, the device has reached a memory paging state, so killing some foreground processes is +required to keep the user interface responsive.
A process that doesn't have any foreground components, but still can + affect what the user sees on screen. A process is considered to be visible if either of the + following conditions are true:
+ +A visible process is considered extremely important and will not be killed unless doing so +is required to keep all foreground processes running.
+A process that is running a service that has been started with the {@link +android.content.Context#startService startService()} method and does not fall into either of the two +higher categories. Although service processes are not directly tied to anything the user sees, they +are generally doing things that the user cares about (such as playing music in the background or +downloading data on the network), so the system keeps them running unless there's not enough memory +to retain them along with all foreground and visible processes.
+A process holding an activity that's not currently visible to the user (the activity's +{@link android.app.Activity#onStop onStop()} method has been called). These processes have no direct +impact on the user experience, and the system can kill them at any time to reclaim memory for a +foreground, +visible, or service process. Usually there are many background processes running, so they are kept +in an LRU (least recently used) list to ensure that the process with the activity that was most +recently seen by the user is the last to be killed. If an activity implements its lifecycle methods +correctly, and saves its current state, killing its process will not have a visible effect on +the user experience, because when the user navigates back to the activity, the activity restores +all of its visible state. See the Activities +document for information about saving and restoring state.
+A process that doesn't hold any active application components. The only reason to keep this +kind of process alive is for caching purposes, to improve startup time the next time a component +needs to run in it. The system often kills these processes in order to balance overall system +resources between process caches and the underlying kernel caches.
+Android ranks a process at the highest level it can, based upon the importance of the +components currently active in the process. For example, if a process hosts a service and a visible +activity, the process is ranked as a visible process, not a service process.
+ +In addition, a process's ranking might be increased because other processes are dependent on +it—a process that is serving another process can never be ranked lower than the process it is +serving. For example, if a content provider in process A is serving a client in process B, or if a +service in process A is bound to a component in process B, process A is always considered at least +as important as process B.
+ +Because a process running a service is ranked higher than a process with background activities, +an activity that initiates a long-running operation might do well to start a service for that operation, rather than +simply create a worker thread—particularly if the operation will likely outlast the activity. +For example, an activity that's uploading a picture to a web site should start a service to perform +the upload so that the upload can continue in the background even if the user leaves the activity. +Using a service guarantees that the operation will have at least "service process" priority, +regardless of what happens to the activity. This is the same reason that broadcast receivers should +employ services rather than simply put time-consuming operations in a thread.
+ + + + +When an application is launched, the system creates a thread of execution for the application, +called "main." This thread is very important because it is in charge of dispatching events to +the appropriate user interface widgets, including drawing events. It is also the thread in which +your application interacts with components from the Android UI toolkit (components from the {@link +android.widget} and {@link android.view} packages). As such, the main thread is also sometimes +called the UI thread.
+ +The system does not create a separate thread for each instance of a component. All +components that run in the same process are instantiated in the UI thread, and system calls to +each component are dispatched from that thread. Consequently, methods that respond to system +callbacks (such as {@link android.view.View#onKeyDown onKeyDown()} to report user actions +or a lifecycle callback method) always run in the UI thread of the process.
+ +For instance, when the user touches a button on the screen, your app's UI thread dispatches the +touch event to the widget, which in turn sets its pressed state and posts an invalidate request to +the event queue. The UI thread dequeues the request and notifies the widget that it should redraw +itself.
+ +When your app performs intensive work in response to user interaction, this single thread model +can yield poor performance unless you implement your application properly. Specifically, if +everything is happening in the UI thread, performing long operations such as network access or +database queries will block the whole UI. When the thread is blocked, no events can be dispatched, +including drawing events. From the user's perspective, the +application appears to hang. Even worse, if the UI thread is blocked for more than a few seconds +(about 5 seconds currently) the user is presented with the infamous "application not +responding" (ANR) dialog. The user might then decide to quit your application and uninstall it +if they are unhappy.
+ +Additionally, the Andoid UI toolkit is not thread-safe. So, you must not manipulate +your UI from a worker thread—you must do all manipulation to your user interface from the UI +thread. Thus, there are simply two rules to Android's single thread model:
+ +Because of the single thread model described above, it's vital to the responsiveness of your +application's UI that you do not block the UI thread. If you have operations to perform +that are not instantaneous, you should make sure to do them in separate threads ("background" or +"worker" threads).
+ +For example, below is some code for a click listener that downloads an image from a separate +thread and displays it in an {@link android.widget.ImageView}:
+ +
+public void onClick(View v) {
+ new Thread(new Runnable() {
+ public void run() {
+ Bitmap b = loadImageFromNetwork("http://example.com/image.png");
+ mImageView.setImageBitmap(b);
+ }
+ }).start();
+}
+
+
+At first, this seems to work fine, because it creates a new thread to handle the network +operation. However, it violates the second rule of the single-threaded model: do not access the +Android UI toolkit from outside the UI thread—this sample modifies the {@link +android.widget.ImageView} from the worker thread instead of the UI thread. This can result in +undefined and unexpected behavior, which can be difficult and time-consuming to track down.
+ +To fix this problem, Android offers several ways to access the UI thread from other +threads. Here is a list of methods that can help:
+ +For example, you can fix the above code by using the {@link +android.view.View#post(java.lang.Runnable) View.post(Runnable)} method:
+ +
+public void onClick(View v) {
+ new Thread(new Runnable() {
+ public void run() {
+ final Bitmap bitmap = loadImageFromNetwork("http://example.com/image.png");
+ mImageView.post(new Runnable() {
+ public void run() {
+ mImageView.setImageBitmap(bitmap);
+ }
+ });
+ }
+ }).start();
+}
+
+
+Now this implementation is thread-safe: the network operation is done from a separate thread +while the {@link android.widget.ImageView} is manipulated from the UI thread.
+ +However, as the complexity of the operation grows, this kind of code can get complicated and +difficult to maintain. To handle more complex interactions with a worker thread, you might consider +using a {@link android.os.Handler} in your worker thread, to process messages delivered from the UI +thread. Perhaps the best solution, though, is to extend the {@link android.os.AsyncTask} class, +which simplifies the execution of worker thread tasks that need to interact with the UI.
+ + +{@link android.os.AsyncTask} allows you to perform asynchronous work on your user +interface. It performs the blocking operations in a worker thread and then publishes the results on +the UI thread, without requiring you to handle threads and/or handlers yourself.
+ +To use it, you must subclass {@link android.os.AsyncTask} and implement the {@link +android.os.AsyncTask#doInBackground doInBackground()} callback method, which runs in a pool of +background threads. To update your UI, you should implement {@link +android.os.AsyncTask#onPostExecute onPostExecute()}, which delivers the result from {@link +android.os.AsyncTask#doInBackground doInBackground()} and runs in the UI thread, so you can safely +update your UI. You can then run the task by calling {@link android.os.AsyncTask#execute execute()} +from the UI thread.
+ +For example, you can implement the previous example using {@link android.os.AsyncTask} this +way:
+ +
+public void onClick(View v) {
+ new DownloadImageTask().execute("http://example.com/image.png");
+}
+
+private class DownloadImageTask extends AsyncTask<String, Void, Bitmap> {
+ /** The system calls this to perform work in a worker thread and
+ * delivers it the parameters given to AsyncTask.execute() */
+ protected Bitmap doInBackground(String... urls) {
+ return loadImageFromNetwork(urls[0]);
+ }
+
+ /** The system calls this to perform work in the UI thread and delivers
+ * the result from doInBackground() */
+ protected void onPostExecute(Bitmap result) {
+ mImageView.setImageBitmap(result);
+ }
+}
+
+
+Now the UI is safe and the code is simpler, because it separates the work into the +part that should be done on a worker thread and the part that should be done on the UI thread.
+ +You should read the {@link android.os.AsyncTask} reference for a full understanding on +how to use this class, but here is a quick overview of how it works:
+ +Caution: Another problem you might encounter when using a worker +thread is unexpected restarts in your activity due to a runtime configuration change +(such as when the user changes the screen orientation), which may destroy your worker thread. To +see how you can persist your task during one of these restarts and how to properly cancel the task +when the activity is destroyed, see the source code for the Shelves sample application.
+ + +In some situations, the methods you implement might be called from more than one thread, and +therefore must be written to be thread-safe.
+ +This is primarily true for methods that can be called remotely—such as methods in a bound service. When a call on a +method implemented in an {@link android.os.IBinder} originates in the same process in which the +{@link android.os.IBinder IBinder} is running, the method is executed in the caller's thread. +However, when the call originates in another process, the method is executed in a thread chosen from +a pool of threads that the system maintains in the same process as the {@link android.os.IBinder +IBinder} (it's not executed in the UI thread of the process). For example, whereas a service's +{@link android.app.Service#onBind onBind()} method would be called from the UI thread of the +service's process, methods implemented in the object that {@link android.app.Service#onBind +onBind()} returns (for example, a subclass that implements RPC methods) would be called from threads +in the pool. Because a service can have more than one client, more than one pool thread can engage +the same {@link android.os.IBinder IBinder} method at the same time. {@link android.os.IBinder +IBinder} methods must, therefore, be implemented to be thread-safe.
+ +Similarly, a content provider can receive data requests that originate in other processes. +Although the {@link android.content.ContentResolver} and {@link android.content.ContentProvider} +classes hide the details of how the interprocess communication is managed, {@link +android.content.ContentProvider} methods that respond to those requests—the methods {@link +android.content.ContentProvider#query query()}, {@link android.content.ContentProvider#insert +insert()}, {@link android.content.ContentProvider#delete delete()}, {@link +android.content.ContentProvider#update update()}, and {@link android.content.ContentProvider#getType +getType()}—are called from a pool of threads in the content provider's process, not the UI +thread for the process. Because these methods might be called from any number of threads at the +same time, they too must be implemented to be thread-safe.
+ + +Android offers a mechanism for interprocess communication (IPC) using remote procedure calls +(RPCs), in which a method is called by an activity or other application component, but executed +remotely (in another process), with any result returned back to the +caller. This entails decomposing a method call and its data to a level the operating system can +understand, transmitting it from the local process and address space to the remote process and +address space, then reassembling and reenacting the call there. Return values are then +transmitted in the opposite direction. Android provides all the code to perform these IPC +transactions, so you can focus on defining and implementing the RPC programming interface.
+ +To perform IPC, your application must bind to a service, using {@link +android.content.Context#bindService bindService()}. For more information, see the Services developer guide.
+ + + diff --git a/docs/html/guide/components/services.jd b/docs/html/guide/components/services.jd new file mode 100644 index 000000000000..ba5e1f03b277 --- /dev/null +++ b/docs/html/guide/components/services.jd @@ -0,0 +1,874 @@ +page.title=Services +@jd:body + +A {@link android.app.Service} is an application component that can perform +long-running operations in the background and does not provide a user interface. Another +application component can start a service and it will continue to run in the background even if the +user switches to another application. Additionally, a component can bind to a service to +interact with it and even perform interprocess communication (IPC). For example, a service might +handle network transactions, play music, perform file I/O, or interact with a content provider, all +from the background.
+ +A service can essentially take two forms:
+ +Although this documentation generally discusses these two types of services separately, your +service can work both ways—it can be started (to run indefinitely) and also allow binding. +It's simply a matter of whether you implement a couple callback methods: {@link +android.app.Service#onStartCommand onStartCommand()} to allow components to start it and {@link +android.app.Service#onBind onBind()} to allow binding.
+ +Regardless of whether your application is started, bound, or both, any application component +can use the service (even from a separate application), in the same way that any component can use +an activity—by starting it with an {@link android.content.Intent}. However, you can declare +the service as private, in the manifest file, and block access from other applications. This is +discussed more in the section about Declaring the service in the +manifest.
+ +Caution: A service runs in the +main thread of its hosting process—the service does not create its own thread +and does not run in a separate process (unless you specify otherwise). This means +that, if your service is going to do any CPU intensive work or blocking operations (such as MP3 +playback or networking), you should create a new thread within the service to do that work. By using +a separate thread, you will reduce the risk of Application Not Responding (ANR) errors and the +application's main thread can remain dedicated to user interaction with your activities.
+ + +A service is simply a component that can run in the background even when the user is not +interacting with your application. Thus, you should create a service only if that is what you +need.
+If you need to perform work outside your main thread, but only while the user is interacting +with your application, then you should probably instead create a new thread and not a service. For +example, if you want to play some music, but only while your activity is running, you might create +a thread in {@link android.app.Activity#onCreate onCreate()}, start running it in {@link +android.app.Activity#onStart onStart()}, then stop it in {@link android.app.Activity#onStop +onStop()}. Also consider using {@link android.os.AsyncTask} or {@link android.os.HandlerThread}, +instead of the traditional {@link java.lang.Thread} class. See the Processes and +Threading document for more information about threads.
+Remember that if you do use a service, it still runs in your application's main thread by +default, so you should still create a new thread within the service if it performs intensive or +blocking operations.
+To create a service, you must create a subclass of {@link android.app.Service} (or one +of its existing subclasses). In your implementation, you need to override some callback methods that +handle key aspects of the service lifecycle and provide a mechanism for components to bind to +the service, if appropriate. The most important callback methods you should override are:
+ +If a component starts the service by calling {@link +android.content.Context#startService startService()} (which results in a call to {@link +android.app.Service#onStartCommand onStartCommand()}), then the service +remains running until it stops itself with {@link android.app.Service#stopSelf()} or another +component stops it by calling {@link android.content.Context#stopService stopService()}.
+ +If a component calls +{@link android.content.Context#bindService bindService()} to create the service (and {@link +android.app.Service#onStartCommand onStartCommand()} is not called), then the service runs +only as long as the component is bound to it. Once the service is unbound from all clients, the +system destroys it.
+ +The Android system will force-stop a service only when memory is low and it must recover system +resources for the activity that has user focus. If the service is bound to an activity that has user +focus, then it's less likely to be killed, and if the service is declared to run in the foreground (discussed later), then it will almost never be killed. +Otherwise, if the service was started and is long-running, then the system will lower its position +in the list of background tasks over time and the service will become highly susceptible to +killing—if your service is started, then you must design it to gracefully handle restarts +by the system. If the system kills your service, it restarts it as soon as resources become +available again (though this also depends on the value you return from {@link +android.app.Service#onStartCommand onStartCommand()}, as discussed later). For more information +about when the system might destroy a service, see the Processes and Threading +document.
+ +In the following sections, you'll see how you can create each type of service and how to use +it from other application components.
+ + + +Like activities (and other components), you must declare all services in your application's +manifest file.
+ +To declare your service, add a {@code <service>} element +as a child of the {@code <application>} +element. For example:
+ ++<manifest ... > + ... + <application ... > + <service android:name=".ExampleService" /> + ... + </application> +</manifest> ++ +
There are other attributes you can include in the {@code <service>} element to +define properties such as permissions required to start the service and the process in +which the service should run. The {@code android:name} +attribute is the only required attribute—it specifies the class name of the service. Once +you publish your application, you should not change this name, because if you do, you might break +some functionality where explicit intents are used to reference your service (read the blog post, Things +That Cannot Change). + +
See the {@code <service>} element +reference for more information about declaring your service in the manifest.
+ +Just like an activity, a service can define intent filters that allow other components to +invoke the service using implicit intents. By declaring intent filters, components +from any application installed on the user's device can potentially start your service if your +service declares an intent filter that matches the intent another application passes to {@link +android.content.Context#startService startService()}.
+ +If you plan on using your service only locally (other applications do not use it), then you +don't need to (and should not) supply any intent filters. Without any intent filters, you must +start the service using an intent that explicitly names the service class. More information +about starting a service is discussed below.
+ +Additionally, you can ensure that your service is private to your application only if +you include the {@code android:exported} +attribute and set it to {@code "false"}. This is effective even if your service supplies intent +filters.
+ +For more information about creating intent filters for your service, see the Intents and Intent Filters +document.
+ + + +If you're building an application for Android 1.6 or lower, you need +to implement {@link android.app.Service#onStart onStart()}, instead of {@link +android.app.Service#onStartCommand onStartCommand()} (in Android 2.0, +{@link android.app.Service#onStart onStart()} was deprecated in favor of {@link +android.app.Service#onStartCommand onStartCommand()}).
+For more information about providing compatibility with versions of Android older than 2.0, see +the {@link android.app.Service#onStartCommand onStartCommand()} documentation.
+A started service is one that another component starts by calling {@link +android.content.Context#startService startService()}, resulting in a call to the service's +{@link android.app.Service#onStartCommand onStartCommand()} method.
+ +When a service is started, it has a lifecycle that's independent of the +component that started it and the service can run in the background indefinitely, even if +the component that started it is destroyed. As such, the service should stop itself when its job +is done by calling {@link android.app.Service#stopSelf stopSelf()}, or another component can stop it +by calling {@link android.content.Context#stopService stopService()}.
+ +An application component such as an activity can start the service by calling {@link +android.content.Context#startService startService()} and passing an {@link android.content.Intent} +that specifies the service and includes any data for the service to use. The service receives +this {@link android.content.Intent} in the {@link android.app.Service#onStartCommand +onStartCommand()} method.
+ +For instance, suppose an activity needs to save some data to an online database. The activity can +start a companion service and deliver it the data to save by passing an intent to {@link +android.content.Context#startService startService()}. The service receives the intent in {@link +android.app.Service#onStartCommand onStartCommand()}, connects to the Internet and performs the +database transaction. When the transaction is done, the service stops itself and it is +destroyed.
+ +Caution: A services runs in the same process as the application +in which it is declared and in the main thread of that application, by default. So, if your service +performs intensive or blocking operations while the user interacts with an activity from the same +application, the service will slow down activity performance. To avoid impacting application +performance, you should start a new thread inside the service.
+ +Traditionally, there are two classes you can extend to create a started service:
+The following sections describe how you can implement your service using either one for these +classes.
+ + +Because most started services don't need to handle multiple requests simultaneously +(which can actually be a dangerous multi-threading scenario), it's probably best if you +implement your service using the {@link android.app.IntentService} class.
+ +The {@link android.app.IntentService} does the following:
+ +All this adds up to the fact that all you need to do is implement {@link +android.app.IntentService#onHandleIntent onHandleIntent()} to do the work provided by the +client. (Though, you also need to provide a small constructor for the service.)
+ +Here's an example implementation of {@link android.app.IntentService}:
+ +
+public class HelloIntentService extends IntentService {
+
+ /**
+ * A constructor is required, and must call the super {@link android.app.IntentService#IntentService}
+ * constructor with a name for the worker thread.
+ */
+ public HelloIntentService() {
+ super("HelloIntentService");
+ }
+
+ /**
+ * The IntentService calls this method from the default worker thread with
+ * the intent that started the service. When this method returns, IntentService
+ * stops the service, as appropriate.
+ */
+ @Override
+ protected void onHandleIntent(Intent intent) {
+ // Normally we would do some work here, like download a file.
+ // For our sample, we just sleep for 5 seconds.
+ long endTime = System.currentTimeMillis() + 5*1000;
+ while (System.currentTimeMillis() < endTime) {
+ synchronized (this) {
+ try {
+ wait(endTime - System.currentTimeMillis());
+ } catch (Exception e) {
+ }
+ }
+ }
+ }
+}
+
+
+That's all you need: a constructor and an implementation of {@link +android.app.IntentService#onHandleIntent onHandleIntent()}.
+ +If you decide to also override other callback methods, such as {@link +android.app.IntentService#onCreate onCreate()}, {@link +android.app.IntentService#onStartCommand onStartCommand()}, or {@link +android.app.IntentService#onDestroy onDestroy()}, be sure to call the super implementation, so +that the {@link android.app.IntentService} can properly handle the life of the worker thread.
+ +For example, {@link android.app.IntentService#onStartCommand onStartCommand()} must return +the default implementation (which is how the intent gets delivered to {@link +android.app.IntentService#onHandleIntent onHandleIntent()}):
+ +
+@Override
+public int onStartCommand(Intent intent, int flags, int startId) {
+ Toast.makeText(this, "service starting", Toast.LENGTH_SHORT).show();
+ return super.onStartCommand(intent,flags,startId);
+}
+
+
+Besides {@link android.app.IntentService#onHandleIntent onHandleIntent()}, the only method +from which you don't need to call the super class is {@link android.app.IntentService#onBind +onBind()} (but you only need to implement that if your service allows binding).
+ +In the next section, you'll see how the same kind of service is implemented when extending +the base {@link android.app.Service} class, which is a lot more code, but which might be +appropriate if you need to handle simultaneous start requests.
+ + +As you saw in the previous section, using {@link android.app.IntentService} makes your +implementation of a started service very simple. If, however, you require your service to +perform multi-threading (instead of processing start requests through a work queue), then you +can extend the {@link android.app.Service} class to handle each intent.
+ +For comparison, the following example code is an implementation of the {@link +android.app.Service} class that performs the exact same work as the example above using {@link +android.app.IntentService}. That is, for each start request, it uses a worker thread to perform the +job and processes only one request at a time.
+ +
+public class HelloService extends Service {
+ private Looper mServiceLooper;
+ private ServiceHandler mServiceHandler;
+
+ // Handler that receives messages from the thread
+ private final class ServiceHandler extends Handler {
+ public ServiceHandler(Looper looper) {
+ super(looper);
+ }
+ @Override
+ public void handleMessage(Message msg) {
+ // Normally we would do some work here, like download a file.
+ // For our sample, we just sleep for 5 seconds.
+ long endTime = System.currentTimeMillis() + 5*1000;
+ while (System.currentTimeMillis() < endTime) {
+ synchronized (this) {
+ try {
+ wait(endTime - System.currentTimeMillis());
+ } catch (Exception e) {
+ }
+ }
+ }
+ // Stop the service using the startId, so that we don't stop
+ // the service in the middle of handling another job
+ stopSelf(msg.arg1);
+ }
+ }
+
+ @Override
+ public void onCreate() {
+ // Start up the thread running the service. Note that we create a
+ // separate thread because the service normally runs in the process's
+ // main thread, which we don't want to block. We also make it
+ // background priority so CPU-intensive work will not disrupt our UI.
+ HandlerThread thread = new HandlerThread("ServiceStartArguments",
+ Process.THREAD_PRIORITY_BACKGROUND);
+ thread.start();
+
+ // Get the HandlerThread's Looper and use it for our Handler
+ mServiceLooper = thread.getLooper();
+ mServiceHandler = new ServiceHandler(mServiceLooper);
+ }
+
+ @Override
+ public int onStartCommand(Intent intent, int flags, int startId) {
+ Toast.makeText(this, "service starting", Toast.LENGTH_SHORT).show();
+
+ // For each start request, send a message to start a job and deliver the
+ // start ID so we know which request we're stopping when we finish the job
+ Message msg = mServiceHandler.obtainMessage();
+ msg.arg1 = startId;
+ mServiceHandler.sendMessage(msg);
+
+ // If we get killed, after returning from here, restart
+ return START_STICKY;
+ }
+
+ @Override
+ public IBinder onBind(Intent intent) {
+ // We don't provide binding, so return null
+ return null;
+ }
+
+ @Override
+ public void onDestroy() {
+ Toast.makeText(this, "service done", Toast.LENGTH_SHORT).show();
+ }
+}
+
+
+As you can see, it's a lot more work than using {@link android.app.IntentService}.
+ +However, because you handle each call to {@link android.app.Service#onStartCommand +onStartCommand()} yourself, you can perform multiple requests simultaneously. That's not what +this example does, but if that's what you want, then you can create a new thread for each +request and run them right away (instead of waiting for the previous request to finish).
+ +Notice that the {@link android.app.Service#onStartCommand onStartCommand()} method must return an +integer. The integer is a value that describes how the system should continue the service in the +event that the system kills it (as discussed above, the default implementation for {@link +android.app.IntentService} handles this for you, though you are able to modify it). The return value +from {@link android.app.Service#onStartCommand onStartCommand()} must be one of the following +constants:
+ +For more details about these return values, see the linked reference documentation for each +constant.
+ + + +You can start a service from an activity or other application component by passing an +{@link android.content.Intent} (specifying the service to start) to {@link +android.content.Context#startService startService()}. The Android system calls the service's {@link +android.app.Service#onStartCommand onStartCommand()} method and passes it the {@link +android.content.Intent}. (You should never call {@link android.app.Service#onStartCommand +onStartCommand()} directly.)
+ +For example, an activity can start the example service in the previous section ({@code +HelloSevice}) using an explicit intent with {@link android.content.Context#startService +startService()}:
+ ++Intent intent = new Intent(this, HelloService.class); +startService(intent); ++ +
The {@link android.content.Context#startService startService()} method returns immediately and +the Android system calls the service's {@link android.app.Service#onStartCommand +onStartCommand()} method. If the service is not already running, the system first calls {@link +android.app.Service#onCreate onCreate()}, then calls {@link android.app.Service#onStartCommand +onStartCommand()}.
+ +If the service does not also provide binding, the intent delivered with {@link +android.content.Context#startService startService()} is the only mode of communication between the +application component and the service. However, if you want the service to send a result back, then +the client that starts the service can create a {@link android.app.PendingIntent} for a broadcast +(with {@link android.app.PendingIntent#getBroadcast getBroadcast()}) and deliver it to the service +in the {@link android.content.Intent} that starts the service. The service can then use the +broadcast to deliver a result.
+ +Multiple requests to start the service result in multiple corresponding calls to the service's +{@link android.app.Service#onStartCommand onStartCommand()}. However, only one request to stop +the service (with {@link android.app.Service#stopSelf stopSelf()} or {@link +android.content.Context#stopService stopService()}) is required to stop it.
+ + +A started service must manage its own lifecycle. That is, the system does not stop or +destroy the service unless it must recover system memory and the service +continues to run after {@link android.app.Service#onStartCommand onStartCommand()} returns. So, +the service must stop itself by calling {@link android.app.Service#stopSelf stopSelf()} or another +component can stop it by calling {@link android.content.Context#stopService stopService()}.
+ +Once requested to stop with {@link android.app.Service#stopSelf stopSelf()} or {@link +android.content.Context#stopService stopService()}, the system destroys the service as soon as +possible.
+ +However, if your service handles multiple requests to {@link
+android.app.Service#onStartCommand onStartCommand()} concurrently, then you shouldn't stop the
+service when you're done processing a start request, because you might have since received a new
+start request (stopping at the end of the first request would terminate the second one). To avoid
+this problem, you can use {@link android.app.Service#stopSelf(int)} to ensure that your request to
+stop the service is always based on the most recent start request. That is, when you call {@link
+android.app.Service#stopSelf(int)}, you pass the ID of the start request (the startId
+delivered to {@link android.app.Service#onStartCommand onStartCommand()}) to which your stop request
+corresponds. Then if the service received a new start request before you were able to call {@link
+android.app.Service#stopSelf(int)}, then the ID will not match and the service will not stop.
Caution: It's important that your application stops its services +when it's done working, to avoid wasting system resources and consuming battery power. If necessary, +other components can stop the service by calling {@link +android.content.Context#stopService stopService()}. Even if you enable binding for the service, +you must always stop the service yourself if it ever received a call to {@link +android.app.Service#onStartCommand onStartCommand()}.
+ +For more information about the lifecycle of a service, see the section below about Managing the Lifecycle of a Service.
+ + + +A bound service is one that allows application components to bind to it by calling {@link +android.content.Context#bindService bindService()} in order to create a long-standing connection +(and generally does not allow components to start it by calling {@link +android.content.Context#startService startService()}).
+ +You should create a bound service when you want to interact with the service from activities +and other components in your application or to expose some of your application's functionality to +other applications, through interprocess communication (IPC).
+ +To create a bound service, you must implement the {@link +android.app.Service#onBind onBind()} callback method to return an {@link android.os.IBinder} that +defines the interface for communication with the service. Other application components can then call +{@link android.content.Context#bindService bindService()} to retrieve the interface and +begin calling methods on the service. The service lives only to serve the application component that +is bound to it, so when there are no components bound to the service, the system destroys it +(you do not need to stop a bound service in the way you must when the service is started +through {@link android.app.Service#onStartCommand onStartCommand()}).
+ +To create a bound service, the first thing you must do is define the interface that specifies +how a client can communicate with the service. This interface between the service +and a client must be an implementation of {@link android.os.IBinder} and is what your service must +return from the {@link android.app.Service#onBind +onBind()} callback method. Once the client receives the {@link android.os.IBinder}, it can begin +interacting with the service through that interface.
+ +Multiple clients can bind to the service at once. When a client is done interacting with the +service, it calls {@link android.content.Context#unbindService unbindService()} to unbind. Once +there are no clients bound to the service, the system destroys the service.
+ +There are multiple ways to implement a bound service and the implementation is more +complicated than a started service, so the bound service discussion appears in a separate +document about Bound Services.
+ + + +Once running, a service can notify the user of events using Toast Notifications or Status Bar Notifications.
+ +A toast notification is a message that appears on the surface of the current window for a +moment then disappears, while a status bar notification provides an icon in the status bar with a +message, which the user can select in order to take an action (such as start an activity).
+ +Usually, a status bar notification is the best technique when some background work has completed +(such as a file completed +downloading) and the user can now act on it. When the user selects the notification from the +expanded view, the notification can start an activity (such as to view the downloaded file).
+ +See the Toast Notifications or Status Bar Notifications +developer guides for more information.
+ + + +A foreground service is a service that's considered to be something the +user is actively aware of and thus not a candidate for the system to kill when low on memory. A +foreground service must provide a notification for the status bar, which is placed under the +"Ongoing" heading, which means that the notification cannot be dismissed unless the service is +either stopped or removed from the foreground.
+ +For example, a music player that plays music from a service should be set to run in the +foreground, because the user is explicitly aware +of its operation. The notification in the status bar might indicate the current song and allow +the user to launch an activity to interact with the music player.
+ +To request that your service run in the foreground, call {@link +android.app.Service#startForeground startForeground()}. This method takes two parameters: an integer +that uniquely identifies the notification and the {@link +android.app.Notification} for the status bar. For example:
+ ++Notification notification = new Notification(R.drawable.icon, getText(R.string.ticker_text), + System.currentTimeMillis()); +Intent notificationIntent = new Intent(this, ExampleActivity.class); +PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0); +notification.setLatestEventInfo(this, getText(R.string.notification_title), + getText(R.string.notification_message), pendingIntent); +startForeground(ONGOING_NOTIFICATION, notification); ++ + +
To remove the service from the foreground, call {@link +android.app.Service#stopForeground stopForeground()}. This method takes a boolean, indicating +whether to remove the status bar notification as well. This method does not stop the +service. However, if you stop the service while it's still running in the foreground, then the +notification is also removed.
+ +Note: The methods {@link +android.app.Service#startForeground startForeground()} and {@link +android.app.Service#stopForeground stopForeground()} were introduced in Android 2.0 (API Level +5). In order to run your service in the foreground on older versions of the platform, you must +use the previous {@code setForeground()} method—see the {@link +android.app.Service#startForeground startForeground()} documentation for information about how +to provide backward compatibility.
+ +For more information about notifications, see Creating Status Bar +Notifications.
+ + + +The lifecycle of a service is much simpler than that of an activity. However, it's even more important +that you pay close attention to how your service is created and destroyed, because a service +can run in the background without the user being aware.
+ +The service lifecycle—from when it's created to when it's destroyed—can follow two +different paths:
+ +The service is created when another component calls {@link +android.content.Context#startService startService()}. The service then runs indefinitely and must +stop itself by calling {@link +android.app.Service#stopSelf() stopSelf()}. Another component can also stop the +service by calling {@link android.content.Context#stopService +stopService()}. When the service is stopped, the system destroys it..
The service is created when another component (a client) calls {@link +android.content.Context#bindService bindService()}. The client then communicates with the service +through an {@link android.os.IBinder} interface. The client can close the connection by calling +{@link android.content.Context#unbindService unbindService()}. Multiple clients can bind to +the same service and when all of them unbind, the system destroys the service. (The service +does not need to stop itself.)
These two paths are not entirely separate. That is, you can bind to a service that was already +started with {@link android.content.Context#startService startService()}. For example, a background +music service could be started by calling {@link android.content.Context#startService +startService()} with an {@link android.content.Intent} that identifies the music to play. Later, +possibly when the user wants to exercise some control over the player or get information about the +current song, an activity can bind to the service by calling {@link +android.content.Context#bindService bindService()}. In cases like this, {@link +android.content.Context#stopService stopService()} or {@link android.app.Service#stopSelf +stopSelf()} does not actually stop the service until all clients unbind.
+ + +Like an activity, a service has lifecycle callback methods that you can implement to monitor +changes in the service's state and perform work at the appropriate times. The following skeleton +service demonstrates each of the lifecycle methods:
+ + +
+Figure 2. The service lifecycle. The diagram on the left +shows the lifecycle when the service is created with {@link android.content.Context#startService +startService()} and the diagram on the right shows the lifecycle when the service is created +with {@link android.content.Context#bindService bindService()}.
+
+public class ExampleService extends Service {
+ int mStartMode; // indicates how to behave if the service is killed
+ IBinder mBinder; // interface for clients that bind
+ boolean mAllowRebind; // indicates whether onRebind should be used
+
+ @Override
+ public void {@link android.app.Service#onCreate onCreate}() {
+ // The service is being created
+ }
+ @Override
+ public int {@link android.app.Service#onStartCommand onStartCommand}(Intent intent, int flags, int startId) {
+ // The service is starting, due to a call to {@link android.content.Context#startService startService()}
+ return mStartMode;
+ }
+ @Override
+ public IBinder {@link android.app.Service#onBind onBind}(Intent intent) {
+ // A client is binding to the service with {@link android.content.Context#bindService bindService()}
+ return mBinder;
+ }
+ @Override
+ public boolean {@link android.app.Service#onUnbind onUnbind}(Intent intent) {
+ // All clients have unbound with {@link android.content.Context#unbindService unbindService()}
+ return mAllowRebind;
+ }
+ @Override
+ public void {@link android.app.Service#onRebind onRebind}(Intent intent) {
+ // A client is binding to the service with {@link android.content.Context#bindService bindService()},
+ // after onUnbind() has already been called
+ }
+ @Override
+ public void {@link android.app.Service#onDestroy onDestroy}() {
+ // The service is no longer used and is being destroyed
+ }
+}
+
+
+Note: Unlike the activity lifecycle callback methods, you are +not required to call the superclass implementation of these callback methods.
+ +By implementing these methods, you can monitor two nested loops of the service's lifecycle:
+ +The {@link android.app.Service#onCreate onCreate()} and {@link android.app.Service#onDestroy +onDestroy()} methods are called for all services, whether +they're created by {@link android.content.Context#startService startService()} or {@link +android.content.Context#bindService bindService()}.
If the service is started, the active lifetime ends the same time that the entire lifetime +ends (the service is still active even after {@link android.app.Service#onStartCommand +onStartCommand()} returns). If the service is bound, the active lifetime ends when {@link +android.app.Service#onUnbind onUnbind()} returns.
+Note: Although a started service is stopped by a call to +either {@link android.app.Service#stopSelf stopSelf()} or {@link +android.content.Context#stopService stopService()}, there is not a respective callback for the +service (there's no {@code onStop()} callback). So, unless the service is bound to a client, +the system destroys it when the service is stopped—{@link +android.app.Service#onDestroy onDestroy()} is the only callback received.
+ +Figure 2 illustrates the typical callback methods for a service. Although the figure separates +services that are created by {@link android.content.Context#startService startService()} from those +created by {@link android.content.Context#bindService bindService()}, keep +in mind that any service, no matter how it's started, can potentially allow clients to bind to it. +So, a service that was initially started with {@link android.app.Service#onStartCommand +onStartCommand()} (by a client calling {@link android.content.Context#startService startService()}) +can still receive a call to {@link android.app.Service#onBind onBind()} (when a client calls +{@link android.content.Context#bindService bindService()}).
+ +For more information about creating a service that provides binding, see the Bound Services document, +which includes more information about the {@link android.app.Service#onRebind onRebind()} +callback method in the section about Managing the Lifecycle of +a Bound Service.
+ + + diff --git a/docs/html/guide/components/tasks-and-back-stack.jd b/docs/html/guide/components/tasks-and-back-stack.jd new file mode 100644 index 000000000000..8b7041cef826 --- /dev/null +++ b/docs/html/guide/components/tasks-and-back-stack.jd @@ -0,0 +1,595 @@ +page.title=Tasks and Back Stack +parent.title=Activities +parent.link=activities.html +@jd:body + +An application usually contains multiple activities. Each activity +should be designed around a specific kind of action the user can perform and can start other +activities. For example, an email application might have one activity to show a list of new email. +When the user selects an email, a new activity opens to view that email.
+ +An activity can even start activities that exist in other applications on the device. For +example, if your application wants to send an email, you can define an intent to perform a "send" +action and include some data, such as an email address and a message. An activity from another +application that declares itself to handle this kind of intent then opens. In this case, the intent +is to send an email, so an email application's "compose" activity starts (if multiple activities +support the same intent, then the system lets the user select which one to use). When the email is +sent, your activity resumes and it seems as if the email activity was part of your application. Even +though the activities may be from different applications, Android maintains this seamless user +experience by keeping both activities in the same task.
+ +A task is a collection of activities that users interact with +when performing a certain job. The activities are arranged in a stack (the "back stack"), in the +order in which each activity is opened.
+ + + +The device Home screen is the starting place for most tasks. When the user touches an icon in the +application +launcher (or a shortcut on the Home screen), that application's task comes to the foreground. If no +task exists for the application (the application has not been used recently), then a new task +is created and the "main" activity for that application opens as the root activity in the stack.
+ +When the current activity starts another, the new activity is pushed on the top of the stack and +takes focus. The previous activity remains in the stack, but is stopped. When an activity +stops, the system retains the current state of its user interface. When the user presses the +Back +button, the current activity is popped from the top of the stack (the activity is destroyed) and the +previous activity resumes (the previous state of its UI is restored). Activities in the stack are +never rearranged, only pushed and popped from the stack—pushed onto the stack when started by +the current activity and popped off when the user leaves it using the Back button. As such, +the back +stack operates as a "last in, first out" object structure. Figure 1 visualizes +this behavior with a timeline showing the progress between activities along with the current back +stack at each point in time.
+ +
+Figure 1. A representation of how each new activity in a +task adds an item to the back stack. When the user presses the Back button, the current +activity is +destroyed and the previous activity resumes.
+ + +If the user continues to press Back, then each activity in the stack is popped off to +reveal the +previous one, until the user returns to the Home screen (or to whichever activity was running when +the task began). When all activities are removed from the stack, the task no longer exists.
+ +
Figure 2. Two tasks: Task B receives user interaction +in the foreground, while Task A is in the background, waiting to be resumed.
+
Figure 3. A single activity is instantiated multiple times.
+A task is a cohesive unit that can move to the "background" when users begin a new task or go +to the Home screen, via the Home button. While in the background, all the activities in the +task are +stopped, but the back stack for the task remains intact—the task has simply lost focus while +another task takes place, as shown in figure 2. A task can then return to the "foreground" so users +can pick up where they left off. Suppose, for example, that the current task (Task A) has three +activities in its stack—two under the current activity. The user presses the Home +button, then +starts a new application from the application launcher. When the Home screen appears, Task A goes +into the background. When the new application starts, the system starts a task for that application +(Task B) with its own stack of activities. After interacting with +that application, the user returns Home again and selects the application that originally +started Task A. Now, Task A comes to the +foreground—all three activities in its stack are intact and the activity at the top of the +stack resumes. At +this point, the user can also switch back to Task B by going Home and selecting the application icon +that started that task (or by touching and holding the Home button to reveal recent tasks +and selecting +one). This is an example of multitasking on Android.
+ +Note: Multiple tasks can be held in the background at once. +However, if the user is running many background tasks at the same time, the system might begin +destroying background activities in order to recover memory, causing the activity states to be lost. +See the following section about Activity state.
+ +Because the activities in the back stack are never rearranged, if your application allows +users to start a particular activity from more than one activity, a new instance of +that activity is created and pushed onto the stack (rather than bringing any previous instance of +the activity to the top). As such, one activity in your application might be instantiated multiple +times (even from different tasks), as shown in figure 3. As such, if the user navigates backward +using the Back button, each instance of the activity is revealed in the order they were +opened (each +with their own UI state). However, you can modify this behavior if you do not want an activity to be +instantiated more than once. How to do so is discussed in the later section about Managing Tasks.
+ + +To summarize the default behavior for activities and tasks:
+ +Navigation Design
+For more about how app navigation works on Android, read Android Design's Navigation guide.
+As discussed above, the system's default behavior preserves the state of an activity when it is +stopped. This way, when users navigate back to a previous activity, its user interface appears +the way they left it. However, you can—and should—proactively retain +the state of your activities using callback methods, in case the activity is destroyed and must +be recreated.
+ +When the system stops one of your activities (such as when a new activity starts or the task +moves to the background), the system might destroy that activity completely if it needs to recover +system memory. When this happens, information about the activity state is lost. If this happens, the +system still +knows that the activity has a place in the back stack, but when the activity is brought to the +top of the stack the system must recreate it (rather than resume it). In order to +avoid losing the user's work, you should proactively retain it by implementing the {@link +android.app.Activity#onSaveInstanceState onSaveInstanceState()} callback +methods in your activity.
+ +For more information about how to save your activity state, see the Activities +document.
+ + + +The way Android manages tasks and the back stack, as described above—by placing all +activities started in succession in the same task and in a "last in, first out" stack—works +great for most applications and you shouldn't have to worry about how your activities are associated +with tasks or how they exist in the back stack. However, you might decide that you want to interrupt +the normal behavior. Perhaps you want an activity in your application to begin a new task when it is +started (instead of being placed within the current task); or, when you start an activity, you want +to bring forward an existing instance of it (instead of creating a new +instance on top of the back stack); or, you want your back stack to be cleared of all +activities except for the root activity when the user leaves the task.
+ +You can do these things and more, with attributes in the +{@code +<activity>} manifest element and with flags in the intent that you pass to {@link +android.app.Activity#startActivity startActivity()}.
+ +In this regard, the the principal {@code <activity>} +attributes you can use are:
+ +And the principal intent flags you can use are:
+ +In the following sections, you'll see how you can use these manifest attributes and intent +flags to define how activities are associated with tasks and how the behave in the back stack.
+ + +Caution: Most applications should not interrupt the default +behavior for activities and tasks. If you determine that it's necessary for your activity to modify +the default behaviors, use caution and be sure to test the usability of the activity during +launch and when navigating back to it from other activities and tasks with the Back button. +Be sure +to test for navigation behaviors that might conflict with the user's expected behavior.
+ + +Launch modes allow you to define how a new instance of an activity is associated with the +current task. You can define different launch modes in two ways:
+When you declare an activity in your manifest file, you can specify how the activity +should associate with tasks when it starts.
When you call {@link android.app.Activity#startActivity startActivity()}, +you can include a flag in the {@link android.content.Intent} that declares how (or +whether) the new activity should associate with the current task.
As such, if Activity A starts Activity B, Activity B can define in its manifest how it +should associate with the current task (if at all) and Activity A can also request how Activity +B should associate with current task. If both activities define how Activity B +should associate with a task, then Activity A's request (as defined in the intent) is honored +over Activity B's request (as defined in its manifest).
+ +Note: Some launch modes available for the manifest file +are not available as flags for an intent and, likewise, some launch modes available as flags +for an intent cannot be defined in the manifest.
+ + +When declaring an activity in your manifest file, you can specify how the activity should +associate with a task using the {@code <activity>} +element's {@code +launchMode} attribute.
+ +The {@code
+launchMode} attribute specifies an instruction on how the activity should be launched into a
+task. There are four different launch modes you can assign to the
+launchMode
+attribute:
For example, suppose a task's back stack consists of root activity A with activities B, C, +and D on top (the stack is A-B-C-D; D is on top). An intent arrives for an activity of type D. +If D has the default {@code "standard"} launch mode, a new instance of the class is launched and the +stack becomes A-B-C-D-D. However, if D's launch mode is {@code "singleTop"}, the existing instance +of D receives the intent through {@link +android.app.Activity#onNewIntent onNewIntent()}, because it's at the top of the stack—the +stack remains A-B-C-D. However, if an intent arrives for an activity of type B, then a new +instance of B is added to the stack, even if its launch mode is {@code "singleTop"}.
+Note: When a new instance of an activity is created, +the user can press the Back button to return to the previous activity. But when an existing +instance of +an activity handles a new intent, the user cannot press the Back button to return to the +state of +the activity before the new intent arrived in {@link android.app.Activity#onNewIntent +onNewIntent()}.
+Note: Although the activity starts in a new task, the +Back button still returns the user to the previous activity.
As another example, the Android Browser application declares that the web browser activity should +always open in its own task—by specifying the {@code singleTask} launch mode in the {@code <activity>} element. +This means that if your application issues an +intent to open the Android Browser, its activity is not placed in the same +task as your application. Instead, either a new task starts for the Browser or, if the Browser +already has a task running in the background, that task is brought forward to handle the new +intent.
+ +Regardless of whether an activity starts in a new task or in the same task as the activity that +started it, the Back button always takes the user to the previous activity. However, if you +start an activity that specifies the {@code singleTask} launch mode, then if an instance of +that activity exists in a background task, that whole task is brought to the foreground. At this +point, the back stack now includes all activities from the task brought forward, at the top of the +stack. Figure 4 illustrates this type of scenario.
+ +
+Figure 4. A representation of how an activity with +launch mode "singleTask" is added to the back stack. If the activity is already a part of a +background task with its own back stack, then the entire back stack also comes +forward, on top of the current task.
+ +For more information about using launch modes in the manifest file, see the
+<activity>
+element documentation, where the {@code launchMode} attribute and the accepted values are
+discussed more.
Note: The behaviors that you specify for your activity with the {@code launchMode} attribute +can be overridden by flags included with the intent that start your activity, as discussed in the +next section.
+ + + +When starting an activity, you can modify the default association of an activity to its task +by including flags in the intent that you deliver to {@link +android.app.Activity#startActivity startActivity()}. The flags you can use to modify the +default behavior are:
+ ++
This produces the same behavior as the {@code "singleTask"} {@code launchMode} value, +discussed in the previous section.
This produces the same behavior as the {@code "singleTop"} {@code launchMode} value, +discussed in the previous section.
There is no value for the {@code launchMode} +attribute that produces this behavior.
+{@code FLAG_ACTIVITY_CLEAR_TOP} is most often used in conjunction with {@code +FLAG_ACTIVITY_NEW_TASK}. When used together, these flags are a way of locating an existing activity +in another task and putting it in a position where it can respond to the intent.
+Note: If the launch mode of the designated activity is {@code +"standard"}, it too is removed from the stack and a new instance is launched in its place to handle +the incoming intent. That's because a new instance is always created for a new intent when the +launch mode is {@code "standard"}.
+The affinity indicates which task an activity prefers to belong to. By default, all the +activities from the same application have an affinity for each other. So, by default, all +activities in the same application prefer to be in the same task. However, you can modify +the default affinity for an activity. Activities defined in +different applications can share an affinity, or activities defined in the same application can be +assigned different task affinities.
+ +You can modify the affinity for any given activity with the {@code taskAffinity} attribute +of the {@code <activity>} +element.
+ +The {@code taskAffinity} +attribute takes a string value, which must be unique from the default package name +declared in the {@code +<manifest>} element, because the system uses that name to identify the default task +affinity for the application.
+ +The affinity comes into play in two circumstances:
+A new activity is, by default, launched into the task of the activity +that called {@link android.app.Activity#startActivity startActivity()}. It's pushed onto the same +back stack as the caller. However, if the intent passed to {@link +android.app.Activity#startActivity startActivity()} contains the {@link +android.content.Intent#FLAG_ACTIVITY_NEW_TASK} +flag, the system looks for a different task to house the new activity. Often, it's a new task. +However, it doesn't have to be. If there's already an existing task with the same affinity as the +new activity, the activity is launched into that task. If not, it begins a new task.
+ +If this flag causes an activity to begin a new task and the user presses the Home button +to leave +it, there must be some way for the user to navigate back to the task. Some entities (such as the +notification manager) always start activities in an external task, never as part of their own, so +they always put {@code FLAG_ACTIVITY_NEW_TASK} in the intents they pass to {@link +android.app.Activity#startActivity startActivity()}. If you have an activity that can be invoked by +an external entity that might use this flag, take care that the user has a independent way to get +back to the task that's started, such as with a launcher icon (the root activity of the task +has a {@link android.content.Intent#CATEGORY_LAUNCHER} intent filter; see the Starting a task section below).
+In this case, the activity can move from the task it starts to the task it has an affinity +for, when that task comes to the foreground.
+For example, suppose that an activity that reports weather conditions in selected cities is +defined as part of a travel application. It has the same affinity as other activities in the same +application (the default application affinity) and it allows re-parenting with this attribute. +When one of your activities starts the weather reporter activity, it initially belongs to the same +task as your activity. However, when the travel application's task comes to the foreground, the +weather reporter activity is reassigned to that task and displayed within it.
+Tip: If an {@code .apk} file contains more than one "application" +from the user's point of view, you probably want to use the {@code taskAffinity} +attribute to assign different affinities to the activities associated with each "application".
+ + + +If the user leaves a task for a long time, the system clears the task of all activities except +the root activity. When the user returns to the task again, only the root activity is restored. +The system behaves this way, because, after an extended amount of time, users likely have abandoned +what they were doing before and are returning to the task to begin something new.
+ +There are some activity attributes that you can use to modify this behavior:
+ +alwaysRetainTaskState
+clearTaskOnLaunchfinishOnTaskLaunch
+You can set up an activity as the entry point for a task by giving it an intent filter with +{@code "android.intent.action.MAIN"} as the specified action and {@code +"android.intent.category.LAUNCHER"} as the specified category. For example:
+ ++<activity ... > + <intent-filter ... > + <action android:name="android.intent.action.MAIN" /> + <category android:name="android.intent.category.LAUNCHER" /> + </intent-filter> + ... +</activity> ++ +
An intent filter of this kind causes an icon and label for the +activity to be displayed in the application launcher, giving users a way to launch the activity and +to return to the task that it creates any time after it has been launched. +
+ +This second ability is important: Users must be able to leave a task and then come back to it +later using this activity launcher. For this reason, the two launch +modes that mark activities as always initiating a task, {@code "singleTask"} and "{@code +"singleInstance"}, should be used only when the activity has an {@link +android.content.Intent#ACTION_MAIN} +and a {@link android.content.Intent#CATEGORY_LAUNCHER} +filter. Imagine, for example, what could happen if the filter is missing: An intent launches a +{@code "singleTask"} activity, initiating a new task, and the user spends some time working in +that task. The user then presses the Home button. The task is now sent to the background +and is +not visible. Now the user has no way to return to the task, because it is not represented in the +application launcher. +
+ +For those cases where you don't want the user to be able to return to an activity, set the
+ <activity> element's
+{@code
+finishOnTaskLaunch} to {@code "true"} (see Clearing the stack).
There are two ways to build your application using the Ant build script: one for - testing/debugging your application — debug mode — and one for building your - final package for release — release mode. Regardless of which way you build your application, - it must be signed before it can install on an emulator or device—with a debug key when building - in debug mode and with your own private key when building in release mode.
- -Whether you're building in debug mode or release mode, you need to use the Ant tool to compile - and build your project. This will create the .apk file that you can install on an emulator or device. - When you build in debug mode, the .apk file is automatically signed by the SDK tools with - a debug key, so it's instantly ready for installation onto an emulator or attached - development device. You cannot distribute an application that is signed with a debug key. - When you build in release mode, the .apk file is unsigned, so you - must manually sign it with your own private key, using Keytool and Jarsigner.
- -It's important that you read and understand Signing Your Applications, particularly once - you're ready to release your application and share it with end-users. That document describes the - procedure for generating a private key and then using it to sign your .apk file. If you're just - getting started, however, you can quickly run your applications on an emulator or your own - development device by building in debug mode.
- -If you don't have Ant, you can obtain it from the Apache Ant - home page. Install it and make sure it is in your executable PATH. Before calling Ant, you - need to declare the JAVA_HOME environment variable to specify the path to where the JDK is - installed.
- -Note: When installing JDK on Windows, the default is to install
- in the "Program Files" directory. This location will cause ant to fail, because of
- the space. To fix the problem, you can specify the JAVA_HOME variable like this:
-
set JAVA_HOME=c:\Progra~1\Java\<jdkdir>- -
The easiest solution, however, is to install JDK in a non-space directory, for example:
- -c:\java\jdk1.6.0_02- -
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}.
- -To build in debug mode:
- --ant debug -- -
This creates your debug .apk file inside the project bin/ directory, named
- <your_project_name>-debug.apk. The file is already signed with
- the debug key and has been aligned with
- zipalign.
-
Each time you change a source file or resource, you must run Ant again in order to package up - the latest version of the application.
- -To install and run your application on an emulator, see the following section about Running on the Emulator.
- -When you're ready to release and distribute your application to end-users, you must build your - application in release mode. Once you have built in release mode, it's a good idea to perform - additional testing and debugging with the final .apk.
- -Before you start building your application in release mode, be aware that you must sign the - resulting application package with your private key, and should then align it using the {@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.
- -If you build your application unsigned, then you will need to manually sign and align - the package.
- -To build an unsigned .apk in release mode:
- --ant release --
This creates your Android application .apk file inside the project bin/
- directory, named <your_project_name>-unsigned.apk.
Note: The .apk file is unsigned at this point and can't - be installed until signed with your private key.
- -Once you have created the unsigned .apk, your next step is to sign the .apk with your private - key and then align it with {@code zipalign}. To complete this procedure, read Signing Your Applications.
- -When your .apk has been signed and aligned, it's ready to be distributed to end-users.
- You should test the final build on different devices or AVDs to ensure that it
- runs properly on different platforms.
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 ant.properties} file. With this information provided, - the build script will prompt you for your keystore and alias password when you build in release - mode and produce your final application package, which will be ready for distribution.
- -Caution: Due to the way Ant handles input, the password that - you enter during the build process will be visible. If you are concerned about - your keystore and alias password being visible on screen, then you may prefer to perform the - application signing manually, via Jarsigner (or a similar tool). To instead perform the signing - procedure manually, build unsigned and then continue with - Signing Your Applications.
- -To specify your keystore and alias, open the project {@code ant.properties} file (found in - the root of the project directory) and add entries for {@code key.store} and {@code key.alias}. - For example:
--key.store=path/to/my.keystore -key.alias=mykeystore -- -
Save your changes. Now you can build a signed .apk in release mode:
- --ant release --
Caution: As described above, your password will be - visible on the screen.
-This creates your Android application .apk file inside the project bin/
- directory, named <your_project_name>-release.apk. This .apk file has
- been signed with the private key specified in {@code ant.properties} and aligned with {@code
- zipalign}. It's ready for installation and distribution.
Once you have signed your application with a private key, you can install and run it on an - emulator or device. You can - also try installing it onto a device from a web server. Simply upload the signed .apk to a web - site, then load the .apk URL in your Android web browser to download the application and begin - installation. (On your device, be sure you have enabled - Settings > Applications > Unknown sources.)
- -Before you can run your application on the Android Emulator, you must create an AVD.
- -To run your application:
- -From your SDK's platform-tools/ directory, execute the {@code android} tool
-with the avd options:
-android avd -- -
In the Virtual Devices view, select an AVD and click Start.
-From your SDK's tools/ directory, install the {@code .apk} on the
- emulator:
-adb install <path_to_your_bin>.apk -- -
Your .apk file (signed with either a release or debug key) is in your project {@code bin/} - directory after you build your application.
- -If there is more than one emulator running, you must specify the emulator upon which to
- install the application, by its serial number, with the -s option. For
- example:
-adb -s emulator-5554 install path/to/your/app.apk -- -
To see a list of available device serial numbers, execute {@code adb devices}.
-If you don't see your application on the emulator, try closing the emulator and launching the - virtual device again from the AVD Manager. Sometimes when you install an application for the - first time, it won't show up in the application launcher or be accessible by other applications. - This is because the package manager usually examines manifests completely only on emulator - startup.
- -Be certain to create multiple AVDs upon which to test your application. You should have one - AVD for each platform and screen type with which your application is compatible. For instance, if - your application compiles against the Android 1.5 (API Level 3) platform, you should create an - AVD for each platform equal to and greater than 1.5 and an AVD for each screen type you support, then test your - application on each one.
- -Tip: If you have only one emulator running, you can
- build your application and install it on the emulator in one simple step. Navigate to the root of
- your project directory and use Ant to compile the project with install mode: ant
- install. This will build your application, sign it with the debug key, and install it on
- the currently running emulator.
Before you can run your application on a device, you must perform some basic setup for your - device:
- -Read Setting up a Device for - Development for more information.
- -Once your device is set up and connected via USB, navigate to your SDK's platform-tools/
- directory and install the .apk on the device:
-adb -d install path/to/your/app.apk -- -
The {@code -d} flag specifies that you want to use the attached device (in case you also have - an emulator running).
- -For more information on the tools used above, please see the following documents:
- -As you begin developing Android applications, understand that all Android applications must be - digitally signed before the system will install them on an emulator or device. There are two ways - to do this: with a debug key (for immediate testing on an emulator or development - device) or with a private key (for application distribution).
- -The Android build tools help you get started by automatically signing your .apk files with a - debug key at build time. This means that you can compile your application and install it on the - emulator without having to generate your own private key. However, please note that if you intend - to publish your application, you must sign the application with your own private - key, rather than the debug key generated by the SDK tools.
- -The ADT plugin helps you get started quickly by signing your .apk files with a debug key, - prior to installing them on an emulator or development device. This means that you can quickly - run your application from Eclipse without having to generate your own private key. No specific - action on your part is needed, provided ADT has access to Keytool. However, please note that if - you intend to publish your application, you must sign the application with your - own private key, rather than the debug key generated by the SDK tools.
- -Please read Signing Your - Applications, which provides a thorough guide to application signing on Android and what it - means to you as an Android application developer. The document also includes a guide to exporting - and signing your application with the ADT's Export Wizard.
- -ant cleanall target before clean
-(ant all clean), other projects are also cleaned. For instance if you clean a
-test project, the tested project is also cleaned.ant debugant emma debugant releaseant instrument
- emma
- target)ant <build_target> installinstall by itself fails.ant installd.apk is not
- already built.ant installr.apk is not
- already built.ant installt.apk of the
- tested application. This fails if the .apk is not already built.ant installi.apk is not already
- built.ant test.apk files must be
- previously installed.ant debug installt test.apk files, and
- runs the tests.ant emma debug install test.apk files, and
- runs the tests with code coverage enabled.Eclipse and ADT provide an environment where most of the details of the build process are - hidden from you. By default, the build process constantly runs in the background as you make - changes to your project.
- -When Eclipse automatically builds your application, it enables debugging and signs the
- .apk with a debug key, by default. When you run the application,
- Eclipse invokes ADB and installs your application to a device or emulator, so you do not have to
- manually perform these tasks. Since most of the build process is taken care of by Eclipse, the
- following topics show you how to run an application, which will automatically build your
- application as well.
To distribute your application, however, you must build your application in release mode and sign the
- .apk file with your own private key.
This document shows you how to run your application on an emulator or a real device - from Eclipse—all of which is done using the debug version of your application. - For more information about how to sign your application with a private key for release, see Signing Your Applications
- -Before you can run your application on the Android Emulator, you must create an AVD.
- -To run (or debug) your application, select Run > Run (or - Run > Debug) from the Eclipse menu bar. The ADT plugin will - automatically create a default run configuration for the project. Eclipse will then perform the - following:
- -By default, Android run configurations use an "automatic target" mode for selecting a - device target. For information on how automatic target mode selects a deployment target, see - Automatic and manual target modes below.
-If you run the application with the Debug option, the application will start in the "Waiting For Debugger" mode. Once the debugger - is attached, Eclipse opens the Debug perspective and starts the application's main activity. Otherwise, if you run the - application with the normal Run option, Eclipse installs the application on the device and launches the main activity.
- -To set or change the run configuration used for your project, use the run configuration - manager. See the section below about Creating a Run Configuration for more information.
- -Be certain to create multiple AVDs upon which to test your application. You should have one - AVD for each platform and screen type with which your application is compatible. For instance, if - your application compiles against the Android 1.5 (API Level 3) platform, you should create an - AVD for each platform equal to and greater than 1.5 and an AVD for each screen type you support, then test your - application on each one.
- -Before you can run your application on a device, you must perform some basic setup for your - device:
- -android:debuggable attribute of the <application>
- element to true. As of ADT 8.0, this is done by default when you build in debug mode.Read Using Hardware Devices - for more information.
- -Once set up and your device is connected via USB, install your application on the device by - selecting Run > Run (or Run > - Debug) from the Eclipse menu bar.
- -The run configuration specifies the project to run, the Activity to start, the emulator or - connected device to use, and so on. When you first run a project as an Android - Application, ADT will automatically create a run configuration. The default run - configuration will launch the default project Activity and use automatic target mode for device - selection (with no preferred AVD). If the default settings don't suit your project, you can - customize the run configuration or even create a new one.
- -To create or modify a run configuration, refer to the Eclipse documentation on how to create Run configurations. - The following steps highlight the important things you need to do for an Android project:
- -In the Target tab, consider whether you'd like to use Manual or Automatic mode when - selecting an AVD to run your application. See the following section on Automatic and manual target modes).
- -You can specify any emulator options to the Additional Emulator Command Line Options
- field. For example, you could add -scale 96dpi to scale the AVD's screen to an
- accurate size, based on the dpi of your computer monitor. For a full list of emulator
- options, see the Android
- Emulator document.
By default, a run configuration uses the automatic target mode in order to - select an AVD. In this mode, ADT will select an AVD for the application in the following - manner:
- -However, if a "preferred AVD" is selected in the run configuration, then the application will - always be deployed to that AVD. If it's not already running, then a new emulator will be - launched.
- -If your run configuration uses manual mode, then the "device chooser" is - presented every time that your application is run, so that you can select which AVD to use.
\ No newline at end of file diff --git a/docs/html/guide/developing/building/index.jd b/docs/html/guide/developing/building/index.jd deleted file mode 100644 index 569cd28387b8..000000000000 --- a/docs/html/guide/developing/building/index.jd +++ /dev/null @@ -1,81 +0,0 @@ -page.title=Building and Running -@jd:body - -During the build process, your Android projects are compiled and packaged into an .apk file,
- the container for your application binary. It contains all of the information necessary to run
- your application on a device or emulator, such as compiled .dex files (.class files
- converted to Dalvik byte code), a binary version of the AndroidManifest.xml file, compiled
- resources (resources.arsc) and uncompiled resource files for your application.
If you are developing in Eclipse, the ADT plugin incrementally builds your project as you
- make changes to the source code. Eclipse outputs an .apk file automatically to the bin folder of
- the project, so you do not have to do anything extra to generate the .apk.
If you are developing in a non-Eclipse environment, you can build your project with the
- generated build.xml Ant file that is in the project directory. The Ant file calls targets that
- automatically call the build tools for you.
To run an application on an emulator or device, the application must be signed using debug or - release mode. You typically want to sign your application in debug mode when you develop and test - your application, because the build tools use a debug key with a known password so you do not have - to enter it every time you build. When you are ready to release the application to Google - Play, you must sign the application in release mode, using your own private key.
- -Fortunately, Eclipse or your Ant build script signs the application for you in debug mode - when you build your application. You can also easily setup Eclipse or your Ant build to sign your - application in release mode as well. For more information on signing applications, see Signing Your Applications.
- -The following diagram depicts the components involved in building and running an application:
- -
-
- The build process involves many tools and processes that generate intermediate files on the
- way to producing an .apk. If you are developing in Eclipse, the complete build process is
- automatically done periodically as you develop and save your code changes. If you are using other
- IDEs, this build process is done every time you run the generated Ant build script for your
- project. It is useful, however, to understand what is happening under the hood since much of the
- tools and processes are masked from you. The following diagram depicts the different tools and
- processes that are involved in a build:
-
- The general process for a typical build is outlined below:
- -AndroidManifest.xml file and the XML files for your Activities, and compiles them. An R.java is
- also produced so you can reference your resources from your Java code..aidl interfaces that you have into Java interfaces.R.java and .aidl files, are compiled by the Java
- compiler and .class files are output..dex files so that
- they can be packaged into the final .apk file..apk file..apk is built, it must be signed with either a debug or release key before it can
- be installed to a device..apk with
- the zipalign tool. Aligning the final .apk decreases memory usage when the application is
- running on a device.You should be redirected. Please click here.
- - \ No newline at end of file diff --git a/docs/html/guide/developing/debugging/ddms.jd b/docs/html/guide/developing/debugging/ddms.jd deleted file mode 100644 index 9892e49f1eec..000000000000 --- a/docs/html/guide/developing/debugging/ddms.jd +++ /dev/null @@ -1,357 +0,0 @@ -page.title=Using DDMS -parent.title=Debugging -parent.link=index.html -@jd:body - -Android ships with a debugging tool called the Dalvik Debug Monitor Server (DDMS), which - provides port-forwarding services, screen capture on the device, thread and heap information on - the device, logcat, process, and radio state information, incoming call and SMS spoofing, - location data spoofing, and more. This page provides a modest discussion of DDMS features; it is - not an exhaustive exploration of all the features and capabilities.
- -DDMS is integrated into Eclipse and is also shipped in the tools/ directory of the
- SDK. DDMS works with both the emulator and a connected device. If both are connected and running simultaneously,
- DDMS defaults to the emulator.
ddms (or ./ddms on Mac/Linux) from the tools/
- directory. On Android, every application runs in its own process, each of which runs in its own virtual machine - (VM). Each VM exposes a unique port that a debugger can attach to.
- -When DDMS starts, it connects to adb.
- When a device is connected, a VM monitoring service is created between
- adb and DDMS, which notifies DDMS when a VM on the device is started or terminated. Once a VM
- is running, DDMS retrieves the the VM's process ID (pid), via adb, and opens a connection to the
- VM's debugger, through the adb daemon (adbd) on the device. DDMS can now talk to the VM using a
- custom wire protocol.
DDMS assigns a debugging port to each VM on the device. Typically, - DDMS assigns port 8600 for the first debuggable VM, the next on 8601, and so on. When a debugger - connects to one of these ports, all traffic is forwarded to the debugger from the associated - VM. You can only attach a single debugger to a single port, but DDMS can handle multiple, attached - debuggers.
- -By default, DDMS also listens on another debugging port, the DDMS "base port" (8700, by default). - The base port is a port forwarder, which can accept VM traffic from any debugging port and forward - it to the debugger on port 8700. This allows you to attach one debugger to port 8700, and debug - all the VMs on a device. The traffic that is forwarded is determined by the currently selected process - in the DDMS Devices view.
- -The following screenshot shows a typical DDMS screen in Eclipse. If you are starting DDMS from
- the command line, the screen is slightly different, but much of the functionality is identical.
- Notice that the highlighted process, com.android.email, that is running in the emulator
- has the debugging port 8700 assigned to it as well as 8606. This signifies that DDMS is currently
- forwarding port 8606 to the static debugging port of 8700.
- Figure 1. - Screenshot of DDMS
- -If you are not using Eclipse and ADT, read Configuring - your IDE to attach to the debugging port, for more information on attaching your - debugger.
- -Tip: You can set a number of DDMS preferences in
- File > Preferences. Preferences are saved to
- $HOME/.android/ddms.cfg.
Known debugging issues with Dalvik
- Debugging an application in the Dalvik VM should work the same as it does in other VMs. However,
- when single-stepping out of synchronized code, the "current line" cursor may jump to the last
- line in the method for one step.
DDMS allows you to view how much heap memory a process is using. This information is useful in - tracking heap usage at a certain point of time during the execution of your application.
-To view heap usage for a process:
-DDMS provides a feature to track objects that are being allocated to memory and to see which - classes and threads are allocating the objects. This allows you to track, in real time, where - objects are being allocated when you perform certain actions in your application. This - information is valuable for assessing memory usage that can affect application performance. -
- -To track memory allocation of objects:
-DDMS provides a File Explorer tab that allows you to view, copy, and delete files on the - device. This feature is useful in examining files that are created by your application or if you - want to transfer files to and from the device.
- -To work with an emulator or device's file system:
-The Threads tab in DDMS shows you the currently running threads for a selected process.
- -Method profiling is a means to track certain metrics about a method, such as number of calls, - execution time, and time spent executing the method. If you want more granular control over - where profiling data is collected, use the {@link android.os.Debug#startMethodTracing()} and - {@link android.os.Debug#stopMethodTracing()} methods. For more information about generating trace logs, see - Profiling and Debugging UIs.
- -Before you start method profiling in DDMS, be aware of the following restrictions:
-To start method profiling:
-In Android 4.0, the DDMS (Dalvik Debug Monitor Server) includes a Detailed -Network Usage tab that makes it possible to track when your application is -making network requests. Using this tool, you can monitor how and when your app -transfers data and optimize the underlying code appropriately. You can also -distinguish between different traffic types by applying a “tag” to network -sockets before use.
- -These tags are shown in a stack area chart in DDMS, as shown in figure 2:
- -
-Figure 2. Network Usage tab.
- -By monitoring the frequency of your data transfers, and the amount of data -transferred during each connection, you can identify areas of your application -that can be made more battery-efficient. Generally, you should look for -short spikes that can be delayed, or that should cause a later transfer to be -pre-empted.
- -To better identify the cause of transfer spikes, the -{@link android.net.TrafficStats} API allows you -to tag the data transfers occurring within a thread using {@link -android.net.TrafficStats#setThreadStatsTag setThreadStatsTag()}, followed -by manually tagging (and untagging) individual sockets using {@link -android.net.TrafficStats#tagSocket tagSocket()} and {@link -android.net.TrafficStats#untagSocket untagSocket()}. For example:
- -TrafficStats.setThreadStatsTag(0xF00D); -TrafficStats.tagSocket(outputSocket); -// Transfer data using socket -TrafficStats.untagSocket(outputSocket);- -
Alternatively, the Apache {@link org.apache.http.client.HttpClient} and -{@link java.net.URLConnection} APIs included in the platform -automatically tag sockets internally based on the active tag (as -identified by -{@link android.net.TrafficStats#getThreadStatsTag getThreadStatsTag()}). -These APIs correctly tag/untag sockets when recycled through -keep-alive pools. In the following example, -{@link android.net.TrafficStats#setThreadStatsTag setThreadStatsTag()} -sets the active tag to be {@code 0xF00D}. -There can only be one active tag per thread. -That is the value that will -be returned by {@link android.net.TrafficStats#getThreadStatsTag getThreadStatsTag()} -and thus used by {@link org.apache.http.client.HttpClient} - to tag sockets. The {@code finally} statement -invokes -{@link android.net.TrafficStats#clearThreadStatsTag clearThreadStatsTag()} -to clear the tag.
- -TrafficStats.setThreadStatsTag(0xF00D);
- try {
- // Make network request using HttpClient.execute()
- } finally {
- TrafficStats.clearThreadStatsTag();
-}
-
-Socket tagging is supported in Android 4.0, but real-time stats will only be -displayed on devices running Android 4.0.3 or higher.
- -LogCat is integrated into DDMS, and outputs the messages that you print out using the {@link android.util.Log} - class along with other system messages such as stack traces when exceptions are thrown. View the - Reading and - Writing Log Messages. topic for more information on how to log messages to the LogCat.
- -When you have set up your logging, you can use the LogCat feature of DDMS to filter certain - messages with the following buttons:
- -You can also setup your own custom filter to specify more details such as filtering messages - with the log tags or with the process id that generated the log message. The add filter, - edit filter, and delete filter buttons let you manage your custom filters.
- -The Emulator control tab lets you simulate a - phone's voice and data network status. This is useful when you want to test your application's - robustness in differing network environments.
- -The Telephony Status section of the Emulator - controls tab lets you change different aspects of the phone's networks status, speed and latency. - The following options are available to you and are effective immediately after you set them:
- -The Telephony Actions section of the Emulator - controls tab lets you spoof calls and messages. This is useful when you want to to test your - application's robustness in responding to incoming calls and messages that are sent to the phone. - The following actions are available to you:
- -If your application depends on the location of the phone, you can have DDMS send your - device or AVD a mock location. This is useful if you - want to test different aspects of your application's location specific features without - physically moving. The following geolocation data types are available to you:
- -The Dev Tools application is installed by default on all system images included with the SDK, - so you can use it with the Android Emulator. With the Dev Tools application, you can enable a - number of settings on your device that will make it easier to test and debug your applications.
- -If you'd like to install the Dev Tools application - on a real development device, you can copy the application from your emulator and then install it - on your device using ADB. To copy the application from a running emulator, execute:
--adb -e pull /system/app/Development.apk ./Development.apk -- -
This copies the .apk file into the current directory. Then install it on your connected device - with:
--adb -d install Development.apk -- -
To get started, launch the Dev Tools application and select Development Settings. This will - open the Development Settings page with the following options (among others):
- -Note: You cannot turn this feature off once it is on, without - restarting the emulator.
These settings will be remembered across emulator restarts.
- - - diff --git a/docs/html/guide/developing/debugging/debugging-log.jd b/docs/html/guide/developing/debugging/debugging-log.jd deleted file mode 100644 index b5b626e9bf3a..000000000000 --- a/docs/html/guide/developing/debugging/debugging-log.jd +++ /dev/null @@ -1,308 +0,0 @@ -page.title=Reading and Writing Logs -parent.title=Debugging -parent.link=index.html -@jd:body - -The Android logging system provides a mechanism for collecting and viewing system debug - output. Logcat dumps a log of system messages, which include things such as stack traces when the - emulator throws an error and messages that you have written from your application by using the - {@link android.util.Log} class. You can run LogCat through ADB or from DDMS, which allows you to - read the messages in real time.
- -Log class{@link android.util.Log} is a logging class that you can utilize in your code to print out - messages to the LogCat. Common logging methods include:
- -
-Log.i("MyActivity", "MyClass.getView() — get item number " + position);
-
-
- The LogCat will then output something like:
--I/MyActivity( 1557): MyClass.getView() — get item number 1 -- -
You can use LogCat from within DDMS or call it on an ADB shell. For more information on how to - use LogCat within DDMS, see Using - DDMS. To run LogCat, through the ADB shell, the general usage is:
--[adb] logcat [<option>] ... [<filter-spec>] ... -- -
You can use the logcat command from your development computer or from a remote
- adb shell in an emulator/device instance. To view log output in your development computer, you
- use
-$ adb logcat -- -
and from a remote adb shell you use
--# logcat -- -
The following table describes the logcat command line options:
-c |
-
- Clears (flushes) the entire log and exits. | -
-d |
-
- Dumps the log to the screen and exits. | -
-f <filename> |
-
- Writes log message output to <filename>. The default is
- stdout. |
-
-g |
- Prints the size of the specified log buffer and exits. | -
-n <count> |
-
- Sets the maximum number of rotated logs to <count>. The default value
- is 4. Requires the -r option. |
-
-r <kbytes> |
-
- Rotates the log file every <kbytes> of output. The default value is
- 16. Requires the -f option. |
-
-s |
-
- Sets the default filter spec to silent. | -
-v <format> |
-
- Sets the output format for log messages. The default is brief format. For a
- list of supported formats, see Controlling Log Output
- Format. |
-
Every Android log message has a tag and a priority associated with it.
- -V — Verbose (lowest priority)D — DebugI — InfoW — WarningE — ErrorF — FatalS — Silent (highest priority, on which nothing is ever printed)You can obtain a list of tags used in the system, together with priorities, by running
- LogCat and observing the first two columns of each message, given as
- <priority>/<tag>.
Here's an example of logcat output that shows that the message relates to priority level "I" - and tag "ActivityManager":
-
-I/ActivityManager( 585): Starting activity: Intent { action=android.intent.action...}
-
-
- To reduce the log output to a manageable level, you can restrict log output using filter - expressions. Filter expressions let you indicate to the system the tags-priority - combinations that you are interested in — the system suppresses other messages for the - specified tags.
- -A filter expression follows this format tag:priority ..., where tag
- indicates the tag of interest and priority indicates the minimum level of
- priority to report for that tag. Messages for that tag at or above the specified priority are
- written to the log. You can supply any number of tag:priority specifications in a
- single filter expression. The series of specifications is whitespace-delimited.
Here's an example of a filter expression that suppresses all log messages except those with - the tag "ActivityManager", at priority "Info" or above, and all log messages with tag "MyApp", - with priority "Debug" or above:
--adb logcat ActivityManager:I MyApp:D *:S -- -
The final element in the above expression, *:S, sets the priority level for all
- tags to "silent", thus ensuring only log messages with "View" and "MyApp" are displayed. Using
- *:S is an excellent way to ensure that log output is restricted to the filters that
- you have explicitly specified — it lets your filters serve as a "whitelist" for log
- output.
The following filter expression displays all log messages with priority level "warning" and higher, on all tags:
--adb logcat *:W -- -
If you're running LogCat from your development computer (versus running it on a
- remote adb shell), you can also set a default filter expression by exporting a value for the
- environment variable ANDROID_LOG_TAGS:
-export ANDROID_LOG_TAGS="ActivityManager:I MyApp:D *:S" -- -
Note that ANDROID_LOG_TAGS filter is not exported to the emulator/device
- instance, if you are running LogCat from a remote shell or using adb shell
- logcat.
Log messages contain a number of metadata fields, in addition to the tag and priority. You can
- modify the output format for messages so that they display a specific metadata field. To do so,
- you use the -v option and specify one of the supported output formats listed
- below.
brief — Display priority/tag and PID of the process issuing the
- message (the default format).process — Display PID only.tag — Display the priority/tag only.raw — Display the raw log message, with no other metadata fields.time — Display the date, invocation time, priority/tag, and PID of the
- process issuing the message.threadtime — Display the date, invocation time, priority, tag, and
- the PID and TID of the thread issuing the message.long — Display all metadata fields and separate messages with blank
- lines.When starting LogCat, you can specify the output format you want by using the
- -v option:
-[adb] logcat [-v <format>] -- -
Here's an example that shows how to generate messages in thread output
- format:
-adb logcat -v thread -- -
Note that you can only specify one output format with the -v option.
The Android logging system keeps multiple circular buffers for log messages, and not all of
- the log messages are sent to the default circular buffer. To see additional log messages, you can
- run the logcat command with the -b option, to request viewing of an alternate
- circular buffer. You can view any of these alternate buffers:
radio — View the buffer that contains radio/telephony related
- messages.events — View the buffer containing events-related messages.main — View the main log buffer (default)The usage of the -b option is:
-[adb] logcat [-b <buffer>] -- -
Here's an example of how to view a log buffer containing radio and telephony messages:
--adb logcat -b radio -- -
By default, the Android system sends stdout and stderr
- (System.out and System.err) output to /dev/null. In
- processes that run the Dalvik VM, you can have the system write a copy of the output to the log
- file. In this case, the system writes the messages to the log using the log tags
- stdout and stderr, both with priority I.
To route the output in this way, you stop a running emulator/device instance and then use the
- shell command setprop to enable the redirection of output. Here's how you do it:
-$ adb shell stop -$ adb shell setprop log.redirect-stdio true -$ adb shell start -- -
The system retains this setting until you terminate the emulator/device instance. To use the
- setting as a default on the emulator/device instance, you can add an entry to
- /data/local.prop on the device.
- If you're developing a web application for Android, you can debug your JavaScript using the console JavaScript APIs, - which output messages to LogCat. For more information, see - Debugging Web Apps.
diff --git a/docs/html/guide/developing/debugging/debugging-projects-cmdline.jd b/docs/html/guide/developing/debugging/debugging-projects-cmdline.jd deleted file mode 100644 index 3b5ceabaf3ba..000000000000 --- a/docs/html/guide/developing/debugging/debugging-projects-cmdline.jd +++ /dev/null @@ -1,78 +0,0 @@ -page.title=Debugging from Other IDEs -parent.title=Debugging -parent.link=index.html -@jd:body - - -If you are not using Eclipse to develop, you can still take advantage of all the tools that - the Android SDK provides for debugging. A basic debugging environment consists of:
- - - -You need to obtain a JDWP-compliant Java debugger to properly debug your application. - Most Java IDEs will already have one included, or you can use a command line debugger, - such as JDB, if you are using a simple text editor to develop applications.
- -A Java Debugger assists you in finding problems with - your code by letting you set breakpoints, step through execution of your application, and examine - variable values. Since you are not using Eclipse, you have to manually start up the debugging - environment yourself by running a few tools that are provided in the Android SDK. To begin - debugging your application, follow these general steps:
- -/tools directory. This also starts ADB if it is
- not already started. You should see your device appear in DDMS..apk file on the device or emulator. In DDMS, you should see your
- application running under the device that you installed it to.DDMS assigns a specific debugging port to every virtual machine that it finds on the - emulator. You must either attach your IDE to that port (listed on the Info tab for that VM), or - you can use a default port 8700 to connect to whatever application is currently selected on the - list of discovered virtual machines.
- -Your IDE should attach to your application running on the emulator, showing you its threads - and allowing you to suspend them, inspect their state, and set breakpoints. If you selected "Wait - for debugger" in the Development settings panel the application will run when Eclipse connects, - so you will need to set any breakpoints you want before connecting.
- -Changing either the application being debugged or the "Wait for debugger" option causes the - system to kill the selected application if it is currently running. You can use this to kill your - application if it is in a bad state by simply going to the settings and toggling the - checkbox.
- - - - - - - diff --git a/docs/html/guide/developing/debugging/debugging-projects.jd b/docs/html/guide/developing/debugging/debugging-projects.jd deleted file mode 100644 index 2283f8be9f6d..000000000000 --- a/docs/html/guide/developing/debugging/debugging-projects.jd +++ /dev/null @@ -1,67 +0,0 @@ -page.title=Debugging from Eclipse with ADT -parent.title=Debugging -parent.link=index.html -@jd:body - -If you are developing in Eclipse with the ADT plugin, you can use the built-in Java Debugger, - along with DDMS, to debug your applications. To access the debugger and - DDMS, Eclipse displays the debugger and DDMS features as perspectives, which are customized - Eclipse views that display certain tabs and windows depending on the perspective that you are in. - Eclipse also takes care of starting the ADB host daemon for you, so you do not have to run this - manually.
- -The Debug Perspective in Eclipse gives you access to the following tabs:
- -You can access the Debug Perspective by clicking Window > Open Perspective > - Debug. Refer to the appropriate documentation for the Eclipse debugger for more - information.
- -The DDMS Perspective in Eclipse lets you access all of the features - of DDMS from within the Eclipse IDE. The following sections of DDMS are available to you:
- -To access the DDMS perspective, go to Window > Open Perspective > - DDMS. If DDMS does not appear, go to Window > Open Perspective > Other - ... and select DDMS from the Open Perspective window that appears. For - more information on using DDMS, see Using the Dalvik Debug Monitor Server. -
\ No newline at end of file diff --git a/docs/html/guide/developing/debugging/debugging-tracing.jd b/docs/html/guide/developing/debugging/debugging-tracing.jd deleted file mode 100644 index 72f64982d9a8..000000000000 --- a/docs/html/guide/developing/debugging/debugging-tracing.jd +++ /dev/null @@ -1,402 +0,0 @@ -page.title=Profiling with Traceview and dmtracedump -parent.title=Debugging -parent.link=index.html -@jd:body - -Traceview is a graphical viewer for execution logs that you create by using the {@link - android.os.Debug} class to log tracing information in your code. Traceview can help you debug - your application and profile its performance.
- -When you have a trace log file (generated by adding tracing code to your application or by DDMS), - you can have Traceview load the log files and display their data in a window visualizes your application - in two panels:
- -The sections below provide addition information about the traceview output panes.
- -The image below shows a close up of the timeline panel. Each thread’s execution is shown
- in its own row, with time increasing to the right. Each method is shown in another color (colors
- are reused in a round-robin fashion starting with the methods that have the most inclusive time).
- The thin lines underneath the first row show the extent (entry to exit) of all the calls to the
- selected method. The method in this case is LoadListener.nativeFinished() and it was selected in
- the profile view.
- Figure 1. The Traceview Timeline Panel
- -Figure 2 shows the profile pane, a summary of all the time spent
- in a method. The table shows both the inclusive and exclusive times (as well as the percentage of
- the total time). Exclusive time is the time spent in the method. Inclusive time is the time spent
- in the method plus the time spent in any called functions. We refer to calling methods as
- "parents" and called methods as "children." When a method is selected (by clicking on it), it
- expands to show the parents and children. Parents are shown with a purple background and children
- with a yellow background. The last column in the table shows the number of calls to this method
- plus the number of recursive calls. The last column shows the number of calls out of the total
- number of calls made to that method. In this view, we can see that there were 14 calls to
- LoadListener.nativeFinished(); looking at the timeline panel shows that one of those calls took
- an unusually long time.
- Figure 2. The Traceview Profile Panel
- -Tracing creates two distinct pieces of output: a data file, which holds the trace - data, and a key file, which provides a mapping from binary identifiers to thread and - method names. The files are concatenated when tracing completes, into a single .trace - file.
- -Note: The previous version of Traceview did not concatenate
- these files for you. If you have old key and data files that you'd still like to trace, you can
- concatenate them yourself with cat mytrace.key mytrace.data >
- mytrace.trace.
The data file is binary, structured as follows (all values are stored in little-endian - order):
-
-* File format:
-* header
-* record 0
-* record 1
-* ...
-*
-* Header format:
-* u4 magic 0x574f4c53 ('SLOW')
-* u2 version
-* u2 offset to data
-* u8 start date/time in usec
-*
-* Record format:
-* u1 thread ID
-* u4 method ID | method action
-* u4 time delta since start, in usec
-
-
- The application is expected to parse all of the header fields, then seek to "offset to data" - from the start of the file. From there it just reads 9-byte records until EOF is reached.
- -u8 start date/time in usec is the output from gettimeofday(). It's mainly there so
- that you can tell if the output was generated yesterday or three months ago.
method action sits in the two least-significant bits of the method word. The - currently defined meanings are:
- -An unsigned 32-bit integer can hold about 70 minutes of time in microseconds.
- -The key file is a plain text file divided into three sections. Each section starts with a - keyword that begins with '*'. If you see a '*' at the start of a line, you have found the start - of a new section.
- -An example file might look like this:
--*version -1 -clock=global -*threads -1 main -6 JDWP Handler -5 Async GC -4 Reference Handler -3 Finalizer -2 Signal Handler -*methods -0x080f23f8 java/io/PrintStream write ([BII)V -0x080f25d4 java/io/PrintStream print (Ljava/lang/String;)V -0x080f27f4 java/io/PrintStream println (Ljava/lang/String;)V -0x080da620 java/lang/RuntimeException <init> ()V -[...] -0x080f630c android/os/Debug startMethodTracing ()V -0x080f6350 android/os/Debug startMethodTracing (Ljava/lang/String;Ljava/lang/String;I)V -*end --
The following list describes the major sections of a key file:
-clock=global, indicates that we use a common clock across all threads. A future
- version may use per-thread CPU time counters that are independent for every thread.Neither the threads nor methods sections are sorted.
- -To use Traceview, you need to generate log files containing the trace information you want to - analyze.
- -There are two ways to generate trace logs:
-Before you start generating trace logs, be aware of the following restrictions:
-This document focuses on using the {@link android.os.Debug} class to generate trace data. For more information on using DDMS - to generate trace data, see Using the Dalvik Debug Monitor Server. -
- -To create the trace files, include the {@link android.os.Debug} class and call one of the - {@link android.os.Debug#startMethodTracing() startMethodTracing()} methods. In the call, you - specify a base name for the trace files that the system generates. To stop tracing, call {@link - android.os.Debug#stopMethodTracing() stopMethodTracing()}. These methods start and stop method - tracing across the entire virtual machine. For example, you could call - {@link android.os.Debug#startMethodTracing() startMethodTracing()} in - your activity's {@link android.app.Activity#onCreate onCreate()} method, and call - {@link android.os.Debug#stopMethodTracing() stopMethodTracing()} in that activity's - {@link android.app.Activity#onDestroy()} method.
-
- // start tracing to "/sdcard/calc.trace"
- Debug.startMethodTracing("calc");
- // ...
- // stop tracing
- Debug.stopMethodTracing();
-
-
- When your application calls startMethodTracing(), the system creates a file called
- <trace-base-name>.trace. This contains the binary method trace data and a
- mapping table with thread and method names.
The system then begins buffering the generated trace data, until your application calls - stopMethodTracing(), at which time it writes the buffered data to the output file. If the system - reaches the maximum buffer size before stopMethodTracing() is called, the system stops tracing - and sends a notification to the console.
- -Interpreted code will run more slowly when profiling is enabled. Don't try to generate - absolute timings from the profiler results (i.e. "function X takes 2.5 seconds to run"). The - times are only useful in relation to other profile output, so you can see if changes have made - the code faster or slower.
- -When using the Android emulator, you must specify an SD card when you create your AVD because the trace files - are written to the SD card. Your application must have permission to write to the SD card as well. - -
The format of the trace files is previously described in this - document.
- -After your application has run and the system has created your trace files
- <trace-base-name>.trace on a device or emulator, you must copy those files to
- your development computer. You can use adb pull to copy the files. Here's an example
- that shows how to copy an example file, calc.trace, from the default location on the emulator to
- the /tmp directory on the emulator host machine:
-adb pull /sdcard/calc.trace /tmp -- -
To run Traceview and view the trace files, enter traceview
- <trace-base-name>. For example, to run Traceview on the example files copied in the
- previous section, use:
-traceview /tmp/calc -- -
Note: If you are trying to view the trace logs of an application
- that is built with ProGuard enabled (release mode build), some method and member names might be obfuscated.
- You can use the Proguard mapping.txt file to figure out the original unobfuscated names. For more information
- on this file, see the Proguard documentation.
dmtracedump is a tool that gives you an alternate way of generating
- graphical call-stack diagrams from trace log files. The tool uses the Graphviz Dot utility to
- create the graphical output, so you need to install Graphviz before running dmtracedump.
The dmtracedump tool generates the call stack data as a tree diagram, with each call - represented as a node. It shows call flow (from parent node to child nodes) using arrows. The - diagram below shows an example of dmtracedump output.
-Figure 3. Screenshot of dmtracedump
- -For each node, dmtracedump shows <ref>
- callname (<inc-ms>, <exc-ms>,<numcalls>), where
<ref> -- Call reference number, as used in trace logs<inc-ms> -- Inclusive elapsed time (milliseconds spent in method,
- including all child methods)<exc-ms> -- Exclusive elapsed time (milliseconds spent in method,
- not including any child methods)<numcalls> -- Number of callsThe usage for dmtracedump is:
--dmtracedump [-ho] [-s sortable] [-d trace-base-name] [-g outfile] <trace-base-name> -- -
The tool then loads trace log data from <trace-base-name>.data and
- <trace-base-name>.key. The table below lists the options for dmtracedump.
| Option | - -Description | -
|---|---|
-d <trace-base-name> |
-
- Diff with this trace name | -
-g <outfile> |
-
- Generate output to <outfile> | -
-h |
-
- Turn on HTML output | -
-o |
-
- Dump the trace file instead of profiling | -
-d <trace-base-name> |
-
- URL base to the location of the sortable javascript file | -
-t <percent> |
-
- Minimum threshold for including child nodes in the graph (child's inclusive time as a - percentage of parent inclusive time). If this option is not used, the default threshold - is 20%. | -
layoutopt
-Sometimes your application's layout can slow down your application.
- To help debug issues in your layout, the Android SDK provides the Hierarchy Viewer and
- layoutopt tools.
-
The Hierarchy Viewer application allows you to debug and optimize your user interface. It - provides a visual representation of the layout's View hierarchy (the View Hierarchy window) - and a magnified view of the display (the Pixel Perfect window).
- -layoutopt is a command-line tool that helps you optimize the layouts and layout
- hierarchies of your applications. You can run it against your layout files or resource
- directories to quickly check for inefficiencies or other types of problems that could be
- affecting the performance of your application.
- To run Hierarchy Viewer, follow these steps:
-- To preserve security, Hierarchy Viewer can only connect to devices running a - developer version of the Android system. -
-hierarchyviewer from the
- <sdk>/tools/
- directory.
- - To learn how to use the View Hierarchy window, go to - About the View Hierarchy window. To learn how to use the - Pixel Perfect window, go to About the Pixel Perfect window. -
-
-Figure 1. Hierarchy Viewer device window
-- The View Hierarchy window displays the View objects that form the UI of the - Activity that is running on your device or emulator. You use it to look at individual - View objects within the context of the entire View tree. For each View object, the View - Hierarchy window also displays rendering performance data. -
-- To see the View Hierarchy window, run Hierarchy Viewer as described in - the section Running Hierarchy Viewer and choosing a window. Next, click - View Hierarchy at the top of the device window. -
-- You should see four panes: -
-- To zoom in on the pane, use the slider at the bottom of the pane, or use your mouse - scroll wheel. To move around in the pane or reveal View objects that are not currently - visible, click and drag the pane. -
-- To highlight the nodes in the tree whose class or ID match a search string, enter the - string in the Filter by class or id: edit box at the bottom of the - window. The background of nodes that match the search string will change from gray to - bright blue. -
-- To save a screenshot of Tree View to a PNG file, click Save As PNG at - the top of the View Hierarchy window. This displays a dialog in which you can choose - a directory and file name. -
-- To save a layered screenshot of your device or emulator to an Adobe Photoshop (PSD) - file, click Capture Layers at the top of the View Hierarchy window. - This displays a dialog in which you can choose a directory or file name. - Each View in the UI is saved as a separate Photoshop layer. -
-- In Photoshop (or similar program that accepts .psd files), you can hide, show or edit a - layer independently of others. When you save a layered screenshot, you can examine and - modify the image of an individual View object. This helps you experiment with design - changes. -
-- You can also use Tree Overview to move around in the Tree View pane. Click and drag - the shaded rectangle over an area to reveal it in Tree View. -
-- The properties are organized by category. To find an individual property, expand - a category name by clicking the arrow on its left. This reveals all the properties - in that category. -
-- The outline colors of blocks in Layout View provide additional information: -
-- When the UI of the current Activity changes, the View Hierarchy window is not automatically - updated. To update it, click Load View Hierarchy at the top of the window. -
-- Also, the window is not updated if you switch to a new Activity. To update it, start by - clicking the window selection icon in the bottom left-hand corner of the window. This - navigates back to the Window Selection window. From this window, click the Android - component name of the new Activity and then click Load View Hierarchy - at the top of the window. -
-- A screenshot of the View Hierarchy window appears in figure 2. -
-
-Figure 2. The View Hierarchy window
-- Each node in Tree View represents a single View. Some information is always visible. Starting - at the top of the node, you see the following: -
-android:id
- attribute.
- - The colors indicate the following relative performance: -
-- When you select a node, additional information for the View appears in a small window above - the node. When you click one of the nodes, you see the following: -
-- An annotated screenshot of an individual node in the Tree View window appears in figure 3. -
-
-Figure 3. An annotated node in Tree View
-- The View Hierarchy window helps you debug an application by providing a static display - of the UI. The display starts with your application's opening screen. As you step through - your application, the display remains unchanged until you redraw it by invalidating and - then requesting layout for a View. -
-- To redraw a View in the display: -
-- Manually redrawing a View allows you to watch the View object tree and examine the properties of - individual View objects one step at a time as you go through breakpoints in your code. -
-- View Hierarchy also helps you identify slow render performance. You start by looking at the - View nodes with red or yellow performance indicators to identify the slower View objects. As you - step through your application, you can judge if a View is consistently slow or slow only in - certain circumstances. -
-- Remember that slow performance is not necessarily evidence of a problem, especially for - ViewGroup objects. View objects that have more children and more complex View objects render - more slowly. -
-- The View Hierarchy window also helps you find performance issues. Just by looking at the - performance indicators (the dots) for each View node, you can see which View objects are the - slowest to measure, layout, and draw. From that, you can quickly identify the problems you - should look at first. -
-- Pixel Perfect is a tool for examining pixel properties and laying out UIs from a design drawing. -
-- The Pixel Perfect window displays a magnified image of the screen that is currently - visible on the emulator or device. In it, you can examine the properties - of individual pixels in the screen image. You can also use the Pixel Perfect window - to help you lay out your application UI based on a bitmap design. -
-- To see the Pixel Perfect window, run Hierarchy Viewer, as described in - the section Running Hierarchy Viewer and choosing a window. Next, click - Inspect Screenshot at the top of the device window. The Pixel Perfect window - appears. -
-- In it, you see three panes: -
-- The magenta crosshair in the pane corresponds to the positioning - crosshair in the next pane. It only moves when you move the crosshair in the next pane. -
-- To zoom in or out on the image, use the Zoom slider at the bottom of - the pane, or use your mouse's scroll wheel. -
-- When you select a pixel in the Loupe pane, you see the following information at the - bottom of the pane: -
-- You use the cyan crosshair to do coarse positioning. Drag the crosshair in the image, - and the Loupe crosshair will move accordingly. You can also click on a point in the - Pixel Perfect pane, and the crosshair will move to that point. -
-- The image corresponding to the View object selected in the View Object pane is - outlined in a box that indicates the View object's position on the screen. For the - selected object, the box is bold red. Sibling and parent View objects have a light - red box. View objects that are neither parents nor siblings are in white. -
-- The layout box may have other rectangles either inside or outside it, each of which - indicates part of the View. A purple or green rectangle indicates the View bounding box. - A white or black box inside the layout box represents the padding, the - defined distance between the View object's content and its bounding box. An outer white - or black rectangle represents the margins, the distance between the - View bounding box and adjacent View objects. The padding and margin boxes are white if - the layout background is black, and vice versa. -
-- You can save the screen image being displayed in the Pixel Perfect pane as a PNG file. - This produces a screenshot of the current screen. To do this, click - Save as PNG at the top of the window. This displays a dialog, - in which you can choose a directory and filename for the file. -
-- The panes are not automatically refreshed when you change one of the View objects or go to - another Activity. To refresh the Pixel Perfect pane and the Loupe pane, click - Refresh Screenshot at the top of the window. This will change the panes - to reflect the current screen image. You still may need to refresh the View Object pane; - to do this, click Refresh Tree at the top of the window. -
-- To automatically refresh the panes while you are debugging, set - Auto Refresh at the top of the window, and then set a refresh rate - with the Refresh Rate slider at the bottom of the Loupe pane. -
-- You often construct a UI based on a design done as a bitmap image. The Pixel Perfect window - helps you match up your View layout to a bitmap image by allowing you to load the bitmap as an - overlay on the screen image. -
-- To use a bitmap image as an overlay: -
-- By default, the overlay has a 50% transparency, which allows you to see the screen - image underneath. You can adjust this with the Overlay: slider at the - bottom of the Loupe pane. -
-- Also by default, the overlay is not displayed in the Loupe pane. To display it, - set Show in Loupe at the top of the window. -
-- The overlay is not saved as part of the screenshot when you save the screen image as a PNG - file. -
-- A screenshot of the Pixel Perfect window appears in figure 4. -
-Figure 4. The Pixel Perfect window
-
- The layoutopt tool lets you analyze the XML files that define your
- application's UI to find inefficiencies in the view hierarchy.
- To run the tool, open a terminal and launch layoutopt <xmlfiles>
- from your SDK tools/ directory. The <xmlfiles> argument is a space-
- delimited list of resources you want to analyze, either uncompiled resource xml files or
- directories of such files.
-
- The tool loads the specified XML files and analyzes their definitions and - hierarchies according to a set of predefined rules. For every issue it detects, it - displays the following information: -
-The following is a sample of the output from the tool:
--$ layoutopt samples/ -samples/compound.xml - 7:23 The root-level <FrameLayout/> can be replaced with <merge/> - 11:21 This LinearLayout layout or its FrameLayout parent is useless -samples/simple.xml - 7:7 The root-level <FrameLayout/> can be replaced with <merge/> -samples/too_deep.xml - -1:-1 This layout has too many nested layouts: 13 levels, it should have <= 10! - 20:81 This LinearLayout layout or its LinearLayout parent is useless - 24:79 This LinearLayout layout or its LinearLayout parent is useless - 28:77 This LinearLayout layout or its LinearLayout parent is useless - 32:75 This LinearLayout layout or its LinearLayout parent is useless - 36:73 This LinearLayout layout or its LinearLayout parent is useless - 40:71 This LinearLayout layout or its LinearLayout parent is useless - 44:69 This LinearLayout layout or its LinearLayout parent is useless - 48:67 This LinearLayout layout or its LinearLayout parent is useless - 52:65 This LinearLayout layout or its LinearLayout parent is useless - 56:63 This LinearLayout layout or its LinearLayout parent is useless -samples/too_many.xml - 7:413 The root-level <FrameLayout/> can be replaced with <merge/> - -1:-1 This layout has too many views: 81 views, it should have <= 80! -samples/useless.xml - 7:19 The root-level <FrameLayout/> can be replaced with <merge/> - 11:17 This LinearLayout layout or its FrameLayout parent is useless -diff --git a/docs/html/guide/developing/debugging/index.jd b/docs/html/guide/developing/debugging/index.jd deleted file mode 100644 index 0ad1a088a6cb..000000000000 --- a/docs/html/guide/developing/debugging/index.jd +++ /dev/null @@ -1,188 +0,0 @@ -page.title=Debugging -@jd:body - - -
The Android SDK provides most of the tools that you need to debug your applications. You need - a JDWP-compliant debugger if you want to be able to do things such as step through code, - view variable values, and pause execution of an application. If you are using Eclipse, a - JDWP-compliant debugger is already included and there is no setup required. If you are using - another IDE, you can use the debugger that comes with it and attach the debugger to a special - port so it can communicate with the application VMs on your devices. The main components that - comprise a typical Android debugging environment are:
- -adb acts as a middleman between a device and your development system. It provides various
- device management capabilities, including moving and syncing files to the emulator, running a
- UNIX shell on the device or emulator, and providing a general means to communicate with
- connected emulators and devices.adb. DDMS can
- capture screenshots, gather thread and stack information, spoof incoming calls and SMS
- messages, and has many other features.adb device
- daemon runs on the device or emulator and provides a means for the adb host daemon to
- communicate with the device or emulator.jdb.Figure 1 shows how the various debugging tools work together in a typical - debugging environment.
-
- In addition to the main debugging tools, the Android SDK provides additional tools to help you - debug and profile your applications:
- -While debugging, keep these helpful tips in mind to help you figure out common problems with your -applications:
- -adb shell, use ps to find the process you
-want, and then kill -3. The stack trace appears in the log file.
-adb shell commands. See
-dumpsys and
-dumpstate on the adb topic page.-adb shell -logcat -b radio --
See the Troubleshooting document -for answers to some common developing and debugging issues.
- - - - - - - diff --git a/docs/html/guide/developing/device.jd b/docs/html/guide/developing/device.jd deleted file mode 100644 index d91551a8e92d..000000000000 --- a/docs/html/guide/developing/device.jd +++ /dev/null @@ -1,267 +0,0 @@ -page.title=Using Hardware Devices -@jd:body - -When building a mobile application, it's important that you always test your application on a -real device before releasing it to users. This page describes how to set up your development -environment and Android-powered device for testing and debugging on the device.
- -You can use any Android-powered device as an environment for running, -debugging, and testing your applications. The tools included in the SDK make it easy to install and -run your application on the device each time you compile. You can install your application on the -device directly from Eclipse or from the command line with ADB. If -you don't yet have a device, check with the service providers in your area to determine which -Android-powered devices are available.
- -If you want a SIM-unlocked phone, then you might consider the Google Nexus S. To find a place -to purchase the Nexus S and other Android-powered devices, visit google.com/phone.
- -Note: When developing on a device, keep in mind that you should -still use the Android emulator to test your -application -on configurations that are not equivalent to those of your real device. Although the emulator -does not allow you to test every device feature (such as the accelerometer), it does -allow you to verify that your application functions properly on different versions of the Android -platform, in different screen sizes and orientations, and more.
- - -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:
- -When using Eclipse, you can skip this step, because running your app directly from -the Eclipse IDE automatically enables debugging.
-In the AndroidManifest.xml file, add android:debuggable="true" to
-the <application> element.
Note: If you manually enable debugging in the manifest - file, be sure to disable it before you build for release (your published application -should usually not be debuggable).
On the device, go to Settings > Applications > Development - and enable USB debugging - (on an Android 4.0 device, the setting is -located in Settings > Developer options).
-udev rules file that contains a USB configuration for each type of device
-you want to use for development. In the rules file, each device manufacturer
-is identified by a unique vendor ID, as specified by the
-ATTR{idVendor} property. For a list of vendor IDs, see USB Vendor IDs, below. To set up device detection on
-Ubuntu Linux:
-
- /etc/udev/rules.d/51-android.rules.
- Use this format to add each vendor to the file:
- SUBSYSTEM=="usb", ATTR{idVendor}=="0bb4", MODE="0666", GROUP="plugdev"
-
-
- In this example, the vendor ID is for HTC. The MODE
-assignment specifies read/write permissions, and GROUP defines
-which Unix group owns the device node.
Note: The rule syntax
-may vary slightly depending on your environment. Consult the udev
-documentation for your system as needed. For an overview of rule syntax, see
-this guide to writing udev
-rules.
chmod a+r /etc/udev/rules.d/51-android.rules
- When plugged in over USB, can verify that your device is connected by executing adb
-devices from your SDK {@code platform-tools/} directory. If connected,
-you'll see the device name listed as a "device."
If using Eclipse, run or debug your application as usual. You will be -presented with a Device Chooser dialog that lists the available -emulator(s) and connected device(s). Select the device upon which you want to -install and run the application.
- -If using the Android
-Debug Bridge (adb), you can issue commands with the -d flag to
-target your connected device.
This table provides a reference to the vendor IDs needed in order to add USB
-device support on Linux. The USB Vendor ID is the value given to the
-ATTR{idVendor} property in the rules file, as described
-above.
| Company | USB Vendor ID |
|---|---|
| Acer | -0502 |
-
| ASUS | -0b05 |
-
| Dell | -413c |
-
| Foxconn | -0489 |
-
| Fujitsu | -04c5 |
-
| Fujitsu Toshiba | -04c5 |
-
| Garmin-Asus | -091e |
-
18d1 |
- |
| Hisense | -109b |
-
| HTC | -0bb4 |
-
| Huawei | -12d1 |
-
| K-Touch | -24e3 |
-
| KT Tech | -2116 |
-
| Kyocera | -0482 |
-
| Lenovo | -17ef |
-
| LG | -1004 |
-
| Motorola | -22b8 |
-
| NEC | -0409 |
-
| Nook | -2080 |
-
| Nvidia | -0955 |
-
| OTGV | -2257 |
-
| Pantech | -10a9 |
-
| Pegatron | -1d4d |
-
| Philips | -0471 |
-
| PMC-Sierra | -04da |
-
| Qualcomm | -05c6 |
-
| SK Telesys | -1f53 |
-
| Samsung | -04e8 |
-
| Sharp | -04dd |
-
| Sony | -054c |
-
| Sony Ericsson | -0fce |
-
| Teleepoch | -2340 |
-
| Toshiba | -0930 |
-
| ZTE | -19d2 |
-
-The Android SDK includes a virtual mobile device emulator -that runs on your computer. The emulator lets you prototype, develop and test -Android applications without using a physical device.
- -The Android emulator mimics all of the hardware and software features -of a typical mobile device, except that it cannot place actual phone -calls. It provides a variety of navigation and control keys, which you can "press" -using your mouse or keyboard to generate events for your application. It also -provides a screen in which your application is displayed, together with any other -active Android applications.
- -To let you model and test your application more easily, the emulator utilizes -Android Virtual Device (AVD) configurations. AVDs let you define certain hardware -aspects of your emulated phone and allow you to create many configurations to test -many Android platforms and hardware permutations. Once your application is running on -the emulator, it can use the services of the Android platform to invoke other -applications, access the network, play audio and video, store and retrieve data, -notify the user, and render graphical transitions and themes.
- -The emulator also includes a variety of debug capabilities, such as a console -from which you can log kernel output, simulate application interrupts (such as -arriving SMS messages or phone calls), and simulate latency effects and dropouts -on the data network.
- - - -The Android emulator is an application that provides a virtual -mobile device on which you can run your Android applications. It runs a full -Android system stack, down to the kernel level, that includes a set of -preinstalled applications (such as the dialer) that you can access from your -applications. You can choose what version of the Android system you want to -run in the emulator by configuring AVDs, and you can also customize the -mobile device skin and key mappings. When launching the emulator and at runtime, -you can use a variety of commands and options to control its behavior. -
- -The Android system images available through the Android SDK Manager contain -code for the Android Linux kernel, the native libraries, the Dalvik VM, and the -various Android packages (such as the Android framework and preinstalled -applications). The emulator provides dynamic binary translation of device -machine code to the OS and processor architecture of your development -machine.
- -The Android emulator supports many hardware features likely to be found on -mobile devices, including:
- -The following sections describe the emulator and its use for development of Android -applications in more detail.
- - -To use the emulator, you first must create one or more AVD configurations. In each -configuration, you specify an Android platform to run in the emulator and the set of hardware -options and emulator skin you want to use. Then, when you launch the emulator, you specify -the AVD configuration that you want to load.
- -Each AVD functions as an independent device, with its own private storage for -user data, SD card, and so on. When you launch the emulator with an AVD configuration, -it automatically loads the user data and SD card data from the AVD directory. By default, -the emulator stores the user data, SD card data, and cache in the AVD directory.
- -To create and manage AVDs you use the AVD Manager UI or the android tool
-that is included in the SDK.
-For complete information about how to set up AVDs, see Managing Virtual Devices.
During development and testing of your application, you install and run your -application in the Android emulator. You can launch the emulator as a standalone -application from a command line, or you can run it from within your Eclipse -development environment. In either case, you specify the AVD configuration to -load and any startup options you want to use, as described in this document. -
- -You can run your application on a single instance of the emulator or, -depending on your needs, you can start multiple emulator instances and run your -application in more than one emulated device. You can use the emulator's -built-in commands to simulate GSM phone calling or SMS between emulator -instances, and you can set up network redirection that allows emulators to send -data to one another. For more information, see Telephony -Emulation, SMS Emulation, and -Emulator Networking
- -To start an instance of the emulator from the command line, navigate to the
-tools/ folder of the SDK. Enter emulator command
-like this:
emulator -avd <avd_name> [<options>]- -
This initializes the emulator, loads an AVD configuration and displays the emulator -window. For more information about command line options for the emulator, see the -Android Emulator tool reference.
- -Note: You can run multiple -instances of the emulator concurrently, each with its own AVD configuration and -storage area for user data, SD card, and so on.
- -If you are working in Eclipse, the ADT plugin for Eclipse installs your -application and starts the emulator automatically, when you run or debug -the application. You can specify emulator startup options in the Run/Debug -dialog, in the Target tab. When the emulator is running, you can issue -console commands as described later in this document.
- -If you are not working in Eclipse, see Installing Applications -on the Emulator for information about how to install your application.
- -To stop an emulator instance, just close the emulator's window.
- -For a reference of the emulator's startup commands and keyboard mapping, see -the Android Emulator tool -reference.
- - -If you don't have access to Eclipse or the ADT Plugin, you can install your application on the
-emulator using the adb utility. Before
-installing the application, you need to build and package it into an .apk as described
-in Building and
-Running Apps. Once the application is installed, you can start the emulator from the command
-line as described previously, using any startup options necessary.
-When the emulator is running, you can also connect to the emulator instance's
-console to issue commands as needed.
As you update your code, you periodically package and install it on the emulator.
-The emulator preserves the application and its state data across restarts,
-in a user-data disk partition. To ensure that the application runs properly
-as you update it, you may need to delete the emulator's user-data partition.
-To do so, start the emulator with the -wipe-data option.
-For more information about the user-data partition and other emulator storage,
-see Working with Emulator Disk Images.
In order to make the Android emulator run faster and be more responsive, you can configure it to -take advantage of hardware acceleration, using a combination of configuration options, specific -Android system images and hardware drivers.
- - -Caution: As of SDK Tools Revision 17, the graphics -acceleration feature for the emulator is experimental; be alert for incompatibilities and -errors when using this feature.
- -Graphics acceleration for the emulator takes advantage of your development computer's graphics -hardware, specifically its graphics processing unit (GPU), to make screen drawing faster. To use -the graphics acceleration feature, you must have the following versions of the Android development -tools installed:
- -Use the Android SDK -Manager to install these components:
- -Note: Not all applications are compatible with graphics hardware -acceleration. In particular, the Browser application and applications using the {@link -android.webkit.WebView} component are not compatible with graphics acceleration.
- -To configure an AVD to use graphics acceleration:
- -Note: You can also enable graphics acceleration when you -start an emulator using command line options as describe in the next section.
-Caution: Do not select the Snapshot: Enabled -option. Snapshots are not supported for emulators with graphics acceleration enabled.
-If you set GPU emulation to Yes for your AVD, then graphics -acceleration is automatically enabled when you run it. If you did not enable GPU -emulation when you created the AVD, you can still enable it at runtime.
- -To enable graphics acceleration at runtime for an AVD:
- -emulator -avd <avd_name> -gpu on-
Note: You must specify an AVD configuration that uses -Android 4.0.3 (API Level 15, revision 3) or higher system image target. Graphics acceleration is not -available for earlier system images.
-Caution: As of SDK Tools Revision 17, the virtual machine -acceleration feature for the emulator is experimental; be alert for incompatibilities and errors -when using this feature.
- -Many modern CPUs provide extensions for running virtual machines (VMs) more efficiently. Taking -advantage of these extensions with the Android emulator requires some additional configuration of -your development system, but can significantly improve the execution speed. Before attempting to use -this type of acceleration, you should first determine if your development system’s CPU supports one -of the following virtualization extensions technologies:
- -The specifications from the manufacturer of your CPU should indicate if it supports -virtualization extensions. If your CPU does not support one of these virtualization technologies, -then you cannot use virtual machine acceleration.
- -Note: Virtualization extensions are typically enabled through -your computer's BIOS and are frequently turned off by default. Check the documentation for your -system's motherboard to find out how to enable virtualization extensions.
- -Once you have determined that your CPU supports virtualization extensions, make sure you can work -within these additional requirements of running an emulator inside an accelerated virtual -machine:
- -To use virtual machine acceleration with the emulator, you need the following version of Android -development tools. Use the Android SDK -Manager to install these components:
- -If your development environment meets all of the requirements for running a VM-accelerated -emulator, you can use the AVD Manager to create an x86-based AVD configuration:
- -Tip: System images are listed under each API Level in the SDK - Manager. An x86 system image may not be available for all API levels.
-Virtual machine acceleration for Windows requires the installation of the Intel Hardware -Accelerated Execution Manager (Intel HAXM). The software requires an Intel CPU with -Virtualization Technology (VT) support and one of the following operating systems:
- -To install the virtualization driver:
- -sc query intelhaxm-
You should see a status message including the following information:
--SERVICE_NAME: intelhaxm - ... - STATE : 4 RUNNING - ... --
To run an x86-based emulator with VM acceleration:
-emulator -avd <avd_name>-
Note: You must provide an x86-based AVD configuration -name, otherwise VM acceleration will not be enabled.
-You can adjust the amount of memory available to the Intel HAXM kernel extension by re-running -its installer.
- -You can stop using the virtualization driver by uninstalling it. Re-run the installer or use -the Control Panel to remove the software.
- - -Virtual machine acceleration on a Mac requires the installation of the Intel Hardware Accelerated -Execution Manager (Intel HAXM) kernel extension to allow the Android emulator to make use of CPU -virtualization extensions. The kernel extension is compatible with Mac OS X Snow Leopard (version -10.6.0) and higher.
- -To install the Intel HAXM kernel extension:
- -kextstat | grep intel-
You should see a status message containing the following extension name, indicating that the - kernel extension is loaded:
-com.intel.kext.intelhaxm-
To run an x86-based emulator with VM acceleration:
-emulator -avd <avd_name>-
Note: You must provide an x86-based AVD configuration -name, otherwise VM acceleration will not be enabled.
-You can adjust the amount of memory available to the Intel HAXM kernel extension by re-running -the installer.
- -You can stop using the virtualization kernel driver by uninstalling it. Before removing it, shut -down any running x86 emulators. To unload the virtualization kernel driver, run the following -command in a terminal window:
- -sudo /System/Library/Extensions/intelhaxm.kext/Contents/Resources/uninstall.sh- -
Linux-based systems support virtual machine acceleration through the KVM software package. Follow -instructions for installing KVM on your -Linux system, and verify that KVM is enabled. In addition to following the installation -instructions, be aware of these configuration requirements:
- -To run an x86-based emulator with VM acceleration:
- -emulator -avd <avd_name> -qemu -m 512 -enable-kvm-
Note: You must provide an x86-based AVD configuration -name, otherwise VM acceleration will not be enabled.
--qemu -m 512 -enable-kvm-
Important: When using the {@code -qemu} command line option, make sure -it is the last parameter in your command. All subsequent options are interpreted as qemu-specific -parameters.
- - -You can create a disk image and then load it to the emulator at startup, to -simulate the presence of a user's SD card in the device. To do this, you can specify -an SD card image when you create an AVD, or you can use the mksdcard utility included -in the SDK.
- -The following sections describe how to create an SD card disk image, how to copy -files to it, and how to load it in the emulator at startup.
- -Note that you can only load a disk image at emulator startup. Similarly, you -can not remove a simulated SD card from a running emulator. However, you can -browse, send files to, and copy/remove files from a simulated SD card either -with adb or the emulator.
- -The emulator supports emulated SDHC cards, so you can create an SD card image -of any size up to 128 gigabytes.
- - -There are several ways of creating an SD card image. The easiest way is to use the
-AVD Manager to create a new SD card by specifying a size when you create an AVD.
-You can also use the {@code android} command line tool when creating an AVD. Just add the
--c option to your command:
android create avd -n <avd_name> -t <targetID> -c <size>[K|M]- -
The -c option can also be used to to specify a path to an SD card
-image for the new AVD. For more information, see Managing Virtual Devices
-from the Command Line.
-
You can also use the mksdcard tool, included in the SDK, to create a FAT32 disk -image that you can load in the emulator at startup. You can access mksdcard in -the tools/ directory of the SDK and create a disk image like this:
- -mksdcard <size> <file>- -
For example:
- -mksdcard 1024M sdcard1.iso- -
For more information, see mksdcard.
Once you have created the disk image, you can copy files to it prior to -loading it in the emulator. To copy files, you can mount the image as a loop -device and then copy the files to it, or you can use a utility such as {@code mtools} to -copy the files directly to the image. The {@code mtools} package is available for Linux, -Mac, and Windows.
- -Alternatively, you can use the {@code adb push} command to move files onto an SD card image -while it is loaded in an emulator. For more information see the {@code adb push} documentation.
- -By default, the emulator loads the SD card image that is stored with the active
-AVD (see the -avd startup option).
Alternatively, you can start the emulator with the
--sdcard flag and specify the name and path of your image (relative
-to the current working directory):
emulator -sdcard <filepath>- - -
The emulator uses mountable disk images stored on your development machine to -simulate flash (or similar) partitions on an actual device. For example, it uses a -disk image containing an emulator-specific kernel, the Android system, a -ramdisk image, and writeable images for user data and simulated SD card.
- -To run properly, the emulator requires access to a specific set of disk image -files. By default, the Emulator always looks for the disk images in the -private storage area of the AVD in use. If no images exist there when -the Emulator is launched, it creates the images in the AVD directory based on -default versions stored in the SDK.
- -Note: The default storage location for
-AVDs is in ~/.android/avd on OS X and Linux, C:\Documents and
-Settings\<user>\.android\ on Windows XP, and
-C:\Users\<user>\.android\
-on Windows Vista.
To let you use alternate or custom versions of the image files, the emulator -provides startup options that override the default locations and filenames of -the image files. When you use one of these options, the emulator searches for the image -file under the image name or location that you specify; if it can not locate the -image, it reverts to using the default names and location.
- -The emulator uses three types of image files: default image files, runtime -image files, and temporary image files. The sections below describe how to -override the location/name of each type of file.
- -When the emulator launches, but does not find an existing user data image in -the active AVD's storage area, it creates a new one from a default version -included in the SDK. The default user data image is read-only. The image -files are read-only.
- -The emulator provides the -system <dir> startup option to
-let you override the location where the emulator looks for the default
-user data image.
The emulator also provides a startup option that lets you override the name
-of the default user data image, as described in the following table. When you use the
-option, the emulator looks in the default directory, or in a custom location
-(if you specified -system <dir>).
| Name | -Description | -Comments | -
|---|---|---|
userdata.img |
- The initial user-data disk image | -Override using -initdata <file>. Also see
--data <file>, below. |
-
At runtime, the emulator reads and writes data to two disk images: a -user-data image and (optionally) an SD card image. These images emulate the user-data -partition and removable storage media on actual device.
- -The emulator provides a default user-data disk image. At startup, the emulator -creates the default image as a copy of the system user-data image (user-data.img), -described above. The emulator stores the new image with the files of the active AVD.
- - - -The emulator provides startup options to let you override the actual names and storage -locations of the runtime images to load, as described in the following table. When you use one -of these options, the emulator looks for the specified file(s) in the current working directory, -in the AVD directory, or in a custom location (if you specified a path with the filename).
- -| Name | -Description | -Comments | -
|---|---|---|
userdata-qemu.img |
- An image to which the emulator writes runtime user-data for a unique user. | -Override using -data <filepath>, where <filepath> is the
-path the image, relative to the current working directory. If you supply a filename only,
-the emulator looks for the file in the current working directory. If the file at <filepath> does
-not exist, the emulator creates an image from the default userdata.img, stores it under the name you
-specified, and persists user data to it at shutdown. |
-
sdcard.img |
- An image representing an SD card inserted into the emulated device. | -Override using -sdcard <filepath>, where <filepath> is the
-path the image, relative to the current working directory. If you supply a filename only,
-the emulator looks for the file in the current working directory. |
-
Each emulator instance uses a writeable user-data image to store user- and -session-specific data. For example, it uses the image to store a unique user's -installed application data, settings, databases, and files.
- -At startup, the emulator attempts to load a user-data image stored during -a previous session. It looks for the file in the current working directory, -in the AVD directory described in a previous section and at the custom location/name -that you specified at startup.
- --data startup option.Note: Because of the AVD configurations used in the emulator,
-each emulator instance gets its own dedicated storage. There is no longer a need
-to use the -d option to specify an instance-specific storage area.
Optionally, you can create a writeable disk image that the emulator can use -to simulate removeable storage in an actual device. For information about how to create an -emulated SD card and load it in the emulator, see SD Card Emulation
- -You can also use the android tool to automatically create an SD Card image -for you, when creating an AVD. For more information, see Managing Virtual Devices with AVD -Manager. - - -
The emulator creates two writeable images at startup that it deletes at -device power-off. The images are:
- -/cache partition imageThe emulator does not permit renaming the temporary system image or -persisting it at device power-off.
- -The /cache partition image is initially empty, and is used by
-the browser to cache downloaded web pages and images. The emulator provides an
--cache <file>, which specifies the name of the file in which
-to persist the /cache image at device power-off. If <file>
- does not exist, the emulator creates it as an empty file.
You can also disable the use of the cache partition by specifying the
--nocache option at startup.
The emulator provides versatile networking capabilities that you can use to -set up complex modeling and testing environments for your application. The -sections below introduce the emulator's network architecture and capabilities. -
- -Each instance of the emulator runs behind a virtual router/firewall service -that isolates it from your development machine's network interfaces and settings -and from the internet. An emulated device can not see your development machine -or other emulator instances on the network. Instead, it sees only that it is -connected through Ethernet to a router/firewall.
- -The virtual router for each instance manages the 10.0.2/24 network address -space — all addresses managed by the router are in the form of -10.0.2.<xx>, where <xx> is a number. Addresses within this space are -pre-allocated by the emulator/router as follows:
- -| Network Address | -Description | -
|---|---|
| 10.0.2.1 | -Router/gateway address | -
| 10.0.2.2 | -Special alias to your host loopback interface (i.e., 127.0.0.1 on your -development machine) | -
| 10.0.2.3 | -First DNS server | -
| 10.0.2.4 / 10.0.2.5 / 10.0.2.6 | -Optional second, third and fourth DNS server (if any) | -
| 10.0.2.15 | -The emulated device's own network/ethernet interface | -
| 127.0.0.1 | -The emulated device's own loopback interface | -
Note that the same address assignments are used by all running emulator -instances. That means that if you have two instances running concurrently on -your machine, each will have its own router and, behind that, each will have an -IP address of 10.0.2.15. The instances are isolated by a router and can -not see each other on the same network. For information about how to -let emulator instances communicate over TCP/UDP, see Connecting Emulator Instances.
- -Also note that the address 127.0.0.1 on your development machine corresponds -to the emulator's own loopback interface. If you want to access services running -on your development machine's loopback interface (a.k.a. 127.0.0.1 on your -machine), you should use the special address 10.0.2.2 instead.
- -Finally, note that each emulated device's pre-allocated addresses are -specific to the Android emulator and will probably be very different on real -devices (which are also very likely to be NAT-ed, i.e., behind a -router/firewall)
- - -Android applications running in an emulator can connect to the network available on your -workstation. However, they connect through the emulator, not directly to hardware, and the emulator -acts like a normal application on your workstation. This means that the emulator, and thus your -Android applications, are subject to some limitations:
- -The emulator's virtual router should be able to handle all outbound TCP and -UDP connections/messages on behalf of the emulated device, provided your -development machine's network environment allows it to do so. There are no -built-in limitations on port numbers or ranges except the one imposed by your -host operating system and network.
- -Depending on the environment, the emulator may not be able to support other -protocols (such as ICMP, used for "ping") might not be supported. Currently, the -emulator does not support IGMP or multicast.
- -To communicate with an emulator instance behind its virtual router, you need -to set up network redirection on the virtual router. Clients can then connect -to a specified guest port on the router, while the router directs traffic -to/from that port to the emulated device's host port.
- -To set up the network redirection, you create a mapping of host and guest -ports/addresses on the the emulator instance. There are two ways to set up -network redirection: using emulator console commands and using the ADB tool, as -described below.
- - -Each emulator instance provides a control console the you can connect to, to
-issue commands that are specific to that instance. You can use the
-redir console command to set up redirection as needed for an
-emulator instance.
First, determine the console port number for the target emulator instance. -For example, the console port number for the first emulator instance launched is -5554. Next, connect to the console of the target emulator instance, specifying -its console port number, as follows:
- -telnet localhost 5554
-
-Once connected, use the redir command to work with redirection.
-To add a redirection, use:
add <protocol>:<host-port>:<guest-port>
-
-
-where <protocol> is either tcp or udp,
-and <host-port> and <guest-port> sets the
-mapping between your own machine and the emulated system, respectively.
For example, the following command sets up a redirection that handles all -incoming TCP connections to your host (development) machine on 127.0.0.1:5000 -and will pass them through to the emulated system's 10.0.2.15:6000.:
- -redir add tcp:5000:6000- -
To delete a redirection, you can use the redir del command. To
-list all redirection for a specific instance, you can use redir
-list. For more information about these and other console commands, see
-Using the Emulator Console.
Note that port numbers are restricted by your local environment. this typically
-means that you cannot use host port numbers under 1024 without special
-administrator privileges. Also, you won't be able to set up a redirection for a
-host port that is already in use by another process on your machine. In that
-case, redir generates an error message to that effect.
The Android Debug Bridge (ADB) tool provides port forwarding, an alternate -way for you to set up network redirection. For more information, see Forwarding Ports in the ADB -documentation.
- -Note that ADB does not currently offer any way to remove a redirection, -except by killing the ADB server.
- - -At startup, the emulator reads the list of DNS servers that your system is -currently using. It then stores the IP addresses of up to four servers on this -list and sets up aliases to them on the emulated addresses 10.0.2.3, 10.0.2.4, -10.0.2.5 and 10.0.2.6 as needed.
- -On Linux and OS X, the emulator obtains the DNS server addresses by parsing
-the file /etc/resolv.conf. On Windows, the emulator obtains the
-addresses by calling the GetNetworkParams() API. Note that this
-usually means that the emulator ignores the content of your "hosts" file
-(/etc/hosts on Linux/OS X, %WINDOWS%/system32/HOSTS
- on Windows).
When starting the emulator at the command line, you can also use the
--dns-server <serverList> option to manually specify the
-addresses of DNS servers to use, where <serverList> is a comma-separated
-list of server names or IP addresses. You might find this option useful if you
-encounter DNS resolution problems in the emulated network (for example, an
-"Unknown Host error" message that appears when using the web browser).
If your emulator must access the Internet through a proxy server, you can use
-the -http-proxy <proxy> option when starting the emulator, to
-set up the appropriate redirection. In this case, you specify proxy information
-in <proxy> in one of these formats:
http://<machineName>:<port>- -
or
- -http://<username>:<password>@<machineName>:<port>- -
The -http-proxy option forces the emulator to use the specified
-HTTP/HTTPS proxy for all outgoing TCP connections. Redirection for UDP is not
-currently supported.
Alternatively, you can define the environment variable
-http_proxy to the value you want to use for
-<proxy>. In this case, you do not need to specify a value for
-<proxy> in the -http-proxy command — the
-emulator checks the value of the http_proxy environment variable at
-startup and uses its value automatically, if defined.
You can use the -verbose-proxy option to diagnose proxy
-connection problems.
To allow one emulator instance to communicate with another, you must set up -the necessary network redirection as illustrated below.
- -Assume that your environment is
- -and you want to run a server on B, to which C will connect, here is how you -could set it up:
- -10.0.2.15:<serverPort>A:localhost:<localPort> to
-B:10.0.2.15:<serverPort>10.0.2.2:<localPort>For example, if you wanted to run an HTTP server, you can select
-<serverPort> as 80 and <localPort> as
-8080:
redir add tcp:8080:80The emulator automatically forwards simulated voice calls and SMS messages from one instance to -another. To send a voice call or SMS, use the dialer application or SMS application, respectively, -from one of the emulators.
- -To initiate a simulated voice call to another emulator instance:
-To send an SMS message to another emulator instance, launch the SMS application (if available). Specify the console port number of the target emulator instance as as the SMS address, enter the message text, and send the message. The message is delivered to the target emulator instance.
- -You can also connect to an emulator instance's console to simulate an incoming voice call or SMS. For more information, see Telephony Emulation and SMS Emulation. - - -
Each running emulator instance provides a console that lets you query and control the emulated -device environment. For example, you can use the console to manage port redirection, network -characteristics, and telephony events while your application is running on the emulator. To -access the console and enter commands, use telnet to connect to the console's port number.
- -To connect to the console of any running emulator instance at any time, use this command:
- -telnet localhost <console-port>- -
An emulator instance occupies a pair of adjacent ports: a console port and an {@code adb} port. -The port numbers differ by 1, with the {@code adb} port having the higher port number. The console -of the first emulator instance running on a given machine uses console port 5554 and {@code adb} -port 5555. Subsequent instances use port numbers increasing by two — for example, 5556/5557, -5558/5559, and so on. Up to 16 concurrent emulator instances can run a console facility.
- -To connect to the emulator console, you must specify a valid console port. If multiple emulator instances are running, you need to determine the console port of the emulator instance you want to connect to. You can find the instance's console port listed in the title of the instance window. For example, here's the window title for an instance whose console port is 5554:
- -Android Emulator (5554)
Alternatively, you can use the adb devices command, which prints a list of running emulator instances and their console port numbers. For more information, see Querying for Emulator/Device Instances in the adb documentation.
Note: The emulator listens for connections on ports 5554-5587 and accepts connections only from localhost.
- -Once you are connected to the console, you can then enter help [command] to see a list of console commands and learn about specific commands.
To exit the console session, use quit or exit.
The following sections below describe the major functional areas of the console.
- - -You can use the console to add and remove port redirection while the emulator is running. After -you connect to the console, manage port redirection by entering the following command:
- -redir <list|add|del>- -
The redir command supports the subcommands listed in the table below.
| Subcommand - | Description | -Comments | -
|---|---|---|
list |
- List the current port redirection. | -- |
add <protocol>:<host-port>:<guest-port> |
- Add a new port redirection. | -
|
-
del <protocol>:<host-port> |
- Delete a port redirection. | -The meanings of <protocol> and <host-port> are listed in the previous row. | -
You can use the console to set the geographic location reported to the applications running
-inside an emulator. Use the geo command to send a simple GPS fix to the
-emulator, with or without NMEA 1083 formatting:
geo <fix|nmea>- -
The geo command supports the subcommands listed in the table below.
| Subcommand | -Description | -Comments | -
|---|---|---|
fix <longitude> <latitude> [<altitude>] |
- Send a simple GPS fix to the emulator instance. | -Specify longitude and latitude in decimal degrees. Specify altitude in meters. | -
nmea <sentence> |
- Send an NMEA 0183 sentence to the emulated device, as if it were sent from an emulated GPS modem. | -<sentence> must begin with '$GP'. Only '$GPGGA' and '$GPRCM' sentences are currently supported. |
-
You can issue the geo command as soon as an emulator instance is running. The
-emulator sets the location you enter by creating a mock location provider. This provider responds to
-location listeners set by applications, and also supplies the location to the {@link
-android.location.LocationManager}. Any application can query the location manager to obtain the
-current GPS fix for the emulated device by calling:
-
-
LocationManager.getLastKnownLocation("gps")
-
-For more information about the Location Manager, see {@link android.location.LocationManager}. -
- -The {@code event} console commands sends hardware events to the emulator. The syntax for this -command is as follows:
- -event <send|types|codes|text>- -
The event command supports the subcommands listed in the table below.
| Subcommand - | Description | -Comments | -
|---|---|---|
send <type>:<code>:<value> [...] |
- Send one or more events to the Android kernel. | -You can use text names or integers for <type> and <value>. |
-
types |
- List all <type> string aliases supported by the event subcommands. |
-- |
codes <type> |
- List all <codes> string aliases supported by the event
- subcommands for the specified <type>. |
-- |
event text <message> |
- Simulate keypresses to send the specified string of characters as a message, | -The message must be a UTF-8 string. Unicode posts will be reverse-mapped according to the current device keyboard. Unsupported characters will be discarded silently. | -
The {@code power} command controls the power state reported by the emulator to applications. The -syntax for this command is as follows:
- -power <display|ac|status|present|health|capacity>- -
The event command supports the subcommands listed in the table below.
| Subcommand | -Description | -Comments | -
|---|---|---|
display |
- Display battery and charger state. | -- |
ac <on|off> |
- Set AC charging state to on or off. | -- |
status <unknown|charging|discharging|not-charging|full> |
- Change battery status as specified. | -- |
present <true|false> |
- Set battery presence state. | -- |
health <unknown|good|overheat|dead|overvoltage|failure> |
- Set battery health state. | -- |
power health <percent> |
- Set remaining battery capacity state (0-100). | -- |
You can use the console to check the network status and current delay and speed characteristics. To do so, connect to the console and use the netstatus command. Here's an example of the command and its output.
network status -- - -
The emulator lets you simulate various network latency levels, so that you can test your -application in an environment more typical of the actual conditions in which it will run. You can -set a latency level or range at emulator startup or you can use the console to change the latency, -while the application is running in the emulator.
- -To set latency at emulator startup, use the -netdelay emulator option with a
-supported <delay> value, as listed in the table below. Here are some
-examples:
emulator -netdelay gprs -emulator -netdelay 40 100- -
To make changes to network delay while the emulator is running, connect to the console and use
-the netdelay command with a supported <delay> value from the table
-below.
network delay gprs- -
The format of network <delay> is one of the following (numbers are milliseconds):
- -| Value | -Description | Comments |
|---|---|---|
gprs | GPRS | -(min 150, max 550) | -
edge | EDGE/EGPRS | -(min 80, max 400) | -
umts | UMTS/3G | -(min 35, max 200) | -
none | No latency | (min 0, max 0) |
<num> |
-Emulate an exact latency (milliseconds). | -|
<min>:<max> |
-Emulate an specified latency range (min, max milliseconds). | -
The emulator also lets you simulate various network transfer rates. -You can set a transfer rate or range at emulator startup or you can use the console to change the -rate, while the application is running in the emulator.
- -To set the network speed at emulator startup, use the -netspeed emulator option with a supported
-<speed> value, as listed in the table below. Here are some examples:
emulator -netspeed gsm -emulator -netspeed 14.4 80- -
To make changes to network speed while the emulator is running, connect to the console and use
-the netspeed command with a supported <speed> value from the table
-below.
network speed 14.4 80- -
The format of network <speed> is one of the following (numbers are
-kilobits/sec):
| Value | -Description | Comments |
|---|---|---|
gsm |
- GSM/CSD | (Up: 14.4, down: 14.4) |
hscsd |
- HSCSD | (Up: 14.4, down: 43.2) |
gprs |
- GPRS | (Up: 40.0, down: 80.0) |
edge |
- EDGE/EGPRS | -(Up: 118.4, down: 236.8) | -
umts |
- UMTS/3G | (Up: 128.0, down: 1920.0) |
hsdpa |
- HSDPA | (Up: 348.0, down: 14400.0) |
full |
- no limit | (Up: 0.0, down: 0.0) |
<num> |
- Set an exact rate used for both upload and download. | |
<up>:<down> |
- Set exact rates for upload and download separately. |
The Android emulator includes its own GSM emulated modem that lets you simulate telephony -functions in the emulator. For example, you can simulate inbound phone calls, establish data -connections and terminate them. The Android system handles simulated calls exactly as it would -actual calls. The emulator does not support call audio.
- -You can use the {@code gsm} command to access the emulator's telephony functions after connecting -to the console. The syntax for this command is as follows:
- -gsm <call|accept|busy|cancel|data|hold|list|voice|status>- -
The gsm command supports the subcommands listed in the table below.
| Subcommand | -Description | -Comments | -
|---|---|---|
call <phonenumber> |
- Simulate an inbound phone call from <phonenumber>. | -- |
accept <phonenumber> |
- Accept an inbound call from <phonenumber> and change the call's state "active". | -You can change a call's state to "active" only if its current state is "waiting" or "held". | -
busy <phonenumber> |
- Close an outbound call to <phonenumber> and change the call's state to "busy". | -You can change a call's state to "busy" only if its current state is "waiting". | -
cancel <phonenumber> |
- Terminate an inbound or outbound phone call to/from <phonenumber>. | -- |
data <state> |
- Change the state of the GPRS data connection to <state>. | -Supported <state> values are: -
|
-
hold |
- Change the state of a call to "held". | -You can change a call's state to "held" only if its current state is "active" or "waiting". | -
list |
- List all inbound and outbound calls and their states. | -- |
voice <state> |
- Change the state of the GPRS voice connection to <state>. | -Supported <state> values are: -
|
-
status |
- Report the current GSM voice/data state. | -Values are those described for the voice and data commands. |
-
The Android emulator console lets you generate an SMS message and direct it to an emulator -instance. Once you connect to an emulator instance, you can generate an emulated incoming SMS using -the following command:
- -sms send <senderPhoneNumber> <textmessage>- -
where <senderPhoneNumber> contains an arbitrary numeric string.
The console forwards the SMS message to the Android framework, which passes it through to an application that handles that message type.
- - -You can use the vm command to control the VM on an emulator instance. The syntax for
-this command is as follows:
vm <start|stop|status>- -
The vm command supports the subcommands listed in the table below.
| Subcommand | -Description | -Comments | -
|---|---|---|
start |
- Start the VM on the instance. | -- |
stop |
- Stop the VM on the instance. | -- |
start |
- Display the current status of the VM (running or stopped). | -- |
You can use the window command to manage the emulator window. The syntax for this
-command is as follows:
window <scale>- -
The vm command supports the subcommands listed in the table below.
| Subcommand | -Description | -Comments | -
|---|---|---|
scale <scale> |
- Scale the emulator window. | -A number between 0.1 and 3 that sets the scaling factor. You can - also specify scale as a DPI value if you add the suffix "dpi" to the scale value. A value of "auto" - tells the emulator to select the best window size. | -
You can terminate an emulator instance through the console, using the kill command.
The functional limitations of the emulator include:
-The {@code adb} utility sees the emulator as an actual physical device. For this reason, you
-might have to use the {@code -d} flag with some common {@code adb} commands, such as
-install. The {@code -d} flag lets you specify which of several connected devices to use
-as the target of a command. If you don't specify {@code -d}, the emulator targets the first
-device in its list. For more information about {@code adb}, see Android Debug Bridge.
For emulators running on Mac OS X, if you see an error {@code Warning: No DNS servers found}
-when starting the emulator, check to see whether you have an /etc/resolv.conf file. If
-not, please run the following line in a command window:
ln -s /private/var/run/resolv.conf /etc/resolv.conf- -
See Frequently Asked Questions for more -troubleshooting information.
diff --git a/docs/html/guide/developing/devices/index.jd b/docs/html/guide/developing/devices/index.jd deleted file mode 100644 index 64651a1ec907..000000000000 --- a/docs/html/guide/developing/devices/index.jd +++ /dev/null @@ -1,78 +0,0 @@ -page.title=Managing Virtual Devices -@jd:body - - -An Android Virtual Device (AVD) is an emulator configuration that lets you model an actual - device by defining hardware and software options to be emulated by the Android Emulator.
- -The easiest way to create an AVD is to use the graphical AVD Manager, which you launch
- from Eclipse by clicking Window > AVD Manager. You can also start the AVD
-Manager from the command line by calling the android tool with the avd
-options, from the <sdk>/tools/ directory.
You can also create AVDs on the command line by passing the android tool options.
- For more information on how to create AVDs in this manner, see Managing Virtual
- Devices from the Command Line.
An AVD consists of:
- -You can create as many AVDs as you need, based on the types of device you want to model. - To thoroughly test your application, you should create an AVD for each general device configuration - (for example, different screen sizes and platform versions) with which your application is compatible - and test your application on each one.
- -Keep these points in mind when you are selecting a system image target for your AVD:
- -minSdkVersion attribute of the application's manifest file. For more
- information about the relationship between system API Level and application
- minSdkVersion, see Specifying Minimum System API Version.uses-library
- element in its manifest file, the application can only run on a system image in which that external
- library is present. If you want to run your application on an emulator, create an AVD that
- includes the required library. Usually, you must create such an AVD using an Add-on component for the
- AVD's platform (for example, the Google APIs Add-on contains the Google Maps library).To learn how to manage AVDs using a graphical tool, read Managing AVDs with AVD Manager. To -learn how to manage AVDs on the command line, read - Managing AVDs - from the Command Line.
- - - - - - diff --git a/docs/html/guide/developing/devices/managing-avds-cmdline.jd b/docs/html/guide/developing/devices/managing-avds-cmdline.jd deleted file mode 100644 index 867433452a7b..000000000000 --- a/docs/html/guide/developing/devices/managing-avds-cmdline.jd +++ /dev/null @@ -1,369 +0,0 @@ -page.title=Managing AVDs from the Command Line -parent.title=Managing Virtual Devices -parent.link=index.html -@jd:body - -The android tool lets you manage AVDs on the command line. For a complete reference
-of the command line options that you can use, see the reference for the
-android tool.
To generate a list of system image targets, use this command:
- -android list targets- -
The android tool scans the <sdk>/platforms/ and
-<sdk>/add-ons/ directories looking for valid system images and
-then generates the list of targets. Here's an example of the command output:
-
Available Android targets: -id: 1 or "android-3" - Name: Android 1.5 - Type: Platform - API level: 3 - Revision: 4 - Skins: QVGA-L, HVGA-L, HVGA (default), HVGA-P, QVGA-P -id: 2 or "android-4" - Name: Android 1.6 - Type: Platform - API level: 4 - Revision: 3 - Skins: QVGA, HVGA (default), WVGA800, WVGA854 -id: 3 or "android-7" - Name: Android 2.1-update1 - Type: Platform - API level: 7 - Revision: 2 - Skins: QVGA, WQVGA400, HVGA (default), WVGA854, WQVGA432, WVGA800 -id: 4 or "android-8" - Name: Android 2.2 - Type: Platform - API level: 8 - Revision: 2 - Skins: WQVGA400, QVGA, WVGA854, HVGA (default), WVGA800, WQVGA432 -id: 5 or "android-9" - Name: Android 2.3 - Type: Platform - API level: 9 - Revision: 1 - Skins: HVGA (default), WVGA800, WQVGA432, QVGA, WVGA854, WQVGA400 -- - - -
In addition to creating AVDs with the
-AVD Manager user interface,
-you can also create them by passing in command line arguments to the android tool.
-
Open a terminal window and change to
-the <sdk>/tools/ directory, if needed.
To create each AVD, you issue the command android create avd,
-with options that specify a name for the new AVD and the system image you want
-to run on the emulator when the AVD is invoked. You can specify other options on
-the command line also, such as the emulated SD card size, the emulator skin, or a custom
-location for the user data files.
Here's the command-line usage for creating an AVD:
- -android create avd -n <name> -t <targetID> [-<option> <value>] ...- -
You can use any name you want for the AVD, but since you are likely to be
-creating multiple AVDs, you should choose a name that lets you recognize the
-general characteristics offered by the AVD. The target ID is an integer assigned by the
-android tool. The target ID is not derived from the system image name,
-version, or API Level, or other attribute, so you need to run the android list targets
-command to list the target ID of each system image. You should do this before you run
-the android create avd command. See the android
-tool documentation for more information on the command line options.
When you've selected the target you want to use and made a note of its ID,
-use the android create avd command to create the AVD, supplying the
-target ID as the -t argument. Here's an example that creates an
-AVD with name "my_android1.5" and target ID "2" (the standard Android 1.5
-system image in the list above):
android create avd -n my_android1.5 -t 2- -
If the target you selected was a standard Android system image ("Type:
-platform"), the android tool next asks you whether you want to
-create a custom hardware profile.
Android 1.5 is a basic Android platform. -Do you wish to create a custom hardware profile [no]- -
If you want to set custom hardware emulation options for the AVD, enter
-"yes" and set values as needed. If you want to use the default hardware
-emulation options for the AVD, just press the return key (the default is "no").
-The android tool creates the AVD with name and system image mapping you
-requested, with the options you specified. For more information, see
-Setting Hardware Emulation Options.
-
-
Note: If you are creating an AVD whose target is an SDK add-on, the
-android tool does not allow you to set hardware emulation options.
-It assumes that the provider of the add-on has set emulation options
-appropriately for the device that the add-on is modeling, and so prevents you
-from resetting the options.
When testing your application, we recommend that you test your application in several different -AVDs, using different screen configurations (different combinations of size and density). In -addition, you should set up the AVDs to run at a physical size that closely matches an actual -device.
- -To set up your AVDs for a specific resolution or density, follow these steps:
- -create avd command to create a new AVD, specifying
-the --skin option with a value that references either a default
-skin name (such as "WVGA800") or a custom skin resolution (such as 240x432).
-Here's an example:
- android create avd -n <name> -t <targetID> --skin WVGA800-
In the example above (WVGA medium density), the new AVD will emulate a 5.8" -WVGA screen.
- -As an alternative to adjusting the emulator skin configuration, you can use
-the emulator skin's default density and add the -dpi-device option
-to the emulator command line when
-starting the AVD. For example:
emulator -avd WVGA800 -scale 96dpi -dpi-device 160- - - -
When you create an AVD, the android tool creates a dedicated directory for it
-on your development computer. The directory contains the AVD configuration file,
-the user data image and SD card image (if available), and any other files
-associated with the device. Note that the directory does not contain a system
-image — instead, the AVD configuration file contains a mapping to the
-system image, which it loads when the AVD is launched.
The android tool also creates an <AVD_name>.ini file for the AVD at the
-root of the .android/avd/ directory on your computer. The file specifies the
-location of the AVD directory and always remains at the root the .android
-directory.
By default, the android tool creates the AVD directory inside
-~/.android/avd/ (on Linux/Mac), C:\Documents and
-Settings\<user>\.android\ on Windows XP, and
-C:\Users\<user>\.android\ on Windows 7 and Vista.
-If you want to use a custom location for the AVD directory, you
-can do so by using the -p <path> option when
-you create the AVD:
android create avd -n my_android1.5 -t 2 -p path/to/my/avd- -
If the .android directory is hosted on a network drive, we recommend using
-the -p option to place the AVD directory in another location.
-The AVD's .ini file remains in the .android directory on the network
-drive, regardless of the location of the AVD directory.
-
-
-
When you are creating a new AVD that uses a standard Android system image ("Type:
-platform"), the android tool lets you set hardware emulation
-options for virtual device. The table below lists the options available and the
-default values, as well as the names of properties that store the emulated
-hardware options in the AVD's configuration file (the config.ini file in the
-AVD's local directory).
Table 1. Available hardware profile options for AVDs and -the default values
- -| Characteristic | -Description | -Property | -
|---|---|---|
| Device ram size | -The amount of physical RAM on the device, in megabytes. Default value is "96". - | hw.ramSize | -
| Touch-screen support | -Whether there is a touch screen or not on the device. Default value is "yes". | -hw.touchScreen - - |
| Trackball support | -Whether there is a trackball on the device. Default value is "yes". | -hw.trackBall | -
| Keyboard support | -Whether the device has a QWERTY keyboard. Default value is "yes". | -hw.keyboard | -
| DPad support | -Whether the device has DPad keys. Default value is "yes". | -hw.dPad | -
| GSM modem support | -Whether there is a GSM modem in the device. Default value is "yes". | -hw.gsmModem | -
| Camera support | -Whether the device has a camera. Default value is "no". | -hw.camera | -
| Maximum horizontal camera pixels | -Default value is "640". | -hw.camera.maxHorizontalPixels | -
| Maximum vertical camera pixels | -Default value is "480". | -hw.camera.maxVerticalPixels | -
| GPS support | -Whether there is a GPS in the device. Default value is "yes". | -hw.gps | -
| Battery support | -Whether the device can run on a battery. Default value is "yes". | -hw.battery | -
| Accelerometer | -Whether there is an accelerometer in the device. Default value is "yes". | -hw.accelerometer | -
| Audio recording support | -Whether the device can record audio. Default value is "yes". | -hw.audioInput | -
| Audio playback support | -Whether the device can play audio. Default value is "yes". | -hw.audioOutput | -
| SD Card support | -Whether the device supports insertion/removal of virtual SD Cards. Default value is "yes". | -hw.sdCard | -
| Cache partition support | -Whether we use a /cache partition on the device. Default value is "yes". | -disk.cachePartition | -
| Cache partition size | -Default value is "66MB". | -disk.cachePartition.size | -
| Abstracted LCD density | -Sets the generalized density characteristic used by the AVD's screen. Default value is "160". | -hw.lcd.density | -
| Trackball support | -Whether there is a trackball present. | -hw.trackBall | -
If you want to move or rename an AVD, you can do so using this command:
- -android move avd -n <name> [-<option> <value>] ...- -
If, for any reason, the platform/add-on root folder has its name changed (maybe because the user has installed an update of the platform/add-on) then the AVD will not be able to load the system image that it is mapped to. In this case, the android list targets command will produce this output:
-
-
The following Android Virtual Devices could not be loaded: -Name: foo -Path: <path>/.android/avd/foo.avd -Error: Invalid value in image.sysdir. Run 'android update avd -n foo'- -
To fix this error, use the android update avd command to recompute the path to the system images.
You can use the android tool to delete an AVD. Here is the command usage:
android delete avd -n <name>- -
When you issue the command, the android tool looks for an AVD matching the
-specified name deletes the AVD's directory and files.
The AVD Manager is an easy to use user interface to manage your AVD (Android Virtual Device)
- configurations. An AVD is a device configuration for the Android emulator that allows you to
- model different configurations of Android-powered devices. When you start the AVD Manager in Eclipse
- or run the android tool on the command line, you will see the AVD Manager as shown in
- figure 1:
-
- Figure 1. Screenshot of the AVD Manager.
- -From the main screen, you can create, delete, repair and start AVDs as well as see the details - of each AVD.
- - -You can create as many AVDs as you would like to test on. It is recommended that you test your - applications on all API levels higher than the target API level for your application.
- -To create an AVD:
- -tools/ directory and execute the
- android tool with no arguments.In the Virtual Devices panel, you'll see a list of existing AVDs. Click - New to create a new AVD. The Create New AVD dialog appears.
- -
- Figure 2. Screenshot of the Create AVD window
-Give it a name, a platform target, an SD card size, and a skin (HVGA is default). You can - also add specific hardware features of the emulated device by clicking the - New... button and selecting the feature. For a list of hardware features, - see Hardware options.
- -Note: Be sure to define a target for your AVD that satisfies - your application's Build Target (the AVD platform target must have an API Level equal to or - greater than the API Level that your application compiles against).
-Your AVD is now ready and you can either close the AVD Manager, create more AVDs, or - launch an emulator with the AVD by selecting a device and clicking Start.
- -If you are creating a new AVD, you can specify the following hardware options for the AVD -to emulate:
- -| Characteristic | - -Description | - -Property | -
|---|---|---|
| Device ram size | - -The amount of physical RAM on the device, in megabytes. Default value is "96". | - -hw.ramSize | -
| Touch-screen support | - -Whether there is a touch screen or not on the device. Default value is "yes". | - -hw.touchScreen | -
| Trackball support | - -Whether there is a trackball on the device. Default value is "yes". | - -hw.trackBall | -
| Keyboard support | - -Whether the device has a QWERTY keyboard. Default value is "yes". | - -hw.keyboard | -
| DPad support | - -Whether the device has DPad keys. Default value is "yes". | - -hw.dPad | -
| GSM modem support | - -Whether there is a GSM modem in the device. Default value is "yes". | - -hw.gsmModem | -
| Camera support | - -Whether the device has a camera. Default value is "no". | - -hw.camera | -
| Maximum horizontal camera pixels | - -Default value is "640". | - -hw.camera.maxHorizontalPixels | -
| Maximum vertical camera pixels | - -Default value is "480". | - -hw.camera.maxVerticalPixels | -
| GPS support | - -Whether there is a GPS in the device. Default value is "yes". | - -hw.gps | -
| Battery support | - -Whether the device can run on a battery. Default value is "yes". | - -hw.battery | -
| Accelerometer | - -Whether there is an accelerometer in the device. Default value is "yes". | - -hw.accelerometer | -
| Audio recording support | - -Whether the device can record audio. Default value is "yes". | - -hw.audioInput | -
| Audio playback support | - -Whether the device can play audio. Default value is "yes". | - -hw.audioOutput | -
| SD Card support | - -Whether the device supports insertion/removal of virtual SD Cards. Default value is - "yes". | - -hw.sdCard | -
| Cache partition support | - -Whether we use a /cache partition on the device. Default value is "yes". | - -disk.cachePartition | -
| Cache partition size | - -Default value is "66MB". | - -disk.cachePartition.size | -
| Abstracted LCD density | - -Sets the generalized density characteristic used by the AVD's screen. Default value is - "160". | - -hw.lcd.density | -
You should be redirected. Please click here.
- - \ No newline at end of file diff --git a/docs/html/guide/developing/index.jd b/docs/html/guide/developing/index.jd deleted file mode 100644 index 3af4a8c06ca7..000000000000 --- a/docs/html/guide/developing/index.jd +++ /dev/null @@ -1,150 +0,0 @@ -page.title=Introduction -@jd:body - -Developing applications for Android devices is facilitated by a group of tools that are - provided with the SDK. You can access these tools through an Eclipse plugin called ADT (Android - Development Tools) or from the command line. Developing with Eclipse is the preferred method because - it can directly invoke the tools that you need while developing applications.
- -However, you may choose to develop with another IDE or a simple text editor and invoke the - tools on the command line or with scripts. This is a less streamlined way to develop because you - will sometimes have to call command line tools manually, but you will have access to the same - number of features that you would have in Eclipse.
- -
- - Figure 1. The development process for Android applications. -
-The basic steps for developing applications (with or without Eclipse) are shown in figure 1. The -development steps encompass four development phases, which include:
- -During this phase you install and set up your development environment. You also create - Android Virtual Devices (AVDs) and connect hardware devices on which you can install your - applications.
-See Managing Virtual Devices - and Using Hardware Devices for more - information. -
During this phase you set up and develop your Android project, which contains all of the - source code and resource files for your application. For more informations, see - Create an Android project.
-During this phase you build your project into a debuggable .apk package that you
- can install and run on the emulator or an Android-powered device. If you are using Eclipse,
- builds are generated each time you project is saved. If you're using another IDE,
- you can build your project using Ant and install it on a device using
- adb. For more information, see
- Build and run your application.
Next, you debug your application using a JDWP-compliant debugger along with the debugging - and logging tools that are provided with the Android SDK. Eclipse already comes packaged with - a compatible debugger. For more information see, - Debug your application with the - SDK debugging and logging tools.
-Last, you test your application using various Android SDK testing tools. For more - information, see Test your application - with the Testing and Instrumentation framework.
-During this phase you configure and build your application for release and distribute your - application to users. For more information, see - Publishing Overview.
-When developing in IDEs or editors other than Eclipse, be familiar with - all of the tools below, because you will have to run them from the command line.
- -In addition to the above tools that are included with the SDK, you need the following open - source and third-party tools:
- -If you are using Eclipse and ADT, tools such as adb and android
- are automatically called by Eclipse and ADT so you don't have to manually invoke these tools.
- You need to be familiar with adb, however, because certain functions are not
-accessible from
- Eclipse, such as the adb shell commands. You might also need to call Keytool and
-Jarsigner to
- sign your applications, but you can set up Eclipse to do this automatically as well.
For more information on the tools provided with the Android SDK, see the - Tools section of the documentation.
- -- The tools described in this section are not developed by the Android SDK team. The Android Dev Guide - does not provide documentation for these tools. Please refer to the linked documents in each - section for documentation. -
-- IntelliJ IDEA is a powerful Java IDE from JetBrains that provides - full-cycle Android development support in both the free Community - Edition and the Ultimate edition. -
-- The IDE ensures compatibility with the latest Android SDK and offers a - smart code editor with completion, quick navigation between code and - resources, a graphical debugger, unit testing support using Android - Testing Framework, and the ability to run applications in either the - emulator or a USB-connected device. -
-- Links: -
-You should be redirected. Please click here.
- - \ No newline at end of file diff --git a/docs/html/guide/developing/projects/index.jd b/docs/html/guide/developing/projects/index.jd deleted file mode 100644 index b16e466e4a1f..000000000000 --- a/docs/html/guide/developing/projects/index.jd +++ /dev/null @@ -1,446 +0,0 @@ -page.title=Managing Projects -@jd:body - -Projects act as containers for storing things such as code and resource files. The SDK tools
- expect your projects to follow a specific structure so it can compile and package your
- application correctly, so it is highly recommended that you create them with Eclipse and ADT or
- with the android tool on the command line. There are three types of projects, and
- they all share the same general structure but differ in function:
.apk file that you install on a
- device..apk file at build time.When you use the Android development tools to create a new project, the essential files and - folders will be created for you. There are only a handful of files and folders generated for you, - and some of them depend on whether you use the Eclipse plugin or the {@code android} tool to - generate your project. As your application grows in complexity, you might require new kinds of - resources, directories, and files.
- -Android projects are the projects that eventually get built into an .apk file that you install
- onto a device. They contain things such as application source code and resource files.
- Some are generated for you by default, while others should be created if
- required. The following directories and files comprise an Android project:
src/src/your/package/namespace/ActivityName.java. All other source code
- files (such as .java or .aidl files) go here as well.bin.apk file and other
- compiled resources.jnigen/R.java file and
- interfaces created from AIDL files.assets/.apk file as-is, and the original filename is preserved. You can navigate this
- directory in the same way as a typical file system using URIs and read files as a stream of
- bytes using the the {@link android.content.res.AssetManager}. For example, this is a good
- location for textures and game data.res/anim/color/drawable/layout/menu/raw/assets/ directory only differs in the way that you access them. These files
- are processed by aapt and must be referenced from the application using a resource
- identifier in the {@code R} class. For example, this is a good place for media, such as MP3
- or Ogg files.values/res/ directory, resources written to XML files in this folder are not
- referenced by the file name. Instead, the XML element type controls how the resources is
- defined within them are placed into the {@code R} class.xml/libs/AndroidManifest.xmlproject.propertieslocal.propertieslocal.properties should not
-be maintained in a source revision control system. If you use Eclipse, this file is not
-used.ant.propertiesbuild.xmlThe SDK includes an example application called TicTacToeMain that shows how a dependent
- application can use code and resources from an Android Library project. The TicTacToeMain
- application uses code and resources from an example library project called TicTacToeLib.
To download the sample applications and run them as projects in - your environment, use the Android SDK Manager to download the "Samples for - SDK API 8" (or later) package into your SDK.
- -For more information and to browse the code of the samples, see - the TicTacToeMain - application.
-An Android library project is a development project that holds shared Android
- source code and resources. Other Android application projects can reference the library project
- and, at build time, include its compiled sources in their .apk files. Multiple
- application projects can reference the same library project and any single application project
- can reference multiple library projects.
Note: You need SDK Tools r14 or newer to use the new library - project feature that generates each library project into its own JAR file. - You can download the tools and platforms using the - Android SDK Manager, as described in - Adding SDK Packages.
- -If you have source code and resources that are common to multiple Android projects, you - can move them to a library project so that it is easier to maintain across applications and - versions. Here are some common scenarios in which you could make use of library projects:
- -Structurally, a library project is similar to a standard Android application project. For
- example, it includes a manifest file at the project root, as well as src/,
- res/ and similar directories. The project can contain the same types of source
- code and resources as a standard Android project, stored in the same way. For example, source
- code in the library project can access its own resources through its R class.
However, a library project differs from an standard Android application project in that you
- cannot compile it directly to its own .apk and run it on an Android device.
- Similarly, you cannot export the library project to a self-contained JAR file, as you would do
- for a true library. Instead, you must compile the library indirectly, by referencing the
- library in the dependent application and building that application.
When you build an application that depends on a library project, the SDK tools compile the
- library into a temporary JAR file and uses it in the main project, then uses the
- result to generate the .apk. In cases where a resource ID is defined in both the
- application and the library, the tools ensure that the resource declared in the application gets
- priority and that the resource in the library project is not compiled into the application
- .apk. This gives your application the flexibility to either use or redefine any
- resource behaviors or values that are defined in any library.
To organize your code further, your application can add references to multiple library - projects, then specify the relative priority of the resources in each library. This lets you - build up the resources actually used in your application in a cumulative manner. When two - libraries referenced from an application define the same resource ID, the tools select the - resource from the library with higher priority and discard the other.
- -Once you have added references to library projects to your Android project, - you can set their relative priority. At build time, the - libraries are merged with the application one at a time, starting from the lowest priority to - the highest.
- -Library projects can reference other library projects and can import an external library - (JAR) in the normal way.
- -As you develop your library project and dependent applications, keep the points listed below - in mind:
- -Resource conflicts
-Since the tools merge the resources of a library project with those of a dependent application - project, a given resource ID might be defined in both projects. In this case, the tools select - the resource from the application, or the library with highest priority, and discard the other - resource. As you develop your applications, be aware that common resource IDs are likely to be - defined in more than one project and will be merged, with the resource from the application or - highest-priority library taking precedence.
-Use prefixes to avoid resource conflicts
- -To avoid resource conflicts for common resource IDs, consider using a prefix or other - consistent naming scheme that is unique to the project (or is unique across all projects).
You cannot export a library project to a JAR file
- -A library cannot be distributed as a binary file (such as a JAR file). This will -be added in a future - version of the SDK Tools.
A library project can include a JAR library
- -You can develop a library project that itself includes a JAR library, however you need to - manually edit the dependent application project's build path and add a path to the JAR file.
A library project can depend on an external JAR library
- -You can develop a library project that depends on an external library (for example, the Maps
- external library). In this case, the dependent application must build against a target that
- includes the external library (for example, the Google APIs Add-On). Note also that both the
- library project and the dependent application must declare the external library in their manifest
- files, in a <uses-library>
- element.
Library projects cannot include raw assets
- -The tools do not support the use of raw asset files (saved in the assets/ directory)
- in a library project. Any asset resources
- used by an application must be stored in the assets/ directory of the application
- project itself. However, resource files saved in the
- res/ directory are supported.
Platform version must be lower than or equal to the Android project
- -A library is compiled as part of the dependent application project, so the API used in the - library project must be compatible with the version of the Android library used to compile the - application project. In general, the library project should use an API level that is the same as — or lower - than — that used by the application. If the library project uses an API level that is - higher than that of the application, the application project will not compile. It is - perfectly acceptable to have a library that uses the Android 1.5 API (API level 3) and that is - used in an Android 1.6 (API level 4) or Android 2.1 (API level 7) project, for instance.
No restriction on library package names
- -There is no requirement for the package name of a library to be the same as that of - applications that use it.
Each library project creates its own R class
- -When you build the dependent application project, library projects are compiled and
- merged with the application project. Each library has its own R class, named according
- to the library's package name. The R class generated from main
- project and the library project is created in all the packages that are needed including the main
- project's package and the libraries' packages.
Library project storage location
- -There are no specific requirements on where you should store a library project, relative to a - dependent application project, as long as the application project can reference the library - project by a relative link. What is important is that the main - project can reference the library project through a relative link.
Test projects contain Android applications that you write using the - Testing and - Instrumentation framework. The framework is an extension of the JUnit test framework and adds - access to Android system objects. The file structure of a test project is the same as an - Android project.
- -src/.java
- file, but can include one.gen/R.java file and
- interfaces created from AIDL files.assets/res/AndroidManifest.xml<instrumentation>
- element that connects the test project with the application project.project.propertieslocal.propertiesant.propertiesbuild.xmlFor more information, see the Testing section.
- - -There are two recommended ways of setting up testing on code and resources in a library - project:
- -The android tool provides you with commands to create all three types of
- projects. An Android project contains all of the files and resources that are needed to build a
- project into an .apk file for installation.
-
-
To create an Android project, you must use the android tool. When you create a
- new project with android, it will generate a project directory with some default
- application files, stub files, configuration files and a build file.
To create a new Android project, open a command-line, navigate to the tools/
- directory of your SDK and run:
-android create project \ ---target <target_ID> \ ---name <your_project_name> \ ---path path/to/your/project \ ---activity <your_activity_name> \ ---package <your_package_namespace> -- -
target is the "build target" for your application. It corresponds to an
- Android platform library (including any add-ons, such as Google APIs) that you would like to
- build your project against. To see a list of available targets and their corresponding IDs,
- execute: android list targets.name is the name for your project. This is optional. If provided, this name
- will be used for your .apk filename when you build your application.path is the location of your project directory. If the directory does not
- exist, it will be created for you.activity is the name for your default {@link android.app.Activity} class. This
- class file will be created for you inside
- <path_to_your_project>/src/<your_package_namespace_path>/
- . This will also be used for your .apk filename unless you provide a name.package is the package namespace for your project, following the same rules as
- for packages in the Java programming language.Here's an example:
--android create project \ ---target 1 \ ---name MyAndroidApp \ ---path ./MyAndroidAppProject \ ---activity MyAndroidAppActivity \ ---package com.example.myandroid -- -
Once you've created your project, you're ready to begin development. You can move your project
- folder wherever you want for development, but keep in mind that you must use the Android Debug Bridge (adb) — located in the
- SDK platform-tools/ directory — to send your application to the emulator (discussed
- later). So you need access between your project solution and the platform-tools/ folder.
Tip: Add the platform-tools/ as well as the tools/ directory
- to your PATH environment variable.
Caution: You should refrain from moving the location of the
- SDK directory, because this will break the SDK location property located in local.properties.
- If you need to update the SDK location, use the android update project command.
- See Updating a Project for more information.
If you're upgrading a project from an older version of the Android SDK or want to create a new
- project from existing code, use the android update project command to update the
- project to the new development environment. You can also use this command to revise the build
- target of an existing project (with the --target option) and the project name (with
- the --name option). The android tool will generate any files and
- folders (listed in the previous section) that are either missing or need to be updated, as needed
- for the Android project.
To update an existing Android project, open a command-line and navigate to the
- tools/ directory of your SDK. Now run:
-android update project --name <project_name> --target <target_ID> ---path <path_to_your_project> -- -
target is the "build target" for your application. It corresponds to an
- Android platform library (including any add-ons, such as Google APIs) that you would like to
- build your project against. To see a list of available targets and their corresponding IDs,
- execute: android list targets.path is the location of your project directory.name is the name for the project. This is optional—if you're not
- changing the project name, you don't need this.Here's an example:
--android update project --name MyApp --target 2 --path ./MyAppProject -- -
A library project is a standard Android project, so you can create a new one in the same way
- as you would a new application project. Specifically, you can use the android tool
- to generate a new library project with all of the necessary files and folders.
To create a new library project, navigate to the <sdk>/tools/ directory and
- use this command:
-android create lib-project --name <your_project_name> \ ---target <target_ID> \ ---path path/to/your/project \ ---package <your_library_package_namespace> -- -
The create lib-project command creates a standard project structure that includes
- preset property that indicates to the build system that the project is a library. It does this by
- adding this line to the project's project.properties file:
-android.library=true -- -
Once the command completes, the library project is created and you can begin moving source - code and resources into it, as described in the sections below.
- -If you want to convert an existing application project to a library project, so that other
- applications can use it, you can do so by adding a the android.library=true property
- to the application's project.properties file.
A library project's manifest file must declare all of the shared components that it includes, - just as would a standard Android application. For more information, see the documentation for - AndroidManifest.xml.
- -For example, the TicTacToeLib example library
- project declares the Activity GameActivity:
-<manifest> - ... - <application> - ... - <activity android:name="GameActivity" /> - ... - </application> -</manifest> -- -
If you want to update the build properties (build target, location) of the library project, - use this command:
--android update lib-project \ ---target <target_ID> \ ---path path/to/your/project -- -
If you are developing an application and want to include the shared code or resources from a - library project, you can do so easily by adding a reference to the library project in the - application project's build properties.
- -To add a reference to a library project, navigate to the <sdk>/tools/
- directory and use this command:
-android update project \ ---target <target_ID> \ ---path path/to/your/project ---library path/to/library_projectA -- -
This command updates the application project's build properties to include a reference to the
- library project. Specifically, it adds an android.library.reference.n
- property to the project's project.properties file. For example:
-android.library.reference.1=path/to/library_projectA -- -
If you are adding references to multiple libraries, note that you can set their relative
- priority (and merge order) by manually editing the project.properties file and
- adjusting the each reference's .n index as appropriate. For example, assume
- these references:
-android.library.reference.1=path/to/library_projectA -android.library.reference.2=path/to/library_projectB -android.library.reference.3=path/to/library_projectC -- -
You can reorder the references to give highest priority to library_projectC in
- this way:
-android.library.reference.2=path/to/library_projectA -android.library.reference.3=path/to/library_projectB -android.library.reference.1=path/to/library_projectC -- -
Note that the .n index in the references must begin at "1" and increase
- uniformly without "holes". References appearing in the index after a hole are ignored.
At build time, the libraries are merged with the application one at a time, starting from the - lowest priority to the highest. Note that a library cannot itself reference another library and - that, at build time, libraries are not merged with each other before being merged with the - application.
- -In the manifest file of the application project, you must add declarations of all components
- that the application will use that are imported from a library project. For example, you must
- declare any <activity>, <service>,
- <receiver>, <provider>, and so on, as well as
- <permission>, <uses-library>, and similar elements.
Declarations should reference the library components by their fully-qualified package names, - where appropriate.
- -For example, the TicTacToeMain example
- application declares the library Activity GameActivity like this:
-<manifest> - ... - <application> - ... - <activity android:name="com.example.android.tictactoe.library.GameActivity" /> - ... - </application> -</manifest> -- -
For more information about the manifest file, see the documentation for - AndroidManifest.xml.
- -To build an application project that depends on one or more library projects, you can use the - standard Ant build commands and compile modes, as described in Building and Running. The tools -compile and merge all libraries referenced by the application as part of - compiling the dependent application project. No additional commands or steps are necessary.
- diff --git a/docs/html/guide/developing/projects/projects-eclipse.jd b/docs/html/guide/developing/projects/projects-eclipse.jd deleted file mode 100644 index 90f7820631ae..000000000000 --- a/docs/html/guide/developing/projects/projects-eclipse.jd +++ /dev/null @@ -1,237 +0,0 @@ -page.title=Managing Projects from Eclipse with ADT -parent.title=Managing Projects -parent.link=index.html -@jd:body - -Eclipse and the ADT plugin provide GUIs and wizards to create all three types of projects - (Android project, Library project, and Test project): - -
The ADT plugin provides a New Project Wizard that you can use to quickly create a new Android - project (or a project from existing code). To create a new project:
- -Select the lowest platform with which your application is compatible.
- -Note: You can change your the Build Target for your - project at any time: Right-click the project in the Package Explorer, select - Properties, select Android and then check the desired - Project Target.
-minSdkVersion attribute in the <uses-sdk> of your
- Android Manifest file. If you're unsure of the appropriate API Level to use, copy the API Level
- listed for the Build Target you selected in the Target tab.Tip: You can also start the New Project Wizard from the - New icon in the toolbar.
- -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.
- -When you are creating the library project, you can select any application name, package, and - set other fields as needed, as shown in figure 1.
- -Next, set the project's properties to indicate that it is a library project:
- -The new project is now marked as a library project. You can begin moving source code and - resources into it, as described in the sections below.
- -You can also convert an existing application project into a library. To do so, simply open the - Properties for the project and select the "is Library" checkbox. Other application projects can - now reference the existing project as a library project.
- -
-
- Figure 1. Marking a project as an - Android library project.
- -A library project's manifest file must declare all of the shared components that it includes, - just as would a standard Android application. For more information, see the documentation for - AndroidManifest.xml.
- -For example, the TicTacToeLib example library
- project declares the Activity GameActivity:
-<manifest> - ... - <application> - ... - <activity android:name="GameActivity" /> - ... - </application> -</manifest> -- -
If you are developing an application and want to include the shared code or resources from a - library project, you can do so easily by adding a reference to the library project in the - application project's Properties.
- -To add a reference to a library project, follow these steps:
- -As soon as the Properties dialog closes, Eclipse rebuilds the project, including the contents - of the library project.
- -Figure 2 shows the Properties dialog that lets you add library references and move - them up and down in priority.
-
- Figure 2. Adding a reference to a - library project in the properties of an application project.
- -If you are adding references to multiple libraries, note that you can set their relative - priority (and merge order) by selecting a library and using the Up and - Down controls. The tools merge the referenced libraries with your application - starting from lowest priority (bottom of the list) to highest (top of the list). If more than one - library defines the same resource ID, the tools select the resource from the library with higher - priority. The application itself has highest priority and its resources are always used in - preference to identical resource IDs defined in libraries.
- -In the manifest file of the application project, you must add declarations of all components
- that the application will use that are imported from a library project. For example, you must
- declare any <activity>, <service>,
- <receiver>, <provider>, and so on, as well as
- <permission>, <uses-library>, and similar elements.
Declarations should reference the library components by their fully-qualified package names, - where appropriate.
- -For example, the TicTacToeMain example
- application declares the library Activity GameActivity like this:
-<manifest> - ... - <application> - ... - <activity android:name="com.example.android.tictactoe.library.GameActivity" /> - ... - </application> -</manifest> -- -
For more information about the manifest file, see the documentation for AndroidManifest.xml.
- - - - - - - diff --git a/docs/html/guide/developing/testing/index.jd b/docs/html/guide/developing/testing/index.jd deleted file mode 100644 index 8a0895989182..000000000000 --- a/docs/html/guide/developing/testing/index.jd +++ /dev/null @@ -1,36 +0,0 @@ -page.title=Testing -@jd:body -- Android includes powerful tools for setting up and running test applications. - Whether you are working in Eclipse with ADT or working from the command line, these tools - help you set up and run your tests within an emulator or the device you are targeting. - The documents listed below explain how to work with the tools in your development environment. -
-- If you aren't yet familiar with the Android testing framework, please read the topic - Testing Fundamentals - before you get started. - For a step-by-step introduction to Android testing, try the Hello, Testing - tutorial, which introduces basic testing concepts and procedures. - For a more advanced tutorial, try Activity Testing, - which guides you through a more complex testing scenario. -
-android tool to create and manage test projects, the Ant build system
- to compile them, and the adb tool to install and run them.
- - 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 an Android application with the - basic processes for creating and running applications with ADT, as described in - Managing Projects from -Eclipse - and Building and Running -from Eclipse. - You may also want to read - Testing Fundamentals, - which provides an overview of the Android testing framework. -
-- ADT provides several features that help you set up and manage your testing environment - effectively: -
-<instrumentation> element in the test package's manifest file.
- - If you are not developing in Eclipse or you want to learn how to create and run tests from the - command line, see - Testing from Other IDEs. -
-
- To set up a test environment for your Android application, you must first create a separate
- project that holds the test code. The new project follows the directory structure
- used for any Android application. It includes the same types of content and files, such as
- source code, resources, a manifest file, and so forth. The test package you
- create is connected to the application under test by an
-
- <instrumentation> element in its manifest file.
-
- The New Android Test Project dialog makes it easy for you to generate a
- new test project that has the proper structure, including the
- <instrumentation> element in the manifest file. You can use the New
- Android Test Project dialog to generate the test project at any time. The dialog appears
- just after you create a new Android main application project, but you can also run it to
- create a test project for a project that you created previously.
-
- To create a test project in Eclipse with ADT: -
-- The name becomes part of the suggested project path, but you can change this in the - next step. -
-/usr/local/workspace and your project name is
- MyTestApp, then the wizard will suggest
- /usr/local/workspace/MyTestApp. To enter your own
- choice for a path, unselect Use default location, then enter or browse to the
- path where you want your project.
- - To learn more about choosing the location of test projects, please read - - Testing Fundamentals. -
-- Once you have created a test project, you populate it with a test package. This package does not - require an Activity, although you can define one if you wish. Although your test package can - combine Activity classes, test case classes, or ordinary classes, your main test case - should extend one of the Android test case classes or JUnit classes, because these provide the - best testing features. -
-- Test packages do not need to have an Android GUI. When you run the package in - Eclipse with ADT, its results appear in the JUnit view. Running tests and seeing the results is - described in more detail in the section Running Tests. -
- -- To create a test package, start with one of Android's test case classes defined in - {@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 - Testing Fundamentals. -
-- Before you create your test package, you choose the Java package identifier you want to use - for your test case classes and the Android package name you want to use. To learn more - about this, please read - - Testing Fundamentals. -
-- To add a test case class to your project: -
-- 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. -
-
- To control your test environment, you will want to override the setUp() and
- tearDown() methods:
-
setUp(): This method is invoked before any of the test methods in the class.
- Use it to set up the environment for the test (the test fixture. You can use
- setUp() to instantiate a new Intent with the action ACTION_MAIN.
- You can then use this intent to start the Activity under test.
- tearDown(): This method is invoked after all the test methods in the class. Use
- it to do garbage collection and to reset the test fixture.
-
- Another useful convention is to add the method testPreconditions() to your test
- class. Use this method to test that the application under test is initialized correctly. If this
- test fails, you know that that the initial conditions were in error. When this happens, further
- test results are suspect, regardless of whether or not the tests succeeded.
-
- The Resources tab contains an - Activity Testing - tutorial with more information about creating test classes and methods. -
-- If you've created your tests in Eclipse, you can still run your tests and test - suites by using command-line tools included with the Android SDK. You may want - to do this, for example, if you have a large number of tests to run, if you - have a large test case, or if you want a fine level of control over which - tests are run at a particular time. -
-
- To run tests created in Eclipse with ADT with command-line tools, you must first
- install additional files into the test project using the android
- tool's "create test-project" option. To see how to do this, read
-
- Testing in Other IDEs.
-
- When you run a test package in Eclipse with ADT, the output appears in the Eclipse JUnit view.
- You can run the entire test package or one test case class. To do run tests, Eclipse runs the
- adb command for running a test package, and displays the output, so there is no
- difference between running tests inside Eclipse and running them from the command line.
-
- As with any other package, to run a test package in Eclipse with ADT you must either attach a - device to your computer or use the Android emulator. If you use the emulator, you must have an - Android Virtual Device (AVD) that uses the same target as the test package. -
-- To run a test in Eclipse, you have two choices:
-- Creating and running test configurations is described in the next section. -
-- To create and run a test suite using a run configuration: -
-- 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. -
-Note: - Although you can run the test immediately by clicking Run, you should save the test - first and then run it by selecting it from the Eclipse standard toolbar. -
-
- The progress of your test appears in the Console view as a series of messages. Each message is
- preceded by a timestamp and the .apk filename to which it applies. For example,
- this message appears when you run a test to the emulator, and the emulator is not yet started:
-
- The examples shown in this section come from the - SpinnerTest - sample test package, which tests the - Spinner - sample application. This test package is also featured in the - Activity Testing - tutorial. -
-
- [yyyy-mm-dd hh:mm:ss - testfile] Waiting for HOME ('android.process.acore') to be launched...
-
-
- In the following description of these messages, devicename is the name of
- the device or emulator you are using to run the test, and port is the
- port number for the device. The name and port number are in the format used by the
- adb devices
- command. Also, testfile is the .apk filename of the test
- package you are running, and appfile is the filename of the application under test.
-
- HOME is up on device 'devicename-port'
-
- Uploading testfile onto device 'devicename-port'
-
-
- then the message Installing testfile.
-
- and finally the message Success!
-
- The following lines are an example of this message sequence: -
-
-[2010-07-01 12:44:40 - MyTest] HOME is up on device 'emulator-5554'
-[2010-07-01 12:44:40 - MyTest] Uploading MyTest.apk onto device 'emulator-5554'
-[2010-07-01 12:44:40 - MyTest] Installing MyTest.apk...
-[2010-07-01 12:44:49 - MyTest] Success!
-
-
- Project dependency found, installing: appfile
-
- then the message Uploading appfile onto device
- 'devicename-port'
-
- then the message Installing appfile
-
- and finally the message Success!
-
- The following lines are an example of this message sequence: -
-
-[2010-07-01 12:44:49 - MyTest] Project dependency found, installing: MyApp
-[2010-07-01 12:44:49 - MyApp] Uploading MyApp.apk onto device 'emulator-5554'
-[2010-07-01 12:44:49 - MyApp] Installing MyApp.apk...
-[2010-07-01 12:44:54 - MyApp] Success!
-
-Launching instrumentation instrumentation_class on device
- devicename-port
-
- instrumentation_class is the fully-qualified class name of the
- instrumentation test runner you have specified (usually
- {@link android.test.InstrumentationTestRunner}.
-
- Collecting test information
-
- followed by -
-
- Sending test information to Eclipse
-
Running tests, which indicates that your tests
- are running. At this point, you should start seeing the test results in the JUnit view.
- When the tests are finished, you see the console message Test run complete.
- This indicates that your tests are finished.
- - The following lines are an example of this message sequence: -
-
-[2010-01-01 12:45:02 - MyTest] Launching instrumentation android.test.InstrumentationTestRunner on device emulator-5554
-[2010-01-01 12:45:02 - MyTest] Collecting test information
-[2010-01-01 12:45:02 - MyTest] Sending test information to Eclipse
-[2010-01-01 12:45:02 - MyTest] Running tests...
-[2010-01-01 12:45:22 - MyTest] Test run complete
-
-- The test results appear in the JUnit view. This is divided into an upper summary pane, - and a lower stack trace pane. -
-- The upper pane contains test information. In the pane's header, you see the following - information: -
-- The body of the upper pane contains the details of the test run. For each test case class - that was run, you see a line with the class name. To look at the results for the individual - test methods in that class, you click the left arrow to expand the line. You now see a - line for each test method in the class, and to its right the time it took to run. - If you double-click the method name, Eclipse opens the test class source in an editor view - pane and moves the focus to the first line of the test method. -
-- The results of a successful test are shown in figure 1. -
- -
-
-- Figure 1. Messages for a successful test. -
-- The lower pane is for stack traces. If you highlight a failed test in the upper pane, the - lower pane contains a stack trace for the test. If a line corresponds to a point in your - test code, you can double-click it to display the code in an editor view pane, with the - line highlighted. For a successful test, the lower pane is empty. -
-The results of a failed test are shown in figure 2.
- -
-
-- Figure 2. Messages for a test failure. -
diff --git a/docs/html/guide/developing/testing/testing_otheride.jd b/docs/html/guide/developing/testing/testing_otheride.jd deleted file mode 100644 index 7745ae775f41..000000000000 --- a/docs/html/guide/developing/testing/testing_otheride.jd +++ /dev/null @@ -1,694 +0,0 @@ -page.title=Testing from Other IDEs -parent.title=Testing -parent.link=index.html -@jd:body - -- This document describes how to create and run tests directly from the command line. - You can use the techniques described here if you are developing in an IDE other than Eclipse - or if you prefer to work from the command line. This document assumes that you already know how - to create a Android application in your programming environment. Before you start this - document, you should read the topic - Testing Fundamentals, - which provides an overview of Android testing. -
-- If you are developing in Eclipse with ADT, you can set up and run your tests - directly in Eclipse. For more information, please read - - Testing from Eclipse with ADT. -
-
- You use the android tool to create test projects.
- You also use android to convert existing test code into an Android test project,
- or to add the run-tests Ant target to an existing Android test project.
- These operations are described in more detail in the section
- Updating a test project. The run-tests target is described in
- Quick build and run with Ant.
-
- To create a test project with the android tool, enter:
-
-android create test-project -m <main_path> -n <project_name> -p <test_path> --
- You must supply all the flags. The following table explains them in detail: -
-| Flag | -Value | -Description | -
|---|---|---|
-m, --main |
- - Path to the project of the application under test, relative to the test package - directory. - | -
- For example, if the application under test is in source/HelloAndroid, and
- you want to create the test project in source/HelloAndroidTest, then the
- value of --main should be ../HelloAndroid.
- - To learn more about choosing the location of test projects, please read - - Testing Fundamentals. - - |
-
-n, --name |
- Name that you want to give the test project. | -- |
-p, --path |
- Directory in which you want to create the new test project. | -
- The android tool creates the test project files and directory structure
- in this directory. If the directory does not exist, android creates it.
- |
-
- If the operation is successful, android lists to STDOUT the names of the files
- and directories it has created.
-
- This creates a new test project with the appropriate directories and build files. The directory - structure and build file contents are identical to those in a regular Android application - project. They are described in detail in the topic - Managing Projects. -
-
- The operation also creates an AndroidManifest.xml file with instrumentation
- information. When you run the test, Android uses this information to load the application you
- are testing and control it with instrumentation.
-
- For example, suppose you create the
- Hello, World tutorial application in the directory ~/source/HelloAndroid.
- In the tutorial, this application uses the package name com.example.helloandroid
- and the activity name HelloAndroid. You can to create the test for this in
- ~/source/HelloAndroidTest. To do so, you enter:
-
-$ cd ~/source -$ android create test-project -m ../HelloAndroid -n HelloAndroidTest -p HelloAndroidTest --
- This creates a directory called ~/src/HelloAndroidTest. In the new directory you
- see the file AndroidManifest.xml. This file contains the following
- instrumentation-related elements and attributes:
-
<application>: to contain the
- <uses-library> element.
- <uses-library android:name="android.test.runner":
- specifies this testing application uses the android.test.runner library.
- <instrumentation>: contains attributes that control Android
- instrumentation. The attributes are:
- android:name="android.test.InstrumentationTestRunner":
- {@link android.test.InstrumentationTestRunner} runs test cases. It extends both
- JUnit test case runner classes and Android instrumentation classes.
- android:targetPackage="com.example.helloandroid": specifies
- that the tests in HelloAndroidTest should be run against the application with the
- Android package name com.example.helloandroid. This is the
- package name of the Hello, World
- tutorial application.
- android:label="Tests for .HelloAndroid": specifies a
- user-readable label for the instrumentation class. By default,
- the android tool gives it the value "Tests for " plus
- the name of the main Activity of the application under test.
-
- You use the android tool when you need to change the path to the
- project of the application under test. If you are changing an existing test project created in
- Eclipse with ADT so that you can also build and run it from the command line, you must use the
- "create" operation. See the section Creating a test project.
-
- Note: If you change the Android package name of the application under test,
- you must manually change the value of the <android:targetPackage>
- attribute within the AndroidManifest.xml file of the test package.
- Running android update test-project does not do this.
-
- To update a test project with the android tool, enter:
-
android update test-project -m <main_path> -p <test_path>- -
| Flag | -Value | -Description | -
|---|---|---|
-m, --main |
- The path to the project of the application under test, relative to the test project | -
- For example, if the application under test is in source/HelloAndroid, and
- the test project is in source/HelloAndroidTest, then the value for
- --main is ../HelloAndroid.
- |
-
-p, --path |
- The of the test project. | -
- For example, if the test project is in source/HelloAndroidTest, then the
- value for --path is HelloAndroidTest.
- |
-
- If the operation is successful, android lists to STDOUT the names of the files
- and directories it has created.
-
- 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. -
-- 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. -
- -- 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. -
-
- For test classes that extend {@link junit.framework.TestCase TestCase}, you probably want to
- override the setUp() and tearDown() methods:
-
setUp(): This method is invoked before any of the test methods in the class.
- Use it to set up the environment for the test. You can use setUp()
- to instantiate a new Intent object with the action ACTION_MAIN.
- You can then use this intent to start the Activity under test.
-
- Note: If you override this method, call
- super.setUp() as the first statement in your code.
-
tearDown(): This method is invoked after all the test methods in the class. Use
- it to do garbage collection and re-setting before moving on to the next set of tests.
- Note: If you override this method, you must call
- super.tearDown() as the last statement in your code.
- Another useful convention is to add the method testPreConditions() to your test
- class. Use this method to test that the application under test is initialized correctly. If this
- test fails, you know that that the initial conditions were in error. When this happens, further
- test results are suspect, regardless of whether or not the tests succeeded.
-
- To learn more about creating test packages, see the topic Testing Fundamentals, - which provides an overview of Android testing. If you prefer to follow a tutorial, - try the Activity Testing - tutorial, which leads you through the creation of tests for an actual Android application. -
-- You run tests from the command line, either with Ant or with an - - Android Debug Bridge (adb) shell. -
-
- You can use Ant to run all the tests in your test project, using the target
- run-tests, which is created automatically when you create a test project with
- the android tool.
-
- This target re-builds your main project and test project if necessary, installs the test
- application to the current AVD or device, and then runs all the test classes in the test
- application. The results are directed to STDOUT.
-
- You can update an existing test project to use this feature. To do this, use the
- android tool with the update test-project option. This is described
- in the section Updating a test project.
-
- When you run tests from the command line with - - Android Debug Bridge (adb), you get more options for choosing the tests - to run than with any other method. You can select individual test methods, filter tests - according to their annotation, or specify testing options. Since the test run is controlled - entirely from a command line, you can customize your testing with shell scripts in various ways. -
-
- To run a test from the command line, you run adb shell to start a command-line
- shell on your device or emulator, and then in the shell run the am instrument
- command. You control am and your tests with command-line flags.
-
- As a shortcut, you can start an adb shell, call am instrument, and
- specify command-line flags all on one input line. The shell opens on the device or emulator,
- runs your tests, produces output, and then returns to the command line on your computer.
-
- To run a test with am instrument:
-
.apk files) to your current Android device or emulator-$ adb shell am instrument -w <test_package_name>/<runner_class> --
- where <test_package_name> is the Android package name of your test
- application, and <runner_class> is the name of the Android test
- runner class you are using. The Android package name is the value of the
- package attribute of the manifest element in the manifest file
- (AndroidManifest.xml) of your test package. The Android test runner
- class is usually {@link android.test.InstrumentationTestRunner}.
-
- Your test results appear in STDOUT.
-
- This operation starts an adb shell, then runs am instrument
- with the specified parameters. This particular form of the command will run all of the tests
- in your test package. You can control this behavior with flags that you pass to
- am instrument. These flags are described in the next section.
-
- The general syntax of the am instrument command is:
-
- am instrument [flags] <test_package>/<runner_class> --
- The main input parameters to am instrument are described in the following table:
-
| - Parameter - | -- Value - | -- Description - | -
|---|---|---|
- <test_package>
- |
- - The Android package name of the test package. - | -
- The value of the package attribute of the manifest
- element in the test package's manifest file.
- |
-
- <runner_class>
- |
- - The class name of the instrumented test runner you are using. - | -- This is usually {@link android.test.InstrumentationTestRunner}. - | -
- The flags for am instrument are described in the following table:
-
| - Flag - | -- Value - | -- Description - | -
|---|---|---|
- -w
- |
- - (none) - | -
- Forces am instrument to wait until the instrumentation terminates
- before terminating itself. The net effect is to keep the shell open until the tests
- have finished. This flag is not required, but if you do not use it, you will not
- see the results of your tests.
- |
-
- -r
- |
- - (none) - | -
- Outputs results in raw format. Use this flag when you want to collect
- performance measurements, so that they are not formatted as test results. This flag is
- designed for use with the flag -e perf true (documented in the section
- Instrument options).
- |
-
- -e
- |
- - <test_options> - | -
- Provides testing options as key-value pairs. The
- am instrument tool passes these to the specified instrumentation class
- via its onCreate() method. You can specify multiple occurrences of
- -e <test_options>. The keys and values are described in the
- section am instrument options.
- - The only instrumentation class that uses these key-value pairs is - {@link android.test.InstrumentationTestRunner} (or a subclass). Using them with - any other class has no effect. - - |
-
- The am instrument tool passes testing options to
- InstrumentationTestRunner or a subclass in the form of key-value pairs,
- using the -e flag, with this syntax:
-
- -e <key> <value> --
- Some keys accept multiple values. You specify multiple values in a comma-separated list.
- For example, this invocation of InstrumentationTestRunner provides multiple
- values for the package key:
-
-$ adb shell am instrument -w -e package com.android.test.package1,com.android.test.package2 \ -> com.android.test/android.test.InstrumentationTestRunner --
- The following table describes the key-value pairs and their result. Please review the - Usage Notes following the table. -
-| Key | -Value | -Description | -
|---|---|---|
- package
- |
- - <Java_package_name> - | -- The fully-qualified Java package name for one of the packages in the test - application. Any test case class that uses this package name is executed. Notice that - this is not an Android package name; a test package has a single - Android package name but may have several Java packages within it. - | -
class |
- <class_name> | -- The fully-qualified Java class name for one of the test case classes. Only this test - case class is executed. - | -
| <class_name>#method name | -- A fully-qualified test case class name, and one of its methods. Only this method is - executed. Note the hash mark (#) between the class name and the method name. - | -|
func |
- true |
- - Runs all test classes that extend {@link android.test.InstrumentationTestCase}. - | -
unit |
- true |
- - Runs all test classes that do not extend either - {@link android.test.InstrumentationTestCase} or - {@link android.test.PerformanceTestCase}. - | -
size |
-
- [small | medium | large]
- |
-
- Runs a test method annotated by size. The annotations are @SmallTest,
- @MediumTest, and @LargeTest.
- |
-
perf |
- true |
-
- Runs all test classes that implement {@link android.test.PerformanceTestCase}.
- When you use this option, also specify the -r flag for
- am instrument, so that the output is kept in raw format and not
- re-formatted as test results.
- |
-
debug |
- true |
- - Runs tests in debug mode. - | -
log |
- true |
-
- Loads and logs all specified tests, but does not run them. The test
- information appears in STDOUT. Use this to verify combinations of other
- filters and test specifications.
- |
-
emma |
- true |
-
- Runs an EMMA code coverage analysis and writes the output to
- /data//coverage.ec on the device. To override the file location, use the
- coverageFile key that is described in the following entry.
-
- Note: This option requires an EMMA-instrumented build of the test
- application, which you can generate with the |
-
coverageFile |
- <filename> |
-
- Overrides the default location of the EMMA coverage file on the device. Specify this
- value as a path and filename in UNIX format. The default filename is described in the
- entry for the emma key.
- |
-
-e Flag Usage Notes
-am instrument invokes
- {@link android.test.InstrumentationTestRunner#onCreate(Bundle)}
- with a {@link android.os.Bundle} containing the key-value pairs.
- package key takes precedence over the class key. If you
- specifiy a package, and then separately specify a class within that package, Android
- will run all the tests in the package and ignore the class key.
- func key and unit key are mutually exclusive.
-
-The following sections provide examples of using am instrument to run tests.
-They are based on the following structure:
com.android.demo.app.tests
- UnitTests, which contains the methods
- testPermissions and testSaveState.
- FunctionTests, which contains the methods
- testCamera, testXVGA, and testHardKeyboard.
- IntegrationTests,
- which contains the method testActivityProvider.
- - To run all of the test classes in the test package, enter: -
--$ adb shell am instrument -w com.android.demo.app.tests/android.test.InstrumentationTestRunner --
- To run all of the tests in the class UnitTests, enter:
-
-$ adb shell am instrument -w \ -> -e class com.android.demo.app.tests.UnitTests \ -> com.android.demo.app.tests/android.test.InstrumentationTestRunner --
- am instrument gets the value of the -e flag, detects the
- class keyword, and runs all the methods in the UnitTests class.
-
- To run all of the tests in UnitTests, and the testCamera method in
- FunctionTests, enter:
-
-$ adb shell am instrument -w \ -> -e class com.android.demo.app.tests.UnitTests,com.android.demo.app.tests.FunctionTests#testCamera \ -> com.android.demo.app.tests/android.test.InstrumentationTestRunner --
- You can find more examples of the command in the documentation for - {@link android.test.InstrumentationTestRunner}. -
diff --git a/docs/html/guide/developing/tools/MonkeyDevice.jd b/docs/html/guide/developing/tools/MonkeyDevice.jd deleted file mode 100644 index abcf8fdbb10f..000000000000 --- a/docs/html/guide/developing/tools/MonkeyDevice.jd +++ /dev/null @@ -1,1355 +0,0 @@ -page.title=MonkeyDevice -parent.title=monkeyrunner -parent.link=index.html -@jd:body - -
- A monkeyrunner class that represents a device or emulator accessible by the workstation running
-monkeyrunner.
-
- This class is used to control an Android device or emulator. The methods send UI events, - retrieve information, install and remove applications, and run applications. -
-
- You normally do not have to create an instance of MonkeyDevice. Instead, you
- use
-
-MonkeyRunner.waitForConnection() to create a new object from a connection to a device or
-emulator. For example, instead of
-using:
-newdevice = MonkeyDevice() --
- you would use: -
--newdevice = MonkeyRunner.waitForConnection() --
| Constants | -|||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|
| string | -DOWN | -
- Use this with the type argument of
- press() or touch()
-
- to send a DOWN event.
- |
- |||||||||
| string | -UP | -
- Use this with the type argument of
- press() or touch()
-
- to send an UP event.
- |
- |||||||||
| string | -DOWN_AND_UP | -
- Use this with the type argument of
- press() or touch()
-
- to send a DOWN event immediately followed by an UP event.
- |
- |||||||||
| Methods | -|||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|
|
- |
-
-
- Broadcasts an Intent to this device, as if the Intent were coming from an
- application.
-
- |
- ||||||||||
|
- |
-
-
- Simulates a drag gesture (touch, hold, and move) on this device's screen.
-
- |
- ||||||||||
|
- |
-
-
- Given the name of a system environment variable, returns its value for this device.
- The available variable names are listed in the
- detailed description of this method.
-
- |
- ||||||||||
|
- |
-
-
-. The API equivalent of
- adb shell getprop <key>. This is provided for use
- by platform developers.
- |
- ||||||||||
|
- |
-
-
- Installs the Android application or test package contained in packageFile onto this
- device. If the application or test package is already installed, it is replaced.
-
- |
- ||||||||||
|
- |
-
-
- Runs the specified component under Android instrumentation, and returns the results
- in a dictionary whose exact format is dictated by the component being run. The
- component must already be present on this device.
-
- |
- ||||||||||
|
- |
-
-
- Sends the key event specified by type to the key specified by
- keycode.
-
- |
- ||||||||||
|
- |
-
-
- Reboots this device into the bootloader specified by bootloadType.
-
- |
- ||||||||||
|
- |
-
-
- Deletes the specified package from this device, including its data and cache.
-
- |
- ||||||||||
|
- |
-
-
- Executes an
- adb shell command and returns the result, if any.
- |
- ||||||||||
|
- |
-
-
- Starts an Activity on this device by sending an Intent constructed from the
- supplied arguments.
-
- |
- ||||||||||
-
-
- MonkeyImage
-
-
- |
-
-
- Captures the entire screen buffer of this device, yielding a
-
-
-
- MonkeyImage
-
- object containing a screen capture of the current display.
- |
- ||||||||||
|
- |
-
-
- Sends a touch event specified by type to the screen location specified
- by x and y.
-
- |
- ||||||||||
|
- |
-
-
- Sends the characters contained in message to this device, as if they
- had been typed on the device's keyboard. This is equivalent to calling
-
- press() for each keycode in message
- using the key event type DOWN_AND_UP.
- |
- ||||||||||
|
- |
-
-
- Wakes the screen of this device.
-
- |
- ||||||||||
- Broadcasts an Intent to this device, as if the Intent were coming from an - application. See {@link android.content.Intent Intent} for more information about the - arguments. -
-| uri | -- The URI for the Intent. - (see {@link android.content.Intent#setData(android.net.Uri) Intent.setData()}). - | -
|---|---|
| action | -- The action for this Intent - (see {@link android.content.Intent#setAction(java.lang.String) Intent.setAction()}). - | -
| data | -- The data URI for this Intent - (see {@link android.content.Intent#setData(android.net.Uri) Intent.setData()}). - | -
| mimetype | -- The MIME type for the Intent - (see {@link android.content.Intent#setType(java.lang.String) Intent.setType()}). - | -
| categories | -- An iterable data structure containing strings that define categories for this - Intent - (see - {@link android.content.Intent#addCategory(java.lang.String) Intent.addCategory()}). - | -
| extras | -
- A dictionary of extra data for this Intent
- (see {@link android.content.Intent#putExtra(java.lang.String,java.lang.String)
- Intent.putExtra()}
- for an example).
- - The key for each dictionary item should be a string. The item's value - can be any simple or structured data type. - - |
-
| component | -- The component for this Intent (see {@link android.content.ComponentName}). - Using this argument will direct the Intent to a specific class within a specific - Android package. - | -
| flags | -- An iterable data structure containing flags that control how the Intent is handled - (see {@link android.content.Intent#setFlags(int) Intent.setFlags()}). - | -
- Simulates a drag gesture (touch, hold, and move) on this device's screen. -
-| start | -- The starting point of the drag gesture, in the form of a tuple - (x,y) where x and y are integers. - | -
|---|---|
| end | -- The end point of the drag gesture, in the form of a tuple (x,y) - where x and y are integers. - | -
| duration | -The duration of the drag gesture in seconds. The default is 1.0 seconds. | -
| steps | -The number of steps to take when interpolating points. The default is 10. | -
- Given the name of a system environment variable, returns its value for this device. -
-| key | -- The name of the system environment variable. The available variable names are listed in - Table 1. Property variable names at the end of this topic. - | -
|---|
- Synonym for getProperty().
-
| key | -- The name of the system environment variable. The available variable names are listed in - Table 1. Property Variable Names. - | -
|---|
- Installs the Android application or test package contained in packageFile - onto this device. If the application or test package is already installed, it is - replaced. -
-| path | -
- The fully-qualified path and filename of the .apk file to install.
- |
-
|---|
- Runs the specified component with Android instrumentation, and returns the results - in a dictionary whose exact format is dictated by the component being run. The - component must already be present on this device. -
-- Use this method to start a test case that uses one of Android's test case classes. - See Testing - Fundamentals to learn more about unit testing with the Android testing - framework. -
-| className | -
- The name of an Android component that is already installed on this device, in the
- standard form packagename/classname, where packagename is the
- Android package name of a .apk file on this device, and
- classname is the class name of an Android component (Activity,
- ContentProvider, Service, or BroadcastReceiver) in that file. Both
- packagename and classname must be fully qualified. See
- {@link android.content.ComponentName} for more details.
- |
-
|---|---|
| args | -- A dictionary containing flags and their values. These are passed to the component as it - is started. If the flag does not take a value, set its dictionary value to an empty - string. - | -
- A dictionary containing the component's output. The contents of the dictionary - are defined by the component itself. -
-
- If you use {@link android.test.InstrumentationTestRunner} as the class name in
- the componentName argument, then the result dictionary contains
- the single key "stream". The value of "stream" is a string containing
- the test output, as if InstrumentationTestRunner was run from the
- command line. The format of this output is described in
-
- Testing in Other IDEs.
-
- Sends the key event specified by type to the key specified by
- keycode.
-
| name | -- The name of the keycode to send. See {@link android.view.KeyEvent} for a list of - keycode names. Use the keycode name, not its integer value. - | -
|---|---|
| type | -
- The type of key event to send. The allowed values are
- DOWN, UP, and
- DOWN_AND_UP.
- |
-
- Reboots this device into the bootloader specified by bootloadType.
-
| into | -- The type of bootloader to reboot into. The allowed values are - "bootloader", "recovery", or "None". - | -
|---|
- Deletes the specified package from this device, including its data and cache. -
-| package | -
- The Android package name of an .apk file on this device.
- |
-
|---|
- Executes an adb shell command and returns the result, if any.
-
| cmd | -
- The command to execute in the adb shell. The form of these commands is
- described in the topic Android
- Debug Bridge.
- |
-
|---|
- Starts an Activity on this device by sending an Intent constructed from the - supplied arguments. -
-| uri | -- The URI for the Intent. - (see {@link android.content.Intent#setData(android.net.Uri) Intent.setData()}). - | -
|---|---|
| action | -- The action for the Intent - (see {@link android.content.Intent#setAction(java.lang.String) Intent.setAction()}). - | -
| data | -- The data URI for the Intent - (see {@link android.content.Intent#setData(android.net.Uri) Intent.setData()}). - | -
| mimetype | -- The MIME type for the Intent - (see {@link android.content.Intent#setType(java.lang.String) Intent.setType()}). - | -
| categories | -- An iterable data structure containing strings that define categories for the - Intent - (see - {@link android.content.Intent#addCategory(java.lang.String) Intent.addCategory()}). - | -
| extras | -
- A dictionary of extra data for the Intent
- (see
- {@link android.content.Intent#putExtra(java.lang.String,java.lang.String)
- Intent.putExtra()}
- for an example).
- - The key for each dictionary item should be a string. The item's value - can be any simple or structured data type. - - |
-
| component | -- The component for the Intent - (see {@link android.content.ComponentName}). Using this argument will direct the - Intent to a specific class within a specific Android package. - | -
| flags | -- An iterable data structure containing flags that control how the Intent is handled - (see {@link android.content.Intent#setFlags(int) Intent.setFlags()}). - | -
-
- MonkeyImage
-
-
-
- takeSnapshot
-
- ()
-
- - Captures the entire screen buffer of this device, yielding a - screen capture of the current display. -
-- Sends a touch event specified by type to the screen location specified - by x and y. -
-| x | -- The horizontal position of the touch in actual device pixels, starting from the left of - the screen in its current orientation. - | -
|---|---|
| y | -- The vertical position of the touch in actual device pixels, starting from the top of - the screen in its current orientation. - | -
| type | -
- The type of key event to send. The allowed values are
- DOWN, UP, and
- DOWN_AND_UP.
- |
-
- Sends the characters contained in message to this device, as if they
- had been typed on the device's keyboard. This is equivalent to calling
- press() for each keycode in message
- using the key event type DOWN_AND_UP.
-
| message | -- A string containing the characters to send. - | -
|---|
- Wakes the screen of this device. -
-- Table 1.Property variable names used with - getProperty() and - getSystemProperty(). -
-| - Property Group - | -- Property - | -- Description - | -- Notes - | -
|---|---|---|---|
build |
- board |
- Code name for the device's system board | -- See {@link android.os.Build} - | -
brand |
- The carrier or provider for which the OS is customized. | -||
device |
- The device design name. | -||
fingerprint |
- A unique identifier for the currently-running build. | -||
host |
- - | ||
ID |
- A changelist number or label. | -||
model |
- The end-user-visible name for the device. | -||
product |
- The overall product name. | -||
tags |
- Comma-separated tags that describe the build, such as "unsigned" and "debug". | -||
type |
- The build type, such as "user" or "eng". | -||
user |
- - | ||
CPU_ABI |
- - The name of the native code instruction set, in the form CPU type plus - ABI convention. - | -||
manufacturer |
- The product/hardware manufacturer. | -||
version.incremental |
- - The internal code used by the source control system to represent this version - of the software. - | -||
version.release |
- The user-visible name of this version of the software. | -||
version.sdk |
- The user-visible SDK version associated with this version of the OS. | -||
version.codename |
- - The current development codename, or "REL" if this version of the software has been - released. - | -||
display |
- width |
- The device's display width in pixels. | -- See - {@link android.util.DisplayMetrics} for details. - | -
height |
- The device's display height in pixels. | -||
density |
-
- The logical density of the display. This is a factor that scales
- DIP (Density-Independent Pixel) units to the device's resolution. DIP is adjusted so
- that 1 DIP is equivalent to one pixel on a 160 pixel-per-inch display. For example,
- on a 160-dpi screen, density = 1.0, while on a 120-dpi screen, density = .75.
- - The value does not exactly follow the real screen size, but is adjusted to - conform to large changes in the display DPI. See - {@link android.util.DisplayMetrics#density} for more details. - - |
- ||
am.current |
- package |
- The Android package name of the currently running package. | -
- The am.current keys return information about the currently-running
- Activity.
- |
-
action |
-
- The current activity's action. This has the same format as the name
- attribute of the action element in a package manifest.
- |
- ||
comp.class |
-
- The class name of the component that started the current Activity. See
- comp.package for more details. |
- ||
comp.package |
- - The package name of the component that started the current Activity. A component - is specified by a package name and the name of class that the package contains. - | -||
data |
- The data (if any) contained in the Intent that started the current Activity. | -||
categories |
- The categories specified by the Intent that started the current Activity. | -||
clock |
- realtime |
- - The number of milliseconds since the device rebooted, including deep-sleep - time. - | -- See {@link android.os.SystemClock} for more information. - | -
uptime |
- - The number of milliseconds since the device rebooted, not including - deep-sleep time - | -||
millis |
- current time since the UNIX epoch, in milliseconds. | -
- A monkeyrunner class to hold an image of the device or emulator's screen. The image is
- copied from the screen buffer during a screenshot. This object's methods allow you to
- convert the image into various storage formats, write the image to a file, copy parts of
- the image, and compare this object to other MonkeyImage objects.
-
- You do not need to create new instances of MonkeyImage. Instead, use
-
-MonkeyDevice.takeSnapshot() to create a new instance from a screenshot. For example, use:
-
-newimage = MonkeyDevice.takeSnapshot() --
| Methods | -|||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|
|
- |
-
-
- Converts the current image to a particular format and returns it as a
- string that you can then access as an iterable of binary bytes.
-
- |
- ||||||||||
|
- |
-
-
- Returns the single pixel at the image location (x,y), as an
- a tuple of integer, in the form (a,r,g,b).
-
- |
- ||||||||||
|
- |
-
-
- Returns the single pixel at the image location (x,y), as
- a 32-bit integer.
-
- |
- ||||||||||
-
- MonkeyImage
-
- |
-
-
- Creates a new
- MonkeyImage object from a rectangular selection of the
- current image.
- |
- ||||||||||
|
- |
-
- MonkeyImage
- other,
- float percent)
-
- Compares this
- MonkeyImage object to another and returns the result of
- the comparison. The percent argument specifies the percentage
- difference that is allowed for the two images to be "equal".
- |
- ||||||||||
|
- |
-
-
- Writes the current image to the file specified by
- filename, in the
- format specified by format.
- |
- ||||||||||
- Converts the current image to a particular format and returns it as a string - that you can then access as an iterable of binary bytes. -
-| format | -- The desired output format. All of the common raster output formats are supported. - The default value is "png" (Portable Network Graphics). - | -
|---|
- Returns the single pixel at the image location (x,y), as an - a tuple of integer, in the form (a,r,g,b). -
-| x | -- The horizontal position of the pixel, starting with 0 at the left of the screen in the - orientation it had when the screenshot was taken. - | -
|---|---|
| y | -- The vertical position of the pixel, starting with 0 at the top of the screen in the - orientation it had when the screenshot was taken. - | -
- Returns the single pixel at the image location (x,y), as an - an integer. Use this method to economize on memory. -
-| x | -- The horizontal position of the pixel, starting with 0 at the left of the screen in the - orientation it had when the screenshot was taken. - | -
|---|---|
| y | -- The vertical position of the pixel, starting with 0 at the top of the screen in the - orientation it had when the screenshot was taken. - | -
- MonkeyImage
-
-
- getSubImage
-
- (tuple rect)
-
-
- Creates a new MonkeyImage object from a rectangular selection of the
- current image.
-
| rect | -
- A tuple (x, y, w, h) specifying the selection. x and y specify the 0-based pixel
- position of the upper left-hand corner of the selection. w specifies the width of the
- region, and h specifies its height, both in units of pixels.
- - The image's orientation is the same as the screen orientation at the time the - screenshot was made. - - |
-
|---|
MonkeyImage object containing the selection.
-
- MonkeyImage
- otherImage,
- float percent
- )
-
-
- Compares this MonkeyImage object to another and returns the result of
- the comparison. The percent argument specifies the percentage
- difference that is allowed for the two images to be "equal".
-
| other | -
- Another MonkeyImage object to compare to this one.
- |
-
|---|---|
| - percent - | -
- A float in the range 0.0 to 1.0, inclusive, indicating
- the percentage of pixels that need to be the same for the method to return
- true. The default is 1.0, indicating that all the pixels
- must match.
- |
-
true if the images match, or boolean false otherwise.
-
- Writes the current image to the file specified by filename, in the
- format specified by format.
-
| path | -- The fully-qualified filename and extension of the output file. - | -
|---|---|
| - format - | -- The output format to use for the file. If no format is provided, then the - method tries to guess the format from the filename's extension. If no - extension is provided and no format is specified, then the default format of - "png" (Portable Network Graphics) is used. - | -
- A monkeyrunner class that contains static utility methods. -
-| Methods | -|||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|
|
- |
-
-
- Displays an alert dialog to the process running the current
- program.
-
- |
- ||||||||||
|
- |
-
-
- Displays a dialog with a list of choices to the process running the current program.
-
- |
- ||||||||||
|
- |
-
-
- Displays the monkeyrunner API reference in a style similar to that of Python's
-
- pydoc tool, using the specified format.
- |
- ||||||||||
|
- |
-
-
- Displays a dialog that accepts input.
-
- |
- ||||||||||
|
- |
-
-
- Pauses the current program for the specified number of seconds.
-
- |
- ||||||||||
-
- MonkeyDevice
-
- |
-
-
- Tries to make a connection between the
- monkeyrunner backend and the
- specified device or emulator.
- |
- ||||||||||
- 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. -
-| message | -- The message to display in the dialog. - | -
|---|---|
| title | -- The dialog's title. The default value is "Alert". - | -
| okTitle | -- The text displayed in the dialog button. The default value is "OK". - | -
- 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. -
-| message | -- The prompt message displayed in the dialog. - | -
|---|---|
| choices | -- A Python iterable containing one or more objects that are displayed as strings. The - recommended form is an array of strings. - | -
| - title - | -- The dialog's title. The default is "Input". - | -
- Displays the monkeyrunner API reference in a style similar to that of Python's
- pydoc tool, using the specified format.
-
| format | -- The markup format to use in the output. The possible values are "text" for plain text - or "html" for HTML. - | -
|---|
- Displays a dialog that accepts input and returns it to the program. The dialog is - modal, so the program pauses until the user clicks one of the dialog's buttons. -
-- The dialog contains two buttons, one of which displays the okTitle value - and the other the cancelTitle value. If the user clicks the okTitle button, - the current value of the input box is returned. If the user clicks the cancelTitle - button, an empty string is returned. -
-| message | -- The prompt message displayed in the dialog. - | -
|---|---|
| initialValue | -- The initial value to display in the dialog. The default is an empty string. - | -
| title | -- The dialog's title. The default is "Input". - | -
| okTitle | -- The text displayed in the okTitle button. The default is "OK". - | -
| cancelTitle | -- The text displayed in the cancelTitle button. The default is "Cancel". - | -
- Pauses the current program for the specified number of seconds. -
-| seconds | -- The number of seconds to pause. - | -
|---|
- MonkeyDevice
-
-
- waitForConnection
-
- (float timeout,
- string deviceId)
-
-
- Tries to make a connection between the monkeyrunner backend and the
- specified device or emulator.
-
| timeout | -- The number of seconds to wait for a connection. The default is to wait forever. - | -
|---|---|
| - deviceId - | -- A regular expression that specifies the serial number of the device or emulator. See - the topic - Android Debug Bridge - for a description of device and emulator serial numbers. - | -
MonkeyDevice
- instance for the device or emulator. Use this object to control and communicate with the
- device or emulator.
- You should be redirected. Please click here.
- - \ No newline at end of file diff --git a/docs/html/guide/developing/tools/adb.jd b/docs/html/guide/developing/tools/adb.jd deleted file mode 100644 index 50c72365d03d..000000000000 --- a/docs/html/guide/developing/tools/adb.jd +++ /dev/null @@ -1,669 +0,0 @@ -page.title=Android Debug Bridge -parent.title=Tools -parent.link=index.html -@jd:body - -Android Debug Bridge (adb) is a versatile command line tool that lets you communicate with an -emulator instance or connected Android-powered device. It is a client-server program that includes -three components:
- -You can find the {@code adb} tool in {@code <sdk>/platform-tools/}.
- -When you start an adb client, the client first checks whether there is an adb server process already running. If there isn't, it starts the server process. When the server starts, it binds to local TCP port 5037 and listens for commands sent from adb clients—all adb clients use port 5037 to communicate with the adb server.
- -The server then sets up connections to all running emulator/device instances. It locates emulator/device instances by scanning odd-numbered ports in the range 5555 to 5585, the range used by emulators/devices. Where the server finds an adb daemon, it sets up a connection to that port. Note that each emulator/device instance acquires a pair of sequential ports — an even-numbered port for console connections and an odd-numbered port for adb connections. For example:
- -
-Emulator 1, console: 5554
-Emulator 1, adb: 5555
-Emulator 2, console: 5556
-Emulator 2, adb: 5557 ...
-
As shown, the emulator instance connected to adb on port 5555 is the same as the instance whose console listens on port 5554.
- -Once the server has set up connections to all emulator instances, you can use adb commands to control and access those instances. Because the server manages connections to emulator/device instances and handles commands from multiple adb clients, you can control any emulator/device instance from any client (or from a script).
- -The sections below describe the commands that you can use to access adb capabilities and manage the state of an emulator/device. Note that if you are developing Android applications in Eclipse and have installed the ADT plugin, you do not need to access adb from the command line. The ADT plugin provides a transparent integration of adb into the Eclipse IDE. However, you can still use adb directly as necessary, such as for debugging.
- - - -You can issue adb commands from a command line on your development machine or from a script. The usage is:
- -adb [-d|-e|-s <serialNumber>] <command>- -
When you issue a command, the program invokes an adb client. The client is not specifically associated with any emulator instance, so if multiple emulators/devices are running, you need to use the -d option to specify the target instance to which the command should be directed. For more information about using this option, see Directing Commands to a Specific Emulator/Device Instance.
Before issuing adb commands, it is helpful to know what emulator/device instances are connected to the adb server. You can generate a list of attached emulators/devices using the devices command:
adb devices- -
In response, adb prints this status information for each instance:
- -<type>-<consolePort>.
- Here's an example serial number: emulator-5554offline — the instance is not connected to adb or is not responding.device — the instance is now connected to the adb server. Note that this state does not
- imply that the Android system is fully booted and operational, since the instance connects to adb
- while the system is still booting. However, after boot-up, this is the normal operational state of
- an emulator/device instance.The output for each instance is formatted like this:
- -[serialNumber] [state]- -
Here's an example showing the devices command and its output:
$ adb devices -List of devices attached -emulator-5554 device -emulator-5556 device -emulator-5558 device- -
If there is no emulator/device running, adb returns no device.
If multiple emulator/device instances are running, you need to specify a target instance when issuing adb commands. To so so, use the -s option in the commands. The usage for the -s option is:
adb -s <serialNumber> <command>- -
As shown, you specify the target instance for a command using its adb-assigned serial number. You can use the devices command to obtain the serial numbers of running emulator/device instances.
Here is an example:
- -adb -s emulator-5556 install helloWorld.apk- -
Note that, if you issue a command without specifying a target emulator/device instance using -s, adb generates an error.
-
-
-
-
You can use adb to copy an application from your development computer and install it on an emulator/device instance. To do so, use the install command. With the command, you must specify the path to the .apk file that you want to install:
adb install <path_to_apk>- -
For more information about how to create an .apk file that you can install on an emulator/device -instance, see Building and Running
- -Note that, if you are using the Eclipse IDE and have the ADT plugin installed, you do not need to use adb (or aapt) directly to install your application on the emulator/device. Instead, the ADT plugin handles the packaging and installation of the application for you.
- - - - -You can use the forward command to set up arbitrary port forwarding — forwarding of requests on a specific host port to a different port on an emulator/device instance. Here's how you would set up forwarding of host port 6100 to emulator/device port 7100:
adb forward tcp:6100 tcp:7100-
You can also use adb to set up forwarding to named abstract UNIX domain sockets, as illustrated here:
-adb forward tcp:6100 local:logd- - - -
You can use the adb commands pull and push to copy files to and from an emulator/device instance's data file. Unlike the install command, which only copies an .apk file to a specific location, the pull and push commands let you copy arbitrary directories and files to any location in an emulator/device instance.
To copy a file or directory (recursively) from the emulator or device, use
-adb pull <remote> <local>- -
To copy a file or directory (recursively) to the emulator or device, use
-adb push <local> <remote>- -
In the commands, <local> and <remote> refer to the paths to the target files/directory on your development machine (local) and on the emulator/device instance (remote).
Here's an example:
-adb push foo.txt /sdcard/foo.txt- - - -
The table below lists all of the supported adb commands and explains their meaning and usage.
- - -| Category | -Command | -Description | -Comments | -
|---|---|---|---|
| Options | --d |
-Direct an adb command to the only attached USB device. | -Returns an error if more than one USB device is attached. | -
-e |
-Direct an adb command to the only running emulator instance. | -Returns an error if more than one emulator instance is running. | -|
-s <serialNumber> |
-Direct an adb command a specific emulator/device instance, referred to by its adb-assigned serial number (such as "emulator-5556"). | -If not specified, adb generates an error. | -|
| General | -devices |
-Prints a list of all attached emulator/device instances. | -See Querying for Emulator/Device Instances for more information. | -
help |
-Prints a list of supported adb commands. | -- | |
version |
-Prints the adb version number. | -- | |
| Debug | -logcat [<option>] [<filter-specs>] |
-Prints log data to the screen. | -- |
bugreport |
-Prints dumpsys, dumpstate, and logcat data to the screen, for the purposes of bug reporting. |
-- | |
jdwp |
-Prints a list of available JDWP processes on a given device. | -You can use the forward jdwp:<pid> port-forwarding specification to connect to a specific JDWP process. For example: - adb forward tcp:8000 jdwp:472- jdb -attach localhost:8000
- |
-|
| Data | -install <path-to-apk> |
-Pushes an Android application (specified as a full path to an .apk file) to the data file of an emulator/device. | -- |
pull <remote> <local> |
-Copies a specified file from an emulator/device instance to your development computer. | -- | |
push <local> <remote> |
-Copies a specified file from your development computer to an emulator/device instance. | -- | |
| Ports and Networking | -forward <local> <remote> |
-Forwards socket connections from a specified local port to a specified remote port on the emulator/device instance. | -Port specifications can use these schemes:
-
|
-
ppp <tty> [parm]... |
-Run PPP over USB.
-
Note that you should not automatically start a PPP connection. |
-- | |
| Scripting | -get-serialno |
-Prints the adb instance serial number string. | -See Querying for Emulator/Device Instances for more information. | -
get-state |
-Prints the adb state of an emulator/device instance. | - -||
wait-for-device |
-Blocks execution until the device is online — that is, until the instance state is device. |
-You can prepend this command to other adb commands, in which case adb will wait until the emulator/device instance is connected before issuing the other commands. Here's an example:
-adb wait-for-device shell getprop- -Note that this command does not cause adb to wait until the entire system is fully booted. For that reason, you should not prepend it to other commands that require a fully booted system. As an example, the install requires the Android package manager, which is available only after the system is fully booted. A command such as
-
-adb wait-for-device install <app>.apk- -would issue the install command as soon as the emulator or device instance connected to the adb server, but before the Android system was fully booted, so it would result in an error. |
-|
| Server | -start-server |
-Checks whether the adb server process is running and starts it, if not. | -- |
kill-server |
-Terminates the adb server process. | -- | |
| Shell | -shell |
-Starts a remote shell in the target emulator/device instance. | -See Issuing Shell Commands for more information. | -
shell [<shellCommand>] |
-Issues a shell command in the target emulator/device instance and then exits the remote shell. | -
Adb provides an ash shell that you can use to run a variety of commands on an emulator -or device. The command binaries are stored in the file system of the emulator or device, -in this location:
- -/system/bin/...- -
You can use the shell command to issue commands, with or without entering the adb remote shell on the emulator/device.
To issue a single command without entering a remote shell, use the shell command like this:
adb [-d|-e|-s {<serialNumber>}] shell <shellCommand>
-
-To drop into a remote shell on a emulator/device instance, use the shell command like this:
adb [-d|-e|-s {<serialNumber>}] shell
-
-When you are ready to exit the remote shell, use CTRL+D or exit to end the shell session.
The sections below provide more information about shell commands that you can use.
- - - -From an adb remote shell, you can use the
-sqlite3 command-line program to
-manage SQLite databases created by Android applications. The
-sqlite3 tool includes many useful commands, such as
-.dump to print out the contents of a table and
-.schema to print the SQL CREATE statement for an existing table.
-The tool also gives you the ability to execute SQLite commands on the fly.
To use sqlite3, enter a remote shell on the emulator instance, as described above, then invoke the tool using the sqlite3 command. Optionally, when invoking sqlite3 you can specify the full path to the database you want to explore. Emulator/device instances store SQLite3 databases in the folder /data/data/<package_name>/databases/.
Here's an example:
- -$ adb -s emulator-5554 shell -# sqlite3 /data/data/com.example.google.rss.rssexample/databases/rssitems.db -SQLite version 3.3.12 -Enter ".help" for instructions -.... enter commands, then quit... -sqlite> .exit- -
Once you've invoked sqlite3, you can issue sqlite3 commands in the shell. To exit and return to the adb remote shell, use exit or CTRL+D.
-
-
-
-
-
The Monkey is a program that runs on your emulator or device and generates pseudo-random -streams of user events such as clicks, touches, or gestures, as well as a number of system-level -events. You can use the Monkey to stress-test applications that you are developing, -in a random yet repeatable manner.
- -The simplest way to use the monkey is with the following command, which will launch your -application and send 500 pseudo-random events to it.
- -$ adb shell monkey -v -p your.package.name 500- -
For more information about command options for Monkey, see the complete -UI/Application Exerciser Monkey documentation page.
- - - - -The table below lists several of the adb shell commands available. For a complete list of commands and programs, start an emulator instance and use the adb -help command.
adb shell ls /system/bin- -
Help is available for most of the commands.
- -| Shell Command | -Description | -Comments | -
|---|---|---|
dumpsys |
-Dumps system data to the screen. | -The Dalvik Debug Monitor Server -(DDMS) tool offers integrated debug environment that you may find easier to use. | -
dumpstate |
-Dumps state to a file. | -|
logcat [<option>]... [<filter-spec>]... |
-Enables radio logging and prints output to the screen. | -|
dmesg |
-Prints kernel debugging messages to the screen. | -|
start |
-Starts (restarts) an emulator/device instance. | -- |
stop |
-Stops execution of an emulator/device instance. | -- |
The Android logging system provides a mechanism for collecting and viewing system debug output. Logs from various applications and portions of the system are collected in a series of circular buffers, which then can be viewed and filtered by the logcat command.
You can use the logcat command to view and follow the contents of the system's log buffers. The general usage is:
[adb] logcat [<option>] ... [<filter-spec>] ...- -
The sections below explain filter specifications and the command options. See Listing of logcat Command Options for a summary of options.
- -You can use the logcat command from your development computer or from a remote adb shell in an emulator/device instance. To view log output in your development computer, you use
$ adb logcat- -
and from a remote adb shell you use
- -# logcat- - - -
Every Android log message has a tag and a priority associated with it.
- -V — Verbose (lowest priority)D — DebugI — Info (default priority)W — WarningE — ErrorF — FatalS — Silent (highest priority, on which nothing is ever printed)You can obtain a list of tags used in the system, together with priorities, by running logcat and observing the first two columns
-of each message, given as <priority>/<tag>.
Here's an example of logcat output that shows that the message relates to priority level "I" and tag "ActivityManager":
- -I/ActivityManager( 585): Starting activity: Intent { action=android.intent.action...}
-
-To reduce the log output to a manageable level, you can restrict log output using filter expressions. Filter expressions let you indicate to the system the tags-priority combinations that you are interested in — the system suppresses other messages for the specified tags.
- -A filter expression follows this format tag:priority ..., where tag indicates the tag of interest and priority indicates the minimum level of priority to report for that tag. Messages for that tag at or above the specified priority are written to the log. You can supply any number of tag:priority specifications in a single filter expression. The series of specifications is whitespace-delimited. The default output is to show all log messages with the Info priority (*:I).
Here's an example of a filter expression that suppresses all log messages except those with the tag "ActivityManager", at priority "Info" or above, and all log messages with tag "MyApp", with priority "Debug" or above:
- -adb logcat ActivityManager:I MyApp:D *:S- -
The final element in the above expression, *:S, sets the priority level for all tags to "silent", thus ensuring only log messages with "View" and "MyApp" are displayed. Using *:S is an excellent way to ensure that log output is restricted to the filters that you have explicitly specified — it lets your filters serve as a "whitelist" for log output.
The following filter expression displays all log messages with priority level "warning" and higher, on all tags:
- -adb logcat *:W- -
If you're running logcat from your development computer (versus running it on a remote adb shell), you can also set a default filter expression by exporting a value for the environment variable ANDROID_LOG_TAGS:
export ANDROID_LOG_TAGS="ActivityManager:I MyApp:D *:S"- -
Note that ANDROID_LOG_TAGS filter is not exported to the emulator/device instance, if you are running logcat from a remote shell or using adb shell logcat.
Log messages contain a number of metadata fields, in addition to the tag and priority. You can modify the output format for messages so that they display a specific metadata field. To do so, you use the -v option and specify one of the supported output formats listed below.
brief — Display priority/tag and the PID of process issuing the message (the default format).process — Display PID only.tag — Display the priority/tag only. raw — Display the raw log message, with no other metadata fields.time — Display the date, invocation time, priority/tag, and PID of the process issuing the message.threadtime — Display the date, invocation time, priority, tag, and the PID and TID of the thread issuing the message.long — Display all metadata fields and separate messages with a blank lines.When starting logcat, you can specify the output format you want by using the -v option:
[adb] logcat [-v <format>]- -
Here's an example that shows how to generate messages in thread output format:
adb logcat -v thread- -
Note that you can only specify one output format with the -v option.
The Android logging system keeps multiple circular buffers for log messages, and not all of the log messages are sent to the default circular buffer. To see additional log messages, you can start logcat with the -b option, to request viewing of an alternate circular buffer. You can view any of these alternate buffers:
radio — View the buffer that contains radio/telephony related messages.events — View the buffer containing events-related messages.main — View the main log buffer (default)The usage of the -b option is:
[adb] logcat [-b <buffer>]- -
Here's an example of how to view a log buffer containing radio and telephony messages:
- -adb logcat -b radio- - - -
By default, the Android system sends stdout and stderr (System.out and System.err) output to /dev/null. In
-processes that run the Dalvik VM, you can have the system write a copy of the output to the log file. In this case, the system writes the messages to the log using the log tags stdout and stderr, both with priority I.
To route the output in this way, you stop a running emulator/device instance and then use the shell command setprop to enable the redirection of output. Here's how you do it:
$ adb shell stop -$ adb shell setprop log.redirect-stdio true -$ adb shell start- -
The system retains this setting until you terminate the emulator/device instance. To use the setting as a default on the emulator/device instance, you can add an entry to /data/local.prop
-on the device.
| Option | -Description | -
|---|---|
-b <buffer> |
-Loads an alternate log buffer for viewing, such as event or radio. The main buffer is used by default. See Viewing Alternative Log Buffers. |
-
-c |
-Clears (flushes) the entire log and exits. | -
-d |
-Dumps the log to the screen and exits. | -
-f <filename> |
-Writes log message output to <filename>. The default is stdout. |
-
-g |
-Prints the size of the specified log buffer and exits. | -
-n <count> |
-Sets the maximum number of rotated logs to <count>. The default value is 4. Requires the -r option. |
-
-r <kbytes> |
-Rotates the log file every <kbytes> of output. The default value is 16. Requires the -f option. |
-
-s |
-Sets the default filter spec to silent. | -
-v <format> |
-Sets the output format for log messages. The default is brief format. For a list of supported formats, see Controlling Log Output Format. |
-
In some cases, you might need to terminate the adb server process and then restart it. For example, if adb does not respond to a command, you can terminate the server and restart it and that may resolve the problem.
- -To stop the adb server, use the kill-server. You can then restart the server by issuing any adb command.
ADT (Android Developer Tools) is a plugin for Eclipse that provides a suite of - tools that are integrated with the Eclipse IDE. It offers you access to many features that help - you develop Android applications quickly. ADT - provides GUI access to many of the command line SDK tools as well as a UI design tool for rapid - prototyping, designing, and building of your application's user interface.
- -Because ADT is a plugin for Eclipse, you get the functionality of a well-established IDE, - along with Android-specific features that are bundled with ADT. The following - describes important features of Eclipse and ADT:
- -You can find the most up-to-date and more detailed information about changes and new features -on the Recent Changes page at the Android Tools -Project site.
- -The Android - Asset Studio is a web-based tool that lets you generate icons from existing images, - clipart, or text. It also generates the icons with different DPIs for different screen sizes and - types.
- -Many of the tools that you can start or run from the command line are integrated into ADT. - They include:
- -android features such as creating or
- updating projects (application and library) are integrated throughout the Eclipse IDE. adb are integrated into ADT such as project installation (Eclipse run menu),
- file transfer, device enumeration, and logcat (DDMS). You must access the more advanced
- features of adb, such as shell commands, from the command line.In addition to Eclipse's standard editor features, ADT provides custom XML editors to help - you create and edit Android manifests, resources, menus, and layouts in a form-based or graphical - mode. Double-clicking on an XML file in Eclipse's package explorer opens the - appropriate XML editor. - -
View the segment on the XML editors for more - information.
-Note: You can edit Android-specific XML files (such as a layout -or manifest) in both a graphical mode and also an XML markup mode. You can switch between -these modes with the pair of tabs at the bottom of each custom XML editor.
- -In addition, some special file types that don't have custom editors, such as drawables, animations, - and color files offer editing enhancements such as XML tag completion.
- -ADT provides the following custom, form-based XML editors:
- -res/layout. For more information, see Graphical Layout
- Editor.AndroidManifest.xml file.<menu> declared (usually located in
- the res/menu folder).<resources> tag declared.In addition to the normal code editing features of Eclipse, ADT provides enhancements to the Android - development experience that allow you to quickly jump to declarations of various types of resources such - as strings or layout files. You can access these enhancements by holding down the control key and - clicking on the following items: - -
R.id.button1, jumps
- to the XML definition of the view.R.java file, such as public
- static final int Button01=0x7f050000", jumps to the corresponding XML definition.<activity android:name=".TestActivity">, jumps to the corresponding Java class. You can
- jump from an activity definition (or service definition) into the corresponding Java class.@string:foo), regardless of
-which XML file
- "foo" is defined in.@layout/bar, opens the file.@drawable/icon, launches
- Eclipse's default application for the given file type, which in this case is an
- image.@android namespace resources opens the resources found in
- the SDK install area.<foo.bar.MyView></foo.bar.MyView>,
- or <view class="foo.bar.MyView">) jump to the corresponding custom view classes.@android:string/ok or android.R.string.id in Java code
- opens the file that declares the strings. The XML tab opens when doing this, not
- the form-based editor.ADT provides many features to allow you to design and build your application's user interface. - Many of these features are in the graphical layout editor, which you can access by opening one of - your application's XML layout files in Eclipse. -
- -The graphical layout editor is the main screen that you use to visually design and build your - UI. It is split up into the following parts:
- -The canvas also provides - context-sensitive actions in the layout actions bar, such as adjusting layout margins and -orientation. - The layout actions bar displays available actions depending on the selected UI element in the - canvas.
-
-
- Figure 1. Graphical layout editor
- -View the segment on the canvas and outline view and the - layout actions bar - for more information. -
-The canvas is the area where you can drag and drop UI widgets from the palette to design your - layout. The canvas offers a rendered preview of your layout depending on factors such as the - selected platform version, screen orientation, and currently selected theme that you specify in - the configuration chooser. You can also drag and drop - items into the outline view, which displays your layout in a hierarchical list. The outline view - exposes much of the same functionality as the canvas but offers another method of organization - that is beneficial for ordering and quickly selecting items. When you right-click a specific item - in the canvas or outline view, you can access a context-sensitive menu that lets you modify the - following attributes of the layout or view:
- -View the segment on the animation features for more - information.
-The canvas has additional features not available in the outline view:
- -
-
- Figure 2. Canvas portion of the layout editor showing - a rendered preview of an application
- -Figure 3. Outline view showing current layout's structure
- -View the segment on the palette for more information.
-The palette contains the UI widgets that you can drag and drop onto the canvas and add to your - layout. The pallete categorizes the widgets and shows rendered previews - for easier lookup. The main features of the palette include:
- -
-
- Figure 4. Palette showing available UI widgets
- -View the segment on the configuration chooser for more - information.
-The configuration chooser allows you to create and configure different configurations of - a layout for different situations, such as one for landscape and one for portrait mode. You can - set the following options for each configuration of a layout: -
-
-
- Figure 5. Configuration chooser
- -View the segment on refactoring features for a rundown -of the more important refactoring features.
- -In both the graphical and XML layout editor, there are many features that help you quickly - refactor your layouts. The following list describes the major refactoring support:
- -<Button> widget named
- "button1"), then the ID is changed to match the new widget type and all
- references are updated.include tag that points to the newly created layout file is inserted
- into the existing layout file. Right-click the view or layout and select Extract as
- Include....styles.xml file. You can select multiple views and this refactoring extracts all
- of the same styles into one style and assigns that style to all the views that use it.layout_
- attribute references to the new root, For example, suppose you have a {@link android.widget.RelativeLayout}.
- If other widgets have layout constraints pointing to your widget, wrapping the widget causes
- these constraints to point to the parent instead.AIDL (Android Interface Definition Language) is similar to other IDLs you might have -worked with. It allows you to define the programming interface that both -the client and service agree upon in order to communicate with each other using -interprocess communication (IPC). On Android, one process cannot 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 objects across that boundary for you. The code to -do that marshalling is tedious to write, so Android handles it for you with AIDL.
- -Note: Using AIDL is necessary only if you allow clients from -different applications to access your service for IPC and want to handle multithreading in your -service. If you do not need to perform concurrent IPC across -different applications, you should create your interface by implementing a -Binder or, if you want to perform IPC, but do not need to handle multithreading, -implement your interface using a Messenger. -Regardless, be sure that you understand Bound Services before -implementing an AIDL.
- -Before you begin designing your AIDL interface, be aware that calls to an AIDL interface are -direct function calls. You should not make assumptions about the thread in which the call -occurs. What happens is different depending on whether the call is from a thread in the -local process or a remote process. Specifically:
- -You must define your AIDL interface in an {@code .aidl} file using the Java -programming language syntax, then save it in the source code (in the {@code src/} directory) of both -the application hosting the service and any other application that binds to the service.
- -When you build each application that contains the {@code .aidl} file, the Android SDK tools -generate an {@link android.os.IBinder} interface based on the {@code .aidl} file and save it in -the project's {@code gen/} directory. The service must implement the {@link android.os.IBinder} -interface as appropriate. The client applications can then bind to the service and call methods from -the {@link android.os.IBinder} to perform IPC.
- -To create a bounded service using AIDL, follow these steps:
-This file defines the programming interface with method signatures.
-The Android SDK tools generate an interface in the Java programming language, based on your -{@code .aidl} file. This interface has an inner abstract class named {@code Stub} that extends -{@link android.os.Binder} and implements methods from your AIDL interface. You must extend the -{@code Stub} class and implement the methods.
-Implement a {@link android.app.Service Service} and override {@link -android.app.Service#onBind onBind()} to return your implementation of the {@code Stub} -class.
-Caution: Any changes that you make to your AIDL interface after -your first release must remain backward compatible in order to avoid breaking other applications -that use your service. That is, because your {@code .aidl} file must be copied to other applications -in order for them to access your service's interface, you must maintain support for the original -interface.
- - -AIDL uses a simple syntax that lets you declare an interface with one or more methods that can -take parameters and return values. The parameters and return values can be of any type, even other -AIDL-generated interfaces.
- -You must construct the {@code .aidl} file using the Java programming language. Each {@code .aidl} -file must define a single interface and requires only the interface declaration and method -signatures.
- -By default, AIDL supports the following data types:
- -All elements in the {@link java.util.List} must be one of the supported data types in this
-list or one of the other AIDL-generated interfaces or parcelables you've declared. A {@link
-java.util.List} may optionally be used as a "generic" class (for example,
-List<String>).
-The actual concrete class that the other side receives is always an {@link
-java.util.ArrayList}, although the method is generated to use the {@link
-java.util.List} interface.
All elements in the {@link java.util.Map} must be one of the supported data types in this -list or one of the other AIDL-generated interfaces or parcelables you've declared. Generic maps, -(such as those of the form -{@code Map<String,Integer>} are not supported. The actual concrete class that the other side -receives is always a {@link java.util.HashMap}, although the method is generated to -use the {@link java.util.Map} interface.
-You must include an {@code import} statement for each additional type not listed above, even if -they are defined in the same package as your interface.
- -When defining your service interface, be aware that:
-in, out, or inout (see the example below).
- Primitives are in by default, and cannot be otherwise.
Caution: You should limit the direction to what is truly -needed, because marshalling parameters is expensive.
Here is an example {@code .aidl} file:
- -
-// IRemoteService.aidl
-package com.example.android;
-
-// Declare any non-default types here with import statements
-
-/** Example service interface */
-interface IRemoteService {
- /** Request the process ID of this service, to do evil things with it. */
- int getPid();
-
- /** Demonstrates some basic types that you can use as parameters
- * and return values in AIDL.
- */
- void basicTypes(int anInt, long aLong, boolean aBoolean, float aFloat,
- double aDouble, String aString);
-}
-
-
-Simply save your {@code .aidl} file in your project's {@code src/} directory and when you -build your application, the SDK tools generate the {@link android.os.IBinder} interface file in your -project's {@code gen/} directory. The generated file name matches the {@code .aidl} file name, but -with a {@code .java} extension (for example, {@code IRemoteService.aidl} results in {@code -IRemoteService.java}).
- -If you use Eclipse, the incremental build generates the binder class almost immediately. If you
-do not use Eclipse, then the Ant tool generates the binder class next time you build your
-application—you should build your project with ant debug (or ant
-release) as soon as you're finished writing the {@code .aidl} file, so that your code can
-link against the generated class.
When you build your application, the Android SDK tools generate a {@code .java} interface file -named after your {@code .aidl} file. The generated interface includes a subclass named {@code Stub} -that is an abstract implementation of its parent interface (for example, {@code -YourInterface.Stub}) and declares all the methods from the {@code .aidl} file.
- -Note: {@code Stub} also -defines a few helper methods, most notably {@code asInterface()}, which takes an {@link -android.os.IBinder} (usually the one passed to a client's {@link -android.content.ServiceConnection#onServiceConnected onServiceConnected()} callback method) and -returns an instance of the stub interface. See the section Calling an IPC -Method for more details on how to make this cast.
- -To implement the interface generated from the {@code .aidl}, extend the generated {@link -android.os.Binder} interface (for example, {@code YourInterface.Stub}) and implement the methods -inherited from the {@code .aidl} file.
- -Here is an example implementation of an interface called {@code IRemoteService} (defined by the -{@code IRemoteService.aidl} example, above) using an anonymous instance:
- -
-private final IRemoteService.Stub mBinder = new IRemoteService.Stub() {
- public int getPid(){
- return Process.myPid();
- }
- public void basicTypes(int anInt, long aLong, boolean aBoolean,
- float aFloat, double aDouble, String aString) {
- // Does nothing
- }
-};
-
-
-Now the {@code mBinder} is an instance of the {@code Stub} class (a {@link android.os.Binder}), -which defines the RPC interface for the service. In the next step, this instance is exposed to -clients so they can interact with the service.
- -There are a few rules you should be aware of when implementing your AIDL interface:
-Once you've implemented the interface for your service, you need to expose it to -clients so they can bind to it. To expose the interface -for your service, extend {@link android.app.Service Service} and implement {@link -android.app.Service#onBind onBind()} to return an instance of your class that implements -the generated {@code Stub} (as discussed in the previous section). Here's an example -service that exposes the {@code IRemoteService} example interface to clients.
- -
-public class RemoteService extends Service {
- @Override
- public void onCreate() {
- super.onCreate();
- }
-
- @Override
- public IBinder onBind(Intent intent) {
- // Return the interface
- return mBinder;
- }
-
- private final IRemoteService.Stub mBinder = new IRemoteService.Stub() {
- public int getPid(){
- return Process.myPid();
- }
- public void basicTypes(int anInt, long aLong, boolean aBoolean,
- float aFloat, double aDouble, String aString) {
- // Does nothing
- }
- };
-}
-
-
-Now, when a client (such as an activity) calls {@link android.content.Context#bindService -bindService()} to connect to this service, the client's {@link -android.content.ServiceConnection#onServiceConnected onServiceConnected()} callback receives the -{@code mBinder} instance returned by the service's {@link android.app.Service#onBind onBind()} -method.
- -The client must also have access to the interface class, so if the client and service are in -separate applications, then the client's application must have a copy of the {@code .aidl} file -in its {@code src/} directory (which generates the {@code android.os.Binder} -interface—providing the client access to the AIDL methods).
- -When the client receives the {@link android.os.IBinder} in the {@link
-android.content.ServiceConnection#onServiceConnected onServiceConnected()} callback, it must call
-YourServiceInterface.Stub.asInterface(service) to cast the returned
-parameter to YourServiceInterface type. For example:
-IRemoteService mIRemoteService;
-private ServiceConnection mConnection = new ServiceConnection() {
- // Called when the connection with the service is established
- public void onServiceConnected(ComponentName className, IBinder service) {
- // Following the example above for an AIDL interface,
- // this gets an instance of the IRemoteInterface, which we can use to call on the service
- mIRemoteService = IRemoteService.Stub.asInterface(service);
- }
-
- // Called when the connection with the service disconnects unexpectedly
- public void onServiceDisconnected(ComponentName className) {
- Log.e(TAG, "Service has unexpectedly disconnected");
- mIRemoteService = null;
- }
-};
-
-
-For more sample code, see the {@code -RemoteService.java} class in ApiDemos.
- - - - - - - - -If you have a class that you would like to send from one process to another through -an IPC interface, you can do that. However, you must ensure that the code for your class is -available to the other side of the IPC channel and your class must support the {@link -android.os.Parcelable} interface. Supporting the {@link android.os.Parcelable} interface is -important because it allows the Android system to decompose objects into primitives that can be -marshalled across processes.
- -To create a class that supports the {@link android.os.Parcelable} protocol, you must do the -following: -
CREATOR to your class which is an object implementing
-the {@link android.os.Parcelable.Creator Parcelable.Creator} interface.If you are using a custom build process, do not add the {@code .aidl} file to your -build. Similar to a header file in the C language, this {@code .aidl} file isn't compiled.
AIDL uses these methods and fields in the code it generates to marshall and unmarshall -your objects.
- -For example, here is a {@code Rect.aidl} file to create a {@code Rect} class that's -parcelable:
- --package android.graphics; - -// Declare Rect so AIDL can find it and knows that it implements -// the parcelable protocol. -parcelable Rect; -- -
And here is an example of how the {@link android.graphics.Rect} class implements the -{@link android.os.Parcelable} protocol.
- -
-import android.os.Parcel;
-import android.os.Parcelable;
-
-public final class Rect implements Parcelable {
- public int left;
- public int top;
- public int right;
- public int bottom;
-
- public static final Parcelable.Creator<Rect> CREATOR = new
-Parcelable.Creator<Rect>() {
- public Rect createFromParcel(Parcel in) {
- return new Rect(in);
- }
-
- public Rect[] newArray(int size) {
- return new Rect[size];
- }
- };
-
- 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();
- }
-}
-
-
-The marshalling in the {@code Rect} class is pretty simple. Take a look at the other -methods on {@link android.os.Parcel} to see the other kinds of values you can write -to a Parcel.
- -Warning: Don't forget the security implications of receiving -data from other processes. In this case, the {@code Rect} reads four numbers from the {@link -android.os.Parcel}, but it is up to you to ensure that these are within the acceptable range of -values for whatever the caller is trying to do. See Security and Permissions for more -information about how to keep your application secure from malware.
- - - -Here are the steps a calling class must take to call a remote interface defined with AIDL:
-service). Call
-YourInterfaceName.Stub.asInterface((IBinder)service) to
- cast the returned parameter to YourInterface type.A few comments on calling an IPC service:
-For more information about binding to a service, read the Bound Services -document.
- -Here is some sample code demonstrating calling an AIDL-created service, taken - from the Remote Service sample in the ApiDemos project.
-{@sample development/samples/ApiDemos/src/com/example/android/apis/app/RemoteService.java - calling_a_service}
diff --git a/docs/html/guide/developing/tools/android.jd b/docs/html/guide/developing/tools/android.jd deleted file mode 100644 index 295a720b36f3..000000000000 --- a/docs/html/guide/developing/tools/android.jd +++ /dev/null @@ -1,393 +0,0 @@ -page.title=android -parent.title=Tools -parent.link=index.html -@jd:body - -{@code android} is an important development tool that lets you:
- -android tool's features are integrated
- into ADT, so you should not need to use this tool directly.
-
- Note: The documentation of options below is not exhaustive
-and may be out of date. For the most current list of options, execute android
---help.
android [global options] action [action options]- -
-s-h-v| Action | - -Option | - -Description | - -Comments | -
|---|---|---|---|
avd |
-
- None | - -Launch the AVD Manager | - -- |
sdk |
-
- None | - -Launch the Android SDK Manager | - -- |
create avd |
-
- -n <name> |
-
- The name for the AVD. | - -Required | -
-t <targetID> |
-
- Target ID of the system image to use with the new AVD. To obtain a list of available
- targets, use android list targets |
-
- Required | -|
-c <path>|<size>[K|M] |
-
- The path to the SD card image to use with this AVD or the size of a new SD card image to
- create for this AVD. For example, -c path/to/sdcard or -c
- 1000M. |
-
- - | |
-f |
-
- Force creation of the AVD | - -- | |
-p <path> |
-
- Path to the location at which to create the directory for this AVD's files. | - -- | |
-s <name>|<width>-<height> |
-
- The skin to use for this AVD, identified by name or dimensions. The android
- tool scans for a matching skin by name or dimension in the skins/ directory of
- the target referenced in the -t <targetID> argument. For example, -s
- HVGA-L |
-
- - | |
delete avd |
-
- -n <name> |
-
- The name of the AVD to delete | - -Required | -
move avd |
-
- -n <name> |
-
- The name of the AVD to move | - -Required | -
-p <path> |
-
- Path to the location at which to create the directory for this AVD's files. | - -- | |
-r <new-name> |
-
- New name of the AVD if you want to rename it | - -- | |
update avd |
-
- -n <name> |
-
- The name of the AVD to move | - -Required | -
| Action | - -Option | - -Description | - -Comments | -
|---|---|---|---|
create project |
-
- -n <name> |
-
- The name for the project | - -Required | -
-t <targetID> |
-
- Target ID of the system image to use with the new AVD. To obtain a list of available
- targets, use android list targets |
-
- Required | -|
-k <path>|<size>[K|M] |
-
- Package namespace | - -Required | -|
-a |
-
- Name for the default Activity class | - -Required | -|
-p <path> |
-
- Location of your project directory | - -Required | -|
update project |
-
- -n <name> |
-
- The name of the project to update | - -- |
-p <path> |
-
- Location path of the project | - -Required | -|
-l <library path> |
-
- Location path of an Android Library to add, relative to the main project | - -- | |
-s <subprojects> |
-
- Update any projects in subfolders such as test projects | - -- | |
-t <targetID> |
-
- Target id to set for the project | - -- | |
create-test-project |
-
- -n <name> |
-
- The name of the project | - -- |
-p <path> |
-
- Location path of the project | - -Required | -|
-m <main> |
-
- The name of the project | - -Required | -|
update-test-project |
-
- -p <path> |
-
- Location path of the project to test, relative to the new project | - -Required | -
-m <main> |
-
- The main class of the project to test | - -Required | -|
create-lib-project |
-
- -k <packageName> |
-
- (Required) Package name of the library project | - -Required | -
-p <path> |
-
- Location path of the project | - -Required | -|
-t <targetID> |
-
- Target ID of the library project | - -Required | -|
-n <name> |
-
- The name of the project | - -Required | -|
update-lib-project |
-
- -p <path> |
-
- Location path of the project | - -Required | -
-l <libraryPath> |
-
- Location path of an Android Library to add, relative to the main project | - -- | |
-t <name> |
-
- Target ID of the library project | - -- |
update adbupdate sdkYou should be redirected. Please click here.
- - \ No newline at end of file diff --git a/docs/html/guide/developing/tools/bmgr.jd b/docs/html/guide/developing/tools/bmgr.jd deleted file mode 100644 index d63dcf291b4f..000000000000 --- a/docs/html/guide/developing/tools/bmgr.jd +++ /dev/null @@ -1,193 +0,0 @@ -page.title=bmgr -parent.title=Tools -parent.link=index.html -@jd:body - - - -bmgr lets you control the backup/restore system on an Android device.
-
-
bmgr is a shell tool you can use to interact with the Backup Manager
-on Android devices supporting API Level 8 or greater. It provides commands to induce backup
-and restore operations so that you don't need to repeatedly wipe data or take similar
-intrusive steps in order to test your application's backup agent. These commands are
-accessed via the adb shell.
-
-
For information about adding support for backup in your application, read Data Backup, which includes a guide to testing -your application using {@code bmgr}.
- - -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 bmgr backup command:
-
-
adb shell bmgr backup <package>- -
<package> is the formal package name of the application you wish to
-schedule for
-backup. When you execute this backup command, your application's backup agent will be invoked to
-perform a backup operation at some time in the future (via your {@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 bmgr run command:
-
-
adb shell bmgr run- -
This causes a backup pass to execute immediately, invoking the backup agents of all applications
-that had previously called {@link android.app.backup.BackupManager#dataChanged()} since the
-last backup operation, plus any applications which had been manually scheduled for
-backup via bmgr backup.
-
-
-
-
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. - -
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 bmgr restore command:
-
-
adb shell bmgr restore <package>- -
<package> is the formal Java-style package name of the application
-participating in the backup/restore mechanism, which you would like to restore. The Backup
-Manager will immediately instantiate the application's backup agent and invoke it for restore. This
-will happen even if your application is not currently running.
-
-
-
-
-
-
The data for a single application can be erased from the active data set on demand. This is
-very useful while you're developing a backup agent, in case bugs lead you to write corrupt data
-or saved state information. You can wipe an application's data with the bmgr wipe
-command:
-
-
adb shell bmgr wipe <package>- -
<package> is the formal package name of the application whose data
-you wish to
-erase. The next backup operation that the application's agent processes will look as
-though the application had never backed anything up before.
-
-
-
You can see whether the Backup Manager is operational at all with the bmgr
-enabled command:
-
-
adb shell bmgr enabled- -
This might be useful if your application's backup agent is never being invoked for backup, to -verify whether the operating system thinks it should be performing such operations at all.
- -You can also directly disable or enable the Backup Manager with this command: - -
adb shell bmgr enable <boolean>- -
<boolean> is either true or false.
-This is equivalent to disabling or enabling backup in the device's main Settings UI.
Warning! When backup is disabled, the current backup transport
-will explicitly wipe
-the entire active data set from its backend storage. This is so that when a user says
-they do not want their data backed up, the Backup Manager respects that wish. No further
-data will be saved from the device, and no restore operations will be possible, unless the Backup
-Manager is re-enabled (either through Settings or through the above bmgr command).
-
-
-
-
-
diff --git a/docs/html/guide/developing/tools/ddms.html b/docs/html/guide/developing/tools/ddms.html
deleted file mode 100644
index 052ccc958593..000000000000
--- a/docs/html/guide/developing/tools/ddms.html
+++ /dev/null
@@ -1,10 +0,0 @@
-
-
You should be redirected. Please click here.
- - \ No newline at end of file diff --git a/docs/html/guide/developing/tools/dmtracedump.jd b/docs/html/guide/developing/tools/dmtracedump.jd deleted file mode 100644 index cb9ad262a671..000000000000 --- a/docs/html/guide/developing/tools/dmtracedump.jd +++ /dev/null @@ -1,66 +0,0 @@ -page.title=dmtracedump -parent.title=Tools -parent.link=index.html -@jd:body - - -dmtracedump is a tool that gives you an alternate way of generating
- graphical call-stack diagrams from trace log files (instead of using Traceview).
This document is a reference to the available command line options. For more information on generating trace - logs, see Profiling with - Traceview and dmtracedump.
- -The usage for dmtracedump is:
-dmtracedump [-ho] [-s sortable] [-d trace-base-name] [-g outfile] <trace-base-name> -- -
The tool then loads trace log data from <trace-base-name>.data and
- <trace-base-name>.key. The table below lists the options for dmtracedump.
| Option | - -Description | -
|---|---|
-d <trace-base-name> |
-
- Diff with this trace name | -
-g <outfile> |
-
- Generate output to <outfile> | -
-h |
-
- Turn on HTML output | -
-o |
-
- Dump the trace file instead of profiling | -
-d <trace-base-name> |
-
- URL base to the location of the sortable javascript file | -
-t <percent> |
-
- Minimum threshold for including child nodes in the graph (child's inclusive time as a - percentage of parent inclusive time). If this option is not used, the default threshold is - 20%. | -
The Draw 9-patch tool allows you to easily create a - {@link android.graphics.NinePatch} graphic using a WYSIWYG editor.
-For an introduction to Nine-patch graphics and how they work, please read -the section about Nine-patch in the -2D Graphics -document.
- -
-
-Here's a quick guide to create a Nine-patch graphic using the Draw 9-patch tool. -You'll need the PNG image with which you'd like to create a NinePatch.
- -draw9patch application from your SDK
- /tools directory.
- 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.
-Your image will be saved with the .9.png file name.
Note: A normal PNG file (*.png) will be
- loaded with an empty one-pixel border added around the image, in which you can draw
- the stretchable patches and content area.
- A previously saved 9-patch file (*.9.png) will be loaded as-is,
- with no drawing area added, because it already exists.
-
-Optional controls include:
-The Android SDK includes a mobile device emulator — a virtual mobile device -that runs on your computer. The emulator lets you develop and test -Android applications without using a physical device.
- -This document is a reference to the available command line options and the keyboard mapping to -device keys. -For a complete guide to using the Android Emulator, see -Using the Android Emulator. - - -
Table 1 summarizes the mappings between the emulator keys and the keys of your keyboard.
- -Table 1. Emulator keyboard mapping
-| Emulated Device Key | -Keyboard Key | -
|---|---|
| Home | -HOME | -
| Menu (left softkey) | -F2 or Page-up button | -
| Star (right softkey) | -Shift-F2 or Page Down | -
| Back | -ESC | -
| Call/dial button | -F3 | -
| Hangup/end call button | -F4 | -
| Search | -F5 | -
| Power button | -F7 | -
| Audio volume up button | -KEYPAD_PLUS, Ctrl-F5 | -
| Audio volume down button | -KEYPAD_MINUS, Ctrl-F6 | -
| Camera button | -Ctrl-KEYPAD_5, Ctrl-F3 | -
| Switch to previous layout orientation (for example, portrait, landscape) | -KEYPAD_7, Ctrl-F11 | -
| Switch to next layout orientation (for example, portrait, landscape) | -KEYPAD_9, Ctrl-F12 | -
| Toggle cell networking on/off | -F8 | -
| Toggle code profiling | -F9 (only with -trace startup option) |
-
| Toggle fullscreen mode | -Alt-Enter | -
| Toggle trackball mode | -F6 | -
| Enter trackball mode temporarily (while key is pressed) | -Delete | -
| DPad left/up/right/down | -KEYPAD_4/8/6/2 | -
| DPad center click | -KEYPAD_5 | -
| Onion alpha increase/decrease | -KEYPAD_MULTIPLY(*) / KEYPAD_DIVIDE(/) | -
The emulator supports a variety of options that you can specify -when launching the emulator, to control its appearance or behavior. -Here's the command-line syntax of the options available to the {@code emulator} program:
- -emulator -avd <avd_name> [-<option> [<value>]] ... [-<qemu args>]- -
Table 2. Emulator command line parameters
-| Category | -Option | -Description | -Comments | -
|---|---|---|---|
| AVD | --avd <avd_name> or - @<avd_name> |
- Required. Specifies the AVD to load for this emulator - instance. | -You must create an AVD configuration before launching the emulator. For - information, see Managing - AVDs with AVD Manager. | -
| Disk Images | --cache <filepath> |
- Use <filepath> as the working cache partition image. | -An absolute or relative path to the current working directory.
- If no cache file is specified, the emulator's default behavior is to use a temporary file instead.
- For more information on disk images, use |
-data <filepath> |
- Use {@code <filepath>} as the working user-data disk image. | -Optionally, you can specify a path relative to the current working directory.
- If -data is not used, the emulator looks for a file named {@code userdata-qemu.img}
- in the storage area of the AVD being used (see -avd).
- | |
-initdata <filepath> |
- When resetting the user-data image (through -wipe-data), copy the contents
- of this file to the new user-data disk image. By default, the emulator copies the <system>/userdata.img. |
- Optionally, you can specify a path relative to the current working directory. See also -wipe-data.
- For more information on disk images, use |
-|
-nocache |
- Start the emulator without a cache partition. | -See also -cache <file>. |
-|
-ramdisk <filepath> |
- Use <filepath> as the ramdisk image. | -Default value is <system>/ramdisk.img.
- Optionally, you can specify a path relative to the current working directory.
- For more information on disk images, use |
-|
-sdcard <filepath> |
- Use <file> as the SD card image. | -Default value is <system>/sdcard.img.
- Optionally, you can specify a path relative to the current working directory. For more information on disk images, use |
-|
-wipe-data |
- Reset the current user-data disk image (that is, the file specified by -datadir and
- -data, or the default file). The emulator deletes all data from the user data image file,
- then copies the contents of the file at -inidata data to the image file before starting.
- |
- See also -initdata.
- For more information on disk images, use |
-|
| Debug | --debug <tags> |
- Enable/disable debug messages for the specified debug tags. | -<tags> is a space/comma/column-separated list of debug component names.
- Use -help-debug-tags to print a list of debug component names that you can use. |
-
-debug-<tag> |
- Enable/disable debug messages for the specified debug tag. | -Use -help-debug-tags to print a list of debug component names that you can use in <tag>. |
-|
-debug-no-<tag> |
- Disable debug messages for the specified debug tag. | -||
-logcat <logtags> |
- Enable logcat output with given tags. | -If the environment variable ANDROID_LOG_TAGS is defined and not - empty, its value will be used to enable logcat output by default. | -|
-shell |
- Create a root shell console on the current terminal. | -You can use this command even if the adb daemon in the emulated system is broken. - Pressing Ctrl-c from the shell stops the emulator instead of the shell. | -|
-shell-serial <device> |
- Enable the root shell (as in -shell and specify the QEMU character
- device to use for communication with the shell. |
- <device> must be a QEMU device type. See the documentation for '-serial dev' at
- http://wiki.qemu.org/download/qemu-doc.html
- for a list of device types.
-
- Here are some examples: -
|
-|
-show-kernel <name> |
- Display kernel messages. | -- | |
-trace <name> |
- Enable code profiling (press F9 to start), written to a specified file. | -- | |
-verbose |
- Enable verbose output. | -Equivalent to -debug-init.
-You can define the default verbose output options used by emulator instances in the Android environment variable
-ANDROID_VERBOSE. Define the options you want to use in a comma-delimited list, specifying only the stem of each option:
- Here's an example showing ANDROID_VERBOSE defined with the
For more information about debug tags, use |
-|
| Media | --audio <backend> |
- Use the specified audio backend. | -- |
-audio-in <backend> |
- Use the specified audio-input backend. | -- | |
-audio-out <backend> |
- Use the specified audio-output backend. | -- | |
-noaudio |
- Disable audio support in the current emulator instance. | -- | |
-radio <device> |
- Redirect radio modem interface to a host character device. | -||
-useaudio |
- Enable audio support in the current emulator instance. | -Enabled by default. | -|
| Network | --dns-server <servers> |
- Use the specified DNS server(s). | -The value of <servers> must be a comma-separated list of up to 4 DNS server names or
- IP addresses. |
-
-http-proxy <proxy> |
- Make all TCP connections through a specified HTTP/HTTPS proxy | -The value of <proxy> can be one of the following:- http://<server>:<port>- http://<username>:<password>@<server>:<port>
- The |
-|
-netdelay <delay> |
- Set network latency emulation to <delay>. | -Default value is none. See the table in
- Network Delay Emulation
- for supported <delay> values. |
-|
-netfast |
- Shortcut for -netspeed full -netdelay none |
- ||
-netspeed <speed> |
- Set network speed emulation to <speed>. | -Default value is full. See the table in
- Network Speed Emulation for
- supported <speed> values. |
-|
-port <port> |
- Set the console port number for this emulator instance to <port>. |
- The console port number must be an even integer between 5554 and 5584, inclusive. <port>+1
- must also be free and will be reserved for ADB. |
-|
-report-console <socket> |
- Report the assigned console port for this emulator instance to a remote third party - before starting the emulation. | -<socket> must use one of these formats:
-
-
Use |
-|
| System | --cpu-delay <delay> |
- Slow down emulated CPU speed by <delay> | -Supported values for <delay> are integers between 0 and 1000.
-
- Note that the <delay> does not correlate to clock speed or other absolute metrics -— it simply represents an abstract, relative delay factor applied non-deterministically -in the emulator. Effective performance does not always -scale in direct relationship with <delay> values. - |
-
-gps <device> |
- Redirect NMEA GPS to character device. | -Use this command to emulate an NMEA-compatible GPS unit connected to
- an external character device or socket. The format of <device> must be QEMU-specific
- serial device specification. See the documentation for 'serial -dev' at
- http://wiki.qemu.org/download/qemu-doc.html.
- |
-|
-nojni |
- Disable JNI checks in the Dalvik runtime. | ||
-qemu |
- Pass arguments to the qemu emulator software. | -Important: When using this option, make sure it is the - last option specified, since all options after it are interpretted as qemu-specific - options. | |
-qemu -enable-kvm |
- Enable KVM acceleration of the emulator virtual machine. | -This option is only effective when your system is set up to use
- KVM-based VM acceleration.
- You can optionally specify a memory size ({@code -m <size>}) for the VM, which should match
- your emulator's memory size:
- {@code -qemu -m 512 -enable-kvm} - {@code -qemu -m 1024 -enable-kvm} - | |
-qemu -h |
- Display qemu help. | -||
-gpu on |
- Turn on graphics acceleration for the emulator. | -This option is only available for emulators using a system image with API Level 15, revision 3 - and higher. For more information, see - Using the Android - Emulator. | |
-radio <device> |
- Redirect radio mode to the specified character device. | -The format of <device> must be QEMU-specific
- serial device specification. See the documentation for 'serial -dev' at
-http://wiki.qemu.org/download/qemu-doc.html.
- |
-|
-timezone <timezone> |
- Set the timezone for the emulated device to <timezone>, instead of the host's timezone. | -<timezone> must be specified in zoneinfo format. For example:
-"America/Los_Angeles" |
-|
-version |
- Display the emulator's version number. | -- | |
| UI | --dpi-device <dpi> |
- Scale the resolution of the emulator to match the screen size - of a physical device. | -The default value is 165. See also -scale. |
-
-no-boot-anim |
- Disable the boot animation during emulator startup. | -Disabling the boot animation can speed the startup time for the emulator. | -|
-no-window |
- Disable the emulator's graphical window display. | -- | |
-scale <scale> |
- Scale the emulator window. | -<scale> is a number between 0.1 and 3 that represents the desired scaling factor. You can
- also specify scale as a DPI value if you add the suffix "dpi" to the scale value. A value of "auto"
- tells the emulator to select the best window size. |
-|
-raw-keys |
- Disable Unicode keyboard reverse-mapping. | -||
-noskin |
- Don't use any emulator skin. | -||
-keyset <file> |
- Use the specified keyset file instead of the default. | -The keyset file defines the list of key bindings between the emulator and the host keyboard.
- For more information, use -help-keyset to print information about this topic.
- |
-|
-onion <image> |
- Use overlay image over screen. | -No support for JPEG. Only PNG is supported. | |
-onion-alpha <percent> |
- Specify onion skin translucency value (as percent). - | Default is 50. | -|
-onion-rotation <position> |
- Specify onion skin rotation. - | <position> must be one of the values 0, 1, 2, 3. |
-|
-skin <skinID> |
- This emulator option is deprecated. | -Please set skin options using AVDs, rather than by using this emulator -option. Using this option may yield unexpected and in some cases misleading -results, since the density with which to render the skin may not be defined. -AVDs let you associate each skin with a default density and override the default -as needed. For more information, see Managing Virtual Devices -with AVD Manager. - | -|
-skindir <dir> |
- This emulator option is deprecated. | -See comments for -skin, above. |
-|
| Help | --help |
- Print a list of all emulator options. | -- |
-help-all |
- Print help for all startup options. | -- | |
-help-<option> |
- Print help for a specific startup option. | -- | |
-help-debug-tags |
- Print a list of all tags for -debug <tags>. |
- - | |
-help-disk-images |
- Print help for using emulator disk images. | -- | |
-help-environment |
- Print help for emulator environment variables. | -s - | |
-help-keys |
- Print the current mapping of keys. | -- | |
-help-keyset-file |
- Print help for defining a custom key mappings file. | -- | |
-help-virtual-device |
- Print help for Android Virtual Device usage. | -- |
etc1tool is a command line utility that lets you encode PNG
- images to the ETC1 compression standard and decode ETC1 compressed images back to PNG.
The usage for etc1tool is:
etc1tool infile [--help | --encode | --encodeNoHeader | --decode] [--showDifference -diff-file] [-o outfile]- -
| Option | - -Description | -
|---|---|
infile |
-
- The input file to compress | -
--help |
-
- Print usage information | -
--encode |
-
- Create an ETC1 file from a PNG file. - This is the default mode for the tool if nothing is specified. | -
--encodeNoHeader |
-
- Create a raw ETC1 data file (without a header) from a PNG file. | -
--decode |
-
- Create a PNG file from an ETC1 file | -
--showDifference diff-file |
-
- Write the difference between the original and encoded image to
- diff-file (only valid when encoding). |
-
-o outfile |
-
- Specify the name of the output file.
- If outfile is not specified, the output file is constructed
- from the input filename with the appropriate suffix (.pkm or .png).
- |
-
Hierarchy Viewer allows you to debug and optimize your user -interface. It provides a visual representation of the layout's View hierarchy -(the Layout View) and a magnified inspector of the display (the Pixel Perfect View). -
- -To start Hierarchy Viewer, enter the following command from the SDK tools/ directory:
hierarchyviewer- - -
For more information on how to use Hierarchy Viewer, see -Debugging and Profiling UIs -
- diff --git a/docs/html/guide/developing/tools/hprof-conv.jd b/docs/html/guide/developing/tools/hprof-conv.jd deleted file mode 100644 index f96def205fb1..000000000000 --- a/docs/html/guide/developing/tools/hprof-conv.jd +++ /dev/null @@ -1,16 +0,0 @@ -page.title=HPROF Converter -parent.title=Tools -parent.link=index.html -@jd:body - -
-The hprof-conv tool converts the HPROF file that is
-generated by the Android SDK tools to a standard format so you
-can view the file in a profiling tool of your choice.
hprof-conv <infile> <outfile>- -
-You can use "-" for <infile> or <outfile>
-to specify stdin or stdout.
-
-
-The Android SDK includes a variety of tools that help you develop mobile -applications for the Android platform. The tools are classified into two groups: SDK tools -and platform tools. SDK tools are platform independent and are required no matter which -Android platform you are developing on. Platform tools are customized to support the features of the -latest Android platform.
- -The SDK tools are installed with the SDK starter package and are periodically updated.
-The SDK tools are required if you are developing Android applications. The most important SDK tools
-include the Android SDK Manager (android sdk), the AVD Manager (android
-avd) the emulator (emulator), and the Dalvik Debug Monitor Server
-(ddms). A short summary of some frequently-used SDK tools is provided below.
dmtracedump. For more information on using dmtracedump, see Profiling
-with Traceview and dmtracedump.apk files by ensuring that all uncompressed data starts with a
-particular alignment relative to the start of the file. This should always be used to align .apk
-files after they have been signed.The platform tools are typically updated every time you install a new SDK platform. Each update
-of the platform tools is backward compatible with older platforms. Usually, you directly use only
-one of the platform tools—the Android Debug Bridge (adb).
-Android Debug Bridge is a versatile tool that lets you manage the state of an emulator instance or
-Android-powered device. You can also use it to install an Android application (.apk) file on a
-device.
The other platform tools, such as aidl,
-aapt, dexdump, and dx, are typically called by the Android
-build tools or Android Development Tools (ADT), so you rarely need to invoke these tools directly.
-As a general rule, you should rely on the build tools or the ADT plugin to call them as needed.
Note: The Android SDK provides additional shell tools that can
-be accessed through adb, such as bmgr and
-logcat.
layoutopt is a command-line tool that helps you optimize the
-layouts and layout hierarchies of your applications.
- -
This document is a reference to the available command line options. For more information and sample -output of the tool, see Optimizing layouts with -layoutopt.
- -To run layoutopt against a given list of layout resources:
layoutopt <file_or_directory> ...- -
For example:
- -$ layoutopt res/layout-land-
$ layoutopt res/layout/main.xml res/layout-land/main.xml- diff --git a/docs/html/guide/developing/tools/logcat.jd b/docs/html/guide/developing/tools/logcat.jd deleted file mode 100644 index 546e3eacd2ae..000000000000 --- a/docs/html/guide/developing/tools/logcat.jd +++ /dev/null @@ -1,106 +0,0 @@ -page.title=logcat -parent.title=Tools -parent.link=index.html -@jd:body - -
The Android logging system provides a mechanism for collecting and viewing system debug
- output. Logs from various applications and portions of the system are collected in a series of
- circular buffers, which then can be viewed and filtered by the logcat command. You can use
- logcat from an ADB shell to view the log messages.
This document is a reference to the available command line options. For more information on logcat, see
- Reading and Writing Logs.
-For more
- information on accessing logcat from DDMS, instead of the command line, see the documentation for the
- Dalvik Debug Monitor Server.
-
-[adb] logcat [<option>] ... [<filter-spec>] ... -- -
You can run logcat as an adb command or directly in a shell prompt
- of your emulator or connected device. To view log output using adb, navigate to your SDK
- platform-tools/ directory and execute:
-$ adb logcat -- -
You can create a shell connection to a device and execute:
--$ adb shell -# logcat -- -
The following table describes the command line options of logcat.
| Option | - -Description | -
|---|---|
-b <buffer> |
-
- Loads an alternate log buffer for viewing, such as event or
- radio. The main buffer is used by default. See Viewing Alternative Log Buffers. |
-
-c |
-
- Clears (flushes) the entire log and exits. | -
-d |
-
- Dumps the log to the screen and exits. | -
-f <filename> |
-
- Writes log message output to <filename>. The default is
- stdout. |
-
-g |
-
- Prints the size of the specified log buffer and exits. | -
-n <count> |
-
- Sets the maximum number of rotated logs to <count>. The default value
- is 4. Requires the -r option. |
-
-r <kbytes> |
-
- Rotates the log file every <kbytes> of output. The default value is
- 16. Requires the -f option. |
-
-s |
-
- Sets the default filter spec to silent. | -
-v <format> |
-
- Sets the output format for log messages. The default is brief format. For a
- list of supported formats, see Controlling Log Output
- Format. |
-
The mksdcard tool lets you quickly create a FAT32 disk image that you can load in the
- emulator, to simulate the presence of an SD card in the device. Because you can specify an SD
- card while creating an AVD in the AVD Manager, you usually use that feature to create an SD card.
- This tool creates an SD card that is not bundled with an AVD, so it is useful for situations
- where you need to share a virtual SD card between multiple emulators.
-mksdcard -l <label> <size> <file> -- -
The following table describes the command-line options of mksdcard
| Option | - -Description | -
|---|---|
-l |
-
- A volume label for the disk image to create. | -
size |
-
- An integer that specifies the size (in bytes) of disk image to create. You can also
- specify size in kilobytes or megabytes, by appending a "K" or "M" to <size>. For
- example, 1048576K, 1024M. |
-
file |
-
- The path/filename of the disk image to create. | -
Once you have created the disk image file, you can load it in the emulator at startup using
- the emulator's -sdcard option. For more information, see Android Emulator.
The usage for the -sdcard option is as follows:
emulator -sdcard <file>- -
mksdcard -l mySdCard 1024M mySdCardFile.img\ No newline at end of file diff --git a/docs/html/guide/developing/tools/monkey.jd b/docs/html/guide/developing/tools/monkey.jd deleted file mode 100644 index a7e539c15655..000000000000 --- a/docs/html/guide/developing/tools/monkey.jd +++ /dev/null @@ -1,242 +0,0 @@ -page.title=UI/Application Exerciser Monkey -parent.title=Tools -parent.link=index.html -@jd:body - -
The Monkey is a program that runs on your -emulator or device and generates pseudo-random -streams of user events such as clicks, touches, or gestures, as well as a number of system-level -events. You can use the Monkey to stress-test applications that you are developing, in a random -yet repeatable manner.
- - -The Monkey is a command-line tool that that you can run on any emulator -instance or on a device. It sends a pseudo-random stream of -user events into the system, which acts as a stress test on the application software you are -developing.
- -The Monkey includes a number of options, but they break down into four primary -categories:
- -When the Monkey runs, it generates events and sends them to the system. It also watches -the system under test and looks for three conditions, which it treats specially:
- -Depending on the verbosity level you have selected, you will also see reports on the progress -of the Monkey and the events being generated.
- - -You can launch the Monkey using a command line on your development machine or from a script.
-Because the Monkey runs in the emulator/device environment, you must launch it from a shell in
-that environment. You can do this by prefacing adb shell to each command,
-or by entering the shell and entering Monkey commands directly.
The basic syntax is:
- -$ adb shell monkey [options] <event-count>- -
With no options specified, the Monkey will launch in a quiet (non-verbose) mode, and will send -events to any (and all) packages installed on your target. Here is a more typical command line, -which will launch your application and send 500 pseudo-random events to it:
- -$ adb shell monkey -p your.package.name -v 500- - -
The table below lists all options you can include on the Monkey command line.
- -| Category | -Option | -Description | -
|---|---|---|
| General | ---help |
-Prints a simple usage guide. | -
-v |
-Each -v on the command line will increment the verbosity level. -Level 0 (the default) provides little information beyond startup notification, test completion, and -final results. -Level 1 provides more details about the test as it runs, such as individual events being sent to -your activities. -Level 2 provides more detailed setup information such as activities selected or not selected for -testing. | -|
| Events | --s <seed> |
-Seed value for pseudo-random number generator. If you re-run the Monkey with the same seed -value, it will generate the same sequence of events. | -
--throttle <milliseconds> |
-Inserts a fixed delay between events. You can use this option to slow down the Monkey. -If not specified, there is no delay and the events are generated as rapidly as possible. | -|
--pct-touch <percent> |
-Adjust percentage of touch events. -(Touch events are a down-up event in a single place on the screen.) | -|
--pct-motion <percent> |
-Adjust percentage of motion events. -(Motion events consist of a down event somewhere on the screen, a series of pseudo-random -movements, and an up event.) | -|
--pct-trackball <percent> |
-Adjust percentage of trackball events. -(Trackball events consist of one or more random movements, sometimes followed by a click.) | -|
--pct-nav <percent> |
-Adjust percentage of "basic" navigation events. -(Navigation events consist of up/down/left/right, as input from a directional input device.) | -|
--pct-majornav <percent> |
-Adjust percentage of "major" navigation events. -(These are navigation events that will typically cause actions within your UI, such as -the center button in a 5-way pad, the back key, or the menu key.) | -|
--pct-syskeys <percent> |
-Adjust percentage of "system" key events. -(These are keys that are generally reserved for use by the system, such as Home, Back, Start Call, -End Call, or Volume controls.) | -|
--pct-appswitch <percent> |
-Adjust percentage of activity launches. At random intervals, the Monkey will issue a startActivity() call, as a way of maximizing -coverage of all activities within your package. | -|
--pct-anyevent <percent> |
-Adjust percentage of other types of events. This is a catch-all for all other types of events such as keypresses, other less-used -buttons on the device, and so forth. | -|
| Constraints | --p <allowed-package-name> |
-If you specify one or more packages this way, the Monkey will only allow the system -to visit activities within those packages. If your application requires access to activities in -other packages (e.g. to select a contact) you'll need to specify those packages as well. -If you don't specify any packages, the Monkey will allow the system to launch activities -in all packages. To specify multiple packages, use the -p option multiple times — one -p -option per package. | -
-c <main-category> |
-If you specify one or more categories this way, the Monkey will only allow the -system to visit activities that are listed with one of the specified categories. -If you don't specify any categories, the Monkey will select activities listed with the category -Intent.CATEGORY_LAUNCHER or Intent.CATEGORY_MONKEY. To specify multiple categories, use the -c -option multiple times — one -c option per category. | -|
| Debugging | ---dbg-no-events |
-When specified, the Monkey will perform the initial launch into a test activity, but -will not generate any further events. -For best results, combine with -v, one or more package constraints, and a non-zero throttle to keep the Monkey -running for 30 seconds or more. This provides an environment in which you can monitor package -transitions invoked by your application. | -
--hprof |
-If set, this option will generate profiling reports immediately before and after -the Monkey event sequence. -This will generate large (~5Mb) files in data/misc, so use with care. See -Traceview for more information -on trace files. | -|
--ignore-crashes |
-Normally, the Monkey will stop when the application crashes or experiences any type of -unhandled exception. If you specify this option, the Monkey will continue to send events to -the system, until the count is completed. | -|
--ignore-timeouts |
-Normally, the Monkey will stop when the application experiences any type of timeout error such -as a "Application Not Responding" dialog. If you specify this option, the Monkey will continue to -send events to the system, until the count is completed. | -|
--ignore-security-exceptions |
-Normally, the Monkey will stop when the application experiences any type of permissions error, -for example if it attempts to launch an activity that requires certain permissions. If you specify -this option, the Monkey will continue to send events to the system, until the count is -completed. | -|
--kill-process-after-error |
-Normally, when the Monkey stops due to an error, the application that failed will be left -running. When this option is set, it will signal the system to stop the process in which the error -occurred. -Note, under a normal (successful) completion, the launched process(es) are not stopped, and -the device is simply left in the last state after the final event. | -|
--monitor-native-crashes |
-Watches for and reports crashes occurring in the Android system native code. If --kill-process-after-error is set, the system will stop. | -|
--wait-dbg |
-Stops the Monkey from executing until a debugger is attached to it. | -
- 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. -
-
- The monkeyrunner tool is not related to the
- UI/Application Exerciser Monkey,
- also known as the monkey tool. The monkey tool runs in an
- adb shell directly on the
- device or emulator and generates 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.
-
- The monkeyrunner tool provides these unique features for Android testing: -
-os and
- subprocess
- modules to call Android tools such as
- Android Debug Bridge.
- - You can also add your own classes to the monkeyrunner API. This is described - in more detail in the section - Extending monkeyrunner with plugins. -
-- The monkeyrunner tool uses Jython, a - implementation of Python that uses the Java programming language. Jython allows the - monkeyrunner API to interact easily with the Android framework. With Jython you can - use Python syntax to access the constants, classes, and methods of the API. -
- -
- Here is a simple monkeyrunner program that connects to a device, creating a
- MonkeyDevice
- object. Using the MonkeyDevice object, the program installs an Android application
- package, runs one of its activities, and sends key events to the activity.
- The program then takes a screenshot of the result, creating a
- MonkeyImage object.
- From this object, the program writes out a .png file containing the screenshot.
-
-# Imports the monkeyrunner modules used by this program
-from com.android.monkeyrunner import MonkeyRunner, MonkeyDevice
-
-# Connects to the current device, returning a MonkeyDevice object
-device = MonkeyRunner.waitForConnection()
-
-# Installs the Android package. Notice that this method returns a boolean, so you can test
-# to see if the installation worked.
-device.installPackage('myproject/bin/MyApplication.apk')
-
-# sets a variable with the package's internal name
-package = 'com.example.android.myapplication'
-
-# sets a variable with the name of an Activity in the package
-activity = 'com.example.android.myapplication.MainActivity'
-
-# sets the name of the component to start
-runComponent = package + '/' + activity
-
-# Runs the component
-device.startActivity(component=runComponent)
-
-# Presses the Menu button
-device.press('KEYCODE_MENU', MonkeyDevice.DOWN_AND_UP)
-
-# Takes a screenshot
-result = device.takeSnapshot()
-
-# Writes the screenshot to a file
-result.writeToFile('myproject/shot1.png','png')
-
-
-
- The monkeyrunner API is contained in three modules in the package
- com.android.monkeyrunner:
-
MonkeyRunner:
- A class of utility methods for monkeyrunner programs. This class provides a method for
- connecting monkeyrunner to a device or emulator. It also provides methods for
- creating UIs for a monkeyrunner program and for displaying the built-in help.
- MonkeyDevice:
- Represents a device or emulator. This class provides methods for installing and
- uninstalling packages, starting an Activity, and sending keyboard or touch events to an
- application. You also use this class to run test packages.
- MonkeyImage:
- Represents a screen capture image. This class provides methods for capturing screens,
- converting bitmap images to various formats, comparing two MonkeyImage objects, and
- writing an image to a file.
-
- In a Python program, you access each class as a Python module. The monkeyrunner tool
- does not import these modules automatically. To import a module, use the
- Python from statement:
-
-from com.android.monkeyrunner import <module> --
- where <module> is the class name you want to import. You can import more
- than one module in the same from statement by separating the module names with
- commas.
-
- You can either run monkeyrunner programs from a file, or enter monkeyrunner statements in
- an interactive session. You do both by invoking the monkeyrunner command
- which is found in the tools/ subdirectory of your SDK directory.
- If you provide a filename as an argument, the monkeyrunner command
- runs the file's contents as a Python program; otherwise, it starts an interactive session.
-
- The syntax of the monkeyrunner command is
-
-monkeyrunner -plugin <plugin_jar> <program_filename> <program_options> --
-Table 1 explains the flags and arguments. -
-
- Table 1. monkeyrunner flags and arguments.
| Argument | -Description | -
|---|---|
- -plugin <plugin_jar>
- |
-
- (Optional) Specifies a .jar file containing a plugin for monkeyrunner.
- To learn more about monkeyrunner plugins, see
- Extending monkeyrunner with plugins. To specify more than one
- file, include the argument multiple times.
- |
-
- <program_filename>
- |
-
- If you provide this argument, the monkeyrunner command runs the contents
- of the file as a Python program. If the argument is not provided, the command starts an
- interactive session.
- |
-
- <program_options>
- |
- - (Optional) Flags and arguments for the program in <program_file>. - | -
- You can generate an API reference for monkeyrunner by running: -
--monkeyrunner help.py <format> <outfile> --
-The arguments are: -
-<format> is either text for plain text output
- or html for HTML output.
- <outfile> is a path-qualified name for the output file.
-
- You can extend the monkeyrunner API with classes you write in the Java programming language
- and build into one or more .jar files. You can use this feature to extend the
- monkeyrunner API with your own classes or to extend the existing classes. You can also use this
- feature to initialize the monkeyrunner environment.
-
- To provide a plugin to monkeyrunner, invoke the monkeyrunner command with the
- -plugin <plugin_jar> argument described in
- table 1.
-
- In your plugin code, you can import and extend the the main monkeyrunner classes
- MonkeyDevice, MonkeyImage, and MonkeyRunner in
- com.android.monkeyrunner (see The monkeyrunner API).
-
- Note that plugins do not give you access to the Android SDK. You can't import packages
- such as com.android.app. This is because monkeyrunner interacts with the
- device or emulator below the level of the framework APIs.
-
- The .jar file for a plugin can specify a class that is instantiated before
- script processing starts. To specify this class, add the key
- MonkeyRunnerStartupRunner to the .jar file's
- manifest. The value should be the name of the class to run at startup. The following
- snippet shows how you would do this within an ant build script:
-
-<jar jarfile="myplugin" basedir="${build.dir}">
-<manifest>
-<attribute name="MonkeyRunnerStartupRunner" value="com.myapp.myplugin"/>
-</manifest>
-</jar>
-
-
-
-
- To get access to monkeyrunner's runtime environment, the startup class can implement
- com.google.common.base.Predicate<PythonInterpreter>. For example, this
- class sets up some variables in the default namespace:
-
-package com.android.example;
-
-import com.google.common.base.Predicate;
-import org.python.util.PythonInterpreter;
-
-public class Main implements Predicate<PythonInterpreter> {
- @Override
- public boolean apply(PythonInterpreter anInterpreter) {
-
- /*
- * Examples of creating and initializing variables in the monkeyrunner environment's
- * namespace. During execution, the monkeyrunner program can refer to the variables "newtest"
- * and "use_emulator"
- *
- */
- anInterpreter.set("newtest", "enabled");
- anInterpreter.set("use_emulator", 1);
-
- return true;
- }
-}
-
diff --git a/docs/html/guide/developing/tools/othertools.html b/docs/html/guide/developing/tools/othertools.html
deleted file mode 100644
index a074f3350fda..000000000000
--- a/docs/html/guide/developing/tools/othertools.html
+++ /dev/null
@@ -1,10 +0,0 @@
-
-
-
-You should be redirected. Please click here.
- - \ No newline at end of file diff --git a/docs/html/guide/developing/tools/proguard.jd b/docs/html/guide/developing/tools/proguard.jd deleted file mode 100644 index ea8a1eabafda..000000000000 --- a/docs/html/guide/developing/tools/proguard.jd +++ /dev/null @@ -1,189 +0,0 @@ -page.title=ProGuard -parent.title=Tools -parent.link=index.html -@jd:body - -The ProGuard tool shrinks, optimizes, and obfuscates your code by removing unused code and
- renaming classes, fields, and methods with semantically obscure names. The result is a smaller
- sized .apk file that is more difficult to reverse engineer. Because ProGuard makes your
- application harder to reverse engineer, it is important that you use it
- when your application utilizes features that are sensitive to security like when you are
- Licensing Your Applications.
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.
- -This document describes how to enable and configure ProGuard as well as use the
- retrace tool to decode obfuscated stack traces.
When you create an Android project, a proguard.cfg file is automatically
- generated in the root directory of the project. This file defines how ProGuard optimizes and
- obfuscates your code, so it is very important that you understand how to customize it for your
- needs. The default configuration file only covers general cases, so you most likely have to edit
- it for your own needs. See the following section about Configuring ProGuard for information on
- customizing the ProGuard configuration file.
To enable ProGuard so that it runs as part of an Ant or Eclipse build, set the
- proguard.config property in the <project_root>/project.properties
- file. The path can be an absolute path or a path relative to the project's root.
If you left the proguard.cfg file in its default location (the project's root directory),
-you can specify its location like this:
-proguard.config=proguard.cfg --
-You can also move the the file to anywhere you want, and specify the absolute path to it: -
--proguard.config=/path/to/proguard.cfg -- - -
When you build your application in release mode, either by running ant release or
- by using the Export Wizard in Eclipse, the build system automatically checks to see if
- the proguard.config property is set. If it is, ProGuard automatically processes
- the application's bytecode before packaging everything into an .apk file. Building in debug mode
- does not invoke ProGuard, because it makes debugging more cumbersome.
ProGuard outputs the following files after it runs:
- -dump.txt.apk filemapping.txtseeds.txtusage.txt.apkThese files are located in the following directories:
- -<project_root>/bin/proguard if you are using Ant.<project_root>/proguard if you are using Eclipse.Caution: Every time you run a build in release mode, these files are - overwritten with the latest files generated by ProGuard. Save a copy of them each time you release your - application in order to de-obfuscate bug reports from your release builds. - For more information on why saving these files is important, see - Debugging considerations for published applications. -
- -For some situations, the default configurations in the proguard.cfg file will
- suffice. However, many situations are hard for ProGuard to analyze correctly and it might remove code
- that it thinks is not used, but your application actually needs. Some examples include:
AndroidManifest.xml fileThe default proguard.cfg file tries to cover general cases, but you might
- encounter exceptions such as ClassNotFoundException, which happens when ProGuard
- strips away an entire class that your application calls.
You can fix errors when ProGuard strips away your code by adding a -keep line in
- the proguard.cfg file. For example:
--keep public class <MyClass> -- -
There are many options and considerations when using the -keep option, so it is
- highly recommended that you read the ProGuard
- Manual for more information about customizing your configuration file. The Overview of Keep options and
- Examples section
- are particularly helpful. The Troubleshooting section of the
- ProGuard Manual outlines other common problems you might encounter when your code gets stripped
- away.
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
- <project_root>/bin/proguard/mapping.txt file, which shows you the original
- class, method, and field names mapped to their obfuscated names.
The retrace.bat script on Windows or the retrace.sh script on Linux
- or Mac OS X can convert an obfuscated stack trace to a readable one. It is located in the
- <sdk_root>/tools/proguard/ directory. The syntax for executing the
- retrace tool is:
retrace.bat|retrace.sh [-verbose] mapping.txt [<stacktrace_file>]-
For example:
- -retrace.bat -verbose mapping.txt obfuscated_trace.txt- -
If you do not specify a value for <stacktrace_file>, the retrace tool reads
- from standard input.
Save the mapping.txt file for every release that you publish to your users.
- By retaining a copy of the mapping.txt file for each release build,
- you ensure that you can debug a problem if a user encounters a bug and submits an obfuscated stack trace.
- A project's mapping.txt file is overwritten every time you do a release build, so you must be
- careful about saving the versions that you need.
For example, say you publish an application and continue developing new features of
- the application for a new version. You then do a release build using ProGuard soon after. The
- build overwrites the previous mapping.txt file. A user submits a bug report
- containing a stack trace from the application that is currently published. You no longer have a way
- of debugging the user's stack trace, because the mapping.txt file associated with the version
- on the user's device is gone. There are other situations where your mapping.txt file can be overwritten, so
- ensure that you save a copy for every release that you anticipate you have to debug.
How you save the mapping.txt file is your decision. For example, you can rename them to
- include a version or build number, or you can version control them along with your source
- code.
From a remote shell to your device or from your host machine, you can use the sqlite3 command-line program to manage SQLite databases
- created by Android applications. The sqlite3 tool includes many useful commands,
- such as .dump to print out the contents of a table and .schema to print
- the SQL CREATE statement for an existing table. The tool also gives you the ability to execute
- SQLite commands on the fly.
To use sqlite3 from a remote shell:
adb [-d|-e|-s {<serialNumber>}] shell
- sqlite3 tool by entering the following command:
- sqlite3- -
You can also optionally specify a full path to a database that you want to explore.
- Emulator/device instances store SQLite3 databases in the directory
- /data/data/<package_name>/databases/.
sqlite3, you can issue sqlite3 commands in the
- shell. To exit and return to the adb remote shell, enter exit or press
- CTRL+D.Here's an example:
-$ adb -s emulator-5554 shell -# sqlite3 /data/data/com.example.google.rss.rssexample/databases/rssitems.db -SQLite version 3.3.12 -Enter ".help" for instructions -.... enter commands, then quit... -# sqlite> .exit -- -
To use sqlite3 locally, instead of within a shell,
- pull the database file from the device and start {@code sqlite3}:
-adb pull <database-file-on-device> --
/tools directory, specifying the database
- file:
- -sqlite3 <database-file-on-host> --
Traceview is a graphical viewer for execution logs saved by your application. -Traceview can help you debug your application and profile its performance.
- -To start Traceview, enter the following command from the SDK tools/ directory:
traceview- - -
For more information on how to use Traceview, see -Profiling with Traceview and dmtracedump -
- diff --git a/docs/html/guide/developing/tools/zipalign.jd b/docs/html/guide/developing/tools/zipalign.jd deleted file mode 100644 index 321608058937..000000000000 --- a/docs/html/guide/developing/tools/zipalign.jd +++ /dev/null @@ -1,67 +0,0 @@ -page.title=zipalign -parent.title=Tools -parent.link=index.html -@jd:body - -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.
- -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 ant.properties} file, so that the build tools -can sign the package first.
- -Caution: zipalign must only be performed -after the .apk file has been signed with your private key. -If you perform zipalign before signing, then the signing procedure will undo -the alignment. Also, do not make alterations to the aligned package. -Alterations to the archive, such as renaming or deleting entries, will -potentially disrupt the alignment of the modified entry and all later -entries. And any files added to an "aligned" archive will not be aligned.
- -The adjustment is made by altering the size of -the "extra" field in the zip Local File Header sections. Existing data -in the "extra" fields may be altered by this process.
- -For more information about how to use zipalign when building your -application, please read Signing -Your Application.
- - -To align {@code infile.apk} and save it as {@code outfile.apk}:
- -zipalign [-f] [-v] <alignment> infile.apk outfile.apk- -
To confirm the alignment of {@code existing.apk}:
- -zipalign -c -v <alignment> existing.apk- -
The {@code <alignment>} is an integer that defines the byte-alignment boundaries. -This must always be 4 (which provides 32-bit alignment) or else it effectively -does nothing.
- -Flags:
- -Google offers a variety of services that help you build new revenue streams, enhance your app's capabilities, manage distribution and payloads, and track usage and installs. Many of the services use static libraries that you download through the Android SDK Manager and build into your app. Others are configurable directly from Google Play Android Developer Console.
+ +The sections below highlight some of the Google Services and link you to more information about how to use them in your Android app.
+ + +Keep your users engaged by offering in-app purchases and subscriptions directly in your app. +
+ Learn more » +Generate more revenue from your app by + displaying ads from multiple ad networks.
+ Learn more » +Protect your revenue streams and integrate policies for usage into your app.
+ Learn more » +Make sure your app gets to the right users by +declaring the hardware and software features needed by your app.
+Learn more » +Distribute different APKs based on a variety of properties such as platform version, screen size, and GLES texture compression support.
+Learn more » +Take load off of your servers and utilize APK expansion files +to deliver up to 4 GB of assets for your Android app, free.
+ +Learn more » +Notify your apps of events with push messages that are lightweight + and battery-saving.
+ Learn more » +The Google Maps library for Android lets you add powerful mapping and geo-location capabilities to your app.
+ Learn more » +Google Analytics gives you powerful insights into how users find your apps
+ and how they use them.
Start integrating analytics to measure
+ your app's success.
You should be redirected. Please click +here.
+ + \ No newline at end of file diff --git a/docs/html/guide/google/play/billing/billing_admin.jd b/docs/html/guide/google/play/billing/billing_admin.jd new file mode 100755 index 000000000000..cb288a5381d5 --- /dev/null +++ b/docs/html/guide/google/play/billing/billing_admin.jd @@ -0,0 +1,530 @@ +page.title=Administering In-app Billing +parent.title=In-app Billing +parent.link=index.html +@jd:body + +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.
+ +You must have a Google Play publisher account to register test accounts. And you must have a +Google Wallet merchant account to create a product list and issue refunds to your users. If you +already have a publisher account on Google Play, 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 a Google Play developer and set up a publisher account at the +Google Play publisher site. If you do not have a +Google Wallet merchant account, you can register for one at the Google Wallet site.
+ +The Google Play publisher site provides a product list for each of your published +applications. You can sell an item using Google Play's 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.
+ +You can access an application's product list by clicking the In-App Products
+link that appears under each of the applications that are listed for your publisher account (see
+figure 1). The In-App Products link appears only if you have a Google Wallet
+merchant account and an application's manifest includes the com.android.vending.BILLING
+permission.
++ Figure 1. You can access an application's product list by clicking the + In-App Products link. +
+ +A product list specifies items you are selling in an application — in-app products, +subscriptions, or a combination of both. For each item, the product list contains information such as a product id, +product description, and price (see figure 2). 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.
+ +
++ Figure 2. An application's product list. +
+ +You can create a product list for any published application or any draft application that's been
+uploaded and saved to the Google Play site. However, you must have a Google Wallet merchant
+account and 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 about this permission, see
+Updating Your
+Application's Manifest.
In addition, an application package can have only one product list. If you create a product +list for an application, and you use the multiple APK feature to distribute +more than one APK for that application, the product list applies to all APK versions that are +associated with the application listing. You cannot create individual product lists for each APK if +you are using the multiple APK feature.
+ +You can add items to a product list two ways: you can add items one at a time by using the In-app +Products UI (see figure 3), or you can add a batch of items by importing the items from a +comma-separated values (CSV) file (see figure 2). Adding items one at a time is useful if your +application has only a few in-app items or you are adding only a few items to a +product list for testing purposes. The CSV file method is useful if your application has a large +number of in-app items.
+ +Note: Batch upload of product lists containing subscriptions is not yet supported.
+ +To add an item to a product list using the In-app Products UI, follow these steps:
+ +
++ Figure 3. The Create New In-app Product page lets you add items to an + application's product list. +
+ +You must enter the following information for each item in a product list:
+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."
+In addition, you cannot modify an item's product ID after it is created, and you cannot reuse + a product ID.
+The purchase type can be Managed per user account, Unmanaged, + or Subscription. You can never change an item's purchase type after you set it. For more + information, see Choosing a purchase type later in this + document.
+An item's publishing state can be Published or Unpublished + . 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 Google Play.
+Note: This is not true for test accounts. An item is visible to + a test account if the application is not published and the item is published. See Testing In-app + Billing for more information.
+The language setting determines which languages are used to display the item title and + item description during checkout. A product list inherits its default language from the + parent application. You can add more languages by clicking add language. You + can also choose to have the title and description automatically translated from the default + language by selecting the Fill fields with auto translation checkbox (see + figure 4). If you do not use the auto translation feature, you must provide the translated + versions of the title and description.
+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. For optimum appearance, titles should be no longer than 25 characters; + however, titles can be up to 55 characters in length.
+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. Descriptions can be up to 80 characters in length.
+You must provide a default price in your home currency. You can also provide prices in other + currencies, but you can do this only if a currency's corresponding country is listed as a + target country for your application. You can specify target countries on the Edit Application + page in the Google Play developer console.
+To specify prices in other currencies, you can manually enter the price for each + currency or you can click Auto Fill and let Google Play do a one-time + conversion from your home currency to the currencies you are targeting (see figure 4).
+For subscription items, note that you can not change the item's price once you have published it.
+
++ Figure 4. Specifying additional currencies and additional languages for the + item title and description. +
+ +For more information about product IDs and product lists, see Creating In-App Product +IDs. For more information about pricing, see In-App Billing +Pricing.
+ +Note: Be sure to plan your product ID namespace. You cannot reuse +or modify product IDs after you save them.
+ +To add a batch of items to a product list using a CSV file, you first need to create your CSV +file. The data values that you specify in the CSV file represent the same data values you specify +manually through the In-app Products UI (see Adding items one at a time +to a product list). + +
If you are importing and exporting CSV files with in-app products, please +keep tax-inclusive pricing in mind. If you use auto-fill, you can provide a +tax-exclusive default price and tax-inclusive prices will be auto-filled. If you +do not use auto-fill, prices you provide must include tax.
+ +Note: Batch upload of product lists containing subscriptions is not yet supported.
+ +The CSV file uses commas (,) and semi-colons (;) to separate data values. +Commas are used to separate primary data values, and semi-colons are used to separate subvalues. For +example, the syntax for the CSV file is as follows: + +"product_id","publish_state","purchase_type","autotranslate +","locale; title; description","autofill","country; +price" +
+ +Descriptions and usage details are provided below.
+ +This is equivalent to the In-app Product ID setting in the In-app Products UI. If you specify + a product_id that already exists in a product list, and you choose to overwrite + the product list while importing the CSV file, the data for the existing item is overwritten with + the values specified in the CSV file. The overwrite feature does not delete items that are on a + product list but not present in the CSV file.
+This is equivalent to the Publishing State setting in the In-app Products UI. Can be
+ published or unpublished.
This is equivalent to the Purchase Type setting in the In-app Products UI. Can be
+ managed_by_android, which is equivalent to Managed per user account
+ in the In-app Products UI, or managed_by_publisher, which is equivalent
+ to Unmanaged in the In-app Products UI.
This is equivalent to selecting the Fill fields with auto translation
+ checkbox in the In-app Products UI. Can be true or false.
This is equivalent to the Language setting in the In-app Products UI. You must have an entry + for the default locale. The default locale must be the first entry in the list of + locales, and it must include a title and description. If you want to provide + translated versions of the title and description in addition to the default, + you must use the following syntax rules:
+If autotranslate is true, you must specify the default locale,
+ default title, default description, and other locales using the following format:
"true,"default_locale; default_locale_title; + default_locale_description; locale_2; locale_3, ..."
+If autotranslate is false, you must specify the default locale,
+ default title, and default description as well as the translated titles and descriptions using
+ the following format:
"false,"default_locale; default_locale_title; + default_locale_description; locale_2; locale_2_title; + local_2_description; locale_3; locale_3_title; + locale_3_description; ..."
+See table 1 for a list of the language codes you can use with the locale field.
+This is equivalent to the Title setting in the In-app Products UI. If the title + contains a semicolon, it must be escaped with a backslash (for example, "\;"). A backslash + should also be escaped with a backslash (for example, "\\">.
+This is equivalent to the Description in the In-app Products UI. If the description + contains a semicolon, it must be escaped with a backslash (for example, "\;"). A backslash + should also be escaped with a backslash (for example, "\\">.
+This is equivalent to clicking Auto Fill in the In-app Products UI. Can be
+ true or false. The syntax for specifying the country
+ and price varies depending on which autofill setting you use.
If autofill is set to true, you need to specify only the default
+ price in your home currency and you must use this syntax:
"true","default_price_in_home_currency" +
If autofill is set to false, you need to specify a country
+ and a price for each currency and you must use the following syntax:
"false", "home_country; default_price_in_home_currency; country_2; + country_2_price; country_3; country_3_price; ..."
+The country for which you are specifying a price. You can only list countries that your + application is targeting. The country codes are two-letter uppercase + ISO country codes (such as "US") as defined by + ISO 3166-2.
+This is equivalent to the Price in the In-app Products UI. The price must be specified in + micro-units. To convert a currency value to micro-units, you multiply the real value by 1,000,000. + For example, if you want to sell an in-app item for $1.99 you specify 1990000 in the + price field.
+Table 1. Language codes you can use +with the locale field.
+ +| Language | +Code | +Language | +Code | +
|---|---|---|---|
| Chinese | +zh_TW | +Italian | +it_IT | +
| Czech | +cs_CZ | +Japanese | +ja_JP | +
| Danish | +da_DK | +Korean | +ko_KR | +
| Dutch | +nl_NL | +Norwegian | +no_NO | +
| English | +en_US | +Polish | +pl_PL | +
| French | +fr_FR | +Portuguese | +pt_PT | +
| Finnish | +fi_FI | +Russian | +ru_RU | +
| German | +de_DE | +Spanish | +es_ES | +
| Hebrew | +iw_IL | +Swedish | +sv_SE | +
| Hindi | +hi_IN | +-- | +-- | +
To import the items that are specified in your CSV file, do the following:
+ +The CSV file must be on your local computer or on a local disk that is connected to your + computer.
+This option overwrites values of existing items only if the value of the product_id + in the CSV file matches the In-app Product ID for an existing item in the product list. + Overwriting does not delete items that are on a product list but not present in the CSV + file.
+You can also export an existing product list to a CSV file by clicking Export to CSV + on the In-app Product List page. This is useful if you have manually added items to +a product list and you want to start managing the product list through a CSV file.
+ +An item's purchase type controls how Google Play manages the purchase of the item. There are +two purchase types: "managed per user account" and "unmanaged."
+ +Items that are managed per user account can be purchased only once per user account. When an item
+is managed per user account, Google Play permanently stores the transaction information for each
+item on a per-user basis. This enables you to query Google Play with the
+RESTORE_TRANSACTIONS request and restore the state of the items a specific user has
+purchased.
If a user attempts to purchase a managed item that has already been purchased, Google Play +displays an "Item already purchased" error. This occurs during checkout, when Google Play +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—either graying out the item or hiding it so that it cannot be selected.
+ +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.
+ +Items that are unmanaged do not have their transaction information stored on Google Play, +which means you cannot query Google Play 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 Google Play +is concerned, so it's also up to you to control how many times an unmanaged item can be +purchased.
+ +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.
+ +In-app billing does not allow users to send a refund request to Google Play. Refunds for +in-app purchases must be directed to you (the application developer). You can then process the +refund through your Google Wallet merchant account. When you do this, Google Play receives a +refund notification from Google Wallet, and Google Play sends a refund message to your +application. For more information, see Handling +IN_APP_NOTIFY messages and In-app Billing +Pricing.
+ +Important: You cannot use the Google Wallet API to issue +refunds or cancel in-app billing transactions. You must do this manually through your Google +Wallet merchant account. However, you can use the Google Wallet API to retrieve order +information.
+ +The Google Play 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 Google Play +site but have not yet published.
+ +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.
+ +Test accounts have three limitations:
+ +To add test accounts to your publisher account, follow these steps:
+ +
++ Figure 5. The Licensing and In-app Billing panel of your account's Edit Profile + page lets you register test accounts. +
+ +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.
+ +Table 2. Developer support resources +for Google Play in-app billing.
+ +| Support Type | +Resource | +Range of Topics | +
|---|---|---|
| Development and testing issues | +Google Groups: android-developers | +In-app billing integration questions, user experience ideas, handling of responses, +obfuscating code, IPC, test environment setup. | +
| Stack Overflow: http://stackoverflow.com/questions/tagged/ +android | +||
| Billing issue tracker | +Billing +project issue tracker | +Bug and issue reports related specifically to in-app billing sample code. | +
For general information about how to post to the groups listed above, see Developer Forums document in the Resources +tab.
+ + + diff --git a/docs/html/guide/google/play/billing/billing_best_practices.jd b/docs/html/guide/google/play/billing/billing_best_practices.jd new file mode 100755 index 000000000000..49d2a299f5da --- /dev/null +++ b/docs/html/guide/google/play/billing/billing_best_practices.jd @@ -0,0 +1,111 @@ +page.title=Security and Design +parent.title=In-app Billing +parent.link=index.html +@jd:body + +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 Google Play's in-app billing service.
+ +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.
+ +To prevent malicious users from redistributing your unlocked content, do not bundle it in your +.apk file. Instead, do one of the following:
+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.
+ +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 Proguard on your +code.
+In addition to running an obfuscation program, we recommend that you use the following techniques +to obfuscate your in-app billing code.
+Using these techniques can help reduce the attack surface of your application and help minimize +attacks that can compromise your in-app billing implementation.
+Note: If you use Proguard to obfuscate your code, you must add the following + line to your Proguard configuration file:
+-keep class com.android.vending.billing.**
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.
+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.
+ +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.
+Also, if you are performing nonce verification on a server, make sure that you generate the +nonces on the server.
+ +If you see your content being redistributed on Google Play, act quickly and decisively. File a +trademark notice +of infringement or a copyright notice of +infringement.
+ +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.
+ +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.
+ diff --git a/docs/html/guide/google/play/billing/billing_integrate.jd b/docs/html/guide/google/play/billing/billing_integrate.jd new file mode 100755 index 000000000000..2d1582eebb34 --- /dev/null +++ b/docs/html/guide/google/play/billing/billing_integrate.jd @@ -0,0 +1,1100 @@ +page.title=Implementing In-app Billing +parent.title=In-app Billing +parent.link=index.html +@jd:body + +In-app Billing on Google Play provides a straightforward, simple interface for sending in-app +billing requests and managing in-app billing transactions using Google Play. 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.
+ +Before you implement in-app billing in your own application, be sure that you read Overview of In-app Billing and Security and Design. These +documents provide background information that will make it easier for you to implement in-app +billing.
+ +To implement in-app billing in your application, you need to do the following:
+MarketBillingService so your application can send billing requests and receive
+ billing responses from Google Play.The in-app billing sample application shows you how to perform several tasks that are common to +all in-app billing implementations, including:
+ +The sample application includes an application file (Dungeons.java), the AIDL file
+for the MarketBillingService (IMarketBillingService.aidl), and several
+classes that demonstrate in-app billing messaging. It also includes a class that demonstrates basic
+security tasks, such as signature verification.
Table 1 lists the source files that are included with the sample application.
+Table 1. In-app billing sample +application source files.
+ +| File | +Description | +
|---|---|
| IMarketBillingService.aidl | +Android Interface Definition Library (AIDL) file that defines the IPC interface to Google
+Play's in-app billing service (MarketBillingService). |
+
| Dungeons.java | +Sample application file that provides a UI for making purchases and displaying purchase +history. | +
| PurchaseDatabase.java | +A local database for storing purchase information. | +
| BillingReceiver.java | +A {@link android.content.BroadcastReceiver} that receives asynchronous response messages
+ (broadcast intents) from Google Play. Forwards all messages to the
+ BillingService. |
+
| BillingService.java | +A {@link android.app.Service} that sends messages to Google Play on behalf of the
+ application by connecting (binding) to the MarketBillingService. |
+
| ResponseHandler.java | +A {@link android.os.Handler} that contains methods for updating the purchases database and the + UI. | +
| PurchaseObserver.java | +An abstract class for observing changes related to purchases. | +
| Security.java | +Provides various security-related methods. | +
| Consts.java | +Defines various Google Play constants and sample application constants. All constants that +are defined by Google Play must be defined the same way in your application. | +
| Base64.java and Base64DecoderException.java | +Provides conversion services from binary to Base64 encoding. The Security class
+relies on these utility classes. |
+
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 Manager and then +select the Google Market Billing package component (see figure 1), and click Install +Selected to begin the download.
+ + +
++ Figure 1. The Google Market Billing package contains the sample application and + the AIDL file. +
+ +When the download is complete, the Android SDK Manager saves the component into the +following directory:
+ +<sdk>/extras/google/market_billing/
If you want to see an end-to-end demonstration of in-app billing before you integrate in-app +billing into your own application, you can build and run the sample application. Building and +running the sample application involves three tasks:
+ +Note: Building and running the sample application is necessary only +if you want to see a demonstration of in-app billing. If you do not want to run the sample +application, you can skip to the next section, Adding the AIDL file to +your project.
+ +Before you can run the sample application, you need to configure it and build it by doing the +following:
+ +This enables the application to verify the signature of the transaction information that is + returned from Google Play. To add your public key to the sample application code, do the + following:
+src/com/example/dungeons/Security.java in the editor of your choice.
+ You can find this file in the sample application's project folder.
+String base64EncodedPublicKey = "your public key here";
The current package name is com.example.dungeons. Google Play does not let
+ you upload applications with package names that contain com.example, so you must
+ change the package name to something else.
To learn how to build and sign applications, see Building and Running.
+After you build a release version of the sample application and sign it, you need to upload it as +a draft to the Google Play publisher site. You also need to create a product list for the in-app +items that are available for purchase in the sample application. The following instructions show you +how to do this.
+Do not publish the sample application; leave it as an unpublished draft application. The + sample application is for demonstration purposes only and should not be made publicly available + on Google Play. To learn how to upload an application to Google Play, see Uploading + applications.
+The sample application lets you purchase two items: a two-handed sword
+ (sword_001) and a potion (potion_001). We recommend that you set up
+ your product list so that sword_001 has a purchase type of "Managed per user
+ account" and potion_001 has a purchase type of "Unmanaged" so you can see how these
+ two purchase types behave. To learn how to set up a product list, see Creating a Product
+ List.
Note: You must publish the items in your product
+ list (sword_001 and potion_001) even though you are not publishing the
+ sample application. Also, you must have a Google Wallet Merchant account to add items to the
+ sample application's product list.
You cannot run the sample application in the emulator. You must install the sample application +onto a device to run it. To run the sample application, do the following:
+ +You cannot purchase items from yourself (Google Wallet prohibits this), so you need to + create at least one test account that you can use to purchase items in the sample application. + To learn how to set up a test account, see Setting up Test + Accounts.
+If your device is running Android 3.0, in-app billing requires version 5.0.12 (or higher) of + the MyApps application. If your device is running any other version of Android, in-app billing + requires version 2.3.4 (or higher) of the Google Play application. To learn how to check the + version of the Google Play application, see Updating Google + Play.
+Even though you uploaded the application to Google Play, the application is not published, + so you cannot download it from Google Play to a device. Instead, you must install the + application onto your device. To learn how to install an application onto a device, see Running on a + device.
+The primary account on your device must be one of the test accounts + that you registered on the Google Play publisher site. If the primary account on your device is not a + test account, you must do a factory reset of the device and then sign in with one of your test + accounts. To perform a factory reset, do the following:
+When you use a test account to purchase items, the test account is billed through Google + Wallet and your Google Wallet Merchant account receives a payout for the purchase. + Therefore, you may want to refund purchases that are made with test accounts, otherwise the + purchases will show up as actual payouts to your merchant account.
+Note: Debug log messages are turned off by default in the
+sample application. You can turn them on by setting the variable DEBUG
+to true in the Consts.java file.
The sample application contains an Android Interface Definition Language (AIDL) file, which
+defines the interface to Google Play's in-app billing service
+(MarketBillingService). When you add this file to your project, the Android build
+environment creates an interface file (IMarketBillingService.java). You can then use
+this interface to make billing requests by invoking IPC method calls.
If you are using the ADT plug-in with Eclipse, you can just add this file to your
+/src 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
+IMarketBillingService.java file gets generated.
To add the IMarketBillingService.aidl file to your project, do the following:
/src directory:
+ com/android/vending/billing/
IMarketBillingService.aidl file into the
+ sample/src/com/android/vending/billing/ directory.You should now find a generated interface file named IMarketBillingService.java in
+the gen folder of your project.
In-app billing relies on the Google Play application, which handles all communication between
+your application and the Google Play server. To use the Google Play application, your
+application must request the proper permission. You can do this by adding the
+com.android.vending.BILLING permission to your AndroidManifest.xml file. If your
+application does not declare the in-app billing permission, but attempts to send billing requests,
+Google Play will refuse the requests and respond with a RESULT_DEVELOPER_ERROR
+response code.
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 Google Play, and you need to declare the {@link android.app.Service}
+that you will use to bind with the IMarketBillingService and send messages to Google
+Play. You must also declare intent filters for the {@link
+android.content.BroadcastReceiver} so that the Android system knows how to handle the broadcast
+intents that are sent from the Google Play application.
For example, here is 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, BillingReceiver is the {@link
+android.content.BroadcastReceiver} that handles broadcast intents from the Google Play
+application and BillingService is the {@link android.app.Service} that sends requests
+to the Google Play application.
+<?xml version="1.0" encoding="utf-8"?> +<manifest xmlns:android="http://schemas.android.com/apk/res/android" + package="com.example.dungeons" + android:versionCode="1" + android:versionName="1.0"> + + <uses-permission android:name="com.android.vending.BILLING" /> + + <application android:icon="@drawable/icon" android:label="@string/app_name"> + <activity android:name=".Dungeons" android:label="@string/app_name"> + <intent-filter> + <action android:name="android.intent.action.MAIN" /> + <category android:name="android.intent.category.LAUNCHER" /> + </intent-filter> + </activity> + + <service android:name="BillingService" /> + + <receiver android:name="BillingReceiver"> + <intent-filter> + <action android:name="com.android.vending.billing.IN_APP_NOTIFY" /> + <action android:name="com.android.vending.billing.RESPONSE_CODE" /> + <action android:name="com.android.vending.billing.PURCHASE_STATE_CHANGED" /> + </intent-filter> + </receiver> + + </application> +</manifest> ++ +
Your application must have a local {@link android.app.Service} to facilitate messaging between +your application and Google Play. At a minimum, this service must do the following:
+ +MarketBillingService.
+ CHECK_BILLING_SUPPORTED requestsREQUEST_PURCHASE requestsGET_PURCHASE_INFORMATION requestsCONFIRM_NOTIFICATIONS requestsRESTORE_TRANSACTIONS requestsBinding to the MarketBillingService is relatively easy if you've already added the
+IMarketBillingService.aidl 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
+MarketBillingService. You could put this code in your service's {@link
+android.app.Activity#onCreate onCreate()} method.
+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);
+}
+
+
+After you bind to the service, you need to create a reference to the
+IMarketBillingService 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.
+/**
+ * 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);
+ }
+
+
+You can now use the mService reference to invoke the
+sendBillingRequest() method.
For a complete implementation of a service that binds to the MarketBillingService,
+see the BillingService class in the sample application.
Now that your {@link android.app.Service} has a reference to the
+IMarketBillingService interface, you can use that reference to send billing requests
+(via IPC method calls) to the MarketBillingService. The
+MarketBillingService IPC interface exposes a single public method
+(sendBillingRequest()), 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
+sendBillingRequest() 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 MarketBillingService, see In-app Billing
+Service Interface.
You can use the sendBillingRequest() method to send five types of billing requests.
+The five request types are specified using the BILLING_REQUEST Bundle key. This Bundle
+key can have the following five values:
CHECK_BILLING_SUPPORTED—verifies that the Google Play application
+ supports in-app billing and the version of the In-app Billing API available.REQUEST_PURCHASE—sends a purchase request for an in-app item.GET_PURCHASE_INFORMATION—retrieves transaction information for a purchase
+ or refund.CONFIRM_NOTIFICATIONS—acknowledges that you received the transaction
+ information for a purchase or refund.RESTORE_TRANSACTIONS—retrieves a user's transaction history for managed
+ purchases.To make any of these billing requests, you first need to build an initial {@link
+android.os.Bundle} that contains the three keys that are required for all requests:
+BILLING_REQUEST, API_VERSION, and PACKAGE_NAME. The following
+code sample shows you how to create a helper method named makeRequestBundle() that does
+this.
+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;
+
+
+To use this helper method, you pass in a String 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.
Important: You must make all in-app billing requests from your +application's main thread.
+ +The following code sample shows how to verify whether the Google Play application supports
+in-app billing and confirm what version of the API it supports. In the sample, mService
+is an instance of the MarketBillingService interface.
+/**
+* Request type is CHECK_BILLING_SUPPORTED
+*/
+ Bundle request = makeRequestBundle("CHECK_BILLING_SUPPORTED");
+ Bundle response = mService.sendBillingRequest(request);
+ // Do something with this response.
+}
+
+
+The makeRequestBundle() method constructs an initial Bundle, which contains the
+three keys that are required for all requests: BILLING_REQUEST,
+API_VERSION, and PACKAGE_NAME. If you are offering subscriptions in
+your app, set the API_VERSION key to a value of "2", to confirm that In-app Billing v2 is
+available. For an examnple, see
+Subscriptions.
The CHECK_BILLING_SUPPORTED request returns a synchronous {@link
+android.os.Bundle} response, which contains only a single key: RESPONSE_CODE. The
+RESPONSE_CODE key can have the following values:
RESULT_OK—the spedified version of in-app billing is supported.RESULT_BILLING_UNAVAILABLE—in-app billing is not available because the API
+ version you specified is not recognized or the user is not eligible to make in-app purchases (for
+ example, the user resides in a country that prohibits in-app purchases).RESULT_ERROR—there was an error connecting with the Google Play
+ application.RESULT_DEVELOPER_ERROR—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.The CHECK_BILLING_SUPPORTED request does not trigger any asynchronous responses
+(broadcast intents).
We recommend that you invoke the CHECK_BILLING_SUPPORTED request within a
+RemoteException block. When your code throws a RemoteException it
+indicates that the remote method call failed, which means that the Google Play application is out
+of date and needs to be updated. In this case, you can provide users with an error message that
+contains a link to the Updating Google Play
+Help topic.
The sample application demonstrates how you can handle this error condition (see
+DIALOG_CANNOT_CONNECT_ID in Dungeons.java).
To make a purchase request you must do the following:
+ +REQUEST_PURCHASE 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 a purchase request for a single in-app item. In the sample,
+mProductId is the Google Play product ID of an in-app item (which is listed in the
+application's product
+list), and mService is an instance of the MarketBillingService
+interface.
+/**
+* Request type is REQUEST_PURCHASE
+*/
+ Bundle request = makeRequestBundle("REQUEST_PURCHASE");
+ request.putString(ITEM_ID, mProductId);
+ // Request is for a standard in-app product
+ request.putString(ITEM_TYPE, "inapp");
+ // 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.
+
+The makeRequestBundle() method constructs an initial Bundle, which contains the
+three keys that are required for all requests: BILLING_REQUEST,
+API_VERSION, and PACKAGE_NAME. The ITEM_ID key is then added
+to the Bundle prior to invoking the sendBillingRequest() method.
The request returns a synchronous {@link android.os.Bundle} response, which contains three keys:
+RESPONSE_CODE, PURCHASE_INTENT, and REQUEST_ID. The
+RESPONSE_CODE key provides you with the status of the request and the
+REQUEST_ID key provides you with a unique request identifier for the request. The
+PURCHASE_INTENT key provides you with a {@link android.app.PendingIntent}, which you
+can use to launch the checkout UI.
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.
+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);
+ }
+ }
+}
+
+
+Important: You must launch the pending intent from an activity
+context and not an application context. Also, you cannot use the singleTop launch mode to launch the
+pending intent. If you do either of these, the Android system will not attach the pending intent to
+your application process. Instead, it will bring Google Play to the foreground, disrupting your
+application.
A REQUEST_PURCHASE request also triggers two asynchronous responses (broadcast
+intents). First, the Google Play application sends a RESPONSE_CODE broadcast intent,
+which provides error information about the request. If the request does not generate an
+error, the RESPONSE_CODE broadcast intent returns RESULT_OK, which
+indicates that the request was successfully sent. (To be clear, a RESULT_OK response
+does not indicate that the requested purchase was successful; it indicates that the request was sent
+successfully to Google Play.)
Next, when the requested transaction changes state (for example, the purchase is successfully
+charged to a credit card or the user cancels the purchase), the Google Play application sends an
+IN_APP_NOTIFY broadcast intent. This message contains a notification ID, which you can
+use to retrieve the transaction details for the REQUEST_PURCHASE request.
Note: The Google Play application also sends
+an IN_APP_NOTIFY for refunds. For more information, see Handling
+IN_APP_NOTIFY messages.
Because the purchase process is not instantaneous and can take several seconds (or more), you
+must assume that a purchase request is pending from the time you receive a RESULT_OK
+message until you receive an IN_APP_NOTIFY message for the transaction. While the
+transaction is pending, the Google Play checkout UI displays an "Authorizing purchase..."
+notification; however, this notification is dismissed after 60 seconds and you should not rely on
+this notification as your primary means of conveying transaction status to users. Instead, we
+recommend that you do the following:
To use these two UI elements, you could invoke a status bar notification with a ticker-text
+message that says "Purchase pending" when your application receives a RESULT_OK
+message. Then, when your application receives an IN_APP_NOTIFY message, you could
+update the notification with a new message that says "Purchase succeeded" or "Purchase failed." When
+a user touches the expanded status bar notification, you could launch the activity that shows the
+status of pending and completed in-app purchases.
If you use some other UI technique to inform users about the state of a pending transaction, +be sure that your pending status UI does not block your application. For example, you should avoid +using a hovering progress wheel to convey the status of a pending transaction because a pending +transaction could last a long time, particularly if a device loses network connectivity and cannot +receive transaction updates from Google Play.
+ +Important: If a user purchases a managed item, you must prevent
+the user from purchasing the item again while the original transaction is pending. If a user
+attempts to purchase a managed item twice, and the first transaction is still pending, Google
+Play will display an error to the user; however, Google Play will not send an error to your
+application notifying you that the second purchase request was canceled. This might cause your
+application to get stuck in a pending state while it waits for an IN_APP_NOTIFY message
+for the second purchase request.
You retrieve transaction information in response to an IN_APP_NOTIFY broadcast
+intent. The IN_APP_NOTIFY message contains a notification ID, which you can use to
+retrieve transaction information.
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, mService is an instance of the
+MarketBillingService interface.
+/**
+* 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.
+}
+
+The makeRequestBundle() method constructs an initial Bundle, which contains the
+three keys that are required for all requests: BILLING_REQUEST,
+API_VERSION, and PACKAGE_NAME. The additional keys are then added to the
+bundle prior to invoking the sendBillingRequest() method. The
+REQUEST_NONCE key contains a cryptographically secure nonce (number used once) that you
+must generate. The Google Play application returns this nonce with the
+PURCHASE_STATE_CHANGED broadcast intent so you can verify the integrity of the
+transaction information. The NOTIFY_IDS key contains an array of notification IDs,
+which you received in the IN_APP_NOTIFY broadcast intent.
The request returns a synchronous {@link android.os.Bundle} response, which contains two keys:
+RESPONSE_CODE and REQUEST_ID. The RESPONSE_CODE key provides
+you with the status of the request and the REQUEST_ID key provides you with a unique
+request identifier for the request.
A GET_PURCHASE_INFORMATION request also triggers two asynchronous responses
+(broadcast intents). First, the Google Play application sends a RESPONSE_CODE
+broadcast intent, which provides status and error information about the request. Next, if the
+request was successful, the Google Play application sends a PURCHASE_STATE_CHANGED
+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.
To acknowledge that you received transaction information you send a
+CONFIRM_NOTIFICATIONS 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, mService is an instance of the MarketBillingService
+interface.
+/**
+* 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.
+}
+
+The makeRequestBundle() method constructs an initial Bundle, which contains the
+three keys that are required for all requests: BILLING_REQUEST,
+API_VERSION, and PACKAGE_NAME. The additional NOTIFY_IDS key
+is then added to the bundle prior to invoking the sendBillingRequest() method. The
+NOTIFY_IDS key contains an array of notification IDs, which you received in an
+IN_APP_NOTIFY broadcast intent and also used in a GET_PURCHASE_INFORMATION
+request.
The request returns a synchronous {@link android.os.Bundle} response, which contains two keys:
+RESPONSE_CODE and REQUEST_ID. The RESPONSE_CODE key provides
+you with the status of the request and the REQUEST_ID key provides you with a unique
+request identifier for the request.
A CONFIRM_NOTIFICATIONS request triggers a single asynchronous response—a
+RESPONSE_CODE broadcast intent. This broadcast intent provides status and error
+information about the request.
You must send a confirmation when you receive transaction information from Google Play. If you
+don't send a confirmation message, Google Play will continue sending
+IN_APP_NOTIFY messages for the transactions you have not confirmed. Also,
+your application must be able to handle IN_APP_NOTIFY messages that contain multiple
+orders.
In addition, as a best practice, you should not send a CONFIRM_NOTIFICATIONS request
+for a purchased item until you have delivered the item to the user. This way, if your application
+crashes or something else prevents your application from delivering the product, your application
+will still receive an IN_APP_NOTIFY broadcast intent from Google Play indicating
+that you need to deliver the product.
To restore a user's transaction information, you send a RESTORE_TRANSACTIONS
+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, mService is an
+instance of the MarketBillingService interface.
+/**
+* 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.
+}
+
+The makeRequestBundle() method constructs an initial Bundle, which contains the
+three keys that are required for all requests: BILLING_REQUEST,
+API_VERSION, and PACKAGE_NAME. The additional REQUEST_NONCE
+key is then added to the bundle prior to invoking the sendBillingRequest() method. The
+REQUEST_NONCE key contains a cryptographically secure nonce (number used once) that you
+must generate. The Google Play application returns this nonce with the transactions information
+contained in the PURCHASE_STATE_CHANGED broadcast intent so you can verify the
+integrity of the transaction information.
The request returns a synchronous {@link android.os.Bundle} response, which contains two keys:
+RESPONSE_CODE and REQUEST_ID. The RESPONSE_CODE key provides
+you with the status of the request and the REQUEST_ID key provides you with a unique
+request identifier for the request.
A RESTORE_TRANSACTIONS request also triggers two asynchronous responses (broadcast
+intents). First, the Google Play application sends a RESPONSE_CODE broadcast intent,
+which provides status and error information about the request. Next, if the request was successful,
+the Google Play application sends a PURCHASE_STATE_CHANGED 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.
Note: You should use the RESTORE_TRANSACTIONS
+request type only when your application is installed for the first time on a device or when your
+application has been removed from a device and reinstalled.
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 Google Play 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 Security and Design.
The Google Play 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:
+ +This broadcast intent contains a Google Play 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 Google Play Response + Codes for In-app Billing.
+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 In-app Billing + Broadcast Intents
+This broadcast intent contains detailed information about one or more transactions. For more + information about purchase state messages, see In-app Billing + Broadcast Intents
+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).
+ +Table 1. Description of broadcast intent extras that are +sent in response to billing requests.
+ +| Intent | +Extra | +Description | +
|---|---|---|
com.android.vending.billing.RESPONSE_CODE |
+ request_id |
+ A long representing a request ID. A request ID identifies a specific billing
+ request and is returned by Google Play at the time a request is made. |
+
com.android.vending.billing.RESPONSE_CODE |
+ response_code |
+ An int representing the actual Google Play server response code. |
+
com.android.vending.billing.IN_APP_NOTIFY |
+ notification_id |
+ A String representing the notification ID for a given purchase state change.
+ Google Play 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 GET_PURCHASE_INFORMATION request. |
+
com.android.vending.billing.PURCHASE_STATE_CHANGED |
+ inapp_signed_data |
+ A String 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. |
+
com.android.vending.billing.PURCHASE_STATE_CHANGED |
+ inapp_signature |
+ A String representing the signature of the JSON string. |
+
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
+BillingReceiver, just as it is in the sample application.
+public class BillingReceiver extends BroadcastReceiver {
+
+ private static final String TAG = "BillingReceiver";
+
+ // Intent actions that we receive in the BillingReceiver from Google Play.
+ // These are defined by Google Play 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 Google Play.
+ // These are defined by Google Play 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";
+
+
+ @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.
+}
+
+
+In addition to receiving broadcast intents from the Google Play 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 Security and Design .
Google Play's in-app billing service uses two mechanisms to help verify the integrity of the
+transaction information you receive from Google Play: nonces and signatures. A nonce (number used
+once) is a cryptographically secure number that your application generates and sends with every
+GET_PURCHASE_INFORMATION and RESTORE_TRANSACTIONS request. The nonce is
+returned with the PURCHASE_STATE_CHANGED broadcast intent, enabling you to verify that
+any given PURCHASE_STATE_CHANGED response corresponds to an actual request that you
+made. Every PURCHASE_STATE_CHANGED broadcast intent also includes a signed JSON string
+and a signature, which you can use to verify the integrity of the response.
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.
+ +
+ private static final SecureRandom RANDOM = new SecureRandom();
+ private static HashSet<Long> sKnownNonces = new HashSet<Long>();
+
+ 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);
+ }
+
+
+Your application must also provide a way to verify the signatures that accompany every
+PURCHASE_STATE_CHANGED 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 Security and Design and
+obfuscate your code.
You will need to use your Google Play public key to perform the signature verification. The +following procedure shows you how to retrieve Base64-encoded public key from the Google Play +publisher site.
+ +Important: 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.
+ +
++ Figure 2. The Licensing and In-app Billing panel of your account's Edit Profile + page lets you see your public key. +
+ +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:
+ +The sample code in Dungeons.java shows you how to do both of these tasks.
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 Security and +Design.
+ +Note: If you store any purchase information on a device, be sure to
+encrypt the data and use a device-specific encryption key. Also, if the purchase type for any of
+your items is "unmanaged," we recommend that you back up the purchase information for these items to
+a remote server or use Android's data
+backup framework to back up the purchase information. Backing up purchase information for
+unmanaged items is important because unmanaged items cannot be restored by using the
+RESTORE_TRANSACTIONS request type.
You must provide users with a means for selecting items that they want to purchase. Google
+Play 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
+sendBillingRequest() method when a user selects an item for purchase.
You can render the control and trigger the sendBillingRequest() 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 Dungeons.java). The user interface also shows a list of
+recently purchased items.
In-app Billing is a Google Play service that provides checkout processing for +in-app purchases. To use the service, your application sends a billing request 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 Google Play's in-app billing +service.
+ +In-app Billing supports different product types and purchase types to give you flexibility in how you monetize your app. In all cases, you define your products using the Google Play Developer Console, including product type, purchase type, SKU, price, description, and so on. For more information, see Administering In-app Billing.
+ +With In-app Billing, you can sell two types of products — in-app products and subscriptions. The billing characteristics of the two types are very different, but the In-app Billing API lets you handle the two product types in your app using the same communication model, data structures, and user interactions, as described later in this document.
+ +In-app products can be sold using either the "managed per user account" or "unmanaged" purchase type. In-app products are always explicitly associated with one and only one app. That is, one app cannot purchase an in-app product published for another app, even if they are from the same developer. In-app products are supported in all versions of In-app Billing.
Subscriptions can only be sold using the "managed per user account" purchase type. As with in-app products, once the user has purchased an in-app product there is no refund window. Users desiring refunds must contact the developer directly. For more information about subscriptions and how to sell them in your apps, see the Subscriptions document.
In-app Billing offers two purchase types that you can use when selling in-app products, "managed per user account" and "unmanaged". The purchase type controls how Google Play handles and tracks purchases for the products.
+ +The "managed per 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.
+ +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.
Your app accesses the In-app Billing service using an API that is exposed by +the Google Play app installed on the device. The Google Play app then uses an +asynchronous message loop to convey billing requests and responses between your +application and the Google Play server. In practice, your application never +directly communicates with the Google Play server (see figure 1). Instead, your +application sends billing requests to the Google Play application over +interprocess communication (IPC) and receives purchase responses from the Google +Play application in the form of asynchronous broadcast intents. Your application +does not manage any network connections between itself and the Google Play +server or use any special APIs from the Android platform.
+ +
++ Figure 1. Your application sends and receives billing messages through the + Google Play application, which handles all communication with the Google Play server.
+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.
+ +A typical in-app billing implementation relies on three components:
+BillingService in the sample application),
+ which processes purchase messages from the application and sends billing requests to the Google
+ Play in-app billing service.BillingReceiver in the sample
+ application), which receives all asynchronous billing responses from the Google Play
+ application.Security 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 Security controls later in this
+ document.You may also want to incorporate two other components to support in-app billing:
+ResponseHandler in the sample
+ application), which provides application-specific processing of purchase notifications, errors,
+ and other status messages.PurchaseObserver 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.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 Google +Play application presents the checkout user interface to your user. When the user completes the +checkout process, your application resumes.
+ +When the user initiates a purchase, your application sends billing messages to Google Play's
+in-app billing service (named MarketBillingService) using simple IPC method calls. The
+Google Play application responds to all billing requests synchronously, providing your
+application with status notifications and other information. The Google Play 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 Google Play application.
Your application sends in-app billing requests by invoking a single IPC method
+(sendBillingRequest()), which is exposed by the MarketBillingService
+interface. This interface is defined in an Android Interface Definition Language file
+(IMarketBillingService.aidl). You can download this AIDL
+file with the in-app billing sample application.
The sendBillingRequest() 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
+its type, and the application that is making the request. For more information about the Bundle keys
+that are sent with a request, see In-app Billing
+Service Interface.
+
+
One of the most important keys that every request Bundle must have is the
+BILLING_REQUEST key. This key lets you specify the type of billing request you are
+making. Google Play's in-app billing service supports the following five types of billing
+requests:
CHECK_BILLING_SUPPORTED
+ This request verifies that the Google Play 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.
+REQUEST_PURCHASE
+ This request sends a purchase message to the Google Play 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. Google Play then handles the financial transaction by displaying + the checkout user interface.
+GET_PURCHASE_INFORMATION
+ 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. Google Play notifies your + application when a purchase changes state, so you only need to send this request when there is + transaction information to retrieve.
+CONFIRM_NOTIFICATIONS
+ This request acknowledges that your application received the details of a purchase state + change. Google Play sends purchase state change notifications to your application until you + confirm that you received them.
+RESTORE_TRANSACTIONS
+ This request retrieves a user's transaction status for managed + purchases and subscriptions. + 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.
+The Google Play 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:
+ +RESPONSE_CODE
+ This key provides status information and error information about a request.
+PURCHASE_INTENT
+ This key provides a {@link android.app.PendingIntent}, which you use to launch the checkout + activity.
+REQUEST_ID
+ This key provides you with a request identifier, which you can use to match asynchronous + responses with requests.
+Some of these keys are not relevant to every request. For more information, see Messaging sequence later in this document.
+ +The asynchronous response messages are sent in the form of individual broadcast intents and +include the following:
+ +com.android.vending.billing.RESPONSE_CODE
+ This response contains a Google Play 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 Google Play or it can indicate that some error occurred during a billing + request. This response 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 Server Response Codes + for In-app Billing.
+com.android.vending.billing.IN_APP_NOTIFY
+ 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
+ IN_APP_NOTIFY broadcast intent, you send a GET_PURCHASE_INFORMATION
+ request with the notification IDs to retrieve message details.
com.android.vending.billing.PURCHASE_STATE_CHANGED
+ 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.
+The JSON string that is returned with the PURCHASE_STATE_CHANGED intent provides
+your application with the details of one or more billing transactions. An example of this JSON
+string for a subscription item is shown below:
{ "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,
+ "purchaseToken" : "rojeslcdyyiapnqcynkjyyjh" }]
+}
+
+
+For more information about the fields in this JSON string, see In-app Billing +Broadcast Intents.
+ +The messaging sequence for a typical purchase request is shown in figure 2. Request types for
+each sendBillingRequest() method are shown in bold, broadcast intents
+are shown in italic. For clarity, figure 2 does not show the RESPONSE_CODE
+broadcast intents that are sent for every request.
The basic message sequence for an in-app purchase request is as follows:
+ +REQUEST_PURCHASE type), specifying a
+ product ID and other parameters.RESPONSE_CODE, PURCHASE_INTENT, and REQUEST_ID. The
+ PURCHASE_INTENT key provides a {@link android.app.PendingIntent}, which your
+ application uses to start the checkout UI for the given product ID.Note: You must launch the pending intent from an activity + context and not an application context.
+IN_APP_NOTIFY broadcast intent). The notification message includes a notification ID,
+ which references the transaction.GET_PURCHASE_STATE_CHANGED request, specifying the notification ID for the
+ transaction.RESPONSE_CODE key and a
+ REQUEST_ID key.
+ PURCHASE_STATE_CHANGED broadcast intent.CONFIRM_NOTIFICATIONS type),
+ specifying the notification ID for which you received transaction information.RESPONSE_CODE key and a REQUEST_ID key.
++ Figure 2. Message sequence for a purchase request. +
+ +Keep in mind, you must send a confirmation when you receive transaction information from Google
+Play (step 8 in figure 2). If you don't send a confirmation message, Google Play will
+continue sending IN_APP_NOTIFY messages for the transactions you have not
+confirmed. As a best practice, you should not send a CONFIRM_NOTIFICATIONS request for
+a purchased item until you have delivered the item to the user. This way, if your application
+crashes or something else prevents your application from delivering the product, your application
+will still receive an IN_APP_NOTIFY broadcast intent from Google Play indicating
+that you need to deliver the product. Also, as a best practice, your application must be able to
+handle IN_APP_NOTIFY messages that contain multiple orders.
The messaging sequence for a restore transaction request is shown in figure 3. Request types for
+each sendBillingRequest() method are shown in bold, broadcast intents
+are shown in italic. For clarity, figure 3 does not show the RESPONSE_CODE
+broadcast intents that are sent for every request.
++ Figure 3. Message sequence for a restore transactions request. +
+The request triggers three responses. The first is a {@link android.os.Bundle} with a
+RESPONSE_CODE key and a REQUEST_ID key. Next, the Google Play
+application sends a RESPONSE_CODE broadcast intent, which provides status information
+or error information about the request. As always, the RESPONSE_CODE message references
+a specific request ID, so you can determine which request a RESPONSE_CODE message
+pertains to.
The RESTORE_TRANSACTIONS request type also triggers a
+PURCHASE_STATE_CHANGED 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 CONFIRM_NOTIFICATIONS message.
Note: You should use the RESTORE_TRANSACTIONS request
+type only when your application is installed for the first time on a device or when your
+application has been removed from a device and reinstalled.
The messaging sequence for checking whether in-app billing is supported is shown in figure 4. The
+request type for the sendBillingRequest() method is shown in bold.
++ Figure 4. Message sequence for checking whether in-app billing is supported. +
+The synchronous response for a CHECK_BILLING_SUPPORTED request provides a Bundle
+with a server response code. A RESULT_OK response code indicates that in-app billing
+is supported; a RESULT_BILLING_UNAVAILABLE response code indicates that in-app billing
+is unavailable because the API version you specified is unrecognized or the user is not eligible to
+make in-app purchases (for example, the user resides in a country that does not allow in-app
+billing). A SERVER_ERROR can also be returned, indicating that there was a problem with
+the Google Play server.
Usually, your application receives an IN_APP_NOTIFY broadcast intent from Google
+Play in response to a REQUEST_PURCHASE message (see figure 2). The
+IN_APP_NOTIFY broadcast intent informs your application that the state of a requested
+purchase has changed. To retrieve the details of that purchase, your application sends a
+GET_PURCHASE_INFORMATION request. Google Play responds with a
+PURCHASE_STATE_CHANGED broadcast intent, which contains the details of the purchase
+state change. Your application then sends a CONFIRM_NOTIFICATIONS message, informing
+Google Play that you have received the purchase state change information.
In some special cases, you may receive multiple IN_APP_NOTIFY messages even though
+you have confirmed receipt of the purchase information, or you may receive
+IN_APP_NOTIFY messages for a purchase change even though you never initiated the
+purchase. Your application must handle both of these special cases.
When Google Play receives a CONFIRM_NOTIFICATIONS message for a given
+PURCHASE_STATE_CHANGED message, it usually stops sending IN_APP_NOTIFY
+intents for that PURCHASE_STATE_CHANGED message. Sometimes, however, Google
+Play may send repeated IN_APP_NOTIFY intents for a
+PURCHASE_STATE_CHANGED message even though your application has sent a
+CONFIRM_NOTIFICATIONS message. This can occur if a device loses network connectivity
+while you are sending the CONFIRM_NOTIFICATIONS message. In this case, Google Play
+might not receive your CONFIRM_NOTIFICATIONS message and it could send multiple
+IN_APP_NOTIFY messages until it receives acknowledgement that you received the
+transaction message. Therefore, your application must be able to recognize that the subsequent
+IN_APP_NOTIFY messages are for a previously processed transaction. You can do this by
+checking the orderID that's contained in the JSON string because every transaction has
+a unique orderId.
There are two cases where your application may receive IN_APP_NOTIFY broadcast
+intents even though your application has not sent a REQUEST_PURCHASE message. Figure 5
+shows the messaging sequence for both of these cases. Request types for each
+sendBillingRequest() method are shown in bold, broadcast intents are
+shown in italic. For clarity, figure 5 does not show the RESPONSE_CODE
+broadcast intents that are sent for every request.
++ Figure 5. Message sequence for refunds and other unsolicited +IN_APP_NOTIFY messages.
+In the first case, your application may receive an IN_APP_NOTIFY broadcast intent
+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, Google Play sends an IN_APP_NOTIFY
+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 REQUEST_PURCHASE message, so that ultimately your application
+receives a PURCHASE_STATE_CHANGED broadcast intent message that includes information
+about the item that has been purchased. This applies only to items that have their purchase type set
+to "managed per user account."
In the second case, your application can receive an IN_APP_NOTIFY broadcast intent
+when Google Play receives a refund notification from Google Wallet. In this case, Google
+Play sends an IN_APP_NOTIFY message to your application. Your application can handle
+this message the same way it handles responses from an application-initiated
+REQUEST_PURCHASE message so that ultimately your application receives a
+PURCHASE_STATE_CHANGED message that includes information about the item that has been
+refunded. The refund information is included in the JSON string that accompanies the
+PURCHASE_STATE_CHANGED broadcast intent. Also, the purchaseState field in
+the JSON string is set to 2.
Important: You cannot use the Google Wallet API to +issue refunds or cancel in-app billing transactions. You must do this manually through your +Google Wallet merchant account. However, you can use the Google Wallet API to retrieve order +information.
+ +To help ensure the integrity of the transaction information that is sent to your application,
+Google Play signs the JSON string that is contained in the PURCHASE_STATE_CHANGED
+broadcast intent. Google Play 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 Google Play licensing.
When Google Play 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.
+ +In-app billing also uses nonces (a random number used once) to help verify the integrity of the
+purchase information that's returned from Google Play. Your application must generate a nonce and
+send it with a GET_PURCHASE_INFORMATION request and a RESTORE_TRANSACTIONS
+request. When Google Play 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.
For more information about best practices for security and design, see Security and Design.
+ +Before you get started with in-app billing, be sure to review the following requirements and +limitations.
+ +For more information about in-app billing requirements, see In-App +Billing Availability and Policies.
diff --git a/docs/html/guide/google/play/billing/billing_reference.jd b/docs/html/guide/google/play/billing/billing_reference.jd new file mode 100755 index 000000000000..f8c69678bb50 --- /dev/null +++ b/docs/html/guide/google/play/billing/billing_reference.jd @@ -0,0 +1,491 @@ +page.title=In-app Billing Reference +parent.title=In-app Billing +parent.link=index.html +@jd:body + +The following document provides technical reference information for the following:
+ +The following table lists all of the server response codes that are sent from Google Play to
+your application. Google Play sends these response codes asynchronously as
+response_code extras in the com.android.vending.billing.RESPONSE_CODE
+broadcast intent. Your application must handle all of these response codes.
Table 1. Summary of response +codes returned by Google Play.
+ +| Response Code | +Value | +Description | +
|---|---|---|
RESULT_OK |
+ 0 | +Indicates that the request was sent to the server successfully. When this code is returned in
+ response to a CHECK_BILLING_SUPPORTED request, indicates that billing is
+ supported. |
+
RESULT_USER_CANCELED |
+ 1 | +Indicates that the user pressed the back button on the checkout page instead of buying the + item. | +
RESULT_SERVICE_UNAVAILABLE |
+ 2 | +Indicates that the network connection is down. | +
RESULT_BILLING_UNAVAILABLE |
+ 3 | +Indicates that in-app billing is not available because the API_VERSION that you
+ specified is not recognized by the Google Play application or the user is ineligible for in-app
+ billing (for example, the user resides in a country that prohibits in-app purchases). |
+
RESULT_ITEM_UNAVAILABLE |
+ 4 | +Indicates that Google Play cannot find the requested item in the application's product
+ list. This can happen if the product ID is misspelled in your REQUEST_PURCHASE
+ request or if an item is unpublished in the application's product list. |
+
RESULT_DEVELOPER_ERROR |
+ 5 | +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. | +
RESULT_ERROR |
+ 6 | +Indicates an unexpected server error. For example, this error is triggered if you try to +purchase an item from yourself, which is not allowed by Google Wallet. | +
The following section describes the interface for Google Play's in-app billing service. The
+interface is defined in the IMarketBillingService.aidl file, which is included with the
+in-app billing sample
+application.
The interface consists of a single request method sendBillingRequest(). This method
+takes a single {@link android.os.Bundle} parameter. The Bundle parameter includes several key-value
+pairs, which are summarized in table 2.
Table 2. Description of Bundle keys passed in a
+sendBillingRequest() request.
| Key | +Type | +Possible Values | +Required? | +Description | +
|---|---|---|---|---|
BILLING_REQUEST |
+ String |
+ CHECK_BILLING_SUPPORTED, REQUEST_PURCHASE,
+ GET_PURCHASE_INFORMATION, CONFIRM_NOTIFICATIONS, or
+ RESTORE_TRANSACTIONS |
+ Yes | +The type of billing request you are making with the sendBillingRequest() request.
+ The possible values are discussed more below this table. |
+
API_VERSION |
+ int |
+ + | Yes | +The version of Google Play's in-app billing service you want to use. The current version is + 2. | +
PACKAGE_NAME |
+ String |
+ A valid package name. | +Yes | +The name of the application that is making the request. | +
ITEM_ID |
+ String |
+ Any valid product identifier. | +Required for REQUEST_PURCHASE requests. |
+ The product ID of the item you are making a billing request for. Every in-app item that you + sell using Google Play's in-app billing service must have a unique product ID, which you + specify on the Google Play publisher site. | +
NONCE |
+ long |
+ Any valid long value. |
+ Required for GET_PURCHASE_INFORMATION and RESTORE_TRANSACTIONS
+ requests. |
+ A number used once. Your application must generate and send a nonce with each
+ GET_PURCHASE_INFORMATION and RESTORE_TRANSACTIONS request. The nonce is
+ returned with the PURCHASE_STATE_CHANGED broadcast intent, so you can use this value
+ to verify the integrity of transaction responses form Google Play. |
+
NOTIFY_IDS |
+ Array of long values |
+ Any valid array of long values |
+ Required for GET_PURCHASE_INFORMATION and CONFIRM_NOTIFICATIONS
+ requests. |
+ An array of notification identifiers. A notification ID is sent to your application in an
+ IN_APP_NOTIFY broadcast intent every time a purchase changes state. You use the
+ notification to retrieve the details of the purchase state change. |
+
DEVELOPER_PAYLOAD |
+ String |
+ Any valid String less than 256 characters long. |
+ No | +A developer-specified string that can be specified when you make a
+ REQUEST_PURCHASE request. This field is returned in the JSON string that contains
+ transaction information for an order. You can use this key to send supplemental information with
+ an order. For example, you can use this key 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 key
+ to send data or content. |
+
The BILLING_REQUEST key can have the following values:
CHECK_BILLING_SUPPORTED
+ This request verifies that the Google Play 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.
+REQUEST_PURCHASE
+ This request sends a purchase message to the Google Play 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. Google Play then handles the financial transaction by displaying + the checkout user interface.
+GET_PURCHASE_INFORMATION
+ 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. Google Play notifies your + application when a purchase changes state, so you only need to send this request when there is + transaction information to retrieve.
+CONFIRM_NOTIFICATIONS
+ This request acknowledges that your application received the details of a purchase state
+ change. That is, this message confirms that you sent a GET_PURCHASE_INFORMATION
+ request for a given notification and that you received the purchase information for the
+ notification.
RESTORE_TRANSACTIONS
+ This request retrieves a user's transaction status for managed purchases (see Choosing a + Purchase Type 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.
+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:
+ +RESPONSE_CODE
+ This key provides status information and error information about a request.
+PURCHASE_INTENT
+ This key provides a {@link android.app.PendingIntent}, which you use to launch the checkout + activity.
+REQUEST_ID
+ This key provides you with a request identifier, which you can use to match asynchronous + responses with requests.
+Some of these keys are not relevant to certain types of requests. Table 3 shows which keys are +returned for each request type.
+ +Table 3. Description of Bundle keys that are returned with +each in-app billing request type.
+ +| Request Type | +Keys Returned | +Possible Response Codes | +
|---|---|---|
CHECK_BILLING_SUPPORTED |
+ RESPONSE_CODE |
+ RESULT_OK, RESULT_BILLING_UNAVAILABLE, RESULT_ERROR,
+ RESULT_DEVELOPER_ERROR |
+
REQUEST_PURCHASE |
+ RESPONSE_CODE, PURCHASE_INTENT, REQUEST_ID |
+ RESULT_OK, RESULT_ERROR, RESULT_DEVELOPER_ERROR |
+
GET_PURCHASE_INFORMATION |
+ RESPONSE_CODE, REQUEST_ID |
+ RESULT_OK, RESULT_ERROR, RESULT_DEVELOPER_ERROR |
+
CONFIRM_NOTIFICATIONS |
+ RESPONSE_CODE, REQUEST_ID |
+ RESULT_OK, RESULT_ERROR, RESULT_DEVELOPER_ERROR |
+
RESTORE_TRANSACTIONS |
+ RESPONSE_CODE, REQUEST_ID |
+ RESULT_OK, RESULT_ERROR, RESULT_DEVELOPER_ERROR |
+
The following section describes the in-app billing broadcast intents that are sent by the Google
+Play 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 BillingReceiver that's shown in the in-app
+billing sample
+application.
This broadcast intent contains a Google Play 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 Google Play 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 Google Play Response Codes for In-app Billing. The sample application
+assigns this broadcast intent to a constant named ACTION_RESPONSE_CODE.
request_id—a long representing a request ID. A request ID
+ identifies a specific billing request and is returned by Google Play at the time a request is
+ made.response_code—an int representing the Google Play server
+ response code.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 IN_APP_NOTIFY broadcast intent,
+you send a GET_PURCHASE_INFORMATION request with the notification IDs to retrieve the
+message details. The sample application assigns this broadcast intent to a constant named
+ACTION_NOTIFY.
notification_id—a String representing the notification ID for
+ a given purchase state change. Google Play 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 GET_PURCHASE_INFORMATION request.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. The
+sample application assigns this broadcast intent to a constant named
+ACTION_PURCHASE_STATE_CHANGED.
inapp_signed_data—a String representing the signed JSON
+ string.inapp_signature—a String representing the signature.Note: Your application should map the broadcast intents and extras
+to constants that are unique to your application. See the Consts.java file in the
+sample application to see how this is done.
The fields in the JSON string are described in the following table (see table 4):
+ +Table 4. Description of JSON fields that are returned with
+a PURCHASE_STATE_CHANGED intent.
| Field | +Description | +
|---|---|
| nonce | +A number used once. Your application generates the nonce and sends it with the
+ GET_PURCHASE_INFORMATION request. Google Play sends the nonce back as part of the
+ JSON string so you can verify the integrity of the message. |
+
| notificationId | +A unique identifier that is sent with an IN_APP_NOTIFY broadcast intent. Each
+ notificationId corresponds to a specify message that is waiting to be retrieved on
+ the Google Play server. Your application sends back the notificationId with the
+ GET_PURCHASE_INFORMATION message so Google Play can determine which messages you
+ are retrieving. |
+
| orderId | +A unique order identifier for the transaction. This corresponds to the Google Wallet Order + ID. | +
| packageName | +The application package from which the purchase originated. | +
| productId | +The item's product identifier. Every item has a product ID, which you must specify in the + application's product list on the Google Play publisher site. | +
| purchaseTime | +The time the product was purchased, in milliseconds since the epoch (Jan 1, 1970). | +
| purchaseState | +The purchase state of the order. Possible values are 0 (purchased), 1 (canceled), 2 + (refunded), or 3 (expired, for subscription purchases only). | +
| purchaseToken | +A token that uniquely identifies a subscription purchase for a given item and user pair.
+ You can use the token to specify the subscription when querying for subscription validity.
+
+
|
+
| developerPayload | +A developer-specified string that contains supplemental information about an order. You can
+ specify a value for this field when you make a REQUEST_PURCHASE request. |
+
Google Play offers an HTTP-based API that you can use to remotely query the +validity of a specific subscription at any time or cancel a subscription. The +API is designed to be used from your backend servers as a way of securely +managing subscriptions, as well as extending and integrating subscriptions with +other services. See +Google Play Android Developer API for more information.
+ +The In-app Billing API is versioned, with each version offering +additional features to your app. At run time, your app can query the Google Play app to determine +what version of the API it supports and what features are available. Typically, the Google Play app +will be updated and will support the latest version of the API. For a summary of versions see +In-app Billing +API Versions.
+ +The sections below list the supported versions of the In-app Billing API.
+Versions are specified in the API_VERSION key of the Bundle object
+passed in the sendBillingRequest(), which is defined in the defined
+in the IMarketBillingService.aidl file, which is included with the
+in-app billing
+sample application. For more information, see In-app Billing Service Interface.
May 2012
+ +API_VERSION key
+ of the Bundle object passed in the sendBillingRequest().purchaseToken, to the
+ orders list returned in a PURCHASE_STATE_CHANGED
+ intent. purchaseState value, 3 (expired), to the
+ orders list returned in a PURCHASE_STATE_CHANGED
+ intent. The value indicates that a subscription has expired and is no longer valid.March 2011
+ +Subscriptions let you sell content, services, or features in your app with +automated, recurring billing. Adding support for subscriptions is +straightforward and you can easily adapt an existing In-app Billing +implementation to sell subscriptions.
+ +If you have already implemented In-app Billing for one-time purchase +products, you will find that you can add support for subscriptions with minimal +impact on your code. If you are new to In-app Billing, you can implement +subscriptions using the standard communication model, data structures, and user +interactions as for other in-app products.subscriptions. Because the +implementation of subscriptions follows the same path as for other in-app +products, details are provided outside of this document, starting with the In-app Billing +Overview.
+ +This document is focused on highlighting implementation details that are +specific to subscriptions, along with some strategies for the associated billing +and business models.
+ +A subscription is a new product type offered in In-app Billing that lets you +sell content, services, or features to users from inside your app with recurring +monthly or annual billing. You can sell subscriptions to almost any type of +digital content, from any type of app or game.
+ +As with other in-app products, you configure and publish subscriptions using +the Developer Console and then sell them from inside apps installed on an +Android-powered devices. In the Developer console, you create subscription +products and add them to a product list, setting a price for each, choosing a +billing interval of monthly or annually, and then publishing. In your apps, it’s +straightforward to add support for subscription purchases. The implementation +extends the standard In-app Billing API to support a new product type but uses +the same communication model, data structures, and user interactions as for +other in-app products.
+ +When users purchase subscriptions in your apps, Google Play handles all +checkout details so your apps never have to directly process any financial +transactions. Google Play processes all payments for subscriptions through +Google Wallet, just as it does for standard in-app products and app purchases. +This ensures a consistent and familiar purchase flow for your users.
+ +
+
+
+After users have purchase subscriptions, they can view the subscriptions and +cancel them, if necessary, from the My Apps screen in the Play Store app or +from the app's product details page in the Play Store app.
+ + + +Once users have purchased a subscription through In-app Billing, you can +easily give them extended access to additional content on your web site (or +other service) through the use of a server-side API provided for In-app Billing. +The server-side API lets you validate the status of a subscription when users +sign into your other services. For more information about the API, see Google Play Android Developer API, below.
+ +You can also build on your existing external subscriber base from inside your +Android apps. If you sell subscriptions on a web site, for example, you can add +your own business logic to your Android app to determine whether the user has +already purchased a subscription elsewhere, then allow access to your content if +so or offer a subscription purchase from Google Play if not.
+ +With the flexibility of In-app Billing, you can even implement your own +solution for sharing subscriptions across as many different apps or products as +you want. For example, you could sell a subscription that gives a subscriber +access to an entire collection of apps, games, or other content for a monthly or +annual fee. To implement this solution, you could add your own business logic to +your app to determine whether the user has already purchased a given +subscription and if so, allow access to your content.
+ +In general the same basic policies and terms apply to subscriptions as to +standard in-app products, however there are some differences. For complete +information about the current policies and terms, please read the policies document.
+ + +To sell a subscription in an app, you use the tools in the Developer Console +to set up a product list for the app and then create and configure a new +subscription. In the subscription, you set the price and billing interval and +define a subscription ID, title, and description. When you are ready, you can +then publish the subscription in the app product list.
+ +In the product list, you can add subscriptions, in-app products, or both. You +can add multiple subscriptions that give access to different content or +services, or you can add multiple subscriptions that give access to the same +content but for different intervals or different prices, such as for a +promotion. For example, a news outlet might decide to offer both monthly and +annual subscriptions to the same content, with annual having a discount. You can +also offer in-app purchase equivalents for subscription products, to ensure that +your content is available to users of older devices that do not support +subscriptions.
+ +After you add a subscription or in-app product to the product list, you must +publish the product before Google Play can make it available for purchase. Note +that you must also publish the app itself before Google Play will make the +products available for purchase inside the app.
+ +Important: At this time, the capability to +unpublish a subscription is not available. Support for unpublishing a +subscription is coming to the Developer Console in the weeks ahead, so this is a +temporary limitation. In the short term, instead of unpublishing, +you can remove the subscription product from the product list offered in your +app to prevent users from seeing or purchasing it.
+ +When you create a subscription in the Developer Console, you can set a price +for it in any available currencies. Each subscription must have a non-zero +price. You can price multiple subscriptions for the same content differently +— for example you could offer a discount on an annual subscription +relative to the monthly equivalent.
+ +Important: At this time, once you publish a +subscription product, you cannot change its price in any currency. Support for +changing the price of published subscriptions is coming to the Developer Console +in the weeks ahead. In the short term, you can work around this limitation by +publishing a new subscription product ID at a new price, then offer it in your +app instead of the original product. Users who have already purchased will +continue to be charged at the original price, but new users will be charged at +the new price.
+ +You can sell subscription products with automated recurring billing at +either of two intervals:
+ +Billing continues indefinitely at the interval and price specified for the +subscription. At each subscription renewal, Google Play charges the user account +automatically, then notifies the user of the charges afterward by email. Billing +cycles will always match subscription cycles, based on the purchase date.
+ +Over the life of a subscription, the form of payment billed remains the same +— Google Play always bills the same form of payment (such as credit card, +Direct Carrier Billing) that was originally used to purchase the +subscription.
+ +When the subscription payment is approved by Google Wallet, Google Play +provides a purchase token back to the purchasing app through the In-app Billing +API. For details, see Purchase token, below. Your apps can +store the token locally or pass it to your backend servers, which can then use +it to validate or cancel the subscription remotely using the Google Play Android Developer API.
+ +In the case of billing errors, such as could happen if the customer’s credit +card becomes invalid, Google Play notifies your app of the change in purchase +state.
+ +As a best practice, we recommend that your app includes business logic to +notify your backend servers of subscription purchases, tokens, and any billing +errors that may occur. Your backend servers can use the server-side API to query +and update your records and follow up with customers directly, if needed.
+ +Users can view the status of all of their subscriptions and cancel them if +necessary from the My Apps screen in the Play Store app. Currently, the In-app +Billing API does not provide support for canceling subscriptions direct from +inside the purchasing app, although your app can broadcast an Intent to launch +the Play Store app directly to the My Apps screen.
+ +When the user cancels a subscription, Google Play does not offer a refund for +the current billing cycle. Instead, it allows the user to have access to the +cancelled subscription until the end of the current billing cycle, at which time +it terminates the subscription. For example, if a user purchases a monthly +subscription and cancels it on the 15th day of the cycle, Google Play will +consider the subscription valid until the end of the 30th day (or other day, +depending on the month).
+ +In some cases, the user may contact you directly to request cancellation of a +subscription. In this and similar cases, you can use the server-side API to +query and directly cancel the user’s subscription from your servers. + +
Important: In all cases, you must continue +to offer the content that your subscribers have purchased through their +subscriptions, for as long any users are able to access it. That is, you must +not remove any subscriber’s content while any user still has an active +subscription to it, even if that subscription will terminate at the end of the +current billing cycle. Removing content that a subscriber is entitled to access +will result in penalties. Please see the policies document for more information.
+ +When the user uninstalls an app that includes purchased subscriptions, the Play Store app will notify the user that there are active subscriptions. If the user chooses to continue with the uninstalltion, the app is removed and the subscriptions remain active and recurring billing continues. The user can return to cancel the associated subscriptions at any time in the My Apps screen of the Play Store app. If the user chooses to cancel the uninstallation, the app and subscriptions remain as they were.
+ +As with other in-app products, Google Play does not provide a refund window +for subscription purchases. For example, users who purchase an app can ask for a +refund from Google Play within a 15-minute window. With subscriptions, Google +Play does not provide a refund window, so users will need to contact you +directly to request a refund. + +
If you receive requests for refunds, you can use the server-side API to +cancel the subscription or verify that it is already cancelled. However, keep in +mind that Google Play considers cancelled subscriptions valid until the end of +their current billing cycles, so even if you grant a refund and cancel the +subscription, the user will still have access to the content. + +
Note: Partial refunds for canceled +subscriptions are not available at this time.
+ +In general, the terms of Google Play allow you to sell in-app subscriptions +only through the standard payment processor, Google Wallet. For purchases of any +subscription products, just as for other in-app products and apps, the +transaction fee for subscriptions, just as for other in-app purchases, is the +same as the transaction fee for application purchases (30%).
+ +Apps published on Google Play that are selling subscriptions must use In-app +Billing to handle the transaction and may not provide links to a purchase flow +outside of the app and Google Play (such as to a web site).
+ +For complete details about terms and policies, see the policies +document.
+ +In-app purchases of subscriptions are supported only on devices that meet +these minimum requirements:
+ +Google Play 3.5 and later versions include support for the In-app Billing +v2 API or higher, which is needed to support handling of subscription +products.
+ +As noted in the previous section, support for subscriptions is available only +on devices that meet the system requirements. Not all devices will receive or +install Google Play 3.5, so not all users who install your apps will have access +to the In-app Billing API and subscriptions.
+ +If you are targeting older devices that run Android 2.1 or earlier, we +recommend that you offer those users an alternative way buy the content that is +available through subscriptions. For example, you could create standard in-app +products (one-time purchases) that give access to similar content as your +subscriptions, possibly for a longer interval such as a year.
+ + +Subscriptions are a standard In-app Billing product type. If you have already +implemented In-app Billing for one-time purchase products, you will find that +adding support for subscriptions is straightforward, with minimal impact on your +code. If you are new to In-app Billing, you can implement subscriptions using +the standard communication model, data structures, and user interactions as for +other in-app products.subscriptions.
+ +The full implementation details for In-app Billing are provided outside of +this document, starting with the In-app Billing +Overview. This document is focused on highlighting implementation details +that are specific to subscriptions, along with some strategies for the +associated billing and business models.
+ + +To help you get started with your In-app Billing implementation and +subscriptions, an updated version of the In-app Billing sample app is available. +You can download the sample app from the Android SDK repository using the +Android SDK Manager. For details, see +Downloading the Sample Application.
+ +With subscriptions, your app uses the standard In-app Billing application +model, sending billing requests to the Play Store application over interprocess +communication (IPC) and receiving purchase responses from the Play Store app in +the form of asynchronous broadcast intents. Your application does not manage any +network connections between itself and the Google Play server or use any special +APIs from the Android platform.
+ +Your app also uses the standard In-app Billing components — a billing +Service for sending requests, a BroadcastReceiver for receiving the responses, +and a security component for verifying that the response was sent by Google +Play. Also recommended are a response Handler for processing notifications, +errors, and status messages, and an observer for sending callbacks to your +application as needed. All of these components and their interactions are +described in full in the In-app Billing +Overview and related documents.
+ +To initiate different types of billing communication with Google Play, your +app will use the standard set of in-app billing requests and receive the same +responses. Inside the requests and responses are two new fields described below. +
+ +Central to the end-to-end architecture for subscriptions is the purchase +token, a string value that uniquely identifies (and associates) a user ID and a +subscription ID. Google Play generates the purchase token when the user +completes the purchase of a subscription product (and payment is approved by +Google Wallet) and then sends it to the purchasing app on the device through the +In-app Billing API.
+ +At the conclusion of a PURCHASE_REQUEST message flow, your app
+can retrieve the purchase token and other transaction details by initiating a
+GET_PURCHASE_INFORMATION request. The Bundle returned by the call
+contains an JSON array of order objects. In the order corresponding to the
+subscription purchase, the token is available in the purchaseToken
+field.
An example of a JSON order object that includes a subscription purchase token +is shown below.
+ +{ "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,
+ "purchaseToken" : "rojeslcdyyiapnqcynkjyyjh" }]
+}
+
+
+After receiving a purchase token, your apps can store the token locally or +pass it to your backend servers, which can then use it to query the billing +status or cancel the subscription remotely. If your app will store the token +locally, please read the Security and +Design document for best practices for maintaining the security of your +data.
+ +Subscriptions support is available only in versions of Google Play that +support the In-app Billing v2 API (Google Play 3.5 and higher). For your app, +an essential first step at launch is to check whether the version of Google Play +installed on the device supports the In-app Billing v2 API and +subscriptions.
+ +To do this, create a CHECK_BILLING_SUPPORTED request Bundle that includes the +required key-value pairs, together with
+ +API_VERSION key, assigning a value of 2.BILLING_REQUEST_ITEM_TYPE key, assigning a value of “subs”Send the request using sendBillingRequest(Bundle) and receive
+the response Bundle. You can extract the response from the
+BILLING_RESPONSE_RESPONSE_CODE key of the response. RESULT_OK
+indicates that subscriptions are supported.
The sample app declares constants for the accepted
+BILLING_REQUEST_ITEM_TYPE values (from Consts.java):
// These are the types supported in the IAB v2 + public static final String ITEM_TYPE_INAPP = "inapp"; + public static final String ITEM_TYPE_SUBSCRIPTION = "subs"; ++ +
It sets up a convenience method for building the request bundle (from BillingService.java):
+ + protected Bundle makeRequestBundle(String method) {
+ Bundle request = new Bundle();
+ request.putString(Consts.BILLING_REQUEST_METHOD, method);
+ request.putInt(Consts.BILLING_REQUEST_API_VERSION, 2);
+ request.putString(Consts.BILLING_REQUEST_PACKAGE_NAME, getPackageName());
+ return request;
+ }
+
+
+Here’s an example of how to test support for In-App Billing v2 and subscriptions +(from BillingService.java):
+ + /**
+ * Wrapper class that checks if in-app billing is supported.
+ */
+ class CheckBillingSupported extends BillingRequest {
+ public String mProductType = null;
+ public CheckBillingSupported() {
+ // This object is never created as a side effect of starting this
+ // service so we pass -1 as the startId to indicate that we should
+ // not stop this service after executing this request.
+ super(-1);
+ }
+
+ public CheckBillingSupported(String type) {
+ super(-1);
+ mProductType = type;
+ }
+
+ @Override
+ protected long run() throws RemoteException {
+ Bundle request = makeRequestBundle("CHECK_BILLING_SUPPORTED");
+ if (mProductType != null) {
+ request.putString(Consts.BILLING_REQUEST_ITEM_TYPE, mProductType);
+ }
+ Bundle response = mService.sendBillingRequest(request);
+ int responseCode = response.getInt(Consts.BILLING_RESPONSE_RESPONSE_CODE);
+ if (Consts.DEBUG) {
+ Log.i(TAG, "CheckBillingSupported response code: " +
+ ResponseCode.valueOf(responseCode));
+ }
+ boolean billingSupported = (responseCode == ResponseCode.RESULT_OK.ordinal());
+ ResponseHandler.checkBillingSupportedResponse(billingSupported, mProductType);
+ return Consts.BILLING_RESPONSE_INVALID_REQUEST_ID;
+ }
+ }
+
+
+Once you’ve checked the API version as described above and determined that +subscriptions are supported, you can present subscription products to the user +for purchase. When the user has selected a subscription product and initiated a +purchase, your app handles the purchase just as it would for other in-app +products — by sending a REQUEST_PURCHASE request. You can then launch +Google Play to display the checkout user interface and handle the financial +transaction.. + +
The REQUEST_PURCHASE includes a Bundle containing the item details, as +described in the In-app Billing +Overview. For a subscription, the Bundle must also specify:
+ +ITEM_ID key, with a value that specifies a valid, published
+ subscription product.ITEM_TYPE key, with a value of “subs”
+ (ITEM_TYPE_SUBSCRIPTION in the sample app). If the request does not
+ specify the subscription's ITEM_TYPE, Google Play attempts to
+ handle the request as a standard in-app purchase (one-time purchase).Google Play synchronously returns a response bundle that includes
+RESPONSE_CODE, PURCHASE_INTENT, and
+REQUEST_ID. Your app uses the PURCHASE_INTENT to
+launch the checkout UI and the message flow proceeds exactly as described in Messaging sequence.
Here’s how the sample app initiates a purchase for a subscription, where
+mProductType is ITEM_TYPE_SUBSCRIPTION (from
+BillingService.java).
/**
+ * Wrapper class that requests a purchase.
+ */
+ class RequestPurchase extends BillingRequest {
+ public final String mProductId;
+ public final String mDeveloperPayload;
+ public final String mProductType;
+
+. . .
+
+ @Override
+ protected long run() throws RemoteException {
+ Bundle request = makeRequestBundle("REQUEST_PURCHASE");
+ request.putString(Consts.BILLING_REQUEST_ITEM_ID, mProductId);
+ request.putString(Consts.BILLING_REQUEST_ITEM_TYPE, mProductType);
+ // Note that the developer payload is optional.
+ if (mDeveloperPayload != null) {
+ request.putString(Consts.BILLING_REQUEST_DEVELOPER_PAYLOAD, mDeveloperPayload);
+ }
+ Bundle response = mService.sendBillingRequest(request);
+ PendingIntent pendingIntent
+ = response.getParcelable(Consts.BILLING_RESPONSE_PURCHASE_INTENT);
+ if (pendingIntent == null) {
+ Log.e(TAG, "Error with requestPurchase");
+ return Consts.BILLING_RESPONSE_INVALID_REQUEST_ID;
+ }
+
+ Intent intent = new Intent();
+ ResponseHandler.buyPageIntentResponse(pendingIntent, intent);
+ return response.getLong(Consts.BILLING_RESPONSE_REQUEST_ID,
+ Consts.BILLING_RESPONSE_INVALID_REQUEST_ID);
+ }
+
+ @Override
+ protected void responseCodeReceived(ResponseCode responseCode) {
+ ResponseHandler.responseCodeReceived(BillingService.this, this, responseCode);
+ }
+ }
+
+
+Subscriptions always use the managed by user account purchase type, +so that you can restore a record of subscription transactions on the device when +needed. When a user installs your app onto a new device, or when the user +uninstalls/reinstalls the app on the original device, your app should restore +the subscriptions that the user has purchased.
+ +The process for restoring subscriptions transactions is the same as described
+in Messaging sequence. Your app sends a
+RESTORE_TRANSACTIONS request to Google Play. Google Play sends two
+broadcast intents as asynchronous responses — a RESPONSE_CODE
+intent and a PURCHASE_STATE_CHANGED intent.
The PURCHASE_STATE_CHANGED intent contains a notification ID
+that your app can use to retrieve the purchase details, including the purchase
+token, by sending a standard GET_PURCHASE_INFORMATION request. The
+Bundle returned in the call includes an JSON array of order objects
+corresponding to subscription (and in-app product) purchases that you can
+restore locally.
Your app can store the restored purchase state and other transaction details +in the way that best meets your needs. Your app can use it later to check the +subscription validity, although please read the Security and +Design document for best practices for maintaining the security of your +data.
+ +Subscriptions are time-bound purchases that require successful billing +recurrences over time to remain valid. Your app should check the validity of +purchased subscriptions at launch or prior to granting access to subscriber +content.
+ +With In-app Billing, you validate a subscription by keeping track of its +purchase state, such as purchased or cancelled, and then checking the state +whenever needed. Google Play provides two ways to let you know when the purchase +state of a subscription changes:
+ +purchaseToken on your
+ backend servers. For more information, see Google Play
+ Android Developer API, below.For most use-cases, especially those where backend servers are already keeping +track of subscribed users, implementing a combination of both methods is the +recommended approach. A typical implementation might work like this:
+ +If you are using both notifications and the Google Play Android Developer API to validate subscriptions, we recommend the following:
+ +If necessary, you can also use a RESTORE_TRANSACTIONS request to retrieve a record of all managed and in-app products purchased by the user, which you can then store locally. However, using RESTORE_TRANSACTIONS on a regular basis is not recommended because of performance impacts.
Regardless of the approach you choose, your app should check subscriptions +and validity at launch, such as prior to accessing subscriber content, game +levels, and so on.
+ +Table 1. Summary of purchaseState
+values for subscription purchases, as received with a
+PURCHASE_STATE_CHANGED intent.
| State | purchaseState Value | Comments | +
|---|---|---|
| Purchased successfully | 0 | Sent at original purchase only (not at recurring billing cycles). | Cancelled | 1 | Sent at original purchase only if the purchase has failed for some reason. | +Refunded | 2 | The purchase was refunded. | +Subscription expired | 3 | Sent if a subscription expires because of non-payment or user cancelation. | +
In-app Billing does not currently provide an API to let users directly view or cancel +subscriptions from within the purchasing app. Instead, users can launch the Play +Store app on their devices and go to the My Apps screen to manage subscriptions. In My Apps, +users can see a list of their subscriptions organized by application. Tapping one of the +subscriptions loads the app's product page, from which users can see active subscriptions +and billing status and cancel subscriptions as needed.
+ +To make it easier for users to find and manage their subscriptions from inside your app, +we recommend that you offer a "View My Subscriptions" or "Manage Subscriptions" option in +your UI that directly loads your app's product page in the Play Store app.
+ +To do this, create an intent with the ACTION_VIEW
+action and include the market:// URI (rather than the http://
+URI) of your app's details page. Here’s an example:
Intent intent = new Intent(Intent.ACTION_VIEW);
+intent.setData(Uri.parse("market://details?id=com.example.app"));
+startActivity(intent);
+
+For more information, see + Linking to Your Products.
+ +Google Play notifies your app when the user completes the purchase of a +subscription, but the purchase state does not change over time, provided that +recurring billing takes place successfully. Google Play does not notify your app +of a purchase state change until the subscription expires because of +non-payment or user cancellation.
+ +Over the life of a subscription, your app does not need to initiate any +recurring billing events — those are all handled by Google Play and they +are transparent to your application if billing is successful.
+ +For subscriptions, you make the same types of modifications to your app as +are described in +Modifying your Application Code.
+ +Note that, in your UI that lets users view and select subscriptions for +purchase, you should add logic to check for purchased subscriptions and validate +them. Your UI should not present subscriptions if the user has already purchased +them.
+ +To create and manage subscriptions, you use the tools in the Developer +Console, just as for other in-app products.
+ +At the Developer Console, you can configure these attributes for each +subscription product:
+ +For details, please see Administering +In-app Billing.
+ + +Google Play offers an HTTP-based API that you can use to remotely query the +validity of a specific subscription at any time or cancel a subscription. The +API is designed to be used from your backend servers as a way of securely +managing subscriptions, as well as extending and integrating subscriptions with +other services.
+ +To use the API, you must first register a project at the Google APIs Console and receive +a Client ID and shared secret that your app will present when calling the +Google Play Android Developer API. All calls to the API are authenticated with +OAuth 2.0.
+ +Once your app is registered, you can access the API directly, using standard +HTTP methods to retrieve and manipulate resources, or you can use the Google +APIs Client Libraries, which are extended to support the API.
+ +The Google Play Android Developer API is built on a RESTful design that uses +HTTP and JSON, so any standard web stack can send requests and parse the +responses. However, if you don’t want to send HTTP requests and parse responses +manually, you can access the API using the client libraries, which provide +better language integration, improved security, and support for making calls +that require user authorization.
+ +For more information about the API and how to access it through the Google +APIs Client Libraries, see the documentation at:
+ +https://developers. +google.com/android-publisher/v1/
+ +Applications using the Google Play Android Developer API are limited to an +initial courtesy usage quota of 15000 requests per day (per +application). This should provide enough access for normal +subscription-validation needs, assuming that you follow the recommendation in +this section.
+ +If you need to request a higher limit for your application, please use the +“Request more” link in the Google APIs Console. +Also, please read the section below on design best practices for minimizing your +use of the API.
+ +Calls to the Google Play Android Developer API require authorization. Google +uses the OAuth 2.0 protocol to allow authorized applications to access user +data. To learn more, see Authorization +in the Google Play Android Developer API documentation.
+ +Access to the Google Play Android Developer API is regulated to help ensure a +high-performance environment for all applications that use it. While you can +request a higher daily quota for your application, we highly recommend that you +minimize your access using the technique(s) below.
+ +By following those general guidelines, your implementation will offer the +best possible performance for users and minimize use of the Google Play Android +Developer API.
+ diff --git a/docs/html/guide/google/play/billing/billing_testing.jd b/docs/html/guide/google/play/billing/billing_testing.jd new file mode 100755 index 000000000000..e2d4a014cbbf --- /dev/null +++ b/docs/html/guide/google/play/billing/billing_testing.jd @@ -0,0 +1,293 @@ +page.title=Testing In-app Billing +parent.title=In-app Billing +parent.link=index.html +@jd:body + +The Google Play 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.
+ +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 Google Play application installed. If a device is not running the +most current Google Play application, your application won't be able to send in-app billing +requests to Google Play. For general information about how to set up a device for use in +developing Android applications, see Using Hardware +Devices.
+ +The following section shows you how to set up and use the in-app billing test tools.
+ +We recommend that you first test your in-app billing implementation using static responses from +Google Play. This enables you to verify that your application is handling the primary Google +Play responses correctly and that your application is able to verify signatures correctly.
+ +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 Google Play. 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.
+ +
++ Figure 1. Wallet flow for the special reserved item android.test.purchased. +
+ +You do not need to list the reserved products in your application's product list. Google Play +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.
+ +There are four reserved product IDs for testing static in-app billing responses:
+ +When you make an in-app billing request with this product ID, Google Play 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.
+When you make an in-app billing request with this product ID Google Play 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.
+When you make an in-app billing request with this product ID, Google Play responds as + though the purchase was refunded. Refunds cannot be initiated through Google Play's in-app + billing service. Refunds must be initiated by you (the merchant). After you process a refund + request through your Google Wallet account, a refund message is sent to your application by + Google Play. This occurs only when Google Play gets notification from Google Wallet that + a refund has been made. For more information about refunds, see Handling + IN_APP_NOTIFY messages and In-app Billing + Pricing.
+When you make an in-app billing request with this product ID, Google Play responds as + though the item being purchased was not listed in your application's product list.
+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 test accounts or +upload your application as a unpublished draft application. Table 1 shows you the conditions under +which static responses are signed.
+ +Table 1. +Conditions under which static responses are signed.
+ +| Application ever been published? | +Draft application uploaded and unpublished? | +User who is running the application | +Static response signature | +
|---|---|---|---|
| No | +No | +Any | +Unsigned | +
| No | +No | +Developer | +Signed | +
| Yes | +No | +Any | +Unsigned | +
| Yes | +No | +Developer | +Signed | +
| Yes | +No | +Test account | +Signed | +
| Yes | +Yes | +Any | +Signed | +
To make an in-app billing request with a reserved product ID, you simply construct a normal
+REQUEST_PURCHASE request, but instead of using a real product ID from your
+application's product list you use one of the reserved product IDs.
To test your application using the reserved product IDs, follow these steps:
+ +You cannot use the emulator to test in-app billing; you must install your application on a + device to test in-app billing.
+To learn how to install an application on a device, see Running on a + device.
+You do not need to use a test account if you are testing only with the reserved product + IDs.
+If your device is running Android 3.0, in-app billing requires version 5.0.12 (or higher) of + the MyApps application. If your device is running any other version of Android, in-app billing + requires version 2.3.4 (or higher) of the Google Play application. To learn how to check the + version of the Google Play application, see Updating Google + Play.
+Note: Making in-app billing requests with the reserved product IDs +overrides the usual Google Play 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.
+ +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 Google Play and the actual checkout flow that +users will experience in your application.
+ +Note: You do not need to publish your application to do end-to-end +testing. You only need to upload your application as a draft application to perform end-to-end +testing.
+ +To test your in-app billing implementation with actual in-app purchases, you will need to +register at least one test account on the Google Play publisher site. You cannot use your +developer account to test the complete in-app purchase process because Google Wallet does not let +you buy items from yourself. If you have not set up test accounts before, see Setting up test +accounts.
+ +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.
+ +When you use a test account to purchase items, the test account is billed through Google Wallet +and your Google Wallet Merchant account receives a payout for the purchase. Therefore, you may +want to refund purchases that are made with test accounts, otherwise the purchases will show up as +actual payouts to your merchant account.
+ +To test your in-app billing implementation with actual purchases, follow these steps:
+ +You do not need to publish your application to perform end-to-end testing with real product + IDs; you only need to upload your application as a draft application. However, you must sign + your application with your release key before you upload it as a draft application. Also, the + version number of the uploaded application must match the version number of the application you + load to your device for testing. To learn how to upload an application to Google Play, see + Uploading + applications.
+Make sure that you publish the items (the application can remain unpublished). See Creating a product + list to learn how to do this.
+You cannot use the emulator to test in-app billing; you must install your application on a + device to test in-app billing.
+To learn how to install an application on a device, see Running on a + device.
+To perform end-to-end testing of in-app billing, the primary account on your device must be + one of the test accounts + that you registered on the Google Play site. If the primary account on your device is not a + test account, you must do a factory reset of the device and then sign in with one of your test + accounts. To perform a factory reset, do the following:
+If your device is running Android 3.0, in-app billing requires version 5.0.12 (or higher) of + the MyApps application. If your device is running any other version of Android, in-app billing + requires version 2.3.4 (or higher) of the Google Play application. To learn how to check the + version of the Google Play application, see Updating Google + Play.
+Note: 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.
+ +When you are finished testing your in-app billing implementation, you are ready to +publish your application on Google Play. You can follow the normal steps for preparing, signing, and publishing on Google Play. +
+ diff --git a/docs/html/guide/google/play/billing/index.jd b/docs/html/guide/google/play/billing/index.jd new file mode 100755 index 000000000000..a33b19961f13 --- /dev/null +++ b/docs/html/guide/google/play/billing/index.jd @@ -0,0 +1,116 @@ +page.title=In-app Billing +@jd:body + +In-app Billing is a Google Play service that lets you sell digital content from inside +your applications. You can use the service to sell a wide range of content, including downloadable +content such as media files or photos, virtual content such as game levels or potions, premium services +and features, and more. You can use In-app Billing to sell products as
+ +In-app Billing now lets you sell subscriptions in your apps, as well as standard in-app products. + For details on how to sell subscriptions to content, services, and features, see the + Subscriptions documentation.
+When you use the in-app billing service to sell an item, +whether it's an in-app product or a subscription, Google Play +handles all checkout details so your application never has to directly process +any financial transactions. Google Play uses the same checkout backend service as +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%).
+ +Any application that you publish through Google Play can implement In-app Billing. No special +account or registration is required other than an Android Market publisher account and a Google +Wallet 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.
+ +To help you integrate in-app billing into your application, the Android SDK +provides a sample application that demonstrates how to sell standard in-app +products and subscriptions from inside an app. The sample 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.
+ +Important: Although the sample application is a working example +of how you can implement in-app billing, we strongly recommend that you modify and +obfuscate the sample code before you use it in a production application. For more information, see +Security and Design.
+ +
++ Figure 1. Applications initiate in-app billing requests through their own UI + (first screen). Google Play responds to the request by providing the checkout user interface + (middle screen). When checkout is complete, the application resumes. +
+ +To learn more about Google Play's in-app billing service and start integrating it into your +applications, read the following documents:
+ +Google Play currently requires that your APK file be no more than 50MB. For most +applications, this is plenty of space for all the application's code and assets. +However, some apps need more space for high-fidelity graphics, media files, or other large assets. +Previously, if your app exceeded 50MB, you had to host and download the additional resources +yourself when the user opens the app. Hosting and serving the extra files can be costly, and the +user experience is often less than ideal. To make this process easier for you and more pleasant +for users, Google Play allows you to attach two large expansion files that supplement your +APK.
+ +Google Play hosts the expansion files for your application and serves them to the device at +no cost to you. The expansion files are saved to the device's shared storage location (the +SD card or USB-mountable partition; also known as the "external" storage) where your app can access +them. On most devices, Google Play downloads the expansion file(s) at the same time it +downloads the APK, so your application has everything it needs when the user opens it for the +first time. In some cases, however, your application must download the files from Google Play +when your application starts.
+ + + +Each time you upload an APK using the Google Play Android Developer Console, you have the option to +add one or two expansion files to the APK. Each file can be up to 2GB and it can be any format you +choose, but we recommend you use a compressed file to conserve bandwidth during the download. +Conceptually, each expansion file plays a different role:
+ +While you can use the two expansion files any way you wish, we recommend that the main +expansion file deliver the primary assets and should rarely if ever updated; the patch expansion +file should be smaller and serve as a “patch carrier,” getting updated with each major +release or as necessary.
+ +However, even if your application update requires only a new patch expansion file, you still must +upload a new APK with an updated {@code +versionCode} in the manifest. (The +Developer Console does not allow you to upload an expansion file to an existing APK.)
+ +Note: The patch expansion file is semantically the same as the +main expansion file—you can use each file any way you want. The system does +not use the patch expansion file to perform patching for your app. You must perform patching +yourself or be able to distinguish between the two files.
+ + + +Each expansion file you upload can be any format you choose (ZIP, PDF, MP4, etc.). Regardless of +the file type, Google Play considers them opaque binary blobs and renames the files +using the following scheme:
+ ++[main|patch].<expansion-version>.<package-name>.obb ++ +
There are three components to this scheme:
+ +"First" is emphasized because although the Developer Console allows you to +re-use an uploaded expansion file with a new APK, the expansion file's name does not change—it +retains the version applied to it when you first uploaded the file.
For example, suppose your APK version is 314159 and your package name is com.example.app. If you +upload a main expansion file, the file is renamed to:
+main.314159.com.example.app.obb+ + +
When Google Play downloads your expansion files to a device, it saves them to the system's +shared storage location. To ensure proper behavior, you must not delete, move, or rename the +expansion files. In the event that your application must perform the download from Google Play +itself, you must save the files to the exact same location.
+ +The specific location for your expansion files is:
+ ++<shared-storage>/Android/obb/<package-name>/ ++ +
For each application, there are never more than two expansion files in this directory. +One is the main expansion file and the other is the patch expansion file (if necessary). Previous +versions are overwritten when you update your application with new expansion files.
+ +If you must unpack the contents of your expansion files, do not delete the +{@code .obb} expansion files afterwards and do not save the unpacked data +in the same directory. You should save your unpacked files in the directory +specified by {@link android.content.Context#getExternalFilesDir getExternalFilesDir()}. However, +if possible, it's best if you use an expansion file format that allows you to read directly from +the file instead of requiring you to unpack the data. For example, we've provided a library +project called the APK Expansion Zip Library that reads your data directly +from the ZIP file.
+ +Note: Unlike APK files, any files saved on the shared storage can +be read by the user and other applications.
+ +Tip: If you're packaging media files into a ZIP, you can use media
+playback calls on the files with offset and length controls (such as {@link
+android.media.MediaPlayer#setDataSource(FileDescriptor,long,long) MediaPlayer.setDataSource()} and
+{@link android.media.SoundPool#load(FileDescriptor,long,long,int) SoundPool.load()}) without the
+need to unpack your ZIP. In order for this to work, you must not perform additional compression on
+the media files when creating the ZIP packages. For example, when using the zip tool,
+you should use the -n option to specify the file suffixes that should not be
+compressed:
+zip -n .mp4;.ogg main_expansion media_files
Most of the time, Google Play downloads and saves your expansion files at the same time it +downloads the APK to the device. However, in some cases Google Play +cannot download the expansion files or the user might have deleted previously downloaded expansion +files. To handle these situations, your app must be able to download the files +itself when the main activity starts, using a URL provided by Google Play.
+ +The download process from a high level looks like this:
+ +If Google Play is unable to download the expansion files, it downloads the +APK only.
+Caution: It is critical that you include the necessary code to +download the expansion files from Google Play in the event that the files are not already on the +device when your application starts. As discussed in the following section about Downloading the Expansion Files, we've made a library available to you that +greatly simplifies this process and performs the download from a service with a minimal amount of +code from you.
+ + + + +Here's a summary of the tasks you should perform to use expansion files with your +application:
+ +Normally, you should only use the second patch expansion file when performing updates to +the main expansion file. However, if your resources exceed the 2GB limit for the main +expansion file, you can use the patch file for the rest of your assets.
+Remember that you must not delete, move, or rename the expansion files.
+If your application doesn't demand a specific format, we suggest you create ZIP files for +your expansion files, then read them using the APK Expansion Zip +Library.
+To greatly reduce the amount of code you must write and ensure a good user experience +during the download, we recommend you use the Downloader +Library to implement your download behavior.
+If you build your own download service instead of using the library, be aware that you +must not change the name of the expansion files and must save them to the proper +storage location.
Once you've finished your application development, follow the guide to Testing +Your Expansion Files.
+ + + + + + +Adding APK expansion files is a feature available when you upload your application using the +Developer Console. When uploading your application for the first time or updating an +application that uses expansion files, you must be aware of the following rules and limitations:
+ +obb/
+directory. If you must unpack some data, save it into the location specified by {@link
+android.content.Context#getExternalFilesDir getExternalFilesDir()}.In most cases, Google Play downloads and saves your expansion files to the device at the same +time it installs or updates the APK. This way, the expansion files are available when your +application launches for the first time. However, in some cases your app must download the +expansion files itself by requesting them from a URL provided to you in a response +from Google Play's Application Licensing service.
+ +The basic logic you need to download your expansion files is the following:
+ +Android/obb/<package-name>/ directory).
+ Android/obb/<package-name>/) and use the exact file name provided
+by Google Play's response.
+ Note: The URL that Google Play provides for your +expansion files is unique for every download and each one expires shortly after it is given to +your application.
+If your application is free (not a paid app), then you probably haven't used the Application Licensing service. It's primarily +designed for you to enforce +licensing policies for your application and ensure that the user has the right to +use your app (he or she rightfully paid for it on Google Play). In order to facilitate the +expansion file functionality, the licensing service has been enhanced to provide a response +to your application that includes the URL of your application's expansion files that are hosted +on Google Play. So, even if your application is free for users, you need to include the +License Verification Library (LVL) to use APK expansion files. Of course, if your application +is free, you don't need to enforce license verification—you simply need the +library to perform the request that returns the URL of your expansion files.
+ +Note: Whether your application is free or not, Google Play +returns the expansion file URLs only if the user acquired your application from Google Play.
+ +In addition to the LVL, you need a set of code that downloads the expansion files +over an HTTP connection and saves them to the proper location on the device's shared storage. +As you build this procedure into your application, there are several issues you should take into +consideration:
+ +To simplify this work for you, we've built the Downloader Library, +which requests the expansion file URLs through the licensing service, downloads the expansion files, +performs all of the tasks listed above, and even allows your activity to pause and resume the +download. By adding the Downloader Library and a few code hooks to your application, almost all the +work to download the expansion files is already coded for you. As such, in order to provide the best +user experience with minimal effort on your behalf, we recommend you use the Downloader Library to +download your expansion files. The information in the following sections explain how to integrate +the library into your application.
+ +If you'd rather develop your own solution to download the expansion files using the Google +Play URLs, you must follow the Application +Licensing documentation to perform a license request, then retrieve the expansion file names, +sizes, and URLs from the response extras. You should use the {@code +APKExpansionPolicy} class (included in the License Verification Library) as your licensing +policy, which captures the expansion file names, sizes, and URLs from the licensing service..
+ + + +To use APK expansion files with your application and provide the best user experience with +minimal effort on your behalf, we recommend you use the Downloader Library that's included in the +Google Market Apk Expansion package. This library downloads your expansion files in a +background service, shows a user notification with the download status, handles network +connectivity loss, resumes the download when possible, and more.
+ +To implement expansion file downloads using the Downloader Library, all you need to do is:
+ +The following sections explain how to set up your app using the Downloader Library.
+ + +To use the Downloader Library, you need to +download two packages from the SDK Manager and add the appropriate libraries to your +application.
+ +First, open the Android SDK Manager, expand +Extras and download:
+If you're using Eclipse, create a project for each library and add it to your app:
+Note: The Downloader Library depends on the License +Verification Library. Be sure to add the License +Verification Library to the Downloader Library's project properties (same process as +steps 2 and 3 below).
+Or, from a command line, update your project to include the libraries:
+<sdk>/tools/ directory.android update project with the {@code --library} option to add both the
+LVL and the Downloader Library to your project. For example:
++android update project --path ~/Android/MyApp \ +--library ~/android_sdk/extras/google/market_licensing \ +--library ~/android_sdk/extras/google/market_apk_expansion/downloader_library ++
With both the License Verification Library and Downloader Library added to your +application, you'll be able to quickly integrate the ability to download expansion files from +Google Play. The format that you choose for the expansion files and how you read them +from the shared storage is a separate implementation that you should consider based on your +application needs.
+ +Tip: The Apk Expansion package includes a sample +application +that shows how to use the Downloader Library in an app. The sample uses a third library +available in the Apk Expansion package called the APK Expansion Zip Library. If +you plan on +using ZIP files for your expansion files, we suggest you also add the APK Expansion Zip Library to +your application. For more information, see the section below +about Using the APK Expansion Zip Library.
+ + + +In order to download the expansion files, the Downloader Library +requires several permissions that you must declare in your application's manifest file. They +are:
+ ++<manifest ...> + <!-- Required to access Google Play Licensing --> + <uses-permission android:name="com.android.vending.CHECK_LICENSE" /> + + <!-- Required to download files from Google Play --> + <uses-permission android:name="android.permission.INTERNET" /> + + <!-- Required to keep CPU alive while downloading files (NOT to keep screen awake) --> + <uses-permission android:name="android.permission.WAKE_LOCK" /> + + <!-- Required to poll the state of the network connection and respond to changes --> + <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" /> + + <!-- Required to check whether Wi-Fi is enabled --> + <uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/> + + <!-- Required to read and write the expansion files on shared storage --> + <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> + ... +</manifest> ++ +
Note: By default, the Downloader Library requires API +level 4, but the APK Expansion Zip Library requires API level 5.
+ + +In order to perform downloads in the background, the Downloader Library provides its +own {@link android.app.Service} subclass called {@code DownloaderService} that you should extend. In +addition to downloading the expansion files for you, the {@code DownloaderService} also:
+ +All you need to do is create a class in your application that extends the {@code +DownloaderService} class and override three methods to provide specific application details:
+ +For example, here's a complete implementation of {@code DownloaderService}:
+ +
+public class SampleDownloaderService extends DownloaderService {
+ // You must use the public key belonging to your publisher account
+ public static final String BASE64_PUBLIC_KEY = "YourLVLKey";
+ // You should also modify this salt
+ public static final byte[] SALT = new byte[] { 1, 42, -12, -1, 54, 98,
+ -100, -12, 43, 2, -8, -4, 9, 5, -106, -107, -33, 45, -1, 84
+ };
+
+ @Override
+ public String getPublicKey() {
+ return BASE64_PUBLIC_KEY;
+ }
+
+ @Override
+ public byte[] getSALT() {
+ return SALT;
+ }
+
+ @Override
+ public String getAlarmReceiverClassName() {
+ return SampleAlarmReceiver.class.getName();
+ }
+}
+
+
+Notice: You must update the {@code BASE64_PUBLIC_KEY} value +to be the public key belonging to your publisher account. You can find the key in the Developer +Console under your profile information. This is necessary even when testing +your downloads.
+ +Remember to declare the service in your manifest file:
++<application ...> + <service android:name=".SampleDownloaderService" /> + ... +</application> ++ + + +
In order to monitor the progress of the file downloads and restart the download if necessary, the +{@code DownloaderService} schedules an {@link android.app.AlarmManager#RTC_WAKEUP} alarm that +delivers an {@link android.content.Intent} to a {@link android.content.BroadcastReceiver} in your +application. You must define the {@link android.content.BroadcastReceiver} to call an API +from the Downloader Library that checks the status of the download and restarts +it if necessary.
+ +You simply need to override the {@link android.content.BroadcastReceiver#onReceive +onReceive()} method to call {@code +DownloaderClientMarshaller.startDownloadServiceIfRequired()}.
+ +For example:
+ +
+public class SampleAlarmReceiver extends BroadcastReceiver {
+ @Override
+ public void onReceive(Context context, Intent intent) {
+ try {
+ DownloaderClientMarshaller.startDownloadServiceIfRequired(context, intent,
+ SampleDownloaderService.class);
+ } catch (NameNotFoundException e) {
+ e.printStackTrace();
+ }
+ }
+}
+
+
+Notice that this is the class for which you must return the name +in your service's {@code getAlarmReceiverClassName()} method (see the previous section).
+ +Remember to declare the receiver in your manifest file:
++<application ...> + <receiver android:name=".SampleAlarmReceiver" /> + ... +</application> ++ + + +
The main activity in your application (the one started by your launcher icon) is +responsible for verifying whether the expansion files are already on the device and initiating +the download if they are not.
+ +Starting the download using the Downloader Library requires the following +procedures:
+ +The Downloader Library includes some APIs in the {@code Helper} class to +help with this process:
+For example, the sample app provided in the Apk Expansion package calls the +following method in the activity's {@link android.app.Activity#onCreate onCreate()} method to check +whether the expansion files already exist on the device:
+
+boolean expansionFilesDelivered() {
+ for (XAPKFile xf : xAPKS) {
+ String fileName = Helpers.getExpansionAPKFileName(this, xf.mIsBase, xf.mFileVersion);
+ if (!Helpers.doesFileExist(this, fileName, xf.mFileSize, false))
+ return false;
+ }
+ return true;
+}
+
+ In this case, each {@code XAPKFile} object holds the version number and file size of a known +expansion file and a boolean as to whether it's the main expansion file. (See the sample +application's {@code SampleDownloaderActivity} class for details.)
+If this method returns false, then the application must begin the download.
+The method takes the following parameters:
+context: Your application's {@link android.content.Context}.notificationClient: A {@link android.app.PendingIntent} to start your main
+activity. This is used in the {@link android.app.Notification} that the {@code DownloaderService}
+creates to show the download progress. When the user selects the notification, the system
+invokes the {@link android.app.PendingIntent} you supply here and should open the activity
+that shows the download progress (usually the same activity that started the download).serviceClass: The {@link java.lang.Class} object for your implementation of
+{@code DownloaderService}, required to start the service and begin the download if necessary.The method returns an integer that indicates +whether or not the download is required. Possible values are:
+The behavior for {@code LVL_CHECK_REQUIRED} and {@code DOWNLOAD_REQUIRED} are essentially the +same and you normally don't need to be concerned about them. In your main activity that calls {@code +startDownloadServiceIfRequired()}, you can simply check whether or not the response is {@code +NO_DOWNLOAD_REQUIRED}. If the response is anything other than {@code NO_DOWNLOAD_REQUIRED}, +the Downloader Library begins the download and you should update your activity UI to +display the download progress (see the next step). If the response is {@code +NO_DOWNLOAD_REQUIRED}, then the files are available and your application can start.
+For example:
+
+@Override
+public void onCreate(Bundle savedInstanceState) {
+ // Check if expansion files are available before going any further
+ if (!expansionFilesDelivered()) {
+ // Build an Intent to start this activity from the Notification
+ Intent notifierIntent = new Intent(this, MainActivity.getClass());
+ notifierIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK |
+ Intent.FLAG_ACTIVITY_CLEAR_TOP);
+ ...
+ PendingIntent pendingIntent = PendingIntent.getActivity(this, 0,
+ notifierIntent, PendingIntent.FLAG_UPDATE_CURRENT);
+
+ // Start the download service (if required)
+ int startResult = DownloaderClientMarshaller.startDownloadServiceIfRequired(this,
+ pendingIntent, SampleDownloaderService.class);
+ // If download has started, initialize this activity to show download progress
+ if (startResult != DownloaderClientMarshaller.NO_DOWNLOAD_REQUIRED) {
+ // This is where you do set up to display the download progress (next step)
+ ...
+ return;
+ } // If the download wasn't necessary, fall through to start the app
+ }
+ startApp(); // Expansion files are available, start the app
+}
+
+ In order to instantiate your {@code IStub} by calling {@code CreateStub()}, you must pass it +an implementation of the {@code IDownloaderClient} interface and your {@code DownloaderService} +implementation. The next section about Receiving download progress discusses +the {@code IDownloaderClient} interface, which you should usually implement in your {@link +android.app.Activity} class so you can update the activity UI when the download state changes.
+We recommend that you call {@code +CreateStub()} to instantiate your {@code IStub} during your activity's {@link +android.app.Activity#onCreate onCreate()} method, after {@code startDownloadServiceIfRequired()} +starts the download.
+For example, in the previous code sample for {@link android.app.Activity#onCreate +onCreate()}, you can respond to the {@code startDownloadServiceIfRequired()} result like this:
+
+ // Start the download service (if required)
+ int startResult = DownloaderClientMarshaller.startDownloadServiceIfRequired(this,
+ pendingIntent, SampleDownloaderService.class);
+ // If download has started, initialize activity to show progress
+ if (startResult != DownloaderClientMarshaller.NO_DOWNLOAD_REQUIRED) {
+ // Instantiate a member instance of IStub
+ mDownloaderClientStub = DownloaderClientMarshaller.CreateStub(this,
+ SampleDownloaderService.class);
+ // Inflate layout that shows download progress
+ setContentView(R.layout.downloader_ui);
+ return;
+ }
+
+
+ After the {@link android.app.Activity#onCreate onCreate()} method returns, your activity +receives a call to {@link android.app.Activity#onResume onResume()}, which is where you should then +call {@code connect()} on the {@code IStub}, passing it your application's {@link +android.content.Context}. Conversely, you should call +{@code disconnect()} in your activity's {@link android.app.Activity#onStop onStop()} callback.
+
+@Override
+protected void onResume() {
+ if (null != mDownloaderClientStub) {
+ mDownloaderClientStub.connect(this);
+ }
+ super.onResume();
+}
+
+@Override
+protected void onStop() {
+ if (null != mDownloaderClientStub) {
+ mDownloaderClientStub.disconnect(this);
+ }
+ super.onStop();
+}
+
+ Calling {@code connect()} on the {@code IStub} binds your activity to the {@code +DownloaderService} such that your activity receives callbacks regarding changes to the download +state through the {@code IDownloaderClient} interface.
+To receive updates regarding the download progress and to interact with the {@code +DownloaderService}, you must implement the Downloader Library's {@code IDownloaderClient} interface. +Usually, the activity you use to start the download should implement this interface in order to +display the download progress and send requests to the service.
+ +The required interface methods for {@code IDownloaderClient} are:
+ +A recommended implementation looks like this:
+
+private IDownloaderService mRemoteService;
+...
+
+@Override
+public void onServiceConnected(Messenger m) {
+ mRemoteService = DownloaderServiceMarshaller.CreateProxy(m);
+ mRemoteService.onClientUpdated(mDownloaderClientStub.getMessenger());
+}
+
+ With the {@code IDownloaderService} object initialized, you can send commands to the +downloader service, such as to pause and resume the download ({@code requestPauseDownload()} +and {@code requestContinueDownload()}).
+The newState value will be one of several possible values specified in
+by one of the {@code IDownloaderClient} class's {@code STATE_*} constants.
To provide a useful message to your users, you can request a corresponding string +for each state by calling {@code Helpers.getDownloaderStringResourceIDFromState()}. This +returns the resource ID for one of the strings bundled with the Downloader +Library. For example, the string "Download paused because you are roaming" corresponds to {@code +STATE_PAUSED_ROAMING}.
Tip: For examples of these callbacks that update the download +progress UI, see the {@code SampleDownloaderActivity} in the sample app provided with the +Apk Expansion package.
+ +Some public methods for the {@code IDownloaderService} interface you might find useful are:
+ ++mRemoteService.setDownloadFlags(IDownloaderService.FLAGS_DOWNLOAD_OVER_CELLULAR); ++
If you decide to build your own downloader service instead of using the Google Play +Downloader Library, you should still use the {@code +APKExpansionPolicy} that's provided in the License Verification Library. The {@code +APKExpansionPolicy} class is nearly identical to {@code ServerManagedPolicy} (available in the +Google Play License Verification Library) but includes additional handling for the APK expansion +file response extras.
+ +Note: If you do use the Downloader Library as discussed in the previous section, the +library performs all interaction with the {@code APKExpansionPolicy} so you don't have to use +this class directly.
+ +The class includes methods to help you get the necessary information about the available +expansion files:
+ +For more information about how to use the {@code APKExpansionPolicy} when you're not +using the Downloader Library, see the documentation for Adding Licensing to Your App, +which explains how to implement a license policy such as this one.
+ + + + + + + +Once your APK expansion files are saved on the device, how you read your files +depends on the type of file you've used. As discussed in the overview, your +expansion files can be any kind of file you +want, but are renamed using a particular file name format and are saved to +{@code <shared-storage>/Android/obb/<package-name>/}.
+ +Regardless of how you read your files, you should always first check that the external +storage is available for reading. There's a chance that the user has the storage mounted to a +computer over USB or has actually removed the SD card.
+ +Note: When your application starts, you should always check whether +the external storage space is available and readable by calling {@link +android.os.Environment#getExternalStorageState()}. This returns one of several possible strings +that represent the state of the external storage. In order for it to be readable by your +application, the return value must be {@link android.os.Environment#MEDIA_MOUNTED}.
+ + +As described in the overview, your APK expansion files are saved +using a specific file name format:
+ ++[main|patch].<expansion-version>.<package-name>.obb ++ +
To get the location and names of your expansion files, you should use the +{@link android.os.Environment#getExternalStorageDirectory()} and {@link +android.content.Context#getPackageName()} methods to construct the path to your files.
+ +Here's a method you can use in your application to get an array containing the complete path +to both your expansion files:
+ +
+// The shared path to all app expansion files
+private final static String EXP_PATH = "/Android/obb/";
+
+static String[] getAPKExpansionFiles(Context ctx, int mainVersion, int patchVersion) {
+ String packageName = ctx.getPackageName();
+ Vector<String> ret = new Vector<String>();
+ if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
+ // Build the full path to the app's expansion files
+ File root = Environment.getExternalStorageDirectory();
+ File expPath = new File(root.toString() + EXP_PATH + packageName);
+
+ // Check that expansion file path exists
+ if (expPath.exists()) {
+ if ( mainVersion > 0 ) {
+ String strMainPath = expPath + File.separator + "main." +
+ mainVersion + "." + packageName + ".obb";
+ File main = new File(strMainPath);
+ if ( main.isFile() ) {
+ ret.add(strMainPath);
+ }
+ }
+ if ( patchVersion > 0 ) {
+ String strPatchPath = expPath + File.separator + "patch." +
+ mainVersion + "." + packageName + ".obb";
+ File main = new File(strPatchPath);
+ if ( main.isFile() ) {
+ ret.add(strPatchPath);
+ }
+ }
+ }
+ }
+ String[] retArray = new String[ret.size()];
+ ret.toArray(retArray);
+ return retArray;
+}
+
+
+You can call this method by passing it your application {@link android.content.Context} +and the desired expansion file's version.
+ +There are many ways you could determine the expansion file version number. One simple way is to +save the version in a {@link android.content.SharedPreferences} file when the download begins, by +querying the expansion file name with the {@code APKExpansionPolicy} class's {@code +getExpansionFileName(int index)} method. You can then get the version code by reading the {@link +android.content.SharedPreferences} file when you want to access the expansion +file.
+ +For more information about reading from the shared storage, see the Data Storage +documentation.
+ + + +If you're using your expansion files to store media files, a ZIP file still allows you to
+use Android media playback calls that provide offset and length controls (such as {@link
+android.media.MediaPlayer#setDataSource(FileDescriptor,long,long) MediaPlayer.setDataSource()} and
+{@link android.media.SoundPool#load(FileDescriptor,long,long,int) SoundPool.load()}). In order for
+this to work, you must not perform additional compression on the media files when creating the ZIP
+packages. For example, when using the zip tool, you should use the -n
+option to specify the file suffixes that should not be compressed:
zip -n .mp4;.ogg main_expansion media_files
The Google Market Apk Expansion package includes a library called the APK +Expansion Zip Library (located in {@code +<sdk>/extras/google/google_market_apk_expansion/zip_file/}). This is an optional library that +helps you read your expansion +files when they're saved as ZIP files. Using this library allows you to easily read resources from +your ZIP expansion files as a virtual file system.
+ +The APK Expansion Zip Library includes the following classes and APIs:
+ +mainVersion and the
+patchVersion, this returns a {@code ZipResourceFile} that provides read access to
+all the data, with the patch file's data merged on top of the main file.assetPath must be the path to the desired file, relative to
+the root of the ZIP file contents.assetPath must be the path to the desired file, relative to
+the root of the ZIP file contents. This is useful for certain Android APIs that require an {@link
+android.content.res.AssetFileDescriptor}, such as some {@link android.media.MediaPlayer} APIs.When using the APK Expansion Zip Library, reading a file from your ZIP usually requires the +following:
+ ++// Get a ZipResourceFile representing a merger of both the main and patch files +ZipResourceFile expansionFile = APKExpansionSupport.getAPKExpansionZipFile(appContext, + mainVersion, patchVersion); + +// Get an input stream for a known file inside the expansion file ZIPs +InputStream fileStream = expansionFile.getInputStream(pathToFileInsideZip); ++ +
The above code provides access to any file that exists in either your main expansion file or +patch expansion file, by reading from a merged map of all the files from both files. All you +need to provide the {@code getAPKExpansionFile()} method is your application {@code +android.content.Context} and the version number for both the main expansion file and patch +expansion file.
+ +If you'd rather read from a specific expansion file, you can use the {@code +ZipResourceFile} constructor with the path to the desired expansion file:
+ ++// Get a ZipResourceFile representing a specific expansion file +ZipResourceFile expansionFile = new ZipResourceFile(filePathToMyZip); + +// Get an input stream for a known file inside the expansion file ZIPs +InputStream fileStream = expansionFile.getInputStream(pathToFileInsideZip); ++ +
For more information about using this library for your expansion files, look at +the sample application's {@code SampleDownloaderActivity} class, which includes additional code to +verify the downloaded files using CRC. Beware that if you use this sample as the basis for +your own implementation, it requires that you declare the byte size of your expansion +files in the {@code xAPKS} array.
+ + + + +Before publishing your application, there are two things you should test: Reading the +expansion files and downloading the files.
+ + +Before you upload your application to Google Play, you +should test your application's ability to read the files from the shared storage. All you need to do +is add the files to the appropriate location on the device shared storage and launch your +application:
+ +For example, if your package name is {@code com.example.android}, you need to create +the directory {@code Android/obb/com.example.android/} on the shared storage space. (Plug in +your test device to your computer to mount the shared storage and manually create this +directory.)
+For example, regardless of the file type, the main expansion file for the {@code +com.example.android} application should be {@code main.0300110.com.example.android.obb}. +The version code can be whatever value you want. Just remember:
+Here are some reminders about handling the expansion files:
+obb/
+directory. If you must unpack some data, save it into the location specified by {@link
+android.content.Context#getExternalFilesDir getExternalFilesDir()}.Because your application must sometimes manually download the expansion files when it first +opens, it's important that you test this process to be sure your application can successfully query +for the URLs, download the files, and save them to the device.
+ +To test your application's implementation of the manual download procedure, you must upload +your application to Google Play as a "draft" to make your expansion files available for +download:
+ +Click the Save button. Do not click Publish. This saves +the application as a draft, such that your application is not published for Google Play users, +but the expansion files are available for you to test the download process.
If everything works as expected, your application should begin downloading the expansion +files as soon as the main activity starts.
+ + + + +One of the great benefits to using expansion files on Google Play is the ability to +update your application without re-downloading all of the original assets. Because Google Play +allows you to provide two expansion files with each APK, you can use the second file as a "patch" +that provides updates and new assets. Doing so avoids the +need to re-download the main expansion file which could be large and expensive for users.
+ +The patch expansion file is technically the same as the main expansion file and neither +the Android system nor Google Play perform actual patching between your main and patch expansion +files. Your application code must perform any necessary patches itself.
+ +If you use ZIP files as your expansion files, the APK Expansion Zip +Library that's included with the Apk Expansion package includes the ability to merge +your +patch file with the main expansion file.
+ +Note: Even if you only need to make changes to the patch +expansion file, you must still update the APK in order for Google Play to perform an update. +If you don't require code changes in the application, you should simply update the {@code versionCode} in the +manifest.
+ +As long as you don't change the main expansion file that's associated with the APK +in the Developer Console, users who previously installed your application will not +download the main expansion file. Existing users receive only the updated APK and the new patch +expansion file (retaining the previous main expansion file).
+ +Here are a few issues to keep in mind regarding updates to expansion files:
+ +<supports-gl-texture><supports-screens><uses-configuration><uses-feature><uses-library><uses-permission><uses-sdk>
+ Go to Google Play to create a publisher +account and upload your app.
When a user searches or browses on Google Play on an Android device, the results are filtered +based on which applications are compatible with that device. For example, if an application +requires a camera (as specified in the application manifest file), then Google Play will not show +the app on any device that does not have a camera.
+ +Declarations in the manifest file that are compared to the device's configuration is not the +only part of how applications are filtered. Filtering might also occur due to the user's country and +carrier, the presence or absence of a SIM card, and other factors.
+ +Changes to the Google Play filters are independent of changes to the Android platform itself. +This document is updated periodically to reflect any changes that affect the way Google Play +filters applications.
+ + +Google Play uses the filter restrictions described below to determine +whether to show your application to a user who is browsing or searching for +applications from the Google Play app. When determining whether to display your app, +Google Play checks the device's hardware and software configuration, as well as it's +carrier, location, and other characteristics. It then compares those against the +restrictions and dependencies expressed by the application's +manifest file and publishing details. If the application is +compatible with the device according to the filter rules, Google Play displays the +application to the user. Otherwise, Google Play hides your application from search +results and category browsing, even if a user specifically requests +the app by clicking a deep link that points directly to the app's ID within Google Play..
+ +Note: When users browse the Google Play web site, they can see all published +applications. The Google Play web site compares the application requirements to each of the +user's registered devices for compatibility, though, and only allows them to install the application +if it's compatible with their device.
+ +You can use any combination of the available filters for your app. For example, you can set a
+minSdkVersion requirement of "4" and set smallScreens="false"
+in the app, then when uploading the app to Google Play you could target European countries (carriers)
+only. Google Play's filters will thus prevent the application from being available on any device
+that does not match all three of these requirements.
All filtering restrictions are associated with an application's version and can +change between versions. For example, if a user has installed your application and you publish an +update that makes the app invisible to the user, the user will not see that an update is +available.
+ + +Most filters are triggered by elements within an application's +manifest file, AndroidManifest.xml +(although not everything in the manifest file can trigger filtering). +Table 1 lists the manifest elements that you should use to trigger +filtering, and explains how the filtering for each element works.
+ +Table 1. Manifest elements that +trigger filtering on Google Play.
+| Manifest Element | +Filter Name | +How It Works | +
|---|---|---|
<supports-screens>
+ |
+ Screen Size | +
+
+ An application indicates the screen sizes that it is capable of supporting by
+setting attributes of the As a general rule, Google Play 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, +Google Play 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. + +If an application does not declare attributes for
+
Example 1 Example 2 Example 3 For more information on how to declare support for screen sizes in your
+ application, see |
+
<uses-configuration>
+ |
+ Device
+ Configuration: + keyboard, navigation, touch screen |
+ An application can + request certain hardware features, and Google Play will show the app only on devices that have the required hardware. +Example 1 Example 2 For more details, see |
+
<uses-feature>
+
+ |
+ Device Features + ( name) |
+ An application can require certain device features to be +present on the device. This functionality was introduced in Android 2.0 (API +Level 5). +Example 1 Example 2 For complete information, see Filtering based on implied features: In some cases, Google
+Play interprets permissions requested through
+ |
+
| OpenGL-ES
+ Version +( openGlEsVersion) |
+ An application can require that the device support a specific
+ OpenGL-ES version using the Example 1 Example 2 Example 3 Example 4 For more details, see |
+ |
<uses-library> |
+ Software Libraries | +An application can require specific + shared libraries to be present on the device. +Example 1 Example 2 For more details, see |
+
<uses-permission> |
+ + | Strictly, Google Play does not filter based on
+<uses-permission> elements. However, it does read the
+elements to determine whether the application has hardware feature requirements
+that may not have been properly declared in <uses-feature>
+elements. For example, if an application requests the CAMERA
+permission but does not declare a <uses-feature> element for
+android.hardware.camera, Google Play considers that the
+application requires a camera and should not be shown to users whose devices do
+not offer a camera.
+ In general, if an application requests hardware-related permissions,
+Google Play assumes that the application requires the underlying hardware
+features, even though there might be no corresponding to
+ For a list of permissions that imply hardware features, see
+the documentation for the |
+
<uses-sdk> |
+ Minimum Framework Version (minSdkVersion) |
+ An application can require a minimum API level. +Example 1 Example 2 Because you want to avoid this second scenario, we recommend that you always declare a |
+
Maximum Framework Version (maxSdkVersion) |
+ Deprecated. Android
+ 2.1 and later do not check or enforce the Declaring |
+
In addition to the manifest elements in table 1, Google Play can also +filter applications based on the advanced manifest elements in table 2.
+ +These manifest elements and the filtering they trigger are for exceptional use-cases +only. These are designed for certain types of high-performance games and similar applications that +require strict controls on application distribution. Most applications should never use +these filters.
+ +Table 2. Advanced manifest elements for +Google Play filtering.
+| Manifest Element | Summary |
|---|---|
|
+ Google Play filters the application if the device screen size and density does not match +any of the screen configurations (declared by a {@code <screen>} element) in the {@code +<compatible-screens>} element. +Caution: Normally, you should not use +this manifest element. Using this element can dramatically +reduce the potential user base for your application, by excluding all combinations of screen size +and density that you have not listed. You should instead use the {@code +<supports-screens>} manifest element (described above in table +1) to enable screen compatibility mode for screen configurations you have not accounted for +with alternative resources. + |
+ |
|
+ Google Play filters the application unless one or more of the GL texture compression +formats supported by the application are also supported by the device. + |
+
Google Play 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.
+ +Table 3. Application and publishing +characteristics that affect filtering on Google Play.
+| Filter Name | How It Works |
|---|---|
| Publishing Status | Only published applications will appear in + searches and browsing within Google Play. 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. If an application has been + suspended, users will not be able to reinstall or update it, even if it appears in their Downloads. |
| Priced + Status | 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. |
+
| Country / Carrier Targeting | When you upload your app to + Google Play, you can select specific countries to target. The app will only + be visible to the countries (carriers) that you select, as follows: +
|
| Native Platform | An application that includes native + libraries that target a specific platform (ARM EABI v7 or x86, for example) are + visible only on devices that support that platform. For details about the NDK and using + native libraries, see What is the + Android NDK? |
| Copy-Protected Applications | To + copy protect an application, set copy protection to "On" when you configure publishing +options for your application. Google Play will not show copy-protected applications on +developer devices or unreleased devices. |
Some specific Google Play filters allow you to publish multiple APKs for the same +application in order to provide a different APK to different device configurations. For example, if +you're creating a video game that uses high-fidelity graphic assets, you might want to create +two APKs that each support different texture compression formats. This way, you can reduce the +size of the APK file by including only the textures that are required for each device +configuration. Depending on each device's support for your texture compression formats, Google +Play will deliver it the APK that you've declared to support that device.
+ +Currently, Google Play allows you to publish multiple APKs for the same application only +when each APK provides different filters based on the following configurations:
+By using the {@code +<supports-gl-texture>} element.
+By using the {@code +<supports-screens>} or {@code +<compatible-screens>} element.
+By using the {@code +<uses-sdk>} element.
+All other filters still work the same as usual, but these three are the only filters that can +distinguish one APK from another within the same application listing on Google Play. For example, +you cannot publish multiple APKs for the same application if the APKs differ only based on +whether the device has a camera.
+ +Caution: Publishing multiple APKs for the same application is +considered an advanced feature and most application should publish only one +APK that supports a wide range of device configurations. Publishing multiple APKs +requires that you follow specific rules within your filters and that you pay extra attention to the +version codes for each APK to ensure proper update paths for each configuration.
+ +If you need more information about how to publish multiple APKs on Google Play, read Multiple APK Support.
diff --git a/docs/html/guide/google/play/index.jd b/docs/html/guide/google/play/index.jd new file mode 100644 index 000000000000..b11bcdca8001 --- /dev/null +++ b/docs/html/guide/google/play/index.jd @@ -0,0 +1,16 @@ +page.title=Google Play APIs +page.landing=1 +page.landing.intro=When you ditribute your Android app using Google Play you have the opportunity to enhance your app's capabilities with services such as in-app billing and control your app distribution with advanced device filtering. +@jd:body + + +After you've set up a publisher account and development environment (see Setting Up for Licensing), you are ready to add license verification to +your app with the License Verification Library (LVL).
+ +Adding license verification with the LVL involves these tasks:
+ +The sections below describe these tasks. When you are done with the +integration, you should be able to compile your application successfully and you +can begin testing, as described in Setting Up the Test +Environment.
+ +For an overview of the full set of source files included in the LVL, see Summary of LVL Classes +and Interfaces.
+ + +To use the Google Play application for sending a license check to the
+server, your application must request the proper permission,
+com.android.vending.CHECK_LICENSE. If your application does
+not declare the licensing permission but attempts to initiate a license check,
+the LVL throws a security exception.
To request the licensing permission in your application, declare a <uses-permission>
+element as a child of <manifest>, as follows:
<uses-permission
+android:name="com.android.vending.CHECK_LICENSE">
For example, here's how the LVL sample application declares the permission: +
+ +<?xml version="1.0" encoding="utf-8"?> + +<manifest xmlns:android="http://schemas.android.com/apk/res/android" ..."> + <!-- Devices >= 3 have version of Google Play that supports licensing. --> + <uses-sdk android:minSdkVersion="3" /> + <!-- Required permission to check licensing. --> + <uses-permission android:name="com.android.vending.CHECK_LICENSE" /> + ... +</manifest> ++ +
Note: Currently, you cannot declare the
+CHECK_LICENSE permission in the LVL library project's manifest,
+because the SDK Tools will not merge it into the manifests of dependent
+applications. Instead, you must declare the permission in each dependent
+application's manifest.
The LVL includes a complete {@code Policy} implementation called ServerManagedPolicy +that makes use of license-management settings provided by the Google Play +server.
+ +Use of ServerManagedPolicy as the basis for your +Policy is strongly recommended. For more information, see ServerManagedPolicy section, below.
+ +Google Play licensing service does not itself determine whether a +given user with a given license should be granted access to your application. +Rather, that responsibility is left to a {@code Policy} implementation that you provide +in your application.
+ +Policy is an interface declared by the LVL that is designed to hold your +application's logic for allowing or disallowing user access, based on the result +of a license check. To use the LVL, your application must provide an +implementation of {@code Policy}.
+ +The {@code Policy} interface declares two methods, allowAccess() and
+processServerResponse(), which are called by a {@code LicenseChecker}
+instance when processing a response from the license server. It also declares an
+enum called LicenseResponse, which specifies the license response
+value passed in calls to processServerResponse().
processServerResponse() lets you preprocess the raw response
+data received from the licensing server, prior to determining whether to grant
+access.
+
+A typical implementation would extract some or all fields from the license +response and store the data locally to a persistent store, such as through +{@link android.content.SharedPreferences} storage, to ensure that the data is +accessible across application invocations and device power cycles. For example, +a {@code Policy} would maintain the timestamp of the last successful license check, the +retry count, the license validity period, and similar information in a +persistent store, rather than resetting the values each time the application is +launched.
+ +When storing response data locally, the {@code Policy} must ensure that the data is +obfuscated (see Implementing an Obfuscator, +below).
allowAccess() determines whether to grant the user access to
+your application, based on any available license response data (from the
+licensing server or from cache) or other application-specific information. For
+example, your implementation of allowAccess() could take into
+account additional criteria, such as usage or other data retrieved from a
+backend server. In all cases, an implementation of allowAccess()
+should only return true if the user is licensed to use the
+application, as determined by the licensing server, or if there is a transient
+network or system problem that prevents the license check from completing. In
+such cases, your implementation can maintain a count of retry responses and
+provisionally allow access until the next license check is complete.To simplify the process of adding licensing to your application and to +provide an illustration of how a {@code Policy} should be designed, the LVL includes +two full {@code Policy} implementations that you can use without modification or +adapt to your needs:
+ +For most applications, the use of ServerManagedPolicy is highly +recommended. ServerManagedPolicy is the LVL default and is integrated with +the LVL sample application.
+ + +In your licensing implementation, you can use one of the complete policies +provided in the LVL (ServerManagedPolicy or StrictPolicy) or you can create a +custom policy. For any type of custom policy, there are several important design +points to understand and account for in your implementation.
+ +The licensing server applies general request limits to guard against overuse +of resources that could result in denial of service. When an application exceeds +the request limit, the licensing server returns a 503 response, which gets +passed through to your application as a general server error. This means that no +license response will be available to the user until the limit is reset, which +can affect the user for an indefinite period.
+ +If you are designing a custom policy, we recommend that the {@code Policy}: +
VT
+extra is highly recommended. See Server Response Extras
+for more information.Designing your {@code Policy} according to the guidelines listed above is critical, +because it ensures the best possible experience for users while giving you +effective control over your application even in error conditions.
+ +Note that any {@code Policy} can use settings provided by the licensing server to +help manage validity and caching, retry grace period, and more. Extracting the +server-provided settings is straightforward and making use of them is highly +recommended. See the ServerManagedPolicy implementation for an example of how to +extract and use the extras. For a list of server settings and information about +how to use them, see Server Response +Extras.
+ +For certain types of licensing responses, the licensing server appends extra +settings to the responses, to help the application manage licensing effectively. +
+ +See Server Response Extras
+for
+a list of settings and ServerManagedPolicy.java for information
+about how a {@code Policy} can use the extras.
The LVL includes a full and recommended implementation of the {@code Policy} +interface called ServerManagedPolicy. The implementation is integrated with the +LVL classes and serves as the default {@code Policy} in the library.
+ +ServerManagedPolicy provides all of the handling for license and retry
+responses. It caches all of the response data locally in a
+{@link android.content.SharedPreferences} file, obfuscating it with the
+application's {@code Obfuscator} implementation. This ensures that the license response
+data is secure and persists across device power cycles. ServerManagedPolicy
+provides concrete implementations of the interface methods
+processServerResponse() and allowAccess() and also
+includes a set of supporting methods and types for managing license
+responses.
Importantly, a key feature of ServerMangedPolicy is its use of
+server-provided settings as the basis for managing licensing across an
+application's refund period and through varying network and error conditions.
+When an application contacts the Google Play server for a license check, the
+server appends several settings as key-value pairs in the extras field of certain
+license response types. For example, the server provides recommended values for the
+application's license validity period, retry grace period, and maximum allowable
+retry count, among others. ServerManagedPolicy extracts the values from the
+license response in its processServerResponse() method and checks
+them in its allowAccess() method. For a list of the server-provided
+settings used by ServerManagedPolicy, see Server Response
+Extras.
For convenience, best performance, and the benefit of using license settings +from the Google Play server, using ServerManagedPolicy as your +licensing {@code Policy} is strongly recommended.
+ +If you are concerned about the security of license response data that is +stored locally in {@link android.content.SharedPreferences}, you can use a stronger obfuscation +algorithm or design a stricter {@code Policy} that does not store license data. The LVL +includes an example of such a {@code Policy} — see StrictPolicy for more information.
+ +To use ServerManagedPolicy, simply import it to your Activity, create an +instance, and pass a reference to the instance when constructing your +{@code LicenseChecker}. See Instantiate LicenseChecker and +LicenseCheckerCallback for more information.
+ +The LVL includes an alternative full implementation of the {@code Policy} interface +called StrictPolicy. The StrictPolicy implementation provides a more restrictive +Policy than ServerManagedPolicy, in that it does not allow the user to access +the application unless a license response is received from the server at the +time of access that indicates that the user is licensed.
+ +The principal feature of StrictPolicy is that it does not store any +license response data locally, in a persistent store. Because no data is stored, +retry requests are not tracked and cached responses can not be used to fulfill +license checks. The {@code Policy} allows access only if:
+ +Using StrictPolicy is appropriate if your primary concern is to ensure that, +in all possible cases, no user will be allowed to access the application unless +the user is confirmed to be licensed at the time of use. Additionally, the +Policy offers slightly more security than ServerManagedPolicy — since +there is no data cached locally, there is no way a malicious user could tamper +with the cached data and obtain access to the application.
+ +At the same time, this {@code Policy} presents a challenge for normal users, since it +means that they won't be able to access the application when there is no network +(cell or Wi-Fi) connection available. Another side-effect is that your +application will send more license check requests to the server, since using a +cached response is not possible.
+ +Overall, this policy represents a tradeoff of some degree of user convenience +for absolute security and control over access. Consider the tradeoff carefully +before using this {@code Policy}.
+ +To use StrictPolicy, simply import it to your Activity, create an instance, +and pass a reference to it when constructing your {@code LicenseChecker}. See +Instantiate LicenseChecker and LicenseCheckerCallback +for more information.
+ +The LVL includes a full {@code Obfuscator} implementation in the
+AESObfuscator.java file. The {@code Obfuscator} uses AES encryption to
+obfuscate/unobfuscate data. If you are using a {@code Policy} (such as
+ServerManagedPolicy) that caches license response data, using AESObfuscator as
+basis for your {@code Obfuscator} implementation is highly recommended.
A typical {@code Policy} implementation needs to save the license response data for +an application to a persistent store, so that it is accessible across +application invocations and device power cycles. For example, a {@code Policy} would +maintain the timestamp of the last successful license check, the retry count, +the license validity period, and similar information in a persistent store, +rather than resetting the values each time the application is launched. The +default {@code Policy} included in the LVL, ServerManagedPolicy, stores license response +data in a {@link android.content.SharedPreferences} instance, to ensure that the +data is persistent.
+ +Because the {@code Policy} will use stored license response data to determine whether +to allow or disallow access to the application, it must ensure that any +stored data is secure and cannot be reused or manipulated by a root user on a +device. Specifically, the {@code Policy} must always obfuscate the data before storing +it, using a key that is unique for the application and device. Obfuscating using +a key that is both application-specific and device-specific is critical, because +it prevents the obfuscated data from being shared among applications and +devices.
+ +The LVL assists the application with storing its license response data in a +secure, persistent manner. First, it provides an {@code Obfuscator} +interface that lets your application supply the obfuscation algorithm of its +choice for stored data. Building on that, the LVL provides the helper class +PreferenceObfuscator, which handles most of the work of calling the +application's {@code Obfuscator} class and reading and writing the obfuscated data in a +{@link android.content.SharedPreferences} instance.
+ +The LVL provides a full {@code Obfuscator} implementation called +AESObfuscator that uses AES encryption to obfuscate data. You can +use AESObfuscator in your application without modification or you +can adapt it to your needs. For more information, see the next section.
+ + +The LVL includes a full and recommended implementation of the {@code Obfuscator} +interface called AESObfuscator. The implementation is integrated with the +LVL sample application and serves as the default {@code Obfuscator} in the library.
+ +AESObfuscator provides secure obfuscation of data by using AES to +encrypt and decrypt the data as it is written to or read from storage. +The {@code Obfuscator} seeds the encryption using three data fields provided +by the application:
+ +To use AESObfuscator, first import it to your Activity. Declare a private +static final array to hold the salt bytes and initialize it to 20 randomly +generated bytes.
+ + ...
+ // Generate 20 random bytes, and put them here.
+ private static final byte[] SALT = new byte[] {
+ -46, 65, 30, -128, -103, -57, 74, -64, 51, 88, -95,
+ -45, 77, -117, -36, -113, -11, 32, -64, 89
+ };
+ ...
+
+
+Next, declare a variable to hold a device identifier and generate a value for
+it in any way needed. For example, the sample application included in the LVL
+queries the system settings for the
+android.Settings.Secure.ANDROID_ID, which is unique to each device.
+
Note that, depending on the APIs you use, your application might need to
+request additional permissions in order to acquire device-specific information.
+For example, to query the {@link android.telephony.TelephonyManager} to obtain
+the device IMEI or related data, the application will also need to request the
+android.permission.READ_PHONE_STATE permission in its manifest.
Before requesting new permissions for the sole purpose of acquiring
+device-specific information for use in your {@code Obfuscator}, consider
+how doing so might affect your application or its filtering on Google Play
+(since some permissions can cause the SDK build tools to add
+the associated <uses-feature>).
Finally, construct an instance of AESObfuscator, passing the salt, +application identifier, and device identifier. You can construct the instance +directly, while constructing your {@code Policy} and {@code LicenseChecker}. For example:
+ +... + // Construct the LicenseChecker with a Policy. + mChecker = new LicenseChecker( + this, new ServerManagedPolicy(this, + new AESObfuscator(SALT, getPackageName(), deviceId)), + BASE64_PUBLIC_KEY // Your public licensing key. + ); + ... ++ +
For a complete example, see MainActivity in the LVL sample application.
+ + +Once you've implemented a {@code Policy} for managing access to your application, the +next step is to add a license check to your application, which initiates a query +to the licensing server if needed and manages access to the application based on +the license response. All of the work of adding the license check and handling +the response takes place in your main {@link android.app.Activity} source file. +
+ +To add the license check and handle the response, you must:
+ +The sections below describe these tasks.
+ +The sample application included with the LVL provides a full example of how
+to initiate a license check and handle the result, in the
+MainActivity.java file.
In most cases, you should add the license check to your application's main +{@link android.app.Activity}, in the {@link android.app.Activity#onCreate onCreate()} method. This +ensures that when the user launches your application directly, the license check +will be invoked immediately. In some cases, you can add license checks in other +locations as well. For example, if your application includes multiple Activity +components that other applications can start by {@link android.content.Intent}, +you could add license checks in those Activities.
+ +A license check consists of two main actions:
+ +checkAccess() method of a {@code LicenseChecker} object that
+you construct.LicenseCheckerCallback interface that you implement. The
+interface declares two methods, allow() and
+dontAllow(), which are invoked by the library based on to the
+result of the license check. You implement these two methods with whatever logic
+you need, to allow or disallow the user access to your application. Note that
+these methods do not determine whether to allow access — that
+determination is the responsibility of your {@code Policy} implementation. Rather, these
+methods simply provide the application behaviors for how to allow and
+disallow access (and handle application errors).
+ The allow() and dontAllow() methods do provide a "reason"
+for their response, which can be one of the {@code Policy} values, {@code LICENSED},
+{@code NOT_LICENSED}, or {@code RETRY}. In particular, you should handle the case in which
+the method receives the {@code RETRY} response for {@code dontAllow()} and provide the user with an
+"Retry" button, which might have happened because the service was unavailable during the
+request.
+The diagram above illustrates how a typical license check takes place:
+ +checkAccess() method on the
+{@code LicenseChecker} object. The method implementation calls the {@code Policy} to determine
+whether there is a valid license response cached locally, in
+{@link android.content.SharedPreferences}.
+ checkAccess() implementation calls
+ allow().Note: The licensing server always returns
+LICENSED when you perform a license check of a draft application.
allow() method on the {@code LicenseCheckerCallback} object. dontAllow() method on {@code LicenseCheckerCallback}. processServerResponse() method.
+ Also, both the {@code allow()} and {@code dontAllow()} callback methods receive a
+reason argument. The {@code allow()} method's reason is usually {@code
+Policy.LICENSED} or {@code Policy.RETRY} and the {@code dontAllow()} reason is usually {@code
+Policy.NOT_LICENSED} or {@code Policy.RETRY}. These response values are useful so you can show
+an appropriate response for the user, such as by providing a "Retry" button when {@code
+dontAllow()} responds with {@code Policy.RETRY}, which might have been because the service was
+unavailable.
applicationError()
+method. Note that, in addition to initiating the license check and handling the +result, which are described in the sections below, your application also needs +to provide a Policy implementation and, if the {@code Policy} +stores response data (such as ServerManagedPolicy), an Obfuscator implementation.
+ + +First, open the class file of the application's main Activity and import +{@code LicenseChecker} and {@code LicenseCheckerCallback} from the LVL package.
+ +import com.android.vending.licensing.LicenseChecker; + import com.android.vending.licensing.LicenseCheckerCallback;+ +
If you are using the default {@code Policy} implementation provided with the LVL, +ServerManagedPolicy, import it also, together with the AESObfuscator. If you are +using a custom {@code Policy} or {@code Obfuscator}, import those instead.
+ +import com.android.vending.licensing.ServerManagedPolicy; + import com.android.vending.licensing.AESObfuscator;+ +
{@code LicenseCheckerCallback} is an interface provided by the LVL for handling +result of a license check. To support licensing using the LVL, you must +implement {@code LicenseCheckerCallback} and +its methods to allow or disallow access to the application.
+ +The result of a license check is always a call to one of the +{@code LicenseCheckerCallback} methods, made based on the validation of the response +payload, the server response code itself, and any additional processing provided +by your {@code Policy}. Your application can implement the methods in any way needed. In +general, it's best to keep the methods simple, limiting them to managing UI +state and application access. If you want to add further processing of license +responses, such as by contacting a backend server or applying custom constraints, +you should consider incorporating that code into your {@code Policy}, rather than +putting it in the {@code LicenseCheckerCallback} methods.
+ +In most cases, you should declare your implementation of +{@code LicenseCheckerCallback} as a private class inside your application's main +Activity class.
+ +Implement the allow() and dontAllow() methods as
+needed. To start with, you can use simple result-handling behaviors in the
+methods, such as displaying the license result in a dialog. This helps you get
+your application running sooner and can assist with debugging. Later, after you
+have determined the exact behaviors you want, you can add more complex handling.
+
Some suggestions for handling unlicensed responses in
+dontAllow() include:
reason supplied is {@code Policy.RETRY}. The example below shows how the LVL sample application implements +{@code LicenseCheckerCallback}, with methods that display the license check result in a +dialog.
+ +
+private class MyLicenseCheckerCallback implements LicenseCheckerCallback {
+ public void allow(int reason) {
+ if (isFinishing()) {
+ // Don't update UI if Activity is finishing.
+ return;
+ }
+ // Should allow user access.
+ displayResult(getString(R.string.allow));
+ }
+
+ public void dontAllow(int reason) {
+ if (isFinishing()) {
+ // Don't update UI if Activity is finishing.
+ return;
+ }
+ displayResult(getString(R.string.dont_allow));
+
+ if (reason == Policy.RETRY) {
+ // If the reason received from the policy is RETRY, it was probably
+ // due to a loss of connection with the service, so we should give the
+ // user a chance to retry. So show a dialog to retry.
+ showDialog(DIALOG_RETRY);
+ } else {
+ // Otherwise, the user is not licensed to use this app.
+ // Your response should always inform the user that the application
+ // is not licensed, but your behavior at that point can vary. You might
+ // provide the user a limited access version of your app or you can
+ // take them to Google Play to purchase the app.
+ showDialog(DIALOG_GOTOMARKET);
+ }
+ }
+}
+
+
+Additionally, you should implement the applicationError()
+method, which the LVL calls to let your application handle errors that are not
+retryable. For a list of such errors, see Server
+Response Codes in the Licensing Reference. You can implement
+the method in any way needed. In most cases, the
+method should log the error code and call dontAllow().
During a license check, the LVL passes the request to the Google Play +application, which handles communication with the licensing server. The LVL +passes the request over asynchronous IPC (using {@link android.os.Binder}) so +the actual processing and network communication do not take place on a thread +managed by your application. Similarly, when the Google Play application +receives the result, it invokes a callback method over IPC, which in turn +executes in an IPC thread pool in your application's process.
+ +The {@code LicenseChecker} class manages your application's IPC communication with +the Google Play application, including the call that sends the request and +the callback that receives the response. {@code LicenseChecker} also tracks open license +requests and manages their timeouts.
+ +So that it can handle timeouts properly and also process incoming responses +without affecting your application's UI thread, {@code LicenseChecker} spawns a +background thread at instantiation. In the thread it does all processing of +license check results, whether the result is a response received from the server +or a timeout error. At the conclusion of processing, the LVL calls your +{@code LicenseCheckerCallback} methods from the background thread.
+ +To your application, this means that:
+ +If you want your {@code LicenseCheckerCallback} methods to update the UI thread,
+instantiate a {@link android.os.Handler} in the main Activity's
+{@link android.app.Activity#onCreate(android.os.Bundle) onCreate()} method,
+as shown below. In this example, the LVL sample application's
+{@code LicenseCheckerCallback} methods (see above) call displayResult() to
+update the UI thread through the Handler's
+{@link android.os.Handler#post(java.lang.Runnable) post()} method.
private Handler mHandler;
+
+ @Override
+ public void onCreate(Bundle savedInstanceState) {
+ ...
+ mHandler = new Handler();
+ }
+
+
+Then, in your {@code LicenseCheckerCallback} methods, you can use Handler methods to +post Runnable or Message objects to the Handler. Here's how the sample +application included in the LVL posts a Runnable to a Handler in the UI thread +to display the license status.
+ + private void displayResult(final String result) {
+ mHandler.post(new Runnable() {
+ public void run() {
+ mStatusText.setText(result);
+ setProgressBarIndeterminateVisibility(false);
+ mCheckLicenseButton.setEnabled(true);
+ }
+ });
+ }
+
+
+In the main Activity's +{@link android.app.Activity#onCreate(android.os.Bundle) onCreate()} method, +create private instances of LicenseCheckerCallback and {@code LicenseChecker}. You must +instantiate {@code LicenseCheckerCallback} first, because you need to pass a reference +to that instance when you call the constructor for {@code LicenseChecker}.
+ +When you instantiate {@code LicenseChecker}, you need to pass in these parameters:
+ +If you are using ServerManagedPolicy, you won't need to access the class +directly, so you can instantiate it in the {@code LicenseChecker} constructor, +as shown in the example below. Note that you need to pass a reference to a new +Obfuscator instance when you construct ServerManagedPolicy.
+ +The example below shows the instantiation of {@code LicenseChecker} and
+{@code LicenseCheckerCallback} from the onCreate() method of an Activity
+class.
public class MainActivity extends Activity {
+ ...
+ private LicenseCheckerCallback mLicenseCheckerCallback;
+ private LicenseChecker mChecker;
+
+ @Override
+ public void onCreate(Bundle savedInstanceState) {
+ super.onCreate(savedInstanceState);
+ ...
+ // Construct the LicenseCheckerCallback. The library calls this when done.
+ mLicenseCheckerCallback = new MyLicenseCheckerCallback();
+
+ // Construct the LicenseChecker with a Policy.
+ mChecker = new LicenseChecker(
+ this, new ServerManagedPolicy(this,
+ new AESObfuscator(SALT, getPackageName(), deviceId)),
+ BASE64_PUBLIC_KEY // Your public licensing key.
+ );
+ ...
+ }
+}
+
+
+
+Note that {@code LicenseChecker} calls the {@code LicenseCheckerCallback} methods from the UI +thread only if there is valid license response cached locally. If the +license check is sent to the server, the callbacks always originate from the +background thread, even for network errors.
+ + +In your main Activity, add a call to the checkAccess() method of the
+{@code LicenseChecker} instance. In the call, pass a reference to your
+{@code LicenseCheckerCallback} instance as a parameter. If you need to handle any
+special UI effects or state management before the call, you might find it useful
+to call checkAccess() from a wrapper method. For example, the LVL
+sample application calls checkAccess() from a
+doCheck() wrapper method:
@Override
+ public void onCreate(Bundle savedInstanceState) {
+ super.onCreate(savedInstanceState);
+ ...
+ // Call a wrapper method that initiates the license check
+ doCheck();
+ ...
+ }
+ ...
+ private void doCheck() {
+ mCheckLicenseButton.setEnabled(false);
+ setProgressBarIndeterminateVisibility(true);
+ mStatusText.setText(R.string.checking_license);
+ mChecker.checkAccess(mLicenseCheckerCallback);
+ }
+
+
+
+For each publisher account, the Google Play service automatically +generates a 2048-bit RSA public/private key pair that is used exclusively for +licensing. The key pair is uniquely associated with the publisher account and is +shared across all applications that are published through the account. Although +associated with a publisher account, the key pair is not the same as +the key that you use to sign your applications (or derived from it).
+ +The Google Play publisher site exposes the public key for licensing to any +developer signed in to the publisher account, but it keeps the private key +hidden from all users in a secure location. When an application requests a +license check for an application published in your account, the licensing server +signs the license response using the private key of your account's key pair. +When the LVL receives the response, it uses the public key provided by the +application to verify the signature of the license response.
+ +To add licensing to an application, you must obtain your publisher account's +public key for licensing and copy it into your application. Here's how to find +your account's public key for licensing:
+ +To add the public key to your application, simply copy/paste the key string
+from the text box into your application as the value of the String variable
+BASE64_PUBLIC_KEY. When you are copying, make sure that you have
+selected the entire key string, without omitting any characters.
Here's an example from the LVL sample application:
+ + public class MainActivity extends Activity {
+ private static final String BASE64_PUBLIC_KEY = "MIIBIjANBgkqhkiG ... "; //truncated for this example
+ ...
+ }
+
+
+Finally, to let the LVL clean up before your application
+{@link android.content.Context} changes, add a call to the {@code LicenseChecker}'s
+onDestroy() method from your Activity's
+{@link android.app.Activity#onDestroy()} implementation. The call causes the
+{@code LicenseChecker} to properly close any open IPC connection to the Google Play
+application's ILicensingService and removes any local references to the service
+and handler.
Failing to call the {@code LicenseChecker}'s onDestroy() method
+can lead to problems over the lifecycle of your application. For example, if the
+user changes screen orientation while a license check is active, the application
+{@link android.content.Context} is destroyed. If your application does not
+properly close the {@code LicenseChecker}'s IPC connection, your application will crash
+when the response is received. Similarly, if the user exits your application
+while a license check is in progress, your application will crash when the
+response is received, unless it has properly called the
+{@code LicenseChecker}'s onDestroy() method to disconnect from the service.
+
Here's an example from the sample application included in the LVL, where
+mChecker is the {@code LicenseChecker} instance:
@Override
+ protected void onDestroy() {
+ super.onDestroy();
+ mChecker.onDestroy();
+ ...
+ }
+
+
+If you are extending or modifying {@code LicenseChecker}, you might also need to call
+the {@code LicenseChecker}'s finishCheck() method, to clean up any open IPC
+connections.
In some cases, you might want your {@code Policy} to limit the number of actual +devices that are permitted to use a single license. This would prevent a user +from moving a licensed application onto a number of devices and using the +application on those devices under the same account ID. It would also prevent a +user from "sharing" the application by providing the account information +associated with the license to other individuals, who could then sign in to that +account on their devices and access the license to the application.
+ +The LVL supports per-device licensing by providing a
+DeviceLimiter interface, which declares a single method,
+allowDeviceAccess(). When a LicenseValidator is handling a response
+from the licensing server, it calls allowDeviceAccess(), passing a
+user ID string extracted from the response.
If you do not want to support device limitation, no work is
+required — the {@code LicenseChecker} class automatically uses a default
+implementation called NullDeviceLimiter. As the name suggests, NullDeviceLimiter
+is a "no-op" class whose allowDeviceAccess() method simply returns
+a LICENSED response for all users and devices.
Caution: Per-device licensing is not recommended for +most applications because:
+To ensure the security of your application, particularly for a paid +application that uses licensing and/or custom constraints and protections, it's +very important to obfuscate your application code. Properly obfuscating your +code makes it more difficult for a malicious user to decompile the application's +bytecode, modify it — such as by removing the license check — +and then recompile it.
+ +Several obfuscator programs are available for Android applications, including +ProGuard, which also offers +code-optimization features. The use of ProGuard or a similar program to obfuscate +your code is strongly recommended for all applications that use Google +Play Licensing.
+ +When you are finished testing your license implementation, you are ready to +publish the application on Google Play. Follow the normal steps to prepare, sign, and then publish the application. +
+ +After uploading your licensed application, remember to remove copy protection +from the application, if it is currently used. To check and remove copy +protection, sign in to the publisher site and go the application's upload +details page. In the Publishing options section, make sure that the Copy +Protection radio button selection is "Off".
+ + +If you have questions or encounter problems while implementing or deploying +publishing in your applications, please use the support resources listed in the +table below. By directing your queries to the correct forum, you can get the +support you need more quickly.
+ +Table 2. Developer support resources +for Google Play Licensing Service.
+ +| Support Type | +Resource | +Range of Topics | +
|---|---|---|
| Development and testing issues | +Google Groups: android-developers + | +LVL download and integration, library projects, {@code Policy} +questions, user experience ideas, handling of responses, {@code Obfuscator}, IPC, test +environment setup | +
| Stack Overflow: http://stackoverflow.com/questions/tagged/android | +||
| Accounts, publishing, and deployment issues | +Google Play +Help Forum | +Publisher accounts, licensing key pair, test accounts, server +responses, test responses, application deployment and results | +
| Market +Licensing Support FAQ | +||
| LVL issue tracker | +Marketlicensing +project issue tracker | +Bug and issue reports related specifically to the LVL source code classes +and interface implementations | +
For general information about how to post to the groups listed above, see Developer Forums document +in the Resources tab.
+ + diff --git a/docs/html/guide/google/play/licensing/index.jd b/docs/html/guide/google/play/licensing/index.jd new file mode 100644 index 000000000000..d393738bac17 --- /dev/null +++ b/docs/html/guide/google/play/licensing/index.jd @@ -0,0 +1,61 @@ +page.title=Application Licensing +@jd:body + + +Google Play offers a licensing service that lets you enforce licensing policies for +applications that you publish on Google Play. With Google Play Licensing, your application can +query Google Play at run time to obtain the 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—each application can enforce licensing in the way most appropriate for it. If necessary, +an application can apply custom constraints based on the licensing status obtained from Google Play. +For example, an application can check the licensing status and then apply custom constraints +that allow the user to run it unlicensed for a specific validity period. An application can also +restrict use of the application to a specific device, in addition to any other constraints.
+ +The licensing service is a secure means of controlling access to your applications. When an
+application checks the licensing status, the Google Play server signs the licensing status
+response using a key pair that is uniquely associated with the publisher account. Your application
+stores the public key in its compiled .apk file and uses it to verify the licensing
+status response.
Any application that you publish through Google Play can use the Google Play Licensing +service. No special account or registration is needed. Additionally, because the service uses no +dedicated framework APIs, you can add licensing to any application that uses a minimum API level of +3 or higher.
+ +Note: The Google Play Licensing service is primarily intended +for paid applications that wish to verify that the current user did in fact pay for the application +on Google Play. However, any application (including free apps) may use the licensing service +to initiate the download of an APK expansion file. In which case, the request that your application +sends to the licensing service is not to check whether the user paid for the app, but to request the +URL of the expansion files. For information about downloading expansion files for your application, +read the guide to APK Expansion Files.
+ + +To learn more about Google Play's application licensing service and start integrating it into +your applications, read the following documents:
+ +Table 1 lists all of the source files in the License Verification
+Library (LVL) available through the Android SDK. All of the files are part of
+the com.android.vending.licensing package.
Table 1. Summary of LVL library +classes and interfaces.
+ +| Category | +Name | +Description | +
|---|---|---|
| License check and result | +LicenseChecker | +Class that you instantiate (or subclass) to initiate a license check. | +
| LicenseCheckerCallback | +Interface that you implement to handle result of the license check. | +|
| Policy | +Policy | +Interface that you implement to determine whether to allow +access to the application, based on the license response. | +
| ServerManagedPolicy | +Default {@code Policy} implementation. Uses settings provided by the +licensing server to manage local storage of license data, license validity, +retry. | +|
| StrictPolicy | +Alternative {@code Policy} implementation. Enforces licensing based on a direct +license response from the server only. No caching or request retry. | +|
| Data obfuscation (optional) |
+Obfuscator | +Interface that you implement if you are using a {@code Policy} (such as +ServerManagedPolicy) that caches license response data in a persistent store. +Applies an obfuscation algorithm to encode and decode data being written or +read. | +
| AESObfuscator | +Default Obfuscator implementation that uses AES encryption/decryption +algorithm to obfuscate/unobfuscate data. | +|
| Device limitation (optional) |
+DeviceLimiter | +Interface that you implement if you want to restrict use of an +application to a specific device. Called from LicenseValidator. Implementing +DeviceLimiter is not recommended for most applications because it requires a +backend server and may cause the user to lose access to licensed applications, +unless designed with care. | +
| NullDeviceLimiter | +Default DeviceLimiter implementation that is a no-op (allows access to all +devices). | +|
| Library core, no integration needed | +ResponseData | +Class that holds the fields of a license response. | +
| LicenseValidator | +Class that decrypts and verifies a response received from the licensing +server. | +|
| ValidationException | +Class that indicates errors that occur when validating the integrity of data +managed by an Obfuscator. | +|
| PreferenceObfuscator | +Utility class that writes/reads obfuscated data to the system's +{@link android.content.SharedPreferences} store. | +|
| ILicensingService | +One-way IPC interface over which a license check request is passed to the +Google Play client. | +|
| ILicenseResultListener | +One-way IPC callback implementation over which the application receives an +asynchronous response from the licensing server. | +
Table 2 lists all of the license response codes supported by the +licensing server. In general, an application should handle all of these response +codes. By default, the LicenseValidator class in the LVL provides all of the +necessary handling of these response codes for you.
+ +Table 2. Summary of response codes +returned by the Google Play server in a license response.
+ +| Response Code | +Description | +Signed? | +Extras | +Comments | +
|---|---|---|---|---|
| {@code LICENSED} | +The application is licensed to the user. The user has purchased the +application or the application only exists as a draft. | +Yes | +VT, GT, GR |
+Allow access according to {@code Policy} constraints. | +
| {@code LICENSED_OLD_KEY} | +The application is licensed to the user, but there is an updated application +version available that is signed with a different key. | +Yes | +VT, GT, GR, UT |
+Optionally allow access according to {@code Policy} constraints.
+ Can indicate that the key pair used by the installed +application version is invalid or compromised. The application can allow access +if needed or inform the user that an upgrade is available and limit further use +until upgrade. + |
+
| {@code NOT_LICENSED} | +The application is not licensed to the user. | +No | ++ | Do not allow access. | +
| {@code ERROR_CONTACTING_SERVER} | +Local error — the Google Play application was not able to reach the +licensing server, possibly because of network availability problems. | +No | ++ | Retry the license check according to {@code Policy} retry limits. | +
| {@code ERROR_SERVER_FAILURE} | +Server error — the server could not load the publisher account's key +pair for licensing. | +No | ++ | Retry the license check according to {@code Policy} retry limits. + | +
| {@code ERROR_INVALID_PACKAGE_NAME} | +Local error — the application requested a license check for a package +that is not installed on the device. | +No | ++ | Do not retry the license check.
+ Typically caused by a development error. + |
+
| {@code ERROR_NON_MATCHING_UID} | +Local error — the application requested a license check for a package +whose UID (package, user ID pair) does not match that of the requesting +application. | +No | ++ | Do not retry the license check.
+ Typically caused by a development error. + |
+
| {@code ERROR_NOT_MARKET_MANAGED} | +Server error — the application (package name) was not recognized by +Google Play. | +No | ++ | Do not retry the license check.
+ Can indicate that the application was not published +through Google Play or that there is an development error in the licensing +implementation. + |
+
Note: As documented in
+Setting Up The Testing Environment, the response code can be manually
+overridden for the application developer and any registered test users via the
+Google Play publisher site.
+
+Additionally, as noted above, applications that are in draft mode (in other
+words, applications that have been uploaded but have never been
+published) will return {@code LICENSED} for all users, even if not listed as a test
+user. Since the application has never been offered for download, it is assumed
+that any users running it must have obtained it from an authorized channel for
+testing purposes.
To assist your application in managing access to the application across the application refund +period and provide other information, The licensing server includes several pieces of +information in the license responses. Specifically, the service provides recommended values for the +application's license validity period, retry grace period, maximum allowable retry count, and other +settings. If your application uses APK +expansion files, the response also includes the file names, sizes, and URLs. The server appends +the settings as key-value pairs in the license response "extras" field.
+ +Any {@code Policy} implementation can extract the extras settings from the license +response and use them as needed. The LVL default {@code Policy} implementation, {@code +ServerManagedPolicy}, serves as a working +implementation and an illustration of how to obtain, store, and use the +settings.
+ +Table 3. Summary of +license-management settings supplied by the Google Play server in a license +response.
+ +| Extra | Description | +
|---|---|
| {@code VT} | +License validity timestamp. Specifies the date/time at which the current +(cached) license response expires and must be rechecked on the licensing server. See the section +below about License validity period. + | +
| {@code GT} | +Grace period timestamp. Specifies the end of the period during which a
+Policy may allow access to the application, even though the response status is
+{@code RETRY}. The value is managed by the server, however a typical value would be 5 +or more days. See the section +below about Retry period and maximum retry count. |
+
| {@code GR} | +Maximum retries count. Specifies how many consecutive {@code RETRY} license checks
+the {@code Policy} should allow, before denying the user access to the application.
+ The value is managed by the server, however a typical value would be "10" or +higher. See the section +below about Retry period and maximum retry count. |
+
| {@code UT} | +Update timestamp. Specifies the day/time when the most recent update to
+this application was uploaded and published. The server returns this extra +only for {@code LICENSED_OLD_KEYS} responses, to allow the {@code Policy} to determine how much +time has elapsed since an update was published with new licensing keys before +denying the user access to the application. |
+
| {@code FILE_URL1} or {@code FILE_URL2} | +The URL for an expansion file (1 is for the main file, 2 is the patch file). Use this to +download the file over HTTP. | +
| {@code FILE_NAME1} or {@code FILE_NAME2} | +The expansion file's name (1 is for the main file, 2 is the patch file). You must use this +name when saving the file on the device. | +
| {@code FILE_SIZE1} or {@code FILE_SIZE2} | +The size of the file in bytes (1 is for the main file, 2 is the patch file). Use this to +assist with downloading and to ensure that enough space is available on the device's shared +storage location before downloading. | +
The Google Play licensing server sets a license validity period for all +downloaded applications. The period expresses the interval of time over which an +application's license status should be considered as unchanging and cacheable by +a licensing {@code Policy} in the application. The licensing server includes the +validity period in its response to all license checks, appending an +end-of-validity timestamp to the response as an extra under the key {@code VT}. A +{@code Policy} can extract the VT key value and use it to conditionally allow access to +the application without rechecking the license, until the validity period +expires.
+ +The license validity signals to a licensing {@code Policy} when it must recheck the +licensing status with the licensing server. It is not intended to imply +whether an application is actually licensed for use. That is, when an +application's license validity period expires, this does not mean that the +application is no longer licensed for use — rather, it indicates only that +the {@code Policy} must recheck the licensing status with the server. It follows that, +as long as the license validity period has not expired, it is acceptable for the +{@code Policy} to cache the initial license status locally and return the cached license +status instead of sending a new license check to the server.
+ +The licensing server manages the validity period as a means of helping the +application properly enforce licensing across the refund period offered by +Google Play for paid applications. It sets the validity period based on +whether the application was purchased and, if so, how long ago. Specifically, +the server sets a validity period as follows:
+ +long.MAX_VALUE). This ensures that, provided the {@code Policy} has
+cached the validity timestamp locally, it will not need to recheck the
+license status of the application in the future.The {@code ServerManagedPolicy} implementation uses the extracted timestamp
+(mValidityTimestamp) as a primary condition for determining whether
+to recheck the license status with the server before allowing the user access to
+the application.
In some cases, system or network conditions can prevent an application's +license check from reaching the licensing server, or prevent the server's +response from reaching the Google Play client application. For example, the +user might launch an application when there is no cell network or data +connection available—such as when on an airplane—or when the +network connection is unstable or the cell signal is weak.
+ +When network problems prevent or interrupt a license check, the Google
+Play client notifies the application by returning a {@code RETRY} response code to
+the {@code Policy}'s processServerResponse() method. In the case of system
+problems, such as when the application is unable to bind with Google Play's
+{@code ILicensingService} implementation, the {@code LicenseChecker} library itself calls the
+Policy processServerResonse() method with a {@code RETRY} response code.
+
In general, the {@code RETRY} response code is a signal to the application that an +error has occurred that has prevented a license check from completing. + +
The Google Play server helps an application to manage licensing under +error conditions by setting a retry "grace period" and a recommended maximum +retries count. The server includes these values in all license check responses, +appending them as extras under the keys {@code GT} and {@code GR}.
+ +The application {@code Policy} can extract the {@code GT} and {@code GR} extras and use them to +conditionally allow access to the application, as follows:
+ +The {@code ServerManagedPolicy} uses the server-supplied {@code GT} and {@code GR} values as
+described above. The example below shows the conditional handling of the retry
+responses in the allow() method. The count of {@code RETRY} responses is
+maintained in the processServerResponse() method, not shown.
+public boolean allowAccess() {
+ long ts = System.currentTimeMillis();
+ if (mLastResponse == LicenseResponse.LICENSED) {
+ // Check if the LICENSED response occurred within the validity timeout.
+ if (ts <= mValidityTimestamp) {
+ // Cached LICENSED response is still valid.
+ return true;
+ }
+ } else if (mLastResponse == LicenseResponse.RETRY &&
+ ts < mLastResponseTime + MILLIS_PER_MINUTE) {
+ // Only allow access if we are within the retry period or we haven't used up our
+ // max retries.
+ return (ts <= mRetryUntil || mRetryCount <= mMaxRetries);
+ }
+ return false;
+}
+
diff --git a/docs/html/guide/google/play/licensing/overview.jd b/docs/html/guide/google/play/licensing/overview.jd
new file mode 100644
index 000000000000..467a3a2c151c
--- /dev/null
+++ b/docs/html/guide/google/play/licensing/overview.jd
@@ -0,0 +1,246 @@
+page.title=Licensing Overview
+parent.title=Application Licensing
+parent.link=index.html
+@jd:body
+
+
+Google Play Licensing is a network-based service that lets an application query a trusted +Google Play licensing server to determine whether the application is licensed to the current +device user. The licensing service is based on the capability of the Google Play licensing server +to determine whether a given user is licensed to use a given application. Google Play considers a +user to be licensed if the user is a recorded purchaser of the application.
+ +The request starts when your application makes a request to a service hosted by +the Google Play client application. The Google Play application then sends a request to +the licensing server and receives the result. The Google Play application sends +the result to your application, which can allow or disallow further use of the +application as needed.
+ +Note: If a paid application has been uploaded to Google Play but +saved only as a draft application (the app is unpublished), the licensing server considers all users +to be licensed users of the application (because it's not even possible to purchase the app). +This exception is necessary in order for you to perform testing of your licensing +implementation.
+ + +
+Figure 1. Your application initiates a +license check through the License Verification Library and the Google Play +client, which handles communication with the Google Play server.
+To properly identify the user and determine the license status, the licensing server requires +information about the application and user—your application and the Google Play client work +together to assemble the information and the Google Play client passes it to the server.
+ +To help you add licensing to your application, the Android SDK provides a downloadable set of +library sources that you can include in your application project: the Google Market +Licensing package. The License Verification Library (LVL) is a library you can add to your +application that +handles all of the licensing-related communication with the Google Play licensing service. With +the LVL added to your application, your application can determine its licensing status for the +current user by simply calling a method and implementing a callback that receives the status +response.
+ +Your application does not query the licensing server +directly, but instead calls the Google Play client over remote IPC to +initiate a license request. In the license request:
+ +You can choose when, and how often, you want your application to check its +license and you have full control over how it handles the response, verifies the +signed response data, and enforces access controls.
+ +Notice that during a license check, your application does not manage any +network connections or use any licensing related APIs in the Android platform.
+ + + + +To ensure the integrity of each license query, the server signs the license +response data using an RSA key pair that is shared exclusively between the Google Play +server and you.
+ +The licensing service generates a single licensing key pair for each +publisher account and exposes the public key in your account's profile page. You must copy the +public key from the web site and embed it in your application source code. The server retains the +private key internally and uses it to sign license responses for the applications you +publish with that account.
+ +When your application receives a signed response, it uses the embedded public +key to verify the data. The use of public key cryptography in the licensing +service makes it possible for the application to detect responses that have been +tampered with or that are spoofed.
+ + + + +The Android SDK provides a downloadable package called the Google Market Licensing package, +which includes the License Verification Library (LVL). The LVL greatly simplifies the process of +adding licensing to your application and helps ensure a more secure, robust implementation for your +application. The LVL provides internal classes that handle most of the standard operations of a +license query, such as contacting the Google Play client to initiate a license request and +verifying and validating the responses. It also exposes interfaces that let you easily plug in your +custom code for defining licensing policy and managing access as needed by your application. The key +LVL interfaces are:
+ +To help you get started with a {@code Policy}, the LVL provides two fully complete +{@code Policy} implementations that you can use without modification or adapt to your +needs:
+ +The LVL is available as a downloadable package of the Android SDK. The +package includes both the LVL itself and an example application that shows how +the library should be integrated with your application and how your application +should manage response data, UI interaction, and error conditions.
+ +The LVL sources are provided as an Android library project, which +means that you can maintain a single set of library sources and share them +across multiple applications. A full test environment is also available through +the SDK, so you can develop and test the licensing implementation in your +applications before publishing them, even if you don't have access to a +physical device.
+ + + + +Google Play Licensing is designed to let you apply license controls to +applications that you publish through Google Play. The service is not +designed to let you control access to applications that are not published +through Google Play or that are run on devices that do not offer the Google +Play client.
+ +Here are some points to keep in mind as you implement licensing in your +application:
+ +Google Play Licensing is a flexible, secure mechanism for controlling +access to your applications. It effectively replaces the Copy Protection +mechanism offered on Google Play and gives you wider distribution +potential for your applications.
+ +Although no license mechanism can completely prevent all unauthorized use, +the licensing service lets you control access for most types of normal usage, +across all compatible devices, locked or unlocked, that run Android 1.5 or +higher version of the platform.
+ +To begin adding application licensing to your application, continue to Setting Up for Licensing.
+ + + + + + diff --git a/docs/html/guide/google/play/licensing/setting-up.jd b/docs/html/guide/google/play/licensing/setting-up.jd new file mode 100644 index 000000000000..80a44192c754 --- /dev/null +++ b/docs/html/guide/google/play/licensing/setting-up.jd @@ -0,0 +1,701 @@ +page.title=Setting Up for Licensing +parent.title=Application Licensing +parent.link=index.html +@jd:body + + +Before you start adding license verification to your application, you need to set up your Google +Play publishing account, your development environment, and test accounts required to verify +your implementation.
+ + +If you don't already have a publisher account for Google Play, you need to register for one +using your Google account and agree to the terms of service on the Google Play publisher site:
+ +http://play.google.com/apps/publish +
+ +For more information, see Get Started with Publishing.
+ +If you already have a publisher account on Google Play, use your existing +account to set up licensing.
+ +Using your publisher account on Google Play, you can:
+ +You can manage several +administrative controls for Google Play licensing on the publisher site. The controls are available +in the Edit Profile page, in the "Licensing" panel, shown in figure 1. The controls +let you:
+ +
+Figure 1. The Licensing +panel of your account's Edit Profile page lets you manage administrative +settings for licensing.
+ +For more information about how to work with test accounts and static test +responses, see Setting Up a Testing Environment, below. + + + +
Setting up your environment for licensing involves these tasks:
+ +The sections below describe these tasks. When you are done with setup, +you can begin Adding +Licensing to Your App.
+ +To get started, you need to set up a proper runtime environment on which +you can run, debug, and test your application's implementation of license +checking and enforcement.
+ + +As described earlier, applications check licensing status not by contacting +the licensing server directly, but by binding to a service provided by the +Google Play application and initiating a license check request. The Google +Play service then handles the direct communication with the licensing server +and finally routes the response back to your application. To debug and test +licensing in your application, you need to set up a runtime environment that +includes the necessary Google Play service, so that your application is able +to send license check requests to the licensing server.
+ +There are two types of runtime environment that you can use:
+ +To use an Android-powered device for +debugging and testing licensing, the device must:
+ +If Google Play is not preinstalled in the system image, your application won't +be able to communicate with the Google Play licensing server.
+ +For general information about how to set up a device for use in developing +Android applications, see Using Hardware Devices.
+ +If you don't have a device available, you can use an Android emulator for debugging and testing +licensing.
+ +Because the Android platforms provided in the Android SDK do +not include Google Play, you need to download the Google APIs Add-On +platform, API level 8 (or higher), from the SDK repository. After downloading +the add-on, you need to create an AVD configuration that uses that system image. +
+ +The Google APIs Add-On does not include the full Google Play client. +However, it does provide:
+ +ILicensingService remote interface, so that your application can
+send license checks over the network to the licensing server. Signing in using your publisher or test account enables you to debug and test +your application without having publish it. For more information see Signing in to an authorized account, below.
Several versions of the Google APIs add-on are available through the SDK Manager, but only +the version for Android 2.2 and higher includes the necessary Google +Play services.
+ +To set up an emulator for adding licensing to an application, follow +these steps:
+ +If you are not familiar with AVDs or how to use them, see Managing Virtual Devices.
+ +After you set up a runtime environment that meets the requirements described
+above — either on an actual device or on an emulator — make sure to
+update your application project or build scripts as needed, so that your compiled
+.apk files that use licensing are deployed into that environment.
+In particular, if you are developing in Eclipse, make sure that you set up a
+Run/Debug Configuration that targets the appropriate device or AVD.
You do not need to make any changes to your application's +build configuration, provided that the project is already configured to compile +against a standard Android 1.5 (API level 3) or higher library. For example: + +
In general, adding licensing to an application should have no impact +whatsoever on the application's build configuration.
+ + +The License Verification Library (LVL) is a collection of helper classes that +greatly simplify the work that you need to do to add licensing to your +application. In all cases, we recommend that you download the LVL and use it as +the basis for the licensing implementation in your application.
+ +The LVL is available as a downloadable package of the Android SDK. The +package includes:
+ +To download the LVL package into your development environment, use the +Android SDK Manager. Launch the Android SDK Manager and then +select the Google Market Licensing package, as shown in figure 2. +Accept the terms and click Install Selected to begin the download.
+ +
+Figure 2. The Licensing package contains the LVL and +the LVL sample application.
+ +When the download is complete, the Android SDK Manager installs both +the LVL library project and the example application into these directories:
+ +<sdk>/extras/google/market_licensing/library/
+ (the LVL library project)
+<sdk>/extras/google/market_licensing/sample/ (the example
+application)
If you aren't familiar with how to download packess into your SDK, see the +Exploring the SDK +document.
+ + +After downloading the LVL to your computer, you need to set it up in your +development environment, either as an Android library project or by +copying (or importing) the library sources directly into your existing +application package. In general, using the LVL as a library project is recommended, +since it lets you reuse your licensing code across multiple applications and +maintain it more easily over time. Note that the LVL is not designed to be +compiled separately and added to an application as a static .jar file.
+ +Because you will be customizing the LVL sources to some extent, you should
+make sure to move or copy the library sources (the entire
+directory at <sdk>/market_licensing/library/)
+to a working directory outside of the SDK. You should then use the relocated
+sources as your working set. If you are using a source-code management
+system, add and track the sources that are in the working location rather
+than those in default location in the SDK.
Moving the library sources is important is because, when you later update the +Licensing package, the SDK installs the new files to the same location as +the older files. Moving your working library files to a safe location ensures +that your work won't be inadvertently overwritten should you download a new +version of the LVL.
+ +The LVL is provided as an Android library project, which means that you can +share its code and resources across multiple applications.
+ +If you aren't familiar with library projects or how +to use them, see +Managing Projects. +
+The recommended way of using the LVL is setting it up as a new Android
+library project. A library project is a type of development project
+that holds shared Android source code and resources. Other Android application
+projects can reference the library project and, at build time, include its
+compiled sources in their .apk files. In the context of licensing,
+this means that you can do most of your licensing development once, in a library
+project, then include the library sources in your various application projects.
+In this way, you can easily maintain a uniform implementation of licensing
+across all of your projects and maintain it centrally.
The LVL is provided as a configured library project — once you have +downloaded it, you can start using it right away.
+ +If you are working in Eclipse with ADT, you need to add the LVL to your +workspace as a new development project, in the same way as you would a new +application project.
+ +library directory
+(the directory containing the library's AndroidManifest.xml file) as the project
+root. When created, the project is
+predefined as a library project in its project.properties file, so
+no further configuration is needed.
For more information about how to create an application project or work with +library projects in Eclipse, see Managing Projects from +Eclipse with ADT.
+ + +As an alternative to adding the LVL as a library project, you can copy the
+library sources directly into your application. To do so, copy (or import) the
+LVL's library/src/com directory into your application's
+src/ directory.
If you add the LVL sources directly to your application, you can skip the +next section and start working with the library, as described in Adding +Licensing to Your App.
+ + +If you want to use the LVL sources as a library project, you need to add a +reference to the LVL library project in your application project properties. This tells +build tools to include the LVL library project sources in your application at +compile time. The process for adding a reference to a library project depends +on your development environment, as described below.
+ +If you are developing in Eclipse with ADT, you should already have added the +library project to your workspace, as described in the previous section. If you +haven't done that already, do it now before continuing.
+ +Next, open the application's project properties window, as shown below. +Select the "Android" properties group and click Add, then +choose the LVL library project (com_android_vending_licensing) and click +OK. For more information, see + +Managing Projects from Eclipse with ADT
. + + +
+Figure 3. If you are +working in Eclipse with ADT, you can add the LVL library project to your +application from the application's project properties.
+ + +If you are developing using the SDK command-line tools, navigate to the
+directory containing your application project and open the
+project.properties file. Add a line to the file that specifies the
+android.library.reference.<n> key and the path to the
+library. For example:
android.library.reference.1=path/to/library_project+ +
Alternatively, you can use this command to update the project +properties, including the reference to the library project:
+ +android update lib-project +--target <target_ID> \ +--path path/to/my/app_project \ +--library path/to/my/library_project ++ +
For more information about working with library projects, +see +Setting up a Library Project.
+ + + + + + + + + + + + + + + + + + + + + +The Google Play publisher site provides configuration tools that let you +and others test licensing on your application before it is published. As you are +implementing licensing, you can make use of the publisher site tools to test +your application's Policy and handling of different licensing responses and +error conditions.
+ +The main components of the test environment for licensing include:
+ +Setting up the test environment properly involves:
+ +The sections below provide more information.
+ + +Google Play provides a configuration setting in your publisher account +that lets you override the normal processing of a license check and return a +specified static response code. The setting is for testing only and applies +only to license checks for applications that you have uploaded, made by +any user signed in to an emulator or device using the credentials of the +publisher account or a registered test account. For other users, the server +always processes license checks according to normal rules.
+ +To set a test response for your account, sign in to your publisher account +and click "Edit Profile". In the Edit Profile page, locate the Test Response +menu in the Licensing panel, shown below. You can select from the full set of +valid server response codes to control the response or condition you want to +test in your application.
+ +In general, you should make sure to test your application's licensing +implementation with every response code available in the Test Response menu. +For a description of the codes, see Server +Response Codes in the Licensing Reference.
+ +
+Figure 4. The Licensing +panel of your account's Edit Profile page, showing the Test Accounts field and the +Test Response menu.
+ +Note that the test response that you configure applies account-wide — +that is, it applies not to a single application, but to all +applications associated with the publisher account. If you are testing multiple +applications at once, changing the test response will affect all of those +applications on their next license check (if the user is signed in to +the emulator or device using the publisher account or a test account).
+ +Before you can successfully receive a test response for a license check, +you must sign in to the device or emulator on which the application +is installed, and from which it is querying the server. Specifically, you must +sign using either your publisher account or one of the test accounts that you +have set up. For more information about test accounts, see the next section.
+ +See Server +Response Codes for a list of +test responses available and their meanings.
+ + +In some cases, you might want to let multiple teams of developers test +licensing on applications that will ultimately be published through your +publisher account, but without giving them access to your publisher account's +sign-in credentials. To meet that need, the Google Play publisher site lets +you set up one or more optional test accounts — accounts that are +authorized to query the licensing server and receive static test responses from +your publisher account.
+ +Test accounts are standard Google accounts that you register on your +publisher account, such that they will receive the test response for +applications that you have uploaded. Developers can then sign in to their +devices or emulators using the test account credentials and initiate license +checks from installed applications. When the licensing server receives a license +check from a user of a test account, it returns the static test response +configured for the publisher account.
+ +Necessarily, there are limitations on the access and permissions given to +users signed in through test accounts, including:
+ +The table below summarizes the differences in capabilities, between the +publisher account, a test account, and any other account.
+ +Table 1. +Differences in account types for testing licensing.
+ +| Account Type | +Can check license before upload? | +Can receive test response? | +Can set test response? | +
|---|---|---|---|
| Publisher account | +Yes | +Yes | +Yes | +
| Test account | +No | +Yes | +No | +
| Other | +No | +No | +No | +
To get started, you need to register each test account in your publisher +account. As shown in Figure 4, you +register test accounts in the Licensing panel of your publisher account's Edit +Profile page. Simply enter the accounts as a comma-delimited list and click +Save to save your profile changes.
+ +You can use any Google account as a test account. 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.
+ +As mentioned above, users of test accounts can only receive static test +responses for applications that are uploaded to the publisher account. Since +those users do not have permission to upload applications, as the publisher you +will need to work with those users to collect apps for upload and distribute +uploaded apps for testing. You can handle collection and distribution in any way +that is convenient.
+ +Once an application is uploaded and becomes known to the licensing server,
+developers and testers can continue modify the application in their local
+development environment, without having to upload new versions. You only need to
+upload a new version if the local application increments the
+versionCode attribute in the manifest file.
The licensing server handles static test responses in the normal way, +including signing the license response data, adding extras parameters, and so +on. To support developers who are implementing licensing using test accounts, +rather than the publisher account, you will need to distribute +your public key to them. Developers without access to the publisher site do not +have access to your public key, and without the key they won't be able to +verify license responses.
+ +Note that if you decide to generate a new licensing key pair for your account +for some reason, you need to notify all users of test accounts. For +testers, you can embed the new key in the application package and distribute it +to users. For developers, you will need to distribute the new key to them +directly.
+ + +The licensing service is designed to determine whether a given user is +licensed to use a given application — during a license check, the Google +Play application gathers the user ID from the primary account on the system +and sends it to the server, together with the package name of the application +and other information. However, if there is no user information available, the +license check cannot succeed, so the Google Play application terminates the +request and returns an error to the application.
+ +During testing, to ensure that your application can successfully query the +licensing server, you must make sure that you sign in to an account on the +device or emulator using:
+ +If you are testing licensing on an emulator, you need to sign in to a Google +account on the emulator. If you do not see an option to create a new Google +account, the problem might be that your AVD is running a standard Android system +image, rather than the Google APIs Add-On, API 8 (release 2) or higher.
+ +For more information, see Setting up the runtime environment, above.
+ +Signing in using a publisher account offers the advantage of letting your +applications receive static test responses even before the applications are +uploaded to the publisher site.
+ +If you are part of a larger organization or are working with external groups +on applications that will be published through your site, you will more likely +want to distribute test accounts instead, then use those to sign in during +testing.
+ +To sign in on a device or emulator, follow the steps below. The preferred +approach is to sign in as the primary account — however, if there are +other accounts already in use on the device or emulator, you can create an +additional account and sign in to it using the publisher or test account +credentials.
+ +Once you are signed in, you can begin testing licensing in your application +(if you have completed the LVL integration steps above). When your application +initiates a license check, it will receive a response containing the static test +response configured on the publisher account.
+ +Note that, if you are using an emulator, you will need to sign in to the +publisher account or test account each time you wipe data when restarting the +emulator.
+ +Once you've completed the setup procedures, continue to Adding Licensing to Your App.
+ + + diff --git a/docs/html/guide/google/play/publishing/multiple-apks.jd b/docs/html/guide/google/play/publishing/multiple-apks.jd new file mode 100644 index 000000000000..e41817e4520d --- /dev/null +++ b/docs/html/guide/google/play/publishing/multiple-apks.jd @@ -0,0 +1,643 @@ +page.title=Multiple APK Support + +@jd:body + +Multiple APK support is a feature on Google Play that allows you to publish different APKs +for your application that are each targeted to different device configurations. Each APK is a +complete and independent version of your application, but they share the same application listing on +Google Play and must share the same package name and be signed with the same release key. This +feature is useful for cases in which your application cannot reach all desired devices with a single +APK.
+ +Android-powered devices may differ in several ways and it's important +to the success of your application that you make it available to as many devices as possible. +Android applications usually run on most compatible devices with a single APK, by supplying +alternative resources for different configurations (for example, different layouts for different +screen sizes) and the Android system selects the appropriate resources for the device at runtime. In +a few cases, however, a single APK is unable to support all device configurations, because +alternative resources make the APK file too big (greater than 50MB) or other technical challenges +prevent a single APK from working on all devices.
+ +Although we encourage you to develop and publish a single APK that supports as +many device configurations as possible, doing so is sometimes not possible. To help +you publish your application for as many devices as possible, Google Play allows you to +publish multiple APKs under the same application listing. Google Play then supplies each APK to +the appropriate devices based on configuration support you've declared in the manifest file of each +APK.
+ +By publishing your application with multiple APKs, you can:
+ +Currently, these are the only device characteristics that Google Play supports for publishing +multiple APKs as the same application.
+ +Note: You should generally use multiple APKs to support +different device configurations only when your APK is too large (greater than +50MB). Using a single APK to support different configurations is always the best practice, +because it makes the path for application updates simple and clear for users (and also makes +your life simpler by avoiding development and publishing complexity). Read the section below about +Using a Single APK Instead to +consider your options before publishing multiple APKs.
+ + +Before you start publishing multiple APKs on Google Play, you must understand a few +concepts regarding how the Google Play publisher site works.
+ +When editing your application, there are two buttons on the top-right side of the page. The +first button is either Publish or Unpublish and the second +button is always Save (but its behavior changes).
+When your application is new or you have unpublished it from Google Play, the first +button says Publish. Clicking it will publish any APKs listed as +Active, making them available on Google Play. Also while your application is new +or unpublished, clicking Save will save any changes you've made, such +as information added to the Product details and APKs you've uploaded, but nothing is made visible on +Google Play—this allows you to save your changes and sign out of the publisher site before +deciding to publish.
+Once you've published your application, the first button changes to +Unpublish. Clicking it in this state unpublishes your application so that none +of the APKs are available on Google Play. Also while published, the behavior of the +Save button is different. In this state, clicking Save not +only saves all your changes, but also publishes them to Google Play. For example, if you've +already published your application and then make changes to your product details or activate new +APKs, clicking Save makes all those changes live on Google Play.
+Before you can publish your application (whether publishing one or multiple APKs), you +must "activate" your APK(s) from the APK files tab. When you activate an APK, it +moves into the list of Active APKs. This list allows you to preview which APK(s) +you're about to publish.
+ +If there are no errors, any "active" APK will be published to +Google Play when you click the Publish button (if the application is +unpublished) or when you click the Save button (if the application is +already published).
+ + +The Google Play publisher site provides two modes for managing the APKs associated with +your application: simple mode and advanced mode. You can switch between these by +clicking the +link at the top-right corner of the APK files tab.
+ +Simple mode is the traditional way to publish an application, using one APK at a time. In +simple mode, only one APK can be activated at a time. If you upload a new APK to update +the application, clicking "Activate" on the new APK deactivates the currently +active APK (you must then click Save to publish the new APK).
+ +Advanced mode allows you to activate and publish multiple APKs that are each designed for a +specific set of device configurations. However, there are several rules based on the manifest +declarations in each APK that determine whether you're allowed to activate each APK along with +others. When you activate an APK and it violates one of the rules, you will receive an error or +warning message. If it's an error, you cannot publish until you resolve the problem; if it's a +warning, you can publish the activated APKs, but there might be unintended consequences as to +whether your application is available for different devices. These rules are discussed more +below.
+ + +The concept for using multiple APKs on Google Play is that you have just one entry in +Google Play for your application, but different devices might download a different APK. This +means that:
+ +To publish multiple APKs for the same application, you must enable Advanced mode +in your application's APK files tab (as discussed in the previous section). Once +in advanced mode, you can upload, activate, then publish multiple APKs for the same application. The +following sections describe more about how it works.
+ + +Which devices receive each APK is determined by Google Play filters that are specified by +elements in the manifest file of each APK. However, Google Play allows you to publish multiple +APKs only when each APK uses filters to support a variation of the following +device characteristics:
+ +This is based on your manifest file's {@code +<supports-gl-texture>} element(s).
+For example, when developing a game that uses OpenGL ES, you can provide one APK for +devices that support ATI texture compression and a separate APK for devices +that support PowerVR compression (among many others).
+This is based on your manifest file's {@code +<supports-screens>} or {@code +<compatible-screens>} element. You should never use both elements and you should use only +{@code +<supports-screens>} when possible.
+For example, you can provide one APK that supports small and normal size screens and another +APK that supports large and xlarge screens.
+ +Note: The Android system provides strong support for +applications to support all screen configurations with a single APK. You should avoid creating +multiple APKs to support different screens unless absolutely necessary and instead follow the guide +to Supporting Multiple +Screens so that your application is flexible and can adapt to all screen configurations +with a single APK.
+Caution: By default, all screen size attributes in the {@code +<supports-screens>} element are "true" if you do not declare them otherwise. However, +because the {@code android:xlargeScreens} attribute was added in Android 2.3 (API level +9), Google Play will assume that it is "false" if your application does not set either {@code +android:minSdkVersion} or {@code +android:targetSdkVersion} to "9" or higher.
+Caution: You should not combine both {@code +<supports-screens>} and {@code +<compatible-screens>} elements in your manifest file. Using both increases the chances +that you'll introduce an error due to conflicts between them. For help deciding which to use, read +Distributing to Specific Screens. +If you can't avoid using both, be aware that for any conflicts in agreement between a given size, +"false" will win.
+This is based on your manifest file's {@code <uses-sdk>} element. +You +can use both the {@code +android:minSdkVersion} and {@code android:maxSdkVersion} +attributes to specify support for different API levels.
+For example, you can publish your application with one APK that supports API levels 4 - 7 +(Android 1.6 - 2.1)—using only APIs available since API level 4 or lower—and another +APK that supports API levels 8 and above (Android 2.2+)—using APIs available since API level 8 +or lower.
+Note:
+Other manifest elements that enable Google Play filters—but are not +listed above—are still applied for each APK as usual. However, Google Play does not allow +you to publish multiple APKs based on variations of them. Thus, you cannot publish +multiple APKs if the above listed filters are the same for each APK (but the APKs differ based on +other characteristics in the manifest file). For +example, you cannot provide different APKs that differ purely on the {@code +<uses-configuration>} characteristics.
+ + + +Before you enable advanced mode to publish multiple APKs for your application, you need to +understand the following rules that define how publishing multiple APKs works:
+ +That is, each APK must declare slightly different support for at least one of +the supported Google Play filters (listed above).
+Usually, you will differentiate your APKs based on a specific characteristic (such as the +supported texture compression formats), and thus, each APK will declare support for different +devices. However, it's OK to publish multiple APKs that overlap their support slightly. When two +APKs do overlap (they support some of the same device configurations), a device that falls within +that overlap range will receive the APK with a higher version code (defined by {@code +android:versionCode}).
This is true only when either: the APKs differ based only on the +supported API levels (no other supported filters +distinguish the APKs from each other) or when the APKs do use another supported filter, but +there is an overlap between the APKs within that filter.
+This is important because a user's device receives an application update from +Google Play only if the version code for the APK on Google Play is higher than the version +code of the APK currently on the device. This ensures that if a device receives a system update that +then qualifies it to install the APK for higher API levels, the device receives an application +update because the version code increases.
+Note: The size of the version code increase is irrelevant; it +simply needs to be larger in the version that supports higher API levels.
+Here are some examples:
+Failure to abide by the above rules results in an error on the Google Play publisher site +when you activate your APKs—you will be unable to publish your application until you +resolve the error.
+ +There are other conflicts that might occur when you activate your APKs, but which will result +in warnings rather than errors. Warnings can be caused by the following:
+ +When such conflicts occur, you will see a warning message, but you can still publish your +application.
+ + + +Once you decide to publish multiple APKs, you probably need to create separate +Android projects for each APK you intend to publish so that you can appropriately develop them +separately. You can do this by simply duplicating your existing project and give it a new name. +(Alternatively, you might use a build system that can output different resources—such +as textures—based on the build configuration.)
+ +Tip: One way to avoid duplicating large portions of your +application code is to use a library project. A library +project holds shared code and resources, which you can include in your actual application +projects.
+ +When creating multiple projects for the same application, it's a good practice to identify each +one with a name that indicates the device restrictions to be placed on the APK, so you can +easily identify them. For example, "HelloWorld_8" might be a good name for an +application designed for API level 8 and above.
+ +Note: All APKs you publish for the same application +must have the same package name and be signed with the same certificate key. Be +sure you also understand each of the Rules for multiple APKs.
+ + +Each APK for the same application must have a unique version code, specified by +the {@code +android:versionCode} attribute. You must be careful about assigning version codes when +publishing multiple APKs, because they must each be different, but in some +cases, must or should be defined in a specific order, based on the configurations that each APK +supports.
+ +An APK that requires a higher API level must usually have a higher version code. For example, if +you create two APKs to support different API levels, the APK for the higher API levels must have the +higher version code. This ensures that if a device receives a system update that then qualifies it +to install the APK for higher API levels, the user receives a notification to update the app. For +more information about how this requirement applies, see the section above about Rules for multiple APKs.
+ +You should also consider how the order of version codes might affect which APK your users +receive either due to overlap between coverage of different APKs or future changes you might make to +your APKs.
+ +For example, if you have different APKs based on screen size, such as one for small - normal and +one for large - xlarge, but foresee a time when you will change the APKs to be one for small and one +for normal - xlarge, then you should make the version code for the large - xlarge APK be higher. +That way, a normal size device will receive the appropriate update when you make the change, because +the version code increases from the existing APK to the new APK that now supports the device.
+ +Also, when creating multiple APKs that differ based on support for different OpenGL texture +compression formats, be aware that many devices support multiple formats. Because a device +receives the APK with the highest version code when there is an overlap in coverage between two +APKs, you should order the version codes among your APKs so that the APK with the +preferred compression format has the highest version code. For example, you might want to perform +separate builds for your app using PVRTC, ATITC, and ETC1 compression formats. If you prefer these +formats in this exact order, then the APK that uses PVRTC should have the highest version code, the +APK that uses ATITC has a lower version code, and the version with ETC1 has the lowest. Thus, if a +device supports both PVRTC and ETC1, it receives the APK with PVRTC, because it has the highest +version code.
+ + +In order to allow different APKs to update their version codes independent of others (for +example, when you fix a bug in only one APK, so don't need to update all APKs), you should use a +scheme for your version codes that +provides sufficient room between each APK so that you can increase the code in one without requiring +an increase in others. You should also include your actual version name in the code (that is, the +user visible version assigned to {@code android:versionName}), +so that it's easy for you to associate the version code and version name.
+ +Note: When you increase the version code for an APK, Google +Play will prompt users of the previous version to update the application. Thus, to avoid +unnecessary updates, you should not increase the version code for APKs that do not actually +include changes.
+ +We suggest using a version code with at least 7 digits: integers that represent +the supported configurations are in the higher order bits, and the version name (from {@code +android:versionName}) is in the lower order bits. For example, when the application version +name is 3.1.0, version codes for an API level 4 +APK and an API level 11 APK would be something like 0400310 and 1100310, respectively. The first +two digits are reserved for the API Level (4 and 11, respectively), the middle two digits are for +either screen sizes or GL texture formats (not used in these examples), and the last three digits +are for the application's version name (3.1.0). Figure 1 shows two examples that split based on both +the platform version (API Level) and screen size.
+ +
+Figure 1. A suggested scheme for your version codes, +using the first two digits for the API Level, the second and third digits for the minimum and +maximum screen size (1 - 4 indicating each of the four sizes) or to denote the texture formats +and the last three digits for the app version.
+ +This scheme for version codes is just a suggestion for how you should establish a +pattern that is scalable as your application evolves. In particular, this scheme doesn't +demonstrate a solution for identifying different texture compression formats. One option might be +to define your own table that specifies a different integer to each of the different +compression formats your application supports (for example, 1 might correspond to ETC1 and 2 is +ATITC, and so on).
+ +You can use any scheme you want, but you should carefully consider how future versions of your +application will need to increase their version codes and how devices can receive updates when +either the device configuration changes (for example, due to a system update) or when you modify the +configuration support for one or several of the APKs.
+ + + + +Creating multiple APKs for your application is not the normal procedure for +publishing an application on Google Play. In most cases, you should be able to publish your +application to most users with a single APK and we encourage that you do so. When you encounter +a situation in which using a single APK becomes difficult, you should carefully consider all your +options before deciding to publish multiple APKs.
+ +First of all, there are a few key benefits to developing a single APK that supports all +devices:
+ +With only one APK to worry about at any given time, you're less likely to become confused by +which APK is what. You also don't have to keep track of multiple version codes for each +APK—by using only one APK, you can simply increase the version code with each release and +be done.
Although you can use a library project +to share code between multiple Android projects, it's still likely that you'll reproduce some code +across each project and this could become difficult to manage, especially when resolving +bugs.
By creating a single APK that contains all the resources for each device configuration, your +application can adapt to configuration changes that occur at runtime. For example, if the user docks +or otherwise connects a handset device to a larger screen, there's a chance that this will invoke a +system configuration change to support the larger screen. If you include all resources for different +screen configurations in the same APK, then your application will load alternative resources and +optimize the user experience for the new interface.
+If a user has enabled data backup on his or her current device and then buys a new device +that has a different configuration, then when the user's apps are automatically restored during +setup, the user receives your application and it runs using the resources optimized for that device. +For example, on a new tablet, the user receives your application and it runs with your +tablet-optimized resources. This restore +process does not work across different APKs, because each APK can potentially have different +permissions that the user has not agreed to, so Google Play may not restore the application at +all. (If you use multiple APKs, the user receives either the exact same APK if it's compatible or +nothing at all and must manually download your application to get the APK designed for the new +device.)
The following sections describe some of the other options you should use to support multiple +device configurations before deciding to publish multiple APKs.
+ + + +To support multiple types of GL textures with a single APK, your application should query the GL +texture formats supported on the device and then use the appropriate resources or download +them from a web server. For example, in order to keep the size of your APK small, you can query the +device's support for different GL texture formats when the application starts for the first time and +then download only the textures you need for that device.
+ +For maximum performance and compatibility, your application should use ETC1 textures wherever it +doesn't impact the visual quality. However, because ETC1 cannot deal with images that have drastic +chroma changes, such as line art and (most) text, and doesn't support alpha, it may not the best +format for all textures.
+ +With a single APK, you should try to use ETC1 textures and uncompressed textures whenever +reasonable, and consider the use of PVRTC, ATITC, or DXTC as a last resort when ETC1 does not +suffice.
+ +Here's an example query for supported texture compression formats from inside a +{@link android.opengl.GLSurfaceView.Renderer GLSurfaceView.Renderer}:
+ +
+public void onSurfaceChanged(GL10 gl, int w, int h) {
+ String extensions = gl.glGetString(GL10.GL_EXTENSIONS);
+ Log.d("ExampleActivity", extensions);
+}
+
+
+This returns a string that lists each of the supported compression formats.
+ + + +Unless your APK file exceeds the Google Play size limit of 50MB, supporting multiple screens +should always be done with a single APK. Since Android 1.6, the Android system manages most of the +work required for your application to run successfully on a variety of screen sizes and +densities.
+ +To further optimize your application for different screen sizes and densities, you should provide +alternative +resources such as bitmap drawables at different resolutions and different layout designs for +different screen sizes.
+ +For more information about how to support multiple screens with a single APK, read Supporting Multiple Screens.
+ +Additionally, you should consider using a support library from the Compatibility Package so that you can add Fragments to your activity designs +when running on larger screens such as tablets.
+ + + +If you want to support as many versions of the Android platform as possible, you should use +only APIs available in the lowest reasonable version. For example, your application may not require +APIs newer than Android 2.1 (API Level 7), which makes an application available to +over 95% of Android-powered devices (as indicated by the Platform Versions dashboard).
+ +By using a support library from the Compatibility Package, you can also use APIs +from some of the latest versions (such as Android 3.0) while +still supporting versions as low as Android 1.6. The support library includes APIs for Fragments, Loaders, and more. Using the fragment +APIs is particularly valuable so that you can optimize your user interface for large devices such as +tablets.
+ +Alternatively, if you want to use some APIs that are available only in newer versions of Android +(which your application can still function without), then you should consider using reflection. By +using reflection, you can check whether the current device supports certain APIs. If the APIs are +not available, your application can gracefully disable and hide the feature.
+ +Another way to use new APIs only when running on a version that supports them is to check the +API level of the current device. That is, you can query the value of {@link +android.os.Build.VERSION#SDK_INT} and create different code paths depending on the API level +supported by the device. For example:
+ +
+if (android.os.Build.VERSION.SDK_INT >= 11) {
+ // Use APIs supported by API level 11 (Android 3.0) and up
+} else {
+ // Do something different to support older versions
+}
+
+
diff --git a/docs/html/guide/guide_toc.cs b/docs/html/guide/guide_toc.cs
index 62d18aee3f9a..44b977e327dd 100644
--- a/docs/html/guide/guide_toc.cs
+++ b/docs/html/guide/guide_toc.cs
@@ -5,236 +5,80 @@
Below are template spans for adding localized doc titles. Please ensure that
localized titles are added in the language order specified below.
?>
-API Level is an integer value that uniquely identifies the framework API +revision offered by a version of the Android platform.
+ +The Android platform provides a framework API that applications can use to +interact with the underlying Android system. The framework API consists of:
+ +Each successive version of the Android platform can include updates to the +Android application framework API that it delivers.
+ +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.
+ +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.
+ +The following table specifies the API Level supported by each version of the +Android platform.
+ +| Platform Version | API Level | VERSION_CODE | Notes |
|---|---|---|---|
| Android 4.0.3 | +15 | +{@link android.os.Build.VERSION_CODES#ICE_CREAM_SANDWICH_MR1} | +Platform +Highlights |
| Android 4.0, 4.0.1, 4.0.2 | +14 | +{@link android.os.Build.VERSION_CODES#ICE_CREAM_SANDWICH} | +|
| Android 3.2 | +13 | +{@link android.os.Build.VERSION_CODES#HONEYCOMB_MR2} | +|
| Android 3.1.x | +12 | +{@link android.os.Build.VERSION_CODES#HONEYCOMB_MR1} | +Platform Highlights |
| Android 3.0.x | +11 | +{@link android.os.Build.VERSION_CODES#HONEYCOMB} | +Platform Highlights |
| Android 2.3.4 Android 2.3.3 |
+ 10 | +{@link android.os.Build.VERSION_CODES#GINGERBREAD_MR1} | +Platform +Highlights |
| Android 2.3.2 Android 2.3.1 Android +2.3 |
+ 9 | +{@link android.os.Build.VERSION_CODES#GINGERBREAD} | +|
| Android 2.2.x | +8 | +{@link android.os.Build.VERSION_CODES#FROYO} | +Platform Highlights |
| Android 2.1.x | +7 | +{@link android.os.Build.VERSION_CODES#ECLAIR_MR1} | +Platform +Highlights |
| Android 2.0.1 | +6 | +{@link android.os.Build.VERSION_CODES#ECLAIR_0_1} | +|
| Android 2.0 | +5 | +{@link android.os.Build.VERSION_CODES#ECLAIR} | +|
| Android 1.6 | +4 | +{@link android.os.Build.VERSION_CODES#DONUT} | +Platform Highlights |
| Android 1.5 | +3 | +{@link android.os.Build.VERSION_CODES#CUPCAKE} | +Platform Highlights |
| Android 1.1 | +2 | +{@link android.os.Build.VERSION_CODES#BASE_1_1} | |
| Android 1.0 | +1 | +{@link android.os.Build.VERSION_CODES#BASE} | +
The API Level identifier serves a key role in ensuring the best possible +experience for users and application developers: + +
Each Android platform version stores its API Level identifier internally, in +the Android system itself.
+ +Applications can use a manifest element provided by the framework API —
+<uses-sdk> — 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:
android:minSdkVersion — Specifies the minimum API Level
+on which the application is able to run. The default value is "1".android:targetSdkVersion — Specifies the API Level
+on which the application is designed to run. In some cases, this allows the
+application to use manifest elements or behaviors defined in the target
+API Level, rather than being restricted to using only those defined
+for the minimum API Level.android:maxSdkVersion — Specifies the maximum API Level
+on which the application is able to run. Important: Please read the <uses-sdk>
+documentation before using this attribute. 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
+<uses-sdk> element with a android:minSdkVersion
+attribute. The value of android:minSdkVersion would be the integer
+corresponding to the API Level of the earliest version of the Android platform
+under which the application can run.
When the user attempts to install an application, or when revalidating an
+appplication after a system update, the Android system first checks the
+<uses-sdk> 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:
android:minSdkVersion 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. android:maxSdkVersion 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 <uses-sdk>
+documentation for more information about how the system handles this attribute.When declared in an application's manifest, a <uses-sdk>
+element might look like this:
<manifest> + <uses-sdk android:minSdkVersion="5" /> + ... +</manifest>+ +
The principal reason that an application would declare an API Level in
+android:minSdkVersion is to tell the Android system that it is
+using APIs that were introduced 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.
For example, the {@link android.appwidget} package was introduced with API
+Level 3. If an application uses that API, it must declare a
+android:minSdkVersion 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).
For more information about how to specify an application's API Level
+requirements, see the <uses-sdk>
+ section of the manifest file documentation.
The sections below provide information related to API level that you should +consider when developing your application.
+ +Android applications are generally forward-compatible with new versions of +the Android platform.
+ +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.
+ +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.
+ +In some cases, changes below 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.
+ +Android applications are not necessarily backward compatible with versions of +the Android platform older than the version against which they were compiled. +
+ +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.
+ +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.
+ +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. + +
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
+android:minSdkVersion attribute in the application's manifest and
+set its value to the API Level of the platform version.
If you build an application that uses APIs or system features introduced in
+the latest platform version, you should set the
+android:minSdkVersion 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.
If your application uses APIs introduced in the latest platform version but
+does not declare a android:minSdkVersion attribute, then
+it will run properly on devices running the latest version of the platform, but
+not 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.
After compiling your application, you should make sure to test it on the
+platform specified in the application's android:minSdkVersion
+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.
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.
+ +To access the updater, use the android command-line tool,
+located in the <sdk>/tools directory. You can launch the SDK updater by
+executing android sdk. 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
+Window > Android SDK
+Manager.
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 Creating and Managing Virtual Devices. 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.
+ +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 provisional API Level 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.
+ +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.
+ +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.
+ + +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 android:minSdkVersion attribute of its manifest file.
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.
+ +Filtering by API Level in the documentation does not provide a view +of what is new or introduced in each API Level — 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.
+ +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. +
+ +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 <api level>" 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.
+ + + + + + + + + diff --git a/docs/html/guide/topics/media/camera.jd b/docs/html/guide/topics/media/camera.jd index 7d72491ef109..a63270a77ead 100644 --- a/docs/html/guide/topics/media/camera.jd +++ b/docs/html/guide/topics/media/camera.jd @@ -162,8 +162,7 @@ information, you must request location permission: <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />For more information about getting user location, see -Obtaining User -Location.
+Location Strategies. diff --git a/docs/html/guide/topics/media/index.jd b/docs/html/guide/topics/media/index.jd index 0e0412a10d52..a750c9a8809f 100644 --- a/docs/html/guide/topics/media/index.jd +++ b/docs/html/guide/topics/media/index.jd @@ -1,63 +1,56 @@ -page.title=Multimedia and Camera +page.title=Media and Camera +page.landing=true +page.landing.intro=Add video, audio, and photo capabilities to your app with Android's robust APIs for playing and recording media. +page.landing.image= + @jd:body -The Android multimedia framework includes support for capturing and playing audio, video and -images in a variety of common media types, so that you can easily integrate them into your -applications. You can play audio or video from media files stored in your application's resources, -from standalone files in the file system, or from a data stream arriving over a -network connection, all using the {@link android.media.MediaPlayer} or {@link -android.media.JetPlayer} APIs. You can also record audio, video and take pictures using the {@link -android.media.MediaRecorder} and {@link android.hardware.Camera} APIs if supported by the device -hardware.
- -The following topics show you how to use the Android framework to implement multimedia capture -and playback.
- -If your media playback application creates a media playback service, just like Music, that +responds to the media button events, how will the user know where those events are going to? Music, +or your new application?
+ + + +Making a game on Android is easy. Making a great game for a mobile, multitasking, often +multi-core, multi-purpose system like Android is trickier. Even the best developers frequently make +mistakes in the way they interact with the Android system and with other applications
+ + + +Android users get used to using the back key. We expect the volume keys to work in some +intuitive fashion. We expect that the home key behaves in a manner consistent with the Android +navigation paradigm.
+ +This class gets you clicking fast with some super-easy ways of leveraging existing camera +applications. In later lessons, you dive deeper and learn how to control the camera hardware +directly.
+ + + +After this class, you will be able to build apps that respond to hardware audio key +presses, which request audio focus when playing audio, and which respond appropriately to changes in +audio focus caused by the system or other applications.
+ + +For more information, see the documentation about Services and +href="{@docRoot}guide/components/services.html#Foreground">Services and Status Bar Notifications.
diff --git a/docs/html/guide/topics/network/sip.jd b/docs/html/guide/topics/network/sip.jd deleted file mode 100644 index 600da78ffcfb..000000000000 --- a/docs/html/guide/topics/network/sip.jd +++ /dev/null @@ -1,490 +0,0 @@ -page.title=Session Initiation Protocol -@jd:body -Android provides an API that supports the Session Initiation Protocol (SIP). -This lets you add SIP-based internet telephony features to your applications. -Android includes a full SIP protocol stack and integrated call management -services that let applications easily set up outgoing and incoming voice calls, -without having to manage sessions, transport-level communication, or audio -record or playback directly.
- -Here are examples of the types of applications that might use the SIP API:
-Here are the requirements for developing a SIP application:
-Here is a summary of the classes and one interface
-(SipRegistrationListener) that are included in the Android SIP
-API:
| Class/Interface | -Description | -
|---|---|
| {@link android.net.sip.SipAudioCall} | -Handles an Internet audio call over SIP. | -
| {@link android.net.sip.SipAudioCall.Listener} | -Listener for events relating to a SIP call, such as when a call is being -received ("on ringing") or a call is outgoing ("on calling"). | -
| {@link android.net.sip.SipErrorCode} | -Defines error codes returned during SIP actions. | -
| {@link android.net.sip.SipManager} | -Provides APIs for SIP tasks, such as initiating SIP connections, and provides access -to related SIP services. | -
| {@link android.net.sip.SipProfile} | -Defines a SIP profile, including a SIP account, domain and server information. - | -
| {@link android.net.sip.SipProfile.Builder} | -Helper class for creating a SipProfile. | -
| {@link android.net.sip.SipSession} | -Represents a SIP session that is associated with a SIP dialog or a standalone transaction -not within a dialog. | -
| {@link android.net.sip.SipSession.Listener} | -Listener for events relating to a SIP session, such as when a session is being registered -("on registering") or a call is outgoing ("on calling"). | -
| {@link android.net.sip.SipSession.State} | -Defines SIP session states, such as "registering", "outgoing call", and "in call". | -
| {@link android.net.sip.SipRegistrationListener} | -An interface that is a listener for SIP registration events. | -
If you are developing an application that uses the SIP API, remember that the -feature is supported only on Android 2.3 (API level 9) and higher versions of -the platform. Also, among devices running Android 2.3 (API level 9) or higher, -not all devices will offer SIP support.
- -To use SIP, add the following permissions to your application's manifest:
-android.permission.USE_SIPandroid.permission.INTERNETTo ensure that your application can only be installed on devices that are -capable of supporting SIP, add the following to your application's -manifest:
- -<uses-sdk android:minSdkVersion="9" />. This
- indicates that your application requires Android 2.3 or higher. For more
-information, see API
-Levels and the documentation for the <uses-sdk> element.To control how your application is filtered from devices that do not support -SIP (for example, on Google Play), add the following to your application's -manifest:
- -<uses-feature android:name="android.hardware.sip.voip"
-/>. This states that your application uses the SIP API. The
-declaration should include an android:required attribute that
-indicates whether you want the application to be filtered from devices that do
-not offer SIP support. Other <uses-feature> declarations
-may also be needed, depending on your implementation. For more information,
-see the documentation for the <uses-
-feature> element.If your application is designed to receive calls, you must also define a receiver ({@link android.content.BroadcastReceiver} subclass) in the application's manifest:
- -<receiver android:name=".IncomingCallReceiver" android:label="Call Receiver"/>Here are excerpts from the SipDemo manifest:
- - - -<?xml version="1.0" encoding="utf-8"?> -<manifest xmlns:android="http://schemas.android.com/apk/res/android" - package="com.example.android.sip"> - ... - <receiver android:name=".IncomingCallReceiver" android:label="Call Receiver"/> - ... - <uses-sdk android:minSdkVersion="9" /> - <uses-permission android:name="android.permission.USE_SIP" /> - <uses-permission android:name="android.permission.INTERNET" /> - ... - <uses-feature android:name="android.hardware.sip.voip" android:required="true" /> - <uses-feature android:name="android.hardware.wifi" android:required="true" /> - <uses-feature android:name="android.hardware.microphone" android:required="true" /> -</manifest> -- - -
To use the SIP API, your application must create a {@link -android.net.sip.SipManager} object. The {@link android.net.sip.SipManager} takes -care of the following in your application:
- -You instantiate a new {@link android.net.sip.SipManager} as follows:
-public SipManager mSipManager = null;
-...
-if(mSipManager == null) {
- mSipManager = SipManager.newInstance(this);
-}
-A typical Android SIP application involves one or more users, each of whom -has a SIP account. In an Android SIP application, each SIP account is -represented by a {@link android.net.sip.SipProfile} object.
- -A {@link android.net.sip.SipProfile} defines a SIP profile, including a SIP -account, and domain and server information. The profile associated with the SIP -account on the device running the application is called the local -profile. The profile that the session is connected to is called the -peer profile. When your SIP application logs into the SIP server with -the local {@link android.net.sip.SipProfile}, this effectively registers the -device as the location to send SIP calls to for your SIP address.
- -This section shows how to create a {@link android.net.sip.SipProfile}, -register it with a SIP server, and track registration events.
- -You create a {@link android.net.sip.SipProfile} object as follows:
--public SipProfile mSipProfile = null; -... - -SipProfile.Builder builder = new SipProfile.Builder(username, domain); -builder.setPassword(password); -mSipProfile = builder.build();- -
The following code excerpt opens the local profile for making calls and/or
-receiving generic SIP calls. The caller can make subsequent calls through
-mSipManager.makeAudioCall. This excerpt also sets the action
-android.SipDemo.INCOMING_CALL, which will be used by an intent
-filter when the device receives a call (see Setting up
-an intent filter to receive calls). This is the registration step:
Intent intent = new Intent();
-intent.setAction("android.SipDemo.INCOMING_CALL");
-PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0, intent, Intent.FILL_IN_DATA);
-mSipManager.open(mSipProfile, pendingIntent, null);
-
-Finally, this code sets a SipRegistrationListener on the {@link
-android.net.sip.SipManager}. This tracks whether the {@link
-android.net.sip.SipProfile} was successfully registered with your SIP service
-provider:
-
mSipManager.setRegistrationListener(mSipProfile.getUriString(), new SipRegistrationListener() {
-
-public void onRegistering(String localProfileUri) {
- updateStatus("Registering with SIP Server...");
-}
-
-public void onRegistrationDone(String localProfileUri, long expiryTime) {
- updateStatus("Ready");
-}
-
-public void onRegistrationFailed(String localProfileUri, int errorCode,
- String errorMessage) {
- updateStatus("Registration failed. Please check settings.");
-}
-
-
-When your application is done using a profile, it should close it to free -associated objects into memory and unregister the device from the server. For -example:
- -public void closeLocalProfile() {
- if (mSipManager == null) {
- return;
- }
- try {
- if (mSipProfile != null) {
- mSipManager.close(mSipProfile.getUriString());
- }
- } catch (Exception ee) {
- Log.d("WalkieTalkieActivity/onDestroy", "Failed to close local profile.", ee);
- }
-}
-
-To make an audio call, you must have the following in place:
-To make an audio call, you should set up a {@link -android.net.sip.SipAudioCall.Listener}. Much of the client's interaction with -the SIP stack happens through listeners. In this snippet, you see how the {@link -android.net.sip.SipAudioCall.Listener} sets things up after the call is -established:
- -
-SipAudioCall.Listener listener = new SipAudioCall.Listener() {
-
- @Override
- public void onCallEstablished(SipAudioCall call) {
- call.startAudio();
- call.setSpeakerMode(true);
- call.toggleMute();
- ...
- }
-
- @Override
- public void onCallEnded(SipAudioCall call) {
- // Do something.
- }
-};
-
-Once you've set up the {@link android.net.sip.SipAudioCall.Listener}, you can
-make the call. The {@link android.net.sip.SipManager} method
-makeAudioCall takes the following parameters:
null,
-but as shown above, the listener is used to set things up once the call is
-established.For example:
-call = mSipManager.makeAudioCall(mSipProfile.getUriString(), sipAddress, listener, 30);- -
To receive calls, a SIP application must include a subclass of {@link -android.content.BroadcastReceiver} that has the ability to respond to an intent -indicating that there is an incoming call. Thus, you must do the following in -your application:
- -AndroidManifest.xml, declare a
-<receiver>. In SipDemo, this is
-<receiver android:name=".IncomingCallReceiver"
-android:label="Call Receiver"/>.IncomingCallReceiver.android.SipDemo.INCOMING_CALL. To receive calls, your SIP application must subclass {@link
-android.content.BroadcastReceiver}. The
-Android system handles incoming SIP calls and broadcasts an "incoming
-call" intent (as defined by the application) when it receives
-a call. Here is the subclassed {@link android.content.BroadcastReceiver}
-code from SipDemo. To see the full example, go to SipDemo sample, which
-is included in the SDK samples. For information on downloading and installing
-the SDK samples, see
-Getting the Samples.
/*** Listens for incoming SIP calls, intercepts and hands them off to WalkieTalkieActivity.
- */
-public class IncomingCallReceiver extends BroadcastReceiver {
- /**
- * Processes the incoming call, answers it, and hands it over to the
- * WalkieTalkieActivity.
- * @param context The context under which the receiver is running.
- * @param intent The intent being received.
- */
- @Override
- public void onReceive(Context context, Intent intent) {
- SipAudioCall incomingCall = null;
- try {
- SipAudioCall.Listener listener = new SipAudioCall.Listener() {
- @Override
- public void onRinging(SipAudioCall call, SipProfile caller) {
- try {
- call.answerCall(30);
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
- };
- WalkieTalkieActivity wtActivity = (WalkieTalkieActivity) context;
- incomingCall = wtActivity.mSipManager.takeAudioCall(intent, listener);
- incomingCall.answerCall(30);
- incomingCall.startAudio();
- incomingCall.setSpeakerMode(true);
- if(incomingCall.isMuted()) {
- incomingCall.toggleMute();
- }
- wtActivity.call = incomingCall;
- wtActivity.updateStatus(incomingCall);
- } catch (Exception e) {
- if (incomingCall != null) {
- incomingCall.close();
- }
- }
- }
-}
-
-
-When the SIP service receives a new call, it sends out an intent with the
-action string provided by the application. In SipDemo, this action string is
-android.SipDemo.INCOMING_CALL.
This code excerpt from SipDemo shows how the {@link
-android.net.sip.SipProfile} object gets created with a pending intent based on
-the action string android.SipDemo.INCOMING_CALL. The
-PendingIntent object will perform a broadcast when the {@link
-android.net.sip.SipProfile} receives a call:
-public SipManager mSipManager = null;
-public SipProfile mSipProfile = null;
-...
-
-Intent intent = new Intent();
-intent.setAction("android.SipDemo.INCOMING_CALL");
-PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0, intent, Intent.FILL_IN_DATA);
-mSipManager.open(mSipProfile, pendingIntent, null);
-
-The broadcast will be intercepted by the intent filter, which will then fire
-the receiver (IncomingCallReceiver). You can specify an intent
-filter in your application's manifest file, or do it in code as in the SipDemo
-sample application's onCreate() method
-of the application's Activity:
-public class WalkieTalkieActivity extends Activity implements View.OnTouchListener {
-...
- public IncomingCallReceiver callReceiver;
- ...
-
- @Override
- public void onCreate(Bundle savedInstanceState) {
-
- IntentFilter filter = new IntentFilter();
- filter.addAction("android.SipDemo.INCOMING_CALL");
- callReceiver = new IncomingCallReceiver();
- this.registerReceiver(callReceiver, filter);
- ...
- }
- ...
-}
-
-
-
-To test SIP applications, you need the following:
-To test a SIP application:
-This document describes advanced NFC topics, such as working with various tag technologies, -writing to NFC tags, and foreground dispatching, which allows an application in the foreground to -handle intents even when other applications filter for the same ones.
- -When working with NFC tags and Android-powered devices, the main format you use to read -and write data on tags is NDEF. When a device scans a tag with NDEF data, Android provides support -in parsing the message and delivering it in an {@link android.nfc.NdefMessage} when -possible. There are cases, however, when you scan a tag that does not contain -NDEF data or when the NDEF data could not be mapped to a MIME type or URI. -In these cases, you need to open communication directly with the tag and read and write to it with -your own protocol (in raw bytes). Android provides generic support for these use cases with the -{@link android.nfc.tech} package, which is described in Table 1. You can -use the {@link android.nfc.Tag#getTechList getTechList()} method to determine the technologies -supported by the tag and create the corresponding {@link android.nfc.tech.TagTechnology} -object with one of classes provided by {@link android.nfc.tech}
- --Table 1. Supported tag technologies
-| Class | - -Description | -
|---|---|
| {@link android.nfc.tech.TagTechnology} | - -The interface that all tag technology classes must implement. | -
| {@link android.nfc.tech.NfcA} | - -Provides access to NFC-A (ISO 14443-3A) properties and I/O operations. | -
| {@link android.nfc.tech.NfcB} | - -Provides access to NFC-B (ISO 14443-3B) properties and I/O operations. | -
| {@link android.nfc.tech.NfcF} | - -Provides access to NFC-F (JIS 6319-4) properties and I/O operations. | -
| {@link android.nfc.tech.NfcV} | - -Provides access to NFC-V (ISO 15693) properties and I/O operations. | -
| {@link android.nfc.tech.IsoDep} | - -Provides access to ISO-DEP (ISO 14443-4) properties and I/O operations. | -
| {@link android.nfc.tech.Ndef} | - -Provides access to NDEF data and operations on NFC tags that have been formatted as - NDEF. | -
| {@link android.nfc.tech.NdefFormatable} | - -Provides a format operations for tags that may be NDEF formattable. | -
The following tag technlogies are not required to be supported by Android-powered devices.
--Table 2. Optional supported tag technologies
-| Class | - -Description | -
|---|---|
| {@link android.nfc.tech.MifareClassic} | - -Provides access to MIFARE Classic properties and I/O operations, if this Android device - supports MIFARE. | -
| {@link android.nfc.tech.MifareUltralight} | - -Provides access to MIFARE Ultralight properties and I/O operations, if this Android - device supports MIFARE. | -
When a device scans a tag that has NDEF data on it, but could not be mapped to a MIME or URI, -the tag dispatch system tries to start an activity with the {@link -android.nfc.NfcAdapter#ACTION_TECH_DISCOVERED} -intent. The {@link android.nfc.NfcAdapter#ACTION_TECH_DISCOVERED} is also used when a tag -with non-NDEF data is scanned. Having this fallback allows you to work with the data on the tag -directly if the tag dispatch system could not parse it for you. The basic steps when working with -tag technologies are as follows:
- -Tag tagFromIntent = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
get factory methods of the classes in the {@link android.nfc.tech} package. You can
-enumerate the supported technologies of the tag by calling {@link android.nfc.Tag#getTechList
-getTechList()} before calling a get factory method. For example, to obtain an instance
-of {@link android.nfc.tech.MifareUltralight} from a {@link android.nfc.Tag}, do the following:
-
--MifareUltralight.get(intent.getParcelableExtra(NfcAdapter.EXTRA_TAG)); --
Reading and writing to an NFC tag involves obtaining the tag from the intent and -opening communication with the tag. You must define your own protocol stack to read and write data -to the tag. Keep in mind, however, that you can still read and write NDEF data when working -directly with a tag. It is up to you how you want to structure things. The -following example shows how to work with a MIFARE Ultralight tag.
- -
-package com.example.android.nfc;
-
-import android.nfc.Tag;
-import android.nfc.tech.MifareUltralight;
-import android.util.Log;
-import java.io.IOException;
-import java.nio.charset.Charset;
-
-public class MifareUltralightTagTester {
-
- private static final String TAG = MifareUltralightTagTester.class.getSimpleName();
-
- public void writeTag(Tag tag, String tagText) {
- MifareUltralight ultralight = MifareUltralight.get(tag);
- try {
- ultralight.connect();
- ultralight.writePage(4, "abcd".getBytes(Charset.forName("US-ASCII")));
- ultralight.writePage(5, "efgh".getBytes(Charset.forName("US-ASCII")));
- ultralight.writePage(6, "ijkl".getBytes(Charset.forName("US-ASCII")));
- ultralight.writePage(7, "mnop".getBytes(Charset.forName("US-ASCII")));
- } catch (IOException e) {
- Log.e(TAG, "IOException while closing MifareUltralight...", e);
- } finally {
- try {
- ultralight.close();
- } catch (IOException e) {
- Log.e(TAG, "IOException while closing MifareUltralight...", e);
- }
- }
- }
-
- public String readTag(Tag tag) {
- MifareUltralight mifare = MifareUltralight.get(tag);
- try {
- mifare.connect();
- byte[] payload = mifare.readPages(4);
- return new String(payload, Charset.forName("US-ASCII"));
- } catch (IOException e) {
- Log.e(TAG, "IOException while writing MifareUltralight
- message...", e);
- } finally {
- if (mifare != null) {
- try {
- mifare.close();
- }
- catch (IOException e) {
- Log.e(TAG, "Error closing tag...", e);
- }
- }
- }
- return null;
- }
-}
-
-
-
-
- The foreground dispatch system allows an activity to intercept an intent and claim -priority over other activities that handle the same intent. Using this system involves - constructing a few data structures for the Android system to be able to send the appropriate - intents to your application. To enable the foreground dispatch system:
- -onCreate() method of your activity:
-
- -PendingIntent pendingIntent = PendingIntent.getActivity( - this, 0, new Intent(this, getClass()).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP), 0); --
null array of intent filters and technology filters, specifies
- that you want to filter for all tags that fallback to the TAG_DISCOVERED
- intent. The code snippet below handles all MIME types for NDEF_DISCOVERED. You
- should only handle the ones that you need.
-
-IntentFilter ndef = new IntentFilter(NfcAdapter.ACTION_NDEF_DISCOVERED);
- try {
- ndef.addDataType("*/*"); /* Handles all MIME based dispatches.
- You should specify only the ones that you need. */
- }
- catch (MalformedMimeTypeException e) {
- throw new RuntimeException("fail", e);
- }
- intentFiltersArray = new IntentFilter[] {ndef, };
-
- Object.class.getName() method to obtain the class of the technology that you
- want to support.
-
-techListsArray = new String[][] { new String[] { NfcF.class.getName() } };
-
-
-public void onPause() {
- super.onPause();
- mAdapter.disableForegroundDispatch(this);
-}
-
-public void onResume() {
- super.onResume();
- mAdapter.enableForegroundDispatch(this, pendingIntent, intentFiltersArray, techListsArray);
-}
-
-public void onNewIntent(Intent intent) {
- Tag tagFromIntent = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
- //do something with tagFromIntent
-}
-
-
- See the -ForegroundDispatch sample from API Demos for the complete sample.
\ No newline at end of file diff --git a/docs/html/guide/topics/nfc/index.jd b/docs/html/guide/topics/nfc/index.jd deleted file mode 100644 index b86d72d418d0..000000000000 --- a/docs/html/guide/topics/nfc/index.jd +++ /dev/null @@ -1,33 +0,0 @@ -page.title=Near Field Communication -@jd:body - -Near Field Communication (NFC) is a set of short-range wireless technologies, typically - requiring a distance of 4cm or less to initiate a connection. NFC allows you to share small - payloads of data between an NFC tag and an Android-powered device, or between two Android-powered - devices. - -
Tags can range in complexity. Simple tags offer just read and write semantics, sometimes with - one-time-programmable areas to make the card read-only. More complex tags offer math operations, - and have cryptographic hardware to authenticate access to a sector. The most sophisticated tags - contain operating environments, allowing complex interactions with code executing on the tag. - The data stored in the tag can also be written in a variety of formats, but many of the Android - framework APIs are based around a NFC Forum standard - called NDEF (NFC Data Exchange Format).
- -This document describes the basic NFC tasks you perform in Android. It explains how to send and -receive NFC data in the form of NDEF messages and describes the Android framework APIs that support -these features. For more advanced topics, including a discussion of working with non-NDEF data, -see Advanced NFC.
- - -There are two major uses cases when working with NDEF data and Android:
- -Reading NDEF data from an NFC tag is handled with the tag dispatch -system, which analyzes discovered NFC tags, appropriately categorizes the data, and starts -an application that is interested in the categorized data. An application that wants to handle the -scanned NFC tag can declare an intent filter and -request to handle the data.
- -The Android Beam™ feature allows a device to push an NDEF message onto -another device by physically tapping the devices together. This interaction provides an easier way -to send data than other wireless technologies like Bluetooth, because with NFC, no manual device -discovery or pairing is required. The connection is automatically started when two devices come -into range. Android Beam is available through a set of NFC APIs, so any application can transmit -information between devices. For example, the Contacts, Browser, and YouTube applications use -Android Beam to share contacts, web pages, and videos with other devices. -
- - -Android-powered devices are usually looking for NFC tags when the screen -is unlocked, unless NFC is disabled in the device's Settings menu. -When an Android-powered device discovers an NFC tag, the desired behavior -is to have the most appropriate activity handle the intent without asking the user what application -to use. Because devices scan NFC tags at a very short range, it is likely that making users manually -select an activity would force them to move the device away from the tag and break the connection. -You should develop your activity to only handle the NFC tags that your activity cares about to -prevent the Activity Chooser from appearing.
- -To help you with this goal, Android provides a special tag dispatch system that analyzes scanned -NFC tags, parses them, and tries to locate applications that are interested in the scanned data. It -does this by:
- -Before you begin writing your NFC applications, it is important to understand the different -types of NFC tags, how the tag dispatch system parses NFC tags, and the special work that the tag -dispatch system does when it detects an NDEF message. NFC tags come in a -wide array of technologies and can also have data written to them in many different ways. -Android has the most support for the NDEF standard, which is defined by the NFC Forum. -
- -NDEF data is encapsulated inside a message ({@link android.nfc.NdefMessage}) that contains one -or more records ({@link android.nfc.NdefRecord}). Each NDEF record must be well-formed according to -the specification of the type of record that you want to create. Android -also supports other types of tags that do not contain NDEF data, which you can work with by using -the classes in the {@link android.nfc.tech} package. To learn more -about these technologies, see the Advanced -NFC topic. Working with these other types of tags involves -writing your own protocol stack to communicate with the tags, so we recommend using NDEF when -possible for ease of development and maximum support for Android-powered devices. -
- -Note: -To download complete NDEF specifications, go to the NFC Forum Specification Download site and see -Creating common types of NDEF records for examples of how to -construct NDEF records.
- -Now that you have some background in NFC tags, the following sections describe in more detail how -Android handles NDEF formatted tags. When an Android-powered device scans an NFC tag containing NDEF -formatted data, it parses the message and tries to figure out the data's MIME type or identifying -URI. To do this, the system reads the first {@link android.nfc.NdefRecord} inside the {@link -android.nfc.NdefMessage} to determine how to interpret the entire NDEF message (an NDEF message can -have multiple NDEF records). In a well-formed NDEF message, the first {@link android.nfc.NdefRecord} -contains the following fields: -
The tag dispatch system uses the TNF and type fields to try to map a MIME type or URI to the -NDEF message. If successful, it encapsulates that information inside of a {@link -android.nfc.NfcAdapter#ACTION_NDEF_DISCOVERED} intent along with the actual payload. However, there -are cases when the tag dispatch system cannot determine the type of data based on the first NDEF -record. This happens when the NDEF data cannot be mapped to a MIME type or URI, or when the -NFC tag does not contain NDEF data to begin with. In such cases, a {@link -android.nfc.Tag} object that has information about the tag's technologies and the payload are -encapsulated inside of a {@link android.nfc.NfcAdapter#ACTION_TECH_DISCOVERED} intent instead.
- --Table 1. describes how the tag dispatch system maps TNF and type -fields to MIME types or URIs. It also describes which TNFs cannot be mapped to a MIME type or URI. -In these cases, the tag dispatch system falls back to -{@link android.nfc.NfcAdapter#ACTION_TECH_DISCOVERED}. - -
For example, if the tag dispatch system encounters a record of type {@link -android.nfc.NdefRecord#TNF_ABSOLUTE_URI}, it maps the variable length type field of that record -into a URI. The tag dispatch system encapsulates that URI in the data field of an {@link -android.nfc.NfcAdapter#ACTION_NDEF_DISCOVERED} intent along with other information about the tag, -such as the payload. On the other hand, if it encounters a record of type {@link -android.nfc.NdefRecord#TNF_UNKNOWN}, it creates an intent that encapsulates the tag's technologies -instead.
- - -- Table 1. Supported TNFs and their mappings
-| Type Name Format (TNF) | -Mapping | -
|---|---|
| {@link android.nfc.NdefRecord#TNF_ABSOLUTE_URI} | -URI based on the type field. | -{@link android.nfc.NdefRecord#TNF_EMPTY} | -Falls back to {@link android.nfc.NfcAdapter#ACTION_TECH_DISCOVERED}. | - -{@link android.nfc.NdefRecord#TNF_EXTERNAL_TYPE} | -URI based on the URN in the type field. The URN is encoded into the NDEF type field in
- a shortened form: <domain_name>:<service_name>.
- Android maps this to a URI in the form:
- vnd.android.nfc://ext/<domain_name>:<service_name>. |
-
- {@link android.nfc.NdefRecord#TNF_MIME_MEDIA} | -MIME type based on the type field. | - -{@link android.nfc.NdefRecord#TNF_UNCHANGED} | -Invalid in the first record, so falls back to - {@link android.nfc.NfcAdapter#ACTION_TECH_DISCOVERED}. | - -{@link android.nfc.NdefRecord#TNF_UNKNOWN} | -Falls back to {@link android.nfc.NfcAdapter#ACTION_TECH_DISCOVERED}. | - -{@link android.nfc.NdefRecord#TNF_WELL_KNOWN} | -MIME type or URI depending on the Record Type Definition (RTD), which you set in the -type field. See Table 2. for more information on -available RTDs and their mappings. | - -
- Table 2. Supported RTDs for TNF_WELL_KNOWN and their -mappings
-| Record Type Definition (RTD) | -Mapping | -
|---|---|
| {@link android.nfc.NdefRecord#RTD_ALTERNATIVE_CARRIER} | -Falls back to {@link android.nfc.NfcAdapter#ACTION_TECH_DISCOVERED}. | -{@link android.nfc.NdefRecord#RTD_HANDOVER_CARRIER} | -Falls back to {@link android.nfc.NfcAdapter#ACTION_TECH_DISCOVERED}. | - -{@link android.nfc.NdefRecord#RTD_HANDOVER_REQUEST} | -Falls back to {@link android.nfc.NfcAdapter#ACTION_TECH_DISCOVERED}. | - -{@link android.nfc.NdefRecord#RTD_HANDOVER_SELECT} | -Falls back to {@link android.nfc.NfcAdapter#ACTION_TECH_DISCOVERED}. | - -{@link android.nfc.NdefRecord#RTD_SMART_POSTER} | -URI based on parsing the payload. | - -{@link android.nfc.NdefRecord#RTD_TEXT} | -MIME type of text/plain. |
-
- {@link android.nfc.NdefRecord#RTD_URI} | -URI based on payload. | - -
When the tag dispatch system is done creating an intent that encapsulates the NFC tag and its -identifying information, it sends the intent to an interested application that -filters for the intent. If more than one application can handle the intent, the Activity Chooser -is presented so the user can select the Activity. The tag dispatch system defines three intents, -which are listed in order of highest to lowest priority:
- -The basic way the tag dispatch system works is as follows:
- -
-
-Figure 1. Tag Dispatch System
- - -Whenever possible, work with NDEF messages and the {@link -android.nfc.NfcAdapter#ACTION_NDEF_DISCOVERED} intent, because it is the most specific out of -the three. This intent allows you to start your application at a more appropriate time than the -other two intents, giving the user a better experience.
- -Before you can access a device's NFC hardware and properly handle NFC intents, declare these
- items in your AndroidManifest.xml file:
<uses-permission> element to access the NFC hardware:
- -<uses-permission android:name="android.permission.NFC" /> --
-<uses-sdk android:minSdkVersion="10"/> --
uses-feature element so that your application shows up in Google
-Play only for devices that have NFC hardware:
- -<uses-feature android:name="android.hardware.nfc" android:required="true" /> --
If your application uses NFC functionality, but that functionality is not crucial to your
-application, you can omit the uses-feature element and check for NFC avalailbility at
-runtime by checking to see if {@link android.nfc.NfcAdapter#getDefaultAdapter getDefaultAdapter()}
-is null.
To start your application when an NFC tag that you want to handle is scanned, your application -can filter for one, two, or all three of the NFC intents in the Android manifest. However, you -usually want to filter for the {@link android.nfc.NfcAdapter#ACTION_NDEF_DISCOVERED} intent for the -most control of when your application starts. The {@link -android.nfc.NfcAdapter#ACTION_TECH_DISCOVERED} intent is a fallback for {@link -android.nfc.NfcAdapter#ACTION_NDEF_DISCOVERED} when no applications filter for - {@link android.nfc.NfcAdapter#ACTION_NDEF_DISCOVERED} or for when the payload is not -NDEF. Filtering for {@link android.nfc.NfcAdapter#ACTION_TAG_DISCOVERED} is usually too general of a -category to filter on. Many applications will filter for {@link -android.nfc.NfcAdapter#ACTION_NDEF_DISCOVERED} or {@link -android.nfc.NfcAdapter#ACTION_TECH_DISCOVERED} before {@link -android.nfc.NfcAdapter#ACTION_TAG_DISCOVERED}, so your application has a low probability of -starting. {@link android.nfc.NfcAdapter#ACTION_TAG_DISCOVERED} is only available as a last resort -for applications to filter for in the cases where no other applications are installed to handle the -{@link android.nfc.NfcAdapter#ACTION_NDEF_DISCOVERED} or {@link -android.nfc.NfcAdapter#ACTION_TECH_DISCOVERED}intent.
- -Because NFC tag deployments vary and are many times not under your control, this is not always -possible, which is why you can fallback to the other two intents when necessary. When you have -control over the types of tags and data written, it is recommended that you use NDEF to format your -tags. The following sections describe how to filter for each type of intent.
- - -
-To filter for {@link android.nfc.NfcAdapter#ACTION_NDEF_DISCOVERED} intents, declare the
-intent filter along with the type of data that you want to filter for. The
-following example filters for {@link android.nfc.NfcAdapter#ACTION_NDEF_DISCOVERED}
-intents with a MIME type of text/plain:
-
-<intent-filter> - <action android:name="android.nfc.action.NDEF_DISCOVERED"/> - <category android:name="android.intent.category.DEFAULT"/> - <data android:mimeType="text/plain" /> -</intent-filter> --
The following example filters for a URI in the form of
-http://developer.android.com/index.html.
-
-<intent-filter> - <action android:name="android.nfc.action.NDEF_DISCOVERED"/> - <category android:name="android.intent.category.DEFAULT"/> - <data android:scheme="http" - android:host="developer.android.com" - android:pathPrefix="/index.html" /> -</intent-filter> -- - -
If your activity filters for the {@link android.nfc.NfcAdapter#ACTION_TECH_DISCOVERED} intent,
-you must create an XML resource file that specifies the technologies that your activity supports
-within a tech-list set. Your activity is
- considered a match if a tech-list set is a subset of the technologies that are
- supported by the tag, which you can obtain by calling {@link android.nfc.Tag#getTechList
- getTechList()}.
For example, if the tag that is scanned supports MifareClassic, NdefFormatable, and NfcA, your
- tech-list set must specify all three, two, or one of the technologies (and nothing
- else) in order for your activity to be matched.
The following sample defines all of the technologies. You can remove the ones that you do not
- need. Save this file (you can name it anything you wish) in the
- <project-root>/res/xml folder.
-<resources xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2"> - <tech-list> - <tech>android.nfc.tech.IsoDep</tech> - <tech>android.nfc.tech.NfcA</tech> - <tech>android.nfc.tech.NfcB</tech> - <tech>android.nfc.tech.NfcF</tech> - <tech>android.nfc.tech.NfcV</tech> - <tech>android.nfc.tech.Ndef</tech> - <tech>android.nfc.tech.NdefFormatable</tech> - <tech>android.nfc.tech.MifareClassic</tech> - <tech>android.nfc.tech.MifareUltralight</tech> - </tech-list> -</resources> -- -
You can also specify multiple tech-list sets. Each of the tech-list
- sets is considered independently, and your activity is considered a match if any single
- tech-list set is a subset of the technologies that are returned by {@link
- android.nfc.Tag#getTechList getTechList()}. This provides AND and OR
- semantics for matching technologies. The following example matches tags that can support the
- NfcA and Ndef technologies or can support the NfcB and Ndef technologies:
-<resources xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2"> - <tech-list> - <tech>android.nfc.tech.NfcA</tech> - <tech>android.nfc.tech.Ndef</tech> - </tech-list> -</resources> - -<resources xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2"> - <tech-list> - <tech>android.nfc.tech.NfcB</tech> - <tech>android.nfc.tech.Ndef</tech> - </tech-list> -</resources> -- -
In your AndroidManifest.xml file, specify the resource file that you just created
- in the <meta-data> element inside the <activity>
- element like in the following example:
-<activity> -... -<intent-filter> - <action android:name="android.nfc.action.TECH_DISCOVERED"/> -</intent-filter> - -<meta-data android:name="android.nfc.action.TECH_DISCOVERED" - android:resource="@xml/nfc_tech_filter" /> -... -</activity> -- -
For more information about working with tag technologies and the {@link -android.nfc.NfcAdapter#ACTION_TECH_DISCOVERED} intent, see Working with Supported Tag -Technologies in the Advanced NFC document.
-To filter for {@link android.nfc.NfcAdapter#ACTION_TAG_DISCOVERED} use the following intent -filter:
- - -<intent-filter> - <action android:name="android.nfc.action.TAG_DISCOVERED"/> -</intent-filter> -- - - -
If an activity starts because of an NFC intent, you can obtain information about the scanned NFC -tag from the intent. Intents can contain the following extras depending on the tag that was scanned: - -
To obtain these extras, check to see if your activity was launched with one of -the NFC intents to ensure that a tag was scanned, and then obtain the extras out of the -intent. The following example checks for the {@link android.nfc.NfcAdapter#ACTION_NDEF_DISCOVERED} -intent and gets the NDEF messages from an intent extra.
- -
-public void onResume() {
- super.onResume();
- ...
- if (NfcAdapter.ACTION_NDEF_DISCOVERED.equals(getIntent().getAction())) {
- Parcelable[] rawMsgs = intent.getParcelableArrayExtra(NfcAdapter.EXTRA_NDEF_MESSAGES);
- if (rawMsgs != null) {
- msgs = new NdefMessage[rawMsgs.length];
- for (int i = 0; i < rawMsgs.length; i++) {
- msgs[i] = (NdefMessage) rawMsgs[i];
- }
- }
- }
- //process the msgs array
-}
-
-
-Alternatively, you can obtain a {@link android.nfc.Tag} object from the intent, which will -contain the payload and allow you to enumerate the tag's technologies:
- -Tag tag = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);- - -
This section describes how to create common types of NDEF records to help you when writing to -NFC tags or sending data with Android Beam. It also describes how to create the corresponding -intent filter for the record. All of these NDEF record examples should be in the first NDEF -record of the NDEF message that you are writing to a tag or beaming.
- -Given the following {@link android.nfc.NdefRecord#TNF_ABSOLUTE_URI} NDEF record, which is -stored as the first record inside of an {@link android.nfc.NdefMessage}:
- -
-NdefRecord uriRecord = new NdefRecord(
- NdefRecord.TNF_ABSOLUTE_URI ,
- "http://developer.android.com/index.html".getBytes(Charset.forName("US-ASCII")),
- new byte[0], new byte[0]);
-
-
-the intent filter would look like this:
--<intent-filter> - <action android:name="android.nfc.action.NDEF_DISCOVERED" /> - <category android:name="android.intent.category.DEFAULT" /> - <data android:scheme="http" - android:host="developer.android.com" - android:pathPrefix="/index.html" /> -</intent-filter> -- - -
Given the following {@link android.nfc.NdefRecord#TNF_MIME_MEDIA} NDEF record, which is stored as -the first record inside -of an {@link android.nfc.NdefMessage}:
-
-NdefRecord mimeRecord = new NdefRecord(
- NdefRecord.TNF_MIME_MEDIA ,
- "application/com.example.android.beam".getBytes(Charset.forName("US-ASCII")),
- new byte[0], "Beam me up, Android!".getBytes(Charset.forName("US-ASCII")));
-
-
-the intent filter would look like this:
--<intent-filter> - <action android:name="android.nfc.action.NDEF_DISCOVERED" /> - <category android:name="android.intent.category.DEFAULT" /> - <data android:mimeType="application/com.example.android.beam" /> -</intent-filter> -- - -
Given the following {@link android.nfc.NdefRecord#TNF_WELL_KNOWN} NDEF record, which is stored as -the first record inside of an {@link android.nfc.NdefMessage}:
-
-public NdefRecord createTextRecord(String payload, Locale locale, boolean encodeInUtf8) {
- byte[] langBytes = locale.getLanguage().getBytes(Charset.forName("US-ASCII"));
- Charset utfEncoding = encodeInUtf8 ? Charset.forName("UTF-8") : Charset.forName("UTF-16");
- byte[] textBytes = payload.getBytes(utfEncoding);
- int utfBit = encodeInUtf8 ? 0 : (1 << 7);
- char status = (char) (utfBit + langBytes.length);
- byte[] data = new byte[1 + langBytes.length + textBytes.length];
- data[0] = (byte) status;
- System.arraycopy(langBytes, 0, data, 1, langBytes.length);
- System.arraycopy(textBytes, 0, data, 1 + langBytes.length, textBytes.length);
- NdefRecord record = new NdefRecord(NdefRecord.TNF_WELL_KNOWN,
- NdefRecord.RTD_TEXT, new byte[0], data);
- return record;
-}
-
-
-the intent filter would look like this:
--<intent-filter> - <action android:name="android.nfc.action.NDEF_DISCOVERED" /> - <category android:name="android.intent.category.DEFAULT" /> - <data android:mimeType="text/plain" /> -</intent-filter> -- - -
Given the following {@link android.nfc.NdefRecord#TNF_WELL_KNOWN} NDEF record, which is stored as -the first record inside of an {@link android.nfc.NdefMessage}:
- -
-byte[] uriField = "example.com".getBytes(Charset.forName("US-ASCII"));
-byte[] payload = new byte[uriField.length + 1]; //add 1 for the URI Prefix
-byte payload[0] = 0x01; //prefixes http://www. to the URI
-System.arraycopy(uriField, 0, payload, 1, uriField.length); //appends URI to payload
-NdefRecord rtdUriRecord = new NdefRecord(
- NdefRecord.TNF_WELL_KNOWN, NdefRecord.RTD_URI, new byte[0], payload);
-
-
-the intent filter would look like this:
- --<intent-filter> - <action android:name="android.nfc.action.NDEF_DISCOVERED" /> - <category android:name="android.intent.category.DEFAULT" /> - <data android:scheme="http" - android:host="example.com" - android:pathPrefix="" /> -</intent-filter> -- -
Given the following {@link android.nfc.NdefRecord#TNF_EXTERNAL_TYPE} NDEF record, which is stored -as the first record inside of an {@link android.nfc.NdefMessage}:
- --byte[] payload; -... -NdefRecord mimeRecord = new NdefRecord( - NdefRecord.TNF_EXTERNAL_TYPE, "example.com:externalType", new byte[0], payload); -- -
the intent filter would look like this:
--<intent-filter> - <action android:name="android.nfc.action.NDEF_DISCOVERED" /> - <category android:name="android.intent.category.DEFAULT" /> - <data android:scheme="vnd.android.nfc" - android:host="ext" - android:pathPrefix="/example.com:externalType"/> -</intent-filter> -- - -
Use TNF_EXTERNAL_TYPE for more generic NFC tag deployments to better support both -Android-powered and non-Android-powered devices.
- -Note: URNs for {@link
-android.nfc.NdefRecord#TNF_EXTERNAL_TYPE} have a canonical format of:
-urn:nfc:ext:example.com:externalType, however the NFC Forum RTD specification
-declares that the urn:nfc:ext: portion of the URN must be ommitted from the
-NDEF record. So all you need to provide is the domain (example.com in the example)
-and type (externalType in the example) separated by a colon.
-When dispatching TNF_EXTERNAL_TYPE, Android converts the urn:nfc:ext:example.com:externalType URN to a
-vnd.android.nfc://ext/example.com:externalType URI, which is what the intent filter in the example
-declares.
-Introduced in Android 4.0 (API level 14), an Android Application Record (AAR) provides a stronger -certainty that your application is started when an NFC tag is scanned. An AAR has the package name -of an application embedded inside an NDEF record. You can add an AAR to any NDEF record of your NDEF message, -because Android searches the entire NDEF message for AARs. If it finds an AAR, it starts the application based -on the package name inside the AAR. If the application is not present on the device, -Google Play is launched to download the application.
- -AARs are useful if you want to prevent other applications from filtering for the same intent and -potentially handling specific tags that you have deployed. AARs are only supported at the -application level, because of the package name constraint, and not at the Activity level as with -intent filtering. If you want to handle an intent at the Activity level, use intent filters. -
- - - -If a tag contains an AAR, the tag dispatch system dispatches in the following manner:
-Note: You can override AARs and the intent dispatch system with the foreground dispatch -system, which allows a foreground activity to have priority when an NFC tag is discovered. -With this method, the activity must be in the foreground to -override AARs and the intent dispatch system.
- -If you still want to filter for scanned tags that do not contain an AAR, you can declare -intent filters as normal. This is useful if your application is interested in other tags -that do not contain an AAR. For example, maybe you want to guarantee that your application handles -proprietary tags that you deploy as well as general tags deployed by third parties. Keep in mind -that AARs are specific to Android 4.0 devices or later, so when deploying tags, you most likely want -to use a combination of AARs and MIME types/URIs to support the widest range of devices. In -addition, when you deploy NFC tags, think about how you want to write your NFC tags to enable -support for the most devices (Android-powered and other devices). You can do this by -defining a relatively unique MIME type or URI to make it easier for applications to distinguish. -
- -Android provides a simple API to create an AAR, -{@link android.nfc.NdefRecord#createApplicationRecord createApplicationRecord()}. All you need to -do is embed the AAR anywhere in your {@link android.nfc.NdefMessage}. You do not want -to use the first record of your {@link android.nfc.NdefMessage}, unless the AAR is the only -record in the {@link android.nfc.NdefMessage}. This is because the Android -system checks the first record of an {@link android.nfc.NdefMessage} to determine the MIME type or -URI of the tag, which is used to create an intent for applications to filter. The following code -shows you how to create an AAR:
- -
-NdefMessage msg = new NdefMessage(
- new NdefRecord[] {
- ...,
- NdefRecord.createApplicationRecord("com.example.android.beam")}
-
-
-
-Android Beam allows simple peer-to-peer data exchange between two Android-powered devices. The -application that wants to beam data to another device must be in the foreground and the device -receiving the data must not be locked. When the beaming device comes in close enough contact with a -receiving device, the beaming device displays the "Touch to Beam" UI. The user can then choose -whether or not to beam the message to the receiving device.
- -Note: Foreground NDEF pushing was available at API level 10, -which provides similar functionality to Android Beam. These APIs have since been deprecated, but -are available to support older devices. See {@link android.nfc.NfcAdapter#enableForegroundNdefPush -enableForegroundNdefPush()} for more information.
- -You can enable Android Beam for your application by calling one of the two methods:
-An activity can only push one NDEF message at a time, so {@link -android.nfc.NfcAdapter#setNdefPushMessageCallback setNdefPushMessageCallback()} takes precedence -over {@link android.nfc.NfcAdapter#setNdefPushMessage setNdefPushMessage()} if both are set. To use -Android Beam, the following general guidelines must be met: -
- -com.android.npp NDEF push protocol or NFC Forum's SNEP (Simple NDEF Exchange
-Protocol). The com.android.npp protocol is required for devices on API level 9 (Android
-2.3) to API level 13 (Android 3.2). com.android.npp and SNEP are both required on
-API level 14 (Android 4.0) and later.Note: If your activity enables Android Beam and is -in the foreground, the standard intent dispatch system is disabled. However, if your activity also -enables foreground -dispatching, then it can still scan tags that match the intent filters set in the foreground -dispatching.
- -To enable Android Beam:
- -onCreate() method of
-your activity. These methods require at least one activity that you want to enable with Android
-Beam, along with an optional list of other activities to activate.
-
-In general, you normally use {@link -android.nfc.NfcAdapter#setNdefPushMessage setNdefPushMessage()} if your Activity only needs to -push the same NDEF message at all times, when two devices are in range to communicate. You use -{@link android.nfc.NfcAdapter#setNdefPushMessageCallback setNdefPushMessageCallback} when your -application cares about the current context of the application and wants to push an NDEF message -depending on what the user is doing in your application.
-The following sample shows how a simple activity calls {@link
-android.nfc.NfcAdapter.CreateNdefMessageCallback} in the onCreate() method of an
-activity (see AndroidBeamDemo
-for the complete sample). This example also has methods to help you create a MIME record:
-package com.example.android.beam;
-
-import android.app.Activity;
-import android.content.Intent;
-import android.nfc.NdefMessage;
-import android.nfc.NdefRecord;
-import android.nfc.NfcAdapter;
-import android.nfc.NfcAdapter.CreateNdefMessageCallback;
-import android.nfc.NfcEvent;
-import android.os.Bundle;
-import android.os.Parcelable;
-import android.widget.TextView;
-import android.widget.Toast;
-import java.nio.charset.Charset;
-
-
-public class Beam extends Activity implements CreateNdefMessageCallback {
- NfcAdapter mNfcAdapter;
- TextView textView;
-
- @Override
- public void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.main);
- TextView textView = (TextView) findViewById(R.id.textView);
- // Check for available NFC Adapter
- mNfcAdapter = NfcAdapter.getDefaultAdapter(this);
- if (mNfcAdapter == null) {
- Toast.makeText(this, "NFC is not available", Toast.LENGTH_LONG).show();
- finish();
- return;
- }
- // Register callback
- mNfcAdapter.setNdefPushMessageCallback(this, this);
- }
-
- @Override
- public NdefMessage createNdefMessage(NfcEvent event) {
- String text = ("Beam me up, Android!\n\n" +
- "Beam Time: " + System.currentTimeMillis());
- NdefMessage msg = new NdefMessage(
- new NdefRecord[] { createMimeRecord(
- "application/com.example.android.beam", text.getBytes())
- /**
- * The Android Application Record (AAR) is commented out. When a device
- * receives a push with an AAR in it, the application specified in the AAR
- * is guaranteed to run. The AAR overrides the tag dispatch system.
- * You can add it back in to guarantee that this
- * activity starts when receiving a beamed message. For now, this code
- * uses the tag dispatch system.
- */
- //,NdefRecord.createApplicationRecord("com.example.android.beam")
- });
- return msg;
- }
-
- @Override
- public void onResume() {
- super.onResume();
- // Check to see that the Activity started due to an Android Beam
- if (NfcAdapter.ACTION_NDEF_DISCOVERED.equals(getIntent().getAction())) {
- processIntent(getIntent());
- }
- }
-
- @Override
- public void onNewIntent(Intent intent) {
- // onResume gets called after this to handle the intent
- setIntent(intent);
- }
-
- /**
- * Parses the NDEF Message from the intent and prints to the TextView
- */
- void processIntent(Intent intent) {
- textView = (TextView) findViewById(R.id.textView);
- Parcelable[] rawMsgs = intent.getParcelableArrayExtra(
- NfcAdapter.EXTRA_NDEF_MESSAGES);
- // only one message sent during the beam
- NdefMessage msg = (NdefMessage) rawMsgs[0];
- // record 0 contains the MIME type, record 1 is the AAR, if present
- textView.setText(new String(msg.getRecords()[0].getPayload()));
- }
-
- /**
- * Creates a custom MIME type encapsulated in an NDEF record
- */
- public NdefRecord createMimeRecord(String mimeType, byte[] payload) {
- byte[] mimeBytes = mimeType.getBytes(Charset.forName("US-ASCII"));
- NdefRecord mimeRecord = new NdefRecord(
- NdefRecord.TNF_MIME_MEDIA, mimeBytes, new byte[0], payload);
- return mimeRecord;
- }
-}
-
-
-Note that this code comments out an AAR, which you can remove. If you enable the AAR, the -application specified in the AAR always receives the Android Beam message. If the application is not -present, Google Play launches to download the application. Therefore, the following intent -filter is not technically necessary for Android 4.0 devices or later if the AAR is used: -
- --<intent-filter> - <action android:name="android.nfc.action.NDEF_DISCOVERED"/> - <category android:name="android.intent.category.DEFAULT"/> - <data android:mimeType="application/com.example.android.beam"/> -</intent-filter> --
With this intent filter, the com.example.android.beam application now can be started
-when it scans an NFC tag or receives an Android Beam with an AAR of
-type com.example.android.beam, or when an NDEF formatted message contains a MIME record
-of type application/com.example.android.beam.
Even though AARs guarantee an application is started or downloaded, intent filters are -recommended, because they let you start an Activity of your choice in your -application instead of always starting the main Activity within the package specified by an AAR. -AARs do not have Activity level granularity. Also, because some Android-powered devices do not -support AARs, you should also embed identifying information in the first NDEF record of your NDEF -messages and filter for that as well, just in case. See Creating Common -Types of NDEF records for more information on how to create records. -
diff --git a/docs/html/guide/topics/providers/calendar-provider.jd b/docs/html/guide/topics/providers/calendar-provider.jd index d30dda423ec5..f53b0625841d 100644 --- a/docs/html/guide/topics/providers/calendar-provider.jd +++ b/docs/html/guide/topics/providers/calendar-provider.jd @@ -250,27 +250,30 @@ and store its events on the device.Here is an example that shows how to get all the calendars for a particular +
Here is an example that shows how to get the calendars that are owned by a particular user. For simplicity's sake, in this example the query operation is shown in the user interface thread ("main thread"). In practice, this should be done in an asynchronous thread instead of on the main thread. For more discussion, see -Loaders. If you are not just reading data but modifying it, see {@link android.content.AsyncQueryHandler}. +Loaders. If you are not just +reading data but modifying it, see {@link android.content.AsyncQueryHandler}.
- // Projection array. Creating indices for this array instead of doing
- // dynamic lookups improves performance.
- public static final String[] EVENT_PROJECTION = new String[] {
+// Projection array. Creating indices for this array instead of doing
+// dynamic lookups improves performance.
+public static final String[] EVENT_PROJECTION = new String[] {
Calendars._ID, // 0
Calendars.ACCOUNT_NAME, // 1
- Calendars.CALENDAR_DISPLAY_NAME // 2
- };
+ Calendars.CALENDAR_DISPLAY_NAME, // 2
+ Calendars.OWNER_ACCOUNT // 3
+};
- // The indices for the projection array above.
- private static final int PROJECTION_ID_INDEX = 0;
- private static final int PROJECTION_ACCOUNT_NAME_INDEX = 1;
- private static final int PROJECTION_DISPLAY_NAME_INDEX = 2;
+// The indices for the projection array above.
+private static final int PROJECTION_ID_INDEX = 0;
+private static final int PROJECTION_ACCOUNT_NAME_INDEX = 1;
+private static final int PROJECTION_DISPLAY_NAME_INDEX = 2;
+private static final int PROJECTION_OWNER_ACCOUNT_INDEX = 3;
In the next part of the example, you construct your query. The selection
specifies the criteria for the query. In this example the query is looking for
-all calendars that have the ACCOUNT_NAME
-"sampleuser@google.com" and the ACCOUNT_TYPE
-"com.google". The query returns a {@link android.database.Cursor}
+calendars that have the ACCOUNT_NAME
+"sampleuser@google.com", the ACCOUNT_TYPE
+"com.google", and the OWNER_ACCOUNT
+"sampleuser@google.com". If you want to see all calendars that a user
+has viewed, not just calendars the user owns, omit the OWNER_ACCOUNT.
+The query returns a {@link android.database.Cursor}
object that you can use to traverse the result set returned by the database
-query. For more discussion of using queries in content providers, see Content Providers.
// Run query
@@ -303,8 +310,10 @@ Cursor cur = null;
ContentResolver cr = getContentResolver();
Uri uri = Calendars.CONTENT_URI;
String selection = "((" + Calendars.ACCOUNT_NAME + " = ?) AND ("
- + Calendars.ACCOUNT_TYPE + " = ?))";
-String[] selectionArgs = new String[] {"sampleuser@gmail.com", "com.google"};
+ + Calendars.ACCOUNT_TYPE + " = ?) AND ("
+ + Calendars.OWNER_ACCOUNT + " = ?))";
+String[] selectionArgs = new String[] {"sampleuser@gmail.com", "com.google",
+ "sampleuser@gmail.com"};
// Submit the query and get a Cursor object back.
cur = cr.query(uri, EVENT_PROJECTION, selection, selectionArgs, null);
@@ -316,12 +325,14 @@ for each field.
while (cur.moveToNext()) {
long calID = 0;
String displayName = null;
- String accountName = null;
+ String accountName = null;
+ String ownerName = null;
// Get the field values
calID = cur.getLong(PROJECTION_ID_INDEX);
displayName = cur.getString(PROJECTION_DISPLAY_NAME_INDEX);
accountName = cur.getString(PROJECTION_ACCOUNT_NAME_INDEX);
+ ownerName = cur.getString(PROJECTION_OWNER_ACCOUNT_INDEX);
// Do something with the values...
@@ -1179,5 +1190,3 @@ However, a sync adapter is restricted to the ACCOUNT_NAME and
For a sample implementation of a sync adapter (not specifically related to Calendar), see SampleSyncAdapter. -