android sdk best practices

87
See also Market Filters Providing Alternative Resources Supporting Multiple Screens <supports-screens> <uses-configuration> <uses-feature> <uses-library> <uses-permission> <uses-sdk> Android Compatibility Android is designed to run on many different types of devices. For developers, the range and number of devices means a huge potential audience: the more devices that run Android apps, the more users who can access your app. In exchange, however, it also means that your apps will have to cope with that same variety of hardware. Fortunately, Android has built-in tools and support that make it easy for your apps to do that, while at the same time maintaining control of what types of devices your app is available to. If you do your work properly, users whose devices can’t run your app will never see it in the Android Market, and will not get in trouble by downloading it. This page explains how you can control which devices have access to your apps, and how to prepare your apps to make sure they reach the right audience. What does “Compatibility” mean? A device is “Android compatible” if it can correctly run apps written for the Android execution environment. There is exactly one Android API for each API level, and it’s the same API no matter what kind of device it’s installed on. No parts of the API are optional, and you never have to worry about parts of the API missing on some devices. Every compatible Android device your app will land on will include every class and every API for that API level. Of course, some APIs won’t work correctly if a particular device lacks the corresponding hardware or feature. But that’s not a problem: we also designed Android to prevent apps from being visible to devices which don’t have features the apps require. We’ve built support for this right into the SDK tools, and it’s part of the Android platform itself, as well as Android Market. As a developer, you have complete control of how and where your apps are available. Android provides tools as a first- class part of the platform that let you manage this. You control the availability of your apps, so that they reach only the devices capable of running them. How does it work? You manage your app’s availability through a simple three-step process: You state the features your app requires by declaring <uses-feature> elements its manifest file. 1. Devices are required to declare the features they include to Android Market. 2. Android Market uses your app’s stated requirements to filter it from devices that don’t meet those requirements. 3. This way, users never even see apps that won’t work properly on their devices. As long as you accurately describe your app’s requirements, you don’t need to worry about users blaming you for compatibility problems. If you’re familiar with web development, you may recognize this model as “capability detection”. Web developers typically prefer this approach to “browser detection”, because it’s very difficult to keep up as new browsers and new versions of current browsers are released. By checking for support for specific required capabilities instead of the current browser, Page 1 of 3 Android Compatibility | Android Developers 9/7/2010 file://V:\android-sdk-windows\docs\guide\practices\compatibility.html

Upload: smartsm78

Post on 13-Apr-2015

34 views

Category:

Documents


2 download

TRANSCRIPT

Page 1: Android Sdk Best Practices

See alsoMarket Filters

Providing Alternative Resources

Supporting Multiple Screens

<supports-screens>

<uses-configuration>

<uses-feature>

<uses-library>

<uses-permission>

<uses-sdk>

Android Compatibility

Android is designed to run on many different types of devices. For developers, the range and number of devices means a huge potential audience: the more devices that run Android apps, the more users who can access your app. In exchange, however, it also means that your apps will have to cope with that same variety of hardware.

Fortunately, Android has built-in tools and support that make it easy for your apps to do that, while at the same time maintaining control of what types of devices your app is available to. If you do your work properly, users whose devices can’t run your app will never see it in the Android Market, and will not get in trouble by downloading it. This page explains how you can control which devices have access to your apps, and how to prepare your apps to make sure they reach the right audience.

What does “Compatibility” mean?

A device is “Android compatible” if it can correctly run apps written for the Android execution environment.

There is exactly one Android API for each API level, and it’s the same API no matter what kind of device it’s installed on. No parts of the API are optional, and you never have to worry about parts of the API missing on some devices. Every compatible Android device your app will land on will include every class and every API for that API level.

Of course, some APIs won’t work correctly if a particular device lacks the corresponding hardware or feature. But that’s not a problem: we also designed Android to prevent apps from being visible to devices which don’t have features the apps require. We’ve built support for this right into the SDK tools, and it’s part of the Android platform itself, as well as Android Market.

As a developer, you have complete control of how and where your apps are available. Android provides tools as a first-class part of the platform that let you manage this. You control the availability of your apps, so that they reach only the devices capable of running them.

How does it work?

You manage your app’s availability through a simple three-step process:

You state the features your app requires by declaring <uses-feature> elements its manifest file.1.

Devices are required to declare the features they include to Android Market.2.

Android Market uses your app’s stated requirements to filter it from devices that don’t meet those requirements.3.

This way, users never even see apps that won’t work properly on their devices. As long as you accurately describe your app’s requirements, you don’t need to worry about users blaming you for compatibility problems.

If you’re familiar with web development, you may recognize this model as “capability detection”. Web developers typically prefer this approach to “browser detection”, because it’s very difficult to keep up as new browsers and new versions of current browsers are released. By checking for support for specific required capabilities instead of the current browser,

Page 1 of 3Android Compatibility | Android Developers

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

Page 2: Android Sdk Best Practices

Filtering on Android MarketAndroid Market filters the applications that are visible to users, so that users

can see and download only those applications that are compatible with their devices.

One of the ways Market filters applications is by feature compatibility. To do this, Market checks the <uses-feature> elements in each application's manifest, to establish the app's feature needs. Market then shows or hides the application to each user, based on a comparison with the features available on the user's device.

For information about other filters that you can use to control the availability of your apps, see the Market Filters document.

web developers get better fine-grained control. That’s the same approach Android uses: since it’s impossible to keep up with all the Android devices being released, you instead use the fine-grained controls Android provides.

Filtering for technical reasons

Android includes support for a lot of features, some hardware and some software. Examples include compass and accelerometer sensors, cameras, and Live Wallpapers. However, not every device will support every feature. For instance, some devices don’t have the hardware horsepower to display Live Wallpapers well.

To manage this, Android defines feature IDs. Every capability has a corresponding feature ID defined by the Android platform. For instance, the feature ID for compass is “android.hardware.sensor.compass” , while the feature ID for Live Wallpapers is “android.software.live_wallpapers” . Each of these IDs also has a corresponding Java-language constant on the PackageManager class that you can use to query whether feature is supported at runtime. As Android adds support for new features in future versions, new feature IDs will be added as well.

When you write your application, you specify which features your app requires by listing their feature IDs in <uses-feature> elements in the AndroidManifest.xml file. This is the information that Android Market uses to match your app to devices that can run it. For instance, if you state that your app requires android.software.live_wallpapers, it won’t be shown to devices that don’t support Live Wallpapers.

This puts you in total control of your app — because you don’t have to declare these features. Consider an example involving cameras.

If you’re building a really impressive next-generation augmented-reality app, your app won’t function at all without a camera. However, if you’re building a shopping app that only uses the camera for barcode scanning, users without cameras might still find it useful even if they can’t scan barcodes. While both apps need to acquire the permission to access the camera, only the first app needs to state that it requires a camera. (The shopping app can simply check at runtime and disable the camera-related features if there’s no camera present.)

Since only you can say what the best approach is for your app, Android provides the tools and lets you make your own tradeoff between maximizing audience size and minimizing development costs.

Filtering for business reasons

It’s possible that you may need to restrict your app’s availability for business or legal reasons. For instance, an app that displays train schedules for the London Underground is unlikely to be useful to users outside the United Kingdom. Other apps might not be permitted in certain countries for business or legal reasons. For cases such as these, Android Market itself provides developers with filtering options that allow them control their app’s availability for non-technical reasons.

The help information for Android Market provides full details, but in a nutshell, developers can use the Market publisher UI to:

List the countries an app is available in.•

Select which carrier’s users are able to access the app.•

Page 2 of 3Android Compatibility | Android Developers

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

Page 3: Android Sdk Best Practices

↑ Go to top

Filtering for technical compatibility (such as required hardware components) is always based on information contained within your .apk file. But filtering for non-technical reasons (such as geographic restrictions) is always handled in the Market user interface.

Future-proofing

There’s one additional quirk that we haven’t yet addressed: protecting apps from changes made to future versions of Android. If the Android platform introduces a new feature or changes how existing features are handled, what happens to existing apps that were written without any knowledge of the new behavior?

Simply put, Android commits to not making existing apps available to devices where they won’t work properly, even when the platform changes. The best way to explain this is through examples, so here are two:

Android 1.0 through 1.5 required a 2 megapixel camera with auto-focus. However, with version 1.6, Android devices were permitted to omit the auto-focus capability, though a (fixed-focus) camera was still required. Some apps such as barcode scanners do not function as well with cameras that do not auto-focus. To prevent users from having a bad experience with those apps, existing apps that obtain permission to use the Camera were assumed by default to require auto-focus. This allowed Android Market to filter those apps from devices that lack auto-focus.

Android 2.2, meanwhile, allowed the microphone to be optional on some devices, such as set-top boxes. Android 2.2 included a new feature ID for the microphone which allows developers to filter their apps if necessary, but — as with camera — apps that obtain permission to record audio are assumed to require the microphone feature by default. If your app can use a microphone but doesn’t strictly need it, you can explicitly state that you don’t require it; but unless you do that, your app won’t be shown to devices without microphones.

In other words, whenever Android introduces new features or changes existing ones, we will always take steps to protect existing applications so that they don’t end up being available to devices where they won’t work.

Conclusion

The goal of Android is to create a huge installed base for developers to take advantage of. One of the ways we will achieve this is through different kinds of hardware running the same software environment. But we also recognize that only developers know which kinds of devices their apps make sense on. We’ve built in tools to the SDK and set up policies and requirements to ensure that developers remain in control of their apps, today and in the future. With the information you just read, and the resources listed in the sidebar of this document, you can publish your app with the confidence that only users who can run it will see it.

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

Page 3 of 3Android Compatibility | Android Developers

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

Page 4: Android Sdk Best Practices

Multiple screens quickview: Android runs on devices that have different screen sizes and resolutions.

The screen on which your application is displayed can affect its user interface.

The platform handles most of the work of adapting your app to the current screen.

You can create screen-specific resources for precise control of your UI, if needed.

Older applications run in a compatibility mode that provides best-effort rendering on the current screen.

It's important to follow the best practices described in this document and test your application in all supported screens.

In this documentOverview of Screen Support

Range of screens supported

How Android supports multiple screens

Density independence

Manifest attributes

Resource qualifiers

Best Practices for Screen Independence

Strategies for Legacy Apps

How to Test Your App

See Also<supports-screens>

<uses-sdk>

Alternative Resources

Android Virtual Devices

Supporting Multiple Screens

Android is designed to run on a variety of devices that offer a range of screen sizes and resolutions. For applications, the platform provides a consistent environment across devices and handles much of the complexity of adapting an application's UI to the screen on which it is being displayed. At the same time, the platform exposes APIs that give application developers precise control over their application's UI when displayed on specific screen sizes and resolutions.

This document explains the screens-support features provided by the platform and how you use them in your application. By following the practices described here, you can easily create an application that displays properly on all supported device screens and that you can deploy to any device as a single .apk.

If you have already developed and published an application for Android 1.5 or earlier, you should read this document and consider how you may need to adapt your application for proper display on new devices that offer different screens and that are running Android 1.6 or later. In most cases, only minor adjustments are needed, however you should make sure to test your application on all supported screens.

In particular, if you have an existing application that you would like to make available for users of devices with small screens (such as QVGA), please see Strategies for Legacy Applications for more information about how to do that.

Overview of Screens Support

The sections below provide an overview of the Android platform's support for multiple screens, including an introduction to terms and concepts used in this document and in the API, a summary of the screen configurations that the platform supports, and an overview of the API and underlying screen-compatibility features.

Terms and Concepts

Screen sizeActual physical size, measured as the screen's diagonal.

For simplicity, Android collapses all actual screen sizes into three generalized sizes: large, normal, and small. Applications can provide custom layouts for each of these three sizes — the platform transparently handles the rendering of the layouts at the actual screen size.

Aspect ratio

Page 1 of 17Supporting Multiple Screens | Android Developers

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

Page 5: Android Sdk Best Practices

The porportional relationship of the screen's physical width to its height. Applications can provide layout resources for specific aspect ratios by using the resource qualifiers long and notlong.

ResolutionThe total number of physical pixels on a screen. Note that, although resolution is often expressed as width x height, resolution does not imply a specific aspect ratio. In Android, applications do not work directly with resolution.

DensityBased on the screen resolution, the spread of pixels across the physical width and height of the screen.

A screen with lower density has fewer available pixels spread across the screen width and height, where a screen with higher density has more — sometimes significantly more — pixels spread across the same area. The density of a screen is important because, other things being equal, a UI element (such as a button) whose height and width are defined in terms of screen pixels will appear larger on the lower density screen and smaller on the higher density screen.

For simplicity, Android collapses all actual screen densities into three generalized densities: high, medium, and low. Applications can provide custom resources for each of these three densities — the platform handles the scaling of the resources up or down to meet the actual screen density.

Density-independent pixel (dip)A virtual pixel unit that applications can use in defining their UI, to express layout dimensions or position in a density-independent way.

The density-independent pixel is equivalent to one physical pixel on a 160 dpi screen, the baseline density assumed by the platform (as described later in this document). At run time, the platform transparently handles any scaling of the dip units needed, based on the actual density of the screen in use. The conversion of dip units to screen pixels is simple: pixels = dips * (density / 160). For example, on 240 dpi screen, 1 dip would equal 1.5 physical pixels. Using dip units to define your application's UI is highly recommended, as a way of ensuring proper display of your UI on different screens.

Range of Screens Supported

Android 1.5 and earlier versions of the platform were designed to support a single screen configuration — HVGA (320x480) resolution on a 3.2" screen. Because the platform targeted just one screen, application developers could write their applications specifically for that screen, without needing to worry about how their applications would be displayed on other screens.

Starting from Android 1.6, the platform adds support for multiple screen sizes and resolutions, reflecting the many new types and sizes of devices on which the platform will run. This means that developers must design their applications for proper display on a range of devices and screens.

To simplify the way application developers design their user interfaces for multiple devices, and to allow more devices to participate without impacting applications, the platform divides the range of actual supported screen sizes and resolutions into:

A set of three generalized sizes: large, normal, and small, and •

A set of three generalized densities: high (hdpi), medium (mdpi), and low (ldpi) •

Applications can provide custom resources (primarily layouts) for any of the three generalized sizes, if needed, and they can also provide resources (primarily drawables such as images) for any of the three generalized densities. Applications do not need to work with the actual physical size or density of the device screen. At run time, the platform handles the loading of the correct size or density resources, based on the generalized size or density of the current device screen, and adapts them to the actual pixel map of the screen.

The table below lists some of the more common screens supported by Android and illustrates how the platform maps them to generalized screen configurations.

Page 2 of 17Supporting Multiple Screens | Android Developers

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

Page 6: Android Sdk Best Practices

Using the alternative resources framework

The platform's support for loading screen size- and density-specific resources at run time is based on the alternative resources framework.

If you want to use size- or density-specific layouts or drawables in your application and you are not familiar with resource qualifiers or how the platform uses them, please read Alternative Resources.

Table 1. Examples of device screens supported by Android.

Low density (120), ldpi Medium density (160), mdpi High density (240), hdpi

Small screen

QVGA (240x320), 2.6"-3.0" diagonal

Normal screen

WQVGA (240x400), 3.2"-3.5" diagonal

FWQVGA (240x432), 3.5"-3.8" diagonal

HVGA (320x480), 3.0"-3.5" diagonal

• WVGA (480x800), 3.3"-4.0" diagonal

FWVGA (480x854), 3.5"-4.0" diagonal

Large screen

WVGA (480x800), 4.8"-5.5" diagonal

FWVGA (480x854), 5.0"-5.8" diagonal

As shown above, the various screen configurations are arranged around a baseline screen that is assigned a size of "normal" and a density of "medium". The HVGA screen is used as the baseline because all applications written against Android 1.5 or earlier are (by definition) written for the HVGA screen used on the T-Mobile G1 and similar devices.

Although the platform currently supports the nine possible size-density configurations listed in the table, you do not necessarily need to create custom resources for each one of them. The platform provides robust compatibility features, described in the sections below, that can handle most of the work of rendering your application on the current device screen, provided that the UI is properly implemented. For more information, see Best Practices for Screen Independence.

How Android supports multiple screens

The foundation of Android's support for multiple screens is a set of built-in compatibility features that together manage the rendering of application resources in an appropriate way for the current device screen. The platform handles most of the work of rendering your application, but also gives you two key ways to control how your application is displayed, if you need or want to use them:

The platform supports a set of resource qualifiers that let you provide size- and density-specific resources, if needed. The qualifiers for size-specific resources are large, normal, and small, and those for density-specific resources are hdpi (high), mdpi (medium), and ldpi (low). The qualifiers correspond to the generalized densities given in Table 1, above.

The platform also provides a <supports-screens> manifest element, whose attributes android:largeScreens, android:normalScreens, and android:smallScreens let you specify what generalized screen sizes your application supports. A fourth attribute, android:anyDensity, lets you indicate whether or not your application includes built-in support for multiple densities.

At run time, the platform provides three types of support to your application, to ensure the best possible display on the current device screen:

Pre-scaling of resources (such as image assets) 1.

Based on the density of the current screen, the platform automatically loads any size- or density-specific resources from your application and displays them without scaling. If no matching resources are available, the platform loads the default resources and scales them up or down as needed to match the current screen's generalized density. The

Page 3 of 17Supporting Multiple Screens | Android Developers

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

Page 7: Android Sdk Best Practices

Publishing to Small Screen DevicesTo ensure the best experience for users on small-screen devices,

Android Market only shows applications that explicitly declare support for small screens. If you developed an application on Android 1.5 or earlier and published it on Android Market, you need to test your application on small screens and then upload an updated version that explicitly indicates support for small screens.

platform assumes that default resources are designed for proper display at the baseline screen density of "medium" (160), unless they are loaded from a density-specific resource directory.

For example, if the current screen's density is "high", the platform loads resources that are tagged with the qualifier hdpi and uses them without scaling. If no such resources are available, the platform uses the default resources instead, scaling them from the baseline density ("medium") to "high".

For more information about how to create size- and density-specific resources, see Resource qualifiers.

Auto-scaling of pixel dimensions and coordinates 2.

If the application states that it does not support different screen densities, the platform auto-scales any absolute pixel coordinates, pixel dimension values, and pixel math used in the application (such as might be used for specifying the width or padding for a view). It does this to ensure that pixel-defined screen elements are displayed at approximately the same physical size as they would be at the baseline density of "medium" (160). The platform handles this scaling transparently to the application and also reports scaled overall pixel dimensions to the application, rather than physical pixel dimensions.

For instance, suppose a given device is using a WVGA high-denisty screen, which is 480x800 and about the same size as a traditional HVGA screen, but it's running an app that states that it does not support multiple densities. In this case, the system will "lie" to the application when it queries for screen dimensions, and report 320x533. Then, when the app does drawing operations, such as invalidating the rectangle from (10,10) to (100, 100), the system will likewise automatically transform the coordinates by scaling them the appropriate amount, and actually invalidate the region (15,15) to (150, 150). The same thing happens in the other direction, if the application is running on a lower-density screen, coordinates are scaled down.

For more information, see the android:anyDensity attribute in Manifest attributes for screens support.

Compatibility-mode display on larger screen-sizes 3.

If the current screen's size is larger than your application supports, as specified in the supports-screens element, the platform displays the application at the baseline size ("normal") and density ("medium). For screens larger than baseline, the platform displays the application in a baseline-sized portion of the overall screen, against a black background.

For instance, suppose a given device is using a WVGA medium density screen, classified as a "large" screen, but the application states that it does not support large screens; in this case, the system will again "lie" to the application when it queries for screen dimensions, and report 320x480. Instead of scaling the application, however, the application's 320x480 interface will be placed as a "postage stamp" in the larger 480x800 screen.

For more information, see the android:anyDensity attribute in Manifest elements for screens support and the Screen-Compatibility Examples section.

In general, these compatibility features ensure that all applications, including those written against Android 1.5 and earlier platform versions, can display properly on most devices, especially when the device's screen is at the baseline "normal" size or larger.

However, note that applications written for the baseline screen may need minor adjustments before they display properly on smaller screens such as QVGA. With the reduced screen area of small screens, there may be tradeoffs in design, content, and function that you, as the application developer, need to consider. For more information about how to prepare an existing application for display on small screens, see Strategies for Legacy Applications.

The sections below provide more information how to take advantage of the platform's multiple-screens support.

Page 4 of 17Supporting Multiple Screens | Android Developers

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

Page 8: Android Sdk Best Practices

Density independence

The goal of density independence is to preserve the physical size, from the user's point of view, of user interface elements declared in an application, when the application is displayed on screens with different densities. Density independence applies to both layouts and drawables such as icons. Maintaining density-independence is important because, other things being equal, a UI element (such as a button) whose height and width are defined in terms of screen pixels will appear physically larger on the lower density screen and smaller on the higher density screen. Such density-related size changes can cause problems in application layout, usability, and consistency with other applications installed on the device.

The platform provides density independence to applications by default. It does this in three ways:

Through pre-scaling of drawable resources (scaled at resource loading time)•

Through auto-scaling of density-independent pixel (dip) values used in layouts•

Through auto-scaling of absolute pixel values used in the application (only needed if the application has set android:anyDensity="false" in its manifest)

The example screens below illustrate the density independence provided by the platform. Note that both the layouts and launcher icons are displayed at the same physical sizes, although screen sizes, aspect ratios, and densities are different.

Figure 1. Examples of density independence on WVGA high density (left), HVGA medium density (center), and QVGA low density (right).

In most cases, you can take advantage of density independence in your application simply by making sure that your layouts specify all dimension values in density-independent pixels (dip or dp) or scale-independent pixels (sip or sp, for text only). If you are using absolute pixel values in the application and manifest includes android:anyDensity="true", you will also need to scale the pixel values. See Converting from dips to pixels for more information.

Page 5 of 17Supporting Multiple Screens | Android Developers

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

Page 9: Android Sdk Best Practices

Manifest attributes for screens support

Android 1.6 introduced a new manifest element, <supports-screens>, whose attributes you can use to control the display of your application on different classes of device screens, as listed below. The smallScreens, normalScreens, and largeScreens attributes correspond to the generalized screen sizes shown in Table 1, earlier in this document.

Attribute Description

android:smallScreens Whether or not the application UI is designed for use on small screens — "true" if it is, and "false" if not. See Default values for attributes for information about the assumed value of this attribute, if not declared.

android:normalScreens Whether or not the application UI is designed for use on normal screens — "true" if it is, and "false" if not. The default value is "true".

android:largeScreens Whether or not the application UI is designed for use on large screens — "true" if it is, and "false" if not. See Default values for attributes for information about the assumed value of this attribute, if not declared.

android:anyDensity Whether or not the application is designed to manage its UI properly in different density environments — "true" if so, and "false" if not.

If set to "true", the platform disables its density-compatibility features for all screen densities — specifically, the auto-scaling of absolute pixel units and math — and relies on the application to use density-independent pixel units and/or to manage the adaptation of pixel values according to density of the current screen.

If set to "false", the platform enables its density-compatibility features for all screen densities. In this case, the platform provides a scaled, virtual screen pixel map to the application, against which it can layout and draw its UI as though against a medium-density screen (160). The platform then transparently auto-scales the application's pixel units and math as needed to match the actual device screen density.

See Default values for attributes for information about the assumed value of this attribute, if not declared.

In general, when you declare a screen-size attribute (smallScreens, normalScreens, or largeScreens) as "true", you are signaling to the platform that your application wants to manage its UI by itself, for all screen sizes, without the platform applying any size-compatibility behaviors (such as a virtual HVGA display area). If you declare a screen-size attribute as "false", you are signaling that your application is not designed for that screen size. The effects are conditioned by the screen size that your application does not support:

If you declare largeScreens="false", your application can still be installed by users of devices with large screens. When run on a device with a large screen, this attribute value causes the platform to run the application in compatibility mode, rendering it in a baseline screen area (normal size, medium density) reserved on the larger screen. See Screen-Compatibility Examples for an illustration of what an application looks like when displayed in compatibility mode.

If you declare smallScreens="false", your application can still be installed by users of devices with small screens. However, this attribute value causes Android Market to filter your application from the list of applications available to such users. In effect, this prevents users from installing the application on small-screen devices.

If you declare the android:anyDensity attribute as "true", you are signaling to the platform that your application wants to manage its UI by itself, for all screen densities, using the actual screen dimensions and pixels. In this case, the

Page 6 of 17Supporting Multiple Screens | Android Developers

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

Page 10: Android Sdk Best Practices

application must ensure that it declares its UI dimensions using density-independent pixels and scales any actual pixel values or math by the scaling factor available from android.util.DisplayMetrics.density.

Note that the setting of the android:anyDensity attribute does not affect the platform's pre-scaling of drawable resources, such as bitmaps and nine-patch images, which always takes place by default.

The following example shows a manifest that declares support for large, normal, and small screens in any densities.

<manifest xmlns:android="http://schemas.android.com/apk/res/android"> <supports-screens android:largeScreens="true" android:normalScreens="true" android:smallScreens="true" android:resizable="true" android:anyDensity="true" /> </manifest>

Default values for attributes

The default values for the <supports-screens> attributes differs, depending on the the value of the android:minSdkVersion attribute in the application's manifest, as well as on the value of android:targetSdkVersion, if declared:

If android:minSdkVersion or android:targetSdkVersion is "3" (Android 1.5) or lower, the default value for everything except android:normalScreens is false. If you are primarily targeting pre-Android 1.6 platforms but also want to support other densities/screen sizes, you need to set the appropriate attributes to true.

If android:minSdkVersion or android:targetSdkVersion is "4" (Android 1.6) or higher, the default value for everything is true. If your application requires Android 1.6 features, but does not support these densities and/or screen sizes, you need to set the appropriate attributes to false.

Note that android:normalScreens always defaults to true. •

Resource directory qualifiers for screen size and density

Android supports resource directory qualifiers for controlling the selection of resources based on the characteristics of the screen on which your application is running. You can use these qualifiers to provide size- and density-specific resources in your application. For more information about the generalized sizes and densities that correspond to the qualifiers, see Table 1, earlier in this document.

Page 7 of 17Supporting Multiple Screens | Android Developers

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

Page 11: Android Sdk Best Practices

Screen characteristic

Qualifier Description

Size small Resources for small screens, such as QVGA low density.

normal Resources for normal (baseline configuration) screens, such as T-Mobile G1/HTC Magic screen size, or equivalent.

large Resources for large screens. Typical example is a tablet like device.

Density ldpi Low-density resources, for 100 to 140 dpi screens.

mdpi Medium-density resources for 140 to 180 dpi screens.

hdpi High-density resources for 190 to 250 dpi screens.

nodpi Density-independent resources. The platform does not auto-scale resources tagged with this qualifier, regardless of the current screen's density.

Aspect ratio long Resources for screens of any size or density that have a significantly taller (in portrait mode) and wider (in landscape mode) aspect ratio than the baseline screen configuration.

notlong Resources for use only on screens that have an aspect ratio that is similar to the baseline screen configuration.

Platform version

v<api-level> Resources that are for use only on a specific API Level or higher. For example, if your application is designed to run on both Android 1.5 (API Level 3) and Android 1.6 (API Level 4 and higher), you can use the -v4 qualifier to tag any resources that should be excluded when your application is running on Android 1.5 (API Level 3).

Note that the density and the screen size are independent parameters and are interpreted by the system individually. For example, WVGA high density is considered a normal screen because its physical size is about the same as one of T-Mobile G1. On the other hand, a WVGA medium density screen is considered a large screen — it offers the same resolution but at lower pixel density, meaning that it is both physically larger than the baseline screen and can display significantly more information than a normal screen size.

Here is an example of the resource directory structure of an application that supports low and high density, and employs different layout schemes.

res/layout/my_layout.xml // layout for normal screen size res/layout-small/my_layout.xml // layout for small screen size res/layout-large/my_layout.xml // layout for large screen size res/layout-large-land/my_layout.xml // layout for large screen size in landscape mode res/drawable-ldpi/my_icon.png // icon image for low density res/drawable-mdpi/dpi/my_icon.png // icon for medium density res/drawable-hdpi/my_icon.png // icon image for high density res/drawable-nodpi/composite.xml // density independent resource

For more information about how to use resource qualifiers or how the platform selects them, please read Alternative Resources.

Page 8 of 17Supporting Multiple Screens | Android Developers

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

Page 12: Android Sdk Best Practices

Best practices for Screen Independence

The objective of supporting multiple screens is to create an application that can run properly on any display and function properly on any of the screen configurations listed in Table 1 earlier in this document.

You can easily ensure that your application will display properly on different screens. Here is a quick checklist:

Prefer wrap_content, fill_parent and the dip unit to px in XML layout files 1.

Avoid AbsoluteLayout 2.

Do not use hard coded pixel values in your code 3.

Use density and/or resolution specific resources 4.

1. Prefer wrap_content, fill_parent and the dip unit to absolute pixels

When defining the layout_width and layout_height of views in an XML layout file, using wrap_content, fill_parent or the dip will guarantee that the view is given an appropriate size on the current device screen. For instance, a view with a layout_width="100dip" will measure 100 pixels wide on an HVGA@160 density display and 150 pixels on a WVGA@240 density display, but the view will occupy approximately the same physical space.

Similarly, you should prefer the sp (scale-independent pixel, the scale factor depends on a user setting) or dip (if you don't want to allow the user to scale the text) to define font sizes.

2. Avoid AbsoluteLayout

AbsoluteLayout is one of the layout containers offered by the Android UI toolkit. Unlike the other layouts however, AbsoluteLayout enforces the use of fixed positions which might easily lead to user interfaces that do not work well on different displays. Because of this, AbsoluteLayout was deprecated in Android 1.5 (API Level 3).

You can achieve much the same layout by using a FrameLayout instead, and setting layout_margin attributes of the children. This approach is more flexible and will yield better results on different screens.

3. Do not use hard-coded pixel values in your code

For performance reasons and to keep the code simpler, the Android framework API uses pixels as the standard unit for expressing dimension or coordinate values. That means that the dimensions of a View are always expressed in the code in pixels. For instance, if myView.getWidth() returns 10, the view is 10 pixels wide. In some cases, you may need to scale the pixel values that you use in your code. The sections below provide more information.

Converting from dips to pixels

In some cases, you will need to express dimensions in dip and then convert them to pixels. Imagine an application in which a scroll gesture is recognized after the user's finger has moved by at least 16 pixels. On a baseline screen, the user will have to move his finger by 16 pixels / 160 dpi = 1/10th of an inch (or 2.5 mm) before the gesture is recognized. On a device with a high (240) density display, the user will move his finger by only 16 pixels / 240 dpi = 1/15th of an inch (or 1.7 mm.) The distance is much shorter and the application thus appears more sensitive to the user. To fix this issue, the gesture threshold must be expressed in the code in dip and then converted to actual pixels.

// The gesture threshold expressed in dip private static final float GESTURE_THRESHOLD_DIP = 16.0f; // Convert the dips to pixels final float scale = getContext().getResources().getDisplayMetrics().density; mGestureThreshold = (int) (GESTURE_THRESHOLD_DIP * scale + 0.5f); // Use mGestureThreshold as a distance in pixels

Page 9 of 17Supporting Multiple Screens | Android Developers

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

Page 13: Android Sdk Best Practices

Figure 2. Comparison of pre-scaled and auto-scaled bitmaps.

The android.util.DisplayMetrics.density field specifies the the scale factor you must use to convert dips to pixels according to the current screen density. You can access the current screen's metrics through a Context or Activity. On a medium (160) density screen, DisplayMetrics.density equals "1.0", whereas on a high (240) density screen it equals "1.5". You can refer to the documentation of the DisplayMetrics class for details.

Use pre-scaled configuration values

The ViewConfiguration class can be used to access the most common distances, speeds, and times used in the Android framework. For instance, the distance in pixels used by the framework as the scroll threshold can be obtained as follows:

ViewConfiguration.get(aContext).getScaledTouchSlop()

Methods starting with the getScaled prefix are guaranteed to return a value in pixels that will display properly regardless of the current screen density.

4. Use density and/or size-specific resources

Even with the size- and density-compatibility features that the platform provides, you may still want to make adjustments to the UI of your application when it displayed on certain screen sizes or densities. You can do this by providing size- or density-specific resources — assets, layouts, strings, and so on. If you want, you can also take control over the scaling of images assets. The sections below provide more information.

Custom resources and directories

If you need to control exactly how your application will look on various displays, simply adjust your assets and layouts in configuration-specific resources directories. For example, consider an icon that you want to display on medium and high density screens. Simply create your icon at two different sizes (for instance 100x100 for medium density and 150x150 for high density) and put the two variations in the appropriate directories, using the proper qualifiers:

res/drawable-mdpi/icon.png // for medium-density screens

res/drawable-hdpi/icon.png // for high-density screens

If a density qualifier is not defined in a resource directory name, the platform assumes that the resources in that directory are designed for the baseline medium density. It is not recommended that you put density-specific resources such as images in the default directory.

For more information about valid resource qualifiers, see Resource directory qualifiers, earlier in this document.

Page 10 of 17Supporting Multiple Screens | Android Developers

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

Page 14: Android Sdk Best Practices

Pre-scaling and auto-scaling of bitmaps and nine-patches

When a bitmap or nine-patch image is loaded from the application's resources, the platform attempts to pre-scale it to match the display's density. For instance, if you placed a 100x100 icon in the res/drawable/ directory and loaded that icon as a bitmap on a high-density screen, Android would automatically scale up the icon and produce a 150x150 bitmap.

This pre-scaling mechanism works independently of the source. For instance, an application targeted for a high-density screen may have bitmaps only in the res/drawable-hdpi/ directory. If one of the bitmaps is a 240x240 icon and is loaded on a medium-density screen, the resulting bitmap will measure 160x160.

The platform pre-scales resources as needed, whether the application is running with density-compatibility features enabled or not (as specified by the value of android:anyDensity). However, when running with density-compatibility enabled, the platform continues to report the size of pre-scaled bitmaps and other resources as if they were loaded in a medium-density environment. For example, when density-compatibility is enabled, if you load a 76x76 image from the default resources for display on a high-density screen, the platform will pre-scale the image to 114x114 internally. However, the API still reports the size of the image as 76x76. This discrepancy may cause unexpected behavior if your application somehow directly manipulates the scaled bitmap, but this was considered a reasonable trade-off to keep the performance of existing applications as good as possible.

This does not apply for the case that an application creates an in-memory bitmap internally and draws something on it, for later display on the screen. The platform auto-scales such bitmaps on the fly, at draw time. Other side effects of such a case might be that fonts drawn in such a bitmap will be scaled at the bitmap level, when the off-screen bitmap is finally rendered to the display, resulting in scaling artifacts.

There are situations in which you may not want Android to automatically scale a resource. The easiest way to accomplish this is to put it in a "nodpi" resource directory:

res/drawable-nodpi/icon.png

You can also take complete control of the scaling mechanism by using the BitmapFactory.Options class, which lets you define whether you want the bitmap to be pre-scaled and what the density of the bitmap should be. For instance, if you are loading a bitmap from a web server, you may want to force the bitmap's density to be high density. When pre-scaling is disabled, the resulting bitmap is in auto-scaling mode. The bitmap is associated with a density (that you may or may not have specified through the BitmapFactory.Options) which will be used to scale the bitmap on screen at drawing time.

Using auto-scaling instead of pre-scaling is more CPU expensive than pre-scaling but uses less memory. You can refer to the documentation of BitmapFactory, Bitmap, and Canvas for more information on auto-scaling.

Figure 2, at right, demonstrates the results of the pre-scale and auto-scale mechanisms when loading low (120), medium (160) and high (240) density bitmaps on a baseline screen. The differences are subtle, because all of the bitmaps are being scaled to match the current screen density, however the scaled bitmaps have slightly different appearances depending on whether they are pre-scaled or auto-scaled at draw time.

Strategies for Legacy Applications

If you have already developed and published an Android application based on Android 1.5 or earlier platform version, you need to consider how you will adapt your application so that it is deployable to

Existing devices, which may be running Android 1.5 (or lower) platform version, as well as to •

Newer devices that are running Android 1.6 (or higher) and offering various screen sizes and resolutions•

To support the newer devices and the different screens they use, you might need to make some changes in your app, but at the same time your app may be very stable and so you want to minimize the changes. There are a variety of ways that you can extend your existing application to support new devices with multiple screens and existing devices running older

Page 11 of 17Supporting Multiple Screens | Android Developers

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

Page 15: Android Sdk Best Practices

platform versions. You should be able to make these changes to your application such that you can distribute a single .apk to any and all devices.

The recommended strategy is to develop against the most recent version of the platform you are targeting, and test on the minimum one you want to run on. Here's how to do that:

Maintain compatibility with existing devices by leaving your application's android:minSdkVersion attribute as it is. You do not need to increment the value of the attribute to support new devices and multiple screens.

1.

Extend compatibility for Android 1.6 (and higher) devices by adding a new attribute — android:targetSdkVersion — to the uses-sdk element. Set the value of the attribute to "4". This allows your application to "inherit" the platform's multiple screens support, even though it is technically using an earlier version of the API.

2.

Add an empty <supports-screens> element as a child of <manifest>. If you need to enable size or density attributes later, this is where you will add them.

3.

Change your application's build properties, such that it compiles against the Android 1.6 (API Level 4) library, rather than against the Android 1.5 (or earlier) library. You will not be able to compile your application against the older platform because of the new manifest attribute.

4.

Set up AVDs for testing your application on Android 1.6 and higher releases. Create AVDs that use the screen sizes and densities that you want to support. When you create the AVDs, make sure to select the Android 1.6 or higher platform as the system image to run. For more information, see How to Test Your Application on Multiple Screens, below.

5.

Set up AVDs for testing your application on Android 1.5 (or earlier platform). You need AVDs running the older platforms you are targeting, so that you can test for compatibility and ensure that there are no functional regressions.

6.

Compile your application against the Android 1.6 library and run it on the AVDs you created. Observe the way your application looks and runs, and test all of the user interactions.

7.

Debug any display or functional issues. For issues that you resolve in your application code, make certain not to use any APIs introduced in API Level 4 or later. If you are in doubt, refer to SDK reference documentation and look for the API Level specifier for the API you want to use. Using an API introduced in API Level 4 or later will mean that your application will no longer be compatible with devices running Android 1.5 or earlier.

8.

For resource-related issues, you can try resolving them by: 9.

Adding a anyDensity="false" attribute to <supports-screens>, to enable density-compatibility scaling.◦

Creating any size- or density-specific resources you need and placing them in directories tagged with the correct qualifiers. Qualifiers must be arranged in a proscribed order. See Alternative Resources for more information.

Note that if you add size- or density-specific resource directories tagged with any of the resource qualifiers listed in this document, you should make sure to also tag those directories with the v<api-level> qualifier (for example, -v4). This ensures that those resources will be ignored when the application is run on Android 1.5 or lower platform versions.

If your application does not offer support (such as custom layouts) for large screens and you want the platform to display your application in screen-compatibility mode on larger screens, add a largeScreens="false" attribute to the <supports-screens> element in the manifest. See Screen-Compatibility Examples for illustrations of how the platform displays your application in this case.

10.

If your application does not offer support (such as custom layouts) for small screens (such as on a QVGA low-density screen) and you do not want Android Market to offer the application to users of small-screen devices, you must add a smallScreens="false" attribute to the <supports-screens> element.

11.

Continue testing and debugging until your application performs as expected on all of the platforms and screen sizes your application will support.

12.

Export, zipalign, and sign your application using the same private key you used when publishing the previous version, then publish the application to users as an update.

13.

Page 12 of 17Supporting Multiple Screens | Android Developers

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

Page 16: Android Sdk Best Practices

Figure 3. A typical set of AVDs for testing screens support.

In particular, remember to test your application on an AVD that emulates a small-screen device. Devices that offer screens with QVGA resolution at low density are available now. Users of those devices may want to download your application, so you should understand how your application will look and function on a small-screen device. In many cases, the reduced screen area and density mean that you may need to make tradeoffs in design, content, and function on those devices.

How to Test Your Application on Multiple Screens

Before publishing an application that supports multiple screens, you should thoroughly test it in all of the targeted screen sizes and densities. You can test how it displays with the platform's compatibility features enabled or with screen-specific UI resources included in your application. The Android SDK includes all the tools you need to test your application on any supported screen.

As a test environment for your applications, set up a series of AVDs that emulate the screen sizes and densities you want to support. The Android SDK includes six emulator skins to get you started. You can use the Android AVD Manager or the android tool to create AVDs that use the various emulator skins and you can also set up custom AVDs to test densities other than the defaults. For general information about working with AVDs, see Android Virtual Devices.

The Android SDK provides a set of default emulator skins that you can use for testing. The skins are included as part of each Android platform that you can install in your SDK. The Android 1.6 platform offers these default skins:

QVGA (240x320, low density, small screen) •

HVGA (320x480, medium density, normal screen) •

WVGA800 (480x800, high density, normal screen) •

WVGA854 (480x854 high density, normal screen) •

The Android 2.0 platform offers all of the Android 1.6 default skins, above, plus:

WQVGA400 (240x400, low density, normal screen) •

WQVGA432 (240x432, low density, normal screen) •

If you are using the android tool command line to create your AVDs, here's an example of how to specify the skin you want to use:

android create avd ... --skin WVGA800

Page 13 of 17Supporting Multiple Screens | Android Developers

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

Page 17: Android Sdk Best Practices

We also recommend that you test your application in an emulator that is set up to run at a physical size that closely matches an actual device. This makes it a lot easier to compare the results at various resolutions and densities. To do so you will need to know the approximate density, in dpi, of your computer monitor (a 30" Dell monitor has for instance a density of about 96 dpi.). Use your monitor's dpi as the value of the -scale option, when launching the emulator, for example:

emulator -avd <name> -scale 96dpi

If you are working in Eclipse with ADT, you can specify the -scale 96dpi option in the Target tab of run and debug configurations, under "Additional Emulator Command Line Options" field.

Note that starting the emulator with the -scale option will scale the entire emulator display, based on both the dpi of the skin and of your monitor. Using the default densities, the emulator skins included in the Android 1.6 SDK will emulate the following screen sizes:

QVGA, low density: 3.3" •

WQVGA, low density: 3.9" •

WQVGA432, low density: 4.1" •

HVGA, medium density: 3.6" •

WVGA800, high density: 3.9" •

WVGA854, high density: 4.1" •

You should also make sure to test your application on different physical screen sizes within a single size-density configuration. For example, according to Table 1, the minimum supported diagonal of QVGA is 2.8". To display this is on a 30" monitor you will need to adjust the value passed to -scale to 96*2.8/3.3 = 81dpi. You can also pass a float value to -scale to specify your own scaling factor:

emulator -avd <name> -scale 0.6

If you would like to test your application on a screen that uses a resolution or density not supported by the built-in skins, you can either adjust an existing skin, or create an AVD that uses a custom resolution or density.

Page 14 of 17Supporting Multiple Screens | Android Developers

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

Page 18: Android Sdk Best Practices

Figure 4. Resolution and density options that you can use, when creating an AVD using the AVD Manager.

In the AVD Manager, you can specify a custom skin resolution or density in the Create New AVD dialog, as shown in Figure 4, at right.

In the android tool, follow these steps to create an AVD with a custom resolution or density:

Use the 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:

1.

android create avd -n <name> -t <targetID> --skin WVGA800

To specify a custom density for the skin, answer "yes" when asked whether you want to create a custom hardware profile for the new AVD.

2.

Continue through the various profile settings until the tool asks you to specify "Abstracted LCD density" (hw.lcd.density). Consult Table 1, earlier in this document, and enter the appropriate value. For example, enter "160" to use medium density for the WVGA800 screen.

3.

Set any other hardware options and complete the AVD creation.4.

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

Screen-Compatibility Examples

This section provides examples of how the Android platform displays an application written for the baseline screen configuration — HVGA (320x480) resolution on a 3.2" screen — with all of the platform's size- and density-compatibility features enabled. That is, the examples show how the platform displays an application that doesn't provide built-in support for the screen on which it is being rendered, but which instead relies completely on the platform.

The platform's screen-compatibility features are designed to provide such an application with a virtual baseline screen environment against which to run, while at the same time ensuring for the user a physical display that is approximately the same as the baseline screen size and density.

Legacy applications that have not been modified to support multiple screens would be typical examples of such applications. In most cases, you would want to add multiple-screens support to a legacy application and publish an updated version, as described in Strategies for Legacy Applications. However, if you did not do so, the platform still performs best-effort rendering of your application, as illustrated below.

Internally, these are the compatibility features that the platform provides, based on the current device screen:

If the device's screen density is not medium, the application's layout and drawing of its content is as if the screen is medium density, but the framework scales the layout and images (if the image for the target density is not available) to fit the target density. It scales 1.5 times if the target density is high density (160->240 virtual dpi), or 0.75 times if the target density is low density (160 -> 120 virtual dpi).

If the device's screen size is small, there are few options options for making Android 1.5 applications work well on such a screen, so Android Market will filter applications that are not known to support these screens from the device.

Page 15 of 17Supporting Multiple Screens | Android Developers

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

Page 19: Android Sdk Best Practices

If the device's screen size is large, it limits the application's screen to the normal size and draws a black background around the application. For example, if an application supports high density, but does not support large screens, it only uses a 480x720 area of the screen and the rest will be filled with a black background (see example below).

HVGA, normal size, normal density [ emulator -skin HVGA ]

WVGA, normal size, high density [emulator -skin WVGA854 -dpi-device 240]

The application occupies full screen as its considered to be normal size. (close to 480x720)

VGA, large size, medium density [ emulator -skin 640x480 ]

The application occupies 320x480 of VGA.

SVGA, large size, high density [ emulator -skin 800x600 -dpi-device 240]

The application occupies 480x720 (=1.5 x [320x480]) of 800x600.

Screen-compatibility limitations on small, low-density screens

Because these device has smaller state/resolution, there are known limitations when application runs in compatibility mode.

QVGA

Because QVGA (240x320) screens have less screen area available and lower density than normal, which is 240x360 in low density, some applications cannot render all their content properly on those screens. As a result, on a QVGA device, Android Market will filter out all applications that do not declare they support small screens.

Examples:

Page 16 of 17Supporting Multiple Screens | Android Developers

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

Page 20: Android Sdk Best Practices

↑ Go to top

The part of z value graph is chopped.

The lap time area is chopped.

Images with 1 pixel height/width.

If an image has 1 pixel height or width, it may not be shown on the screen due to rounding issue. This is inevitable as it just does not have enough pixels.

For example, in the screen below, the divider in the menu is invisible because the width of the image is trancated to 0. (This particular problem is solvable because menu is handled inside framework, but there is no generic solution as it just does not have enough pixels.)

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

Page 17 of 17Supporting Multiple Screens | Android Developers

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

Page 21: Android Sdk Best Practices

↑ Go to top

User Interface Guidelines

The Android UI team has begun developing guidelines for the interaction and visual design of Android applications. Look here for articles that describe these guidelines as we release them.

Icon Design Guidelines and Android Icon Templates Pack » Your applications need a wide variety of icons, from a launcher icon to icons in menus, dialogs, tabs, the status bar, and lists. The Icon Guidelines describe each kind of icon in detail, with specifications for the size, color, shading, and other details for making all your icons fit in the Android system. The Icon Templates Pack is an archive of Photoshop and Illustrator templates and filters that make it much simpler to create conforming icons.

Widget Design Guidelines A widget displays an application's most important or timely information at a glance, on a user's Home screen. These design guidelines describe how to design widgets that fit with others on the Home screen. They include links to graphics files and templates that will make your designer's life easier.

Activity and Task Design Guidelines Activities are the basic, independent building blocks of applications. As you design your application's UI and feature set, you are free to re-use activities from other applications as if they were yours, to enrich and extend your application. These guidelines describe how activities work, illustrates them with examples, and describes important underlying principles and mechanisms, such as multitasking, activity reuse, intents, the activity stack, and tasks. It covers this all from a high-level design perspective.

Menu Design Guidelines Android applications make use of Option menus and Context menus that enable users to perform operations and navigate to other parts of your application or to other applications. These guidelines describe the difference between Options and Context menus, how to arrange menu items, when to put commands on-screen, and other details about menu design.

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

Page 1 of 1User Interface Guidelines | Android Developers

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

Page 22: Android Sdk Best Practices

Icon design quickviewYou can use several types of icons in an Android application.

Your icons should follow the general specification in this document.

You should create separate icon sets for high-, medium-, and low-density screens.

In this documentLauncher icon

Menu icon

Status bar icon

Tab icon

Dialog icon

List view icon

Tips for Designers

Using the Icon Templates Pack

Icon appendix

Standard Launcher icons

Standard Menu icons

Standard Status bar icons

See alsoSupporting Multiple Screens

Android Icon Templates Pack, v2.0 »

Older versionsIcon Design Guidelines, Android 1.0

Android Icon Templates Pack, v1.0 »

Icon Design Guidelines, Android 2.0

Creating a unified look and feel throughout a user interface adds value to your product. Streamlining the graphic style will also make the UI seem more professional to users.

This document provides information to help you create icons for various parts of your application’s user interface that match the general styles used by the Android 2.x framework. Following these guidelines will help you to create a polished and unified experience for the user.

To get started creating your icons more quickly, you can download the Android Icon Templates Pack. For more information, see Using the Android Icon Template Pack.

Providing Density-Specific Icon Sets

Android is designed to run on a variety of devices that offer a range of screen sizes and resolutions. When you design the icons for your application, it's important keep in mind that your application may be installed on any of those devices. As described in the Supporting Multiple Screens document, the Android platform makes it straightforward for you to provide icons in such a way that they will be displayed properly on any device, regardless of the device's screen size or resolution.

In general, the recommended approach is to create a separate set of icons for each of the three generalized screen densities listed in Table 1, below, then store them in density-specific resource directories in your application. When your application runs, the Android platform will check the characteristics of the device screen and load icons from the appropriate density-specific resources. For more information about how to store density-specific resources in your application, see Resource directory qualifiers for screen size and density.

The baseline screen density for Android devices is medium (mdpi). For this reason, a recommended approach to creating icon sets for multiple screen densities is to:

Design the icons for the baseline density first (see Table 1 for the actual pixel dimensions at which to design the icons).

1.

Place the icons in the application's default drawable resources, then run the application on an Android Virtual Device (AVD) or an HVGA device such as the T-Mobile G1.

2.

Test and adjust your baseline icons as needed.3.

When you are satisfied with the icons you've developed at the baseline density, create scaled copies for the other densities.

4.

Page 1 of 24Icon Design Guidelines, Android 2.0 | Android Developers

9/7/2010file://V:\android-sdk-windows\docs\guide\practices\ui_guidelines\icon_design.html

Page 23: Android Sdk Best Practices

Scale the baseline icons up 150% to create the high-density assets.◦

Scale the baseline icons down 75% to create the low-density assets.◦

Place the icons in density-specific resource directories in your application. For example: 5.

Medium-density assets go in a res/drawable-mdpi/ directory (or in the default res/drawable/ directory),◦

High-density assets go in a res/drawable-hdpi/ directory, and◦

Low-density assets go in a res/drawable-ldpi/ directory.◦

Test and adjust the high- and low-density icons if needed6.

For tips on how to create and manage icon sets for multiple densities, see Tips for Designers.

Table 1. Summary of finished icon dimensions for each of the three generalized screen densities, by icon type.

Icon Type Standard Asset Sizes (in Pixels), for Gene ralized Screen Densities

Low density screen (ldpi) Medium density screen (mdpi) High density screen (hdpi)

Launcher 36 x 36 px 48 x 48 px 72 x 72 px

Menu 36 x 36 px 48 x 48 px 72 x 72 px

Status Bar 24 x 24 px 32 x 32 px 48 x 48 px

Tab 24 x 24 px 32 x 32 px 48 x 48 px

Dialog 24 x 24 px 32 x 32 px 48 x 48 px

List View 24 x 24 px 32 x 32 px 48 x 48 px

Launcher Icon

A Launcher icon is a graphic that represents your application on the device’s Home screen and in the Launcher window.

The user opens the Launcher by touching the icon at the bottom of the Home screen. The Launcher opens and exposes the icons for all of the installed applications, which are arranged in a grid. The user selects an application and opens it by touching the Launcher icon or by means of any hardware navigation controls available, such as a trackball or d-pad.

The user can also drag an icon out of the Launcher window and onto the Home screen itself, for more convenient access to the application. In this case, the system displays your application's Launcher icon against the Home screen wallpaper, rendering it at the same dimensions as it is rendered inside the Launcher.

The system manages the scaling of all Launcher icons so that they rendered at a uniform height and width. The actual pixel dimensions of the rendered Launcher icons on any given device varies, based on the size and pixel-density characteristics of the device's screen. To ensure the best possible rendering for your icons, supply versions of the icons that are designed for low, medium, and high density screens. For information, see Providing Density-Specific Icon Sets, above, or Tips for Designers, below.

Style

The launcher icons that you create should follow the general style principles below. The guidelines aren't meant to restrict what you can do with your icons, but rather they are meant to emphasize the common approaches that your icons can share with others on the device. Figure 1, at right, provides examples.

Clean and contemporary:

Page 2 of 24Icon Design Guidelines, Android 2.0 | Android Developers

9/7/2010file://V:\android-sdk-windows\docs\guide\practices\ui_guidelines\icon_design.html

Page 24: Android Sdk Best Practices

Figure 1. Illustration of Launcher icon style.

Launcher icons should be current and sometimes quirky, but they should not appear aged or ragged. You should avoid overused symbolic metaphors whenever possible.

Simple and iconic:

Android Launcher icons are caricatural in nature; your icons should be highly simplified and exaggerated, so that they are appropriate for use at small sizes. Your icons should not be overly complicated.

Try featuring a single part of an application as a symbolic representation of the whole (for example, the Music icon features a speaker).

Consider using natural outlines and shapes, both geometric and organic, with a realistic (but never photorealistic) rendering.

Your icons should not present a cropped view of a larger image.

Tactile and textured:

Icons should feature non-glossy, textured material. See Materials and colors, below, for more information.•

Forward-facing and top-lit:

New for Android 2.0 and later platforms: Android Launcher icons should be forward-facing, with very little perspective, and they should be top-lit.

Additionally, note all icons will have separate text labels, so rather than working to include embedded text in the design of of your icons, focus your efforts on the icon's visual distinctiveness and memorability instead.

To look at more examples of the Launcher icons used by built-in Android applications, see Standard Launcher Icons in the Icons Appendix of this document.

Do's and Don'ts

Below are some "do and don't" examples to consider when creating icons for your application.

Android Launcher icons are...

Modern, minimal, matte, tactile, and textured•

Forward-facing and top-lit, whole, limited in color palette

Android Launcher icons are not...

Antique, over-complicated, glossy, flat vector•

Rotated, Cropped, Over-Saturated•

Page 3 of 24Icon Design Guidelines, Android 2.0 | Android Developers

9/7/2010file://V:\android-sdk-windows\docs\guide\practices\ui_guidelines\icon_design.html

Page 25: Android Sdk Best Practices

Figure 2. Side-by-side examples of "do's and don'ts" for Android launcher icons.

Materials and colors

Launcher icons should make use of tactile, top-lit, textured materials. Even if your icon is just a simple shape, you should try to render in a way that makes it appear to be sculpted from some real-world material.

The Launcher icons for the platform's default applications use the set of materials shown in Figure 3, below. Your icons can use these materials or you can create new materials.

Android launcher icons usually consist of a smaller shape within a larger base shape and combine one neutral and one primary color. Icons may use a combination of neutral colors but should maintain a fairly high level of contrast. Icons should not use more than one primary color per icon, if possible.

Launcher icons should use a limited color palette that includes a range of neutral and primary colors. The icons should not be over-saturated.

The recommended color palette to use for Launcher icons is shown in Figure 4. You can use elements of the palette for both the base color and the highlight color. You can use the colors of the palette in conjunction with a white-to-black vertical linear gradient overlay. This creates the impression that the icon is lit from above and keeps the color less saturated.

Figure 3. Example materials that you can use to create your icons.

Page 4 of 24Icon Design Guidelines, Android 2.0 | Android Developers

9/7/2010file://V:\android-sdk-windows\docs\guide\practices\ui_guidelines\icon_design.html

Page 26: Android Sdk Best Practices

Figure 4. Examples of materials combined with base and highlight colors from the recommended palette.

When you combine the materials above with a color highlight from the recommended pallete, you can create materials combinations such as those shown in Figure 5. To get you started, the icons pack includes a Photoshop template file (Launcher-icon-template.psd) that provides all of the default materials, colors, and gradients.

Figure 5. Recommended color palette for icons.

Size and positioning

Launcher icons should use a variety of shapes and forms and those must be scaled and positioned to create consistent visual weight.

Launcher icons should use a variety of shapes and forms and those must be scaled and positioned inside the asset to create consistent visual weight with other

Figure 6 illustrates various ways of positioning the icon inside the asset. As detailed in the table below, you should size the icons smaller than the actual bounds of the asset, to create a consistent visual weight and to allow for the inclusion of shadows. If your icon is square or nearly square, it should be scaled even smaller.

The bounding box for the full asset is shown in red.•

The recommended bounding box for the actual icon itself is shown in blue. The icon box is sized smaller than the full asset box so that there is space to include shadows and special icon treatments.

Page 5 of 24Icon Design Guidelines, Android 2.0 | Android Developers

9/7/2010file://V:\android-sdk-windows\docs\guide\practices\ui_guidelines\icon_design.html

Page 27: Android Sdk Best Practices

The recommended bounding box for an icon that is square is shown in orange. The box for square icons is smaller than that for other icons to establish a consistent visual weight across the two types.

Icon dimensions for high-density (hdpi) screens:

Full Asset: 72 x 72 px

Icon: 60 x 60 px

Square Icon: 56 x 56 px

Icon Dimensions for medium-density (mdpi) screens:

Full Asset: 48 x 48 px

Icon: 40 x 40 px

Square Icon: 38 x 38 px

Icon Dimensions for low-density (ldpi) screens:

Full Asset: 36 x 36 px

Icon: 30 x 30 px

Square Icon: 28 x 28 px

Figure 6. Icon sizing and positioning inside the bounds of the icon asset.

Using the Launcher Icon Template

Included in the Android Icon Templates Pack 2.0 is a template containing palettes for default icon materials and colors. The template is provided in .psd format for Adobe Photoshop or similar raster image editor.

To get started, first download the Android Icon Templates Pack 2.0 ».

Once you've downloaded the pack, unzip it and open the file Launcher-icon-template.psd in Adobe Photoshop or similar raster image editing program. Notice the palettes for materials and colors. You can use as the template as a starting point for creating your Launcher icons.

After you create your icon, you can add a shadow effect according to the specification below, as appropriate for the size of image you are creating.

Page 6 of 24Icon Design Guidelines, Android 2.0 | Android Developers

9/7/2010file://V:\android-sdk-windows\docs\guide\practices\ui_guidelines\icon_design.html

Page 28: Android Sdk Best Practices

Shadow for WVGA (high density) sreens:

Effect: Drop Shadow

Color: #000000

Blend Mode: Multiply

Opacity: 75%

Angle: 90°

Distance: 2px

Spread: 0%

Size: 5px

Shadow for HVGA (medium density) sreens:

Effect: Drop Shadow

Color: #000000

Blend Mode: Multiply

Opacity: 75%

Angle: 90°

Distance: 1px

Spread: 0%

Size: 3px

When the shadow is added and the icon is complete, export it as a PNG file with transparency enabled, ensuring that you size the icon at 72 x 72px for high-density screens and 48 x 48px for medium density screens. For more information about why you should provide different Launcher assets for high-, medium, and low-density screens, see Supporting Multiple Screens.

Menu icon

Menu icons are graphical elements placed in the pop-up menu shown to users when they press the Menu button. They are drawn in a flat-front perspective. Elements in a menu icon must not be visualized in 3D or perspective.

Page 7 of 24Icon Design Guidelines, Android 2.0 | Android Developers

9/7/2010file://V:\android-sdk-windows\docs\guide\practices\ui_guidelines\icon_design.html

Page 29: Android Sdk Best Practices

As described in Providing Density-Specific Icon Sets, above, you should create separate icon sets for low-, normal, and high-density screens. This ensures that your icons will display properly across the range of devices on which your application can be installed. See Table 1 for a listing of the recommended finished icon sizes for each density. Also, see Tips for Designers for suggestions on how to work with multiple sets of icons.

Structure

In order to maintain consistency, all menu icons must use the same primary palette and the same effects. For more information, see the menu icon color palette.

Menu icons should include rounded corners, but only when logically appropriate. For example, in Figure 7 the logical place for rounded corners is the roof and not the rest of the building.

All dimensions specified on this page are based on a 48x48 pixel artboard size with a 6 pixel safeframe.•

The menu icon effect (the outer glow) described in Light, effects, and shadows can overlap the 6px safeframe, but only when necessary. The base shape must always stay inside the safeframe.

Final art must be exported as a transparent PNG fil e.•

Templates for creating menu icons in Adobe Photoshop are available in the Icon Templates Pack.•

Figure 7. Safeframe and corner-rounding for menu icons. Icon size is 48x48.

Light, effects, and shadows

Menu icons are flat and pictured face on. A slight deboss and some other effects, which are shown below, are used to create depth.

Page 8 of 24Icon Design Guidelines, Android 2.0 | Android Developers

9/7/2010file://V:\android-sdk-windows\docs\guide\practices\ui_guidelines\icon_design.html

Page 30: Android Sdk Best Practices

Figure 8. Light, effects, and shadows for menu icons.

1. Front part: Use fill gradient from primary color palette

2. Inner shadow:

black | 20 % opacity angle 90° | distance 2px size 2px

3. Outer glow: white | 55% opacity spread 10% | size 3px

5. Inner bevel: depth 1% | direction down size 0px angle 90° | altitude 10° highlight white 70% opacity shadow black 25% opacity

Color palette

White r 255 | g 255 | b 255 Used for outer glow and bevel highlight.

Fill gradient 1: r 163 | g 163 | b 163 2: r 120 | g 120 | b 120 Used as color fill.

Black r 0 | g 0 | b 0 Used for inner shadow and bevel shadow.

Step by step

Create the basic shapes using a tool like Adobe Illustrator.

1.

Import the shape into a tool like Adobe Photoshop and scale to fit an image of 48x48 px on a transparent background. Mind the safeframe.

2.

Add the effects seen as described in Figure 8.3.

Export the icon at 48x48 as a PNG file with transparency enabled.

4.

"Do's and don'ts"

Below are some "do and don't" examples to consider when creating menu icons for your application.

Status bar icon

Status bar icons are used to represent notifications from your application in the status bar. Graphically, they are very similar to menu icons, but are smaller and higher in contrast.

Page 9 of 24Icon Design Guidelines, Android 2.0 | Android Developers

9/7/2010file://V:\android-sdk-windows\docs\guide\practices\ui_guidelines\icon_design.html

Page 31: Android Sdk Best Practices

As described in Providing Density-Specific Icon Sets, above, you should create separate icon sets for low-, normal, and high-density screens. This ensures that your icons will display properly across the range of devices on which your application can be installed. See Table 1 for a listing of the recommended finished icon sizes for each density. Also, see Tips for Designers for suggestions on how to work with multiple sets of icons.

Structure

Rounded corners must always be applied to the base shape and to the details of a status bar icon shown Figure 9.•

All dimensions specified are based on a 25x25 pixel artboard size with a 2 pixel safeframe.•

Status bar icons can overlap the safeframe to the left and right when necessary, but must not overlap the safeframe at the top and bottom.

Final art must be exported as a transparent PNG fil e.•

Templates for creating status bar icons using Adobe Photoshop are available in the Icon Templates Pack.•

Figure 9. Safeframe and corner-rounding for status bar icons. Icon size is 25x25.

Light, effects, and shadows

Status bar icons are slightly debossed, high in contrast, and pictured face-on to enhance clarity at small sizes.

Page 10 of 24Icon Design Guidelines, Android 2.0 | Android Developers

9/7/2010file://V:\android-sdk-windows\docs\guide\practices\ui_guidelines\icon_design.html

Page 32: Android Sdk Best Practices

Figure 10. Light, effects, and shadows for status bar icons.

1. Front part: Use fill gradient from primary color palette

2. Inner bevel:

depth 100% | direction down size 0px | angle 90° | altitude 30° highlight white 75% opacity shadow black 75% opacity

3. Detail: white4. Disabled

detail:grey gradient from palette + inner bevel: smooth | depth 1% | direction down | size 0px | angle 117° | altitude 42° | highlight white 70% | no shadow

Color palette

Only status bar icons related to the phone function use full color; all other status bar icons should remain monochromatic.

White r 255 | g 255 | b 255 Used for details within the icons and bevel highlight.

Grey gradient 1: r 169 | g 169 | b 169 2: r 126 | g 126 | b 126 Used for disabled details within the icon.

Fill gradient 1: 1 r 105 | g 105 | b 105 2: r 10 | g 10 | b 10 Used as color fill.

Black r 0 | g 0 | b 0 Used for bevel shadow.

Step by step

In a tool like Adobe Photoshop, create the base shape within a 25x25 px image on a transparent background. Mind the safeframe, and keep the upper and lower 2 pixels free.

1.

Add rounded corners as specified in Figure 9.2.

Add light, effects, and shadows as specified in Figure 10.

3.

Export the icon at 25x25 as a PNG file with transparency enabled.

4.

"Do's and don'ts"

Below are some "do and don't" examples to consider when creating status bar icons for your application.

Page 11 of 24Icon Design Guidelines, Android 2.0 | Android Developers

9/7/2010file://V:\android-sdk-windows\docs\guide\practices\ui_guidelines\icon_design.html

Page 33: Android Sdk Best Practices

Tab icon

Tab icons are graphical elements used to represent individual tabs in a multi-tab interface. Each tab icon has two states: unselected and selected.

As described in Providing Density-Specific Icon Sets, above, you should create separate icon sets for low-, normal, and high-density screens. This ensures that your icons will display properly across the range of devices on which your application can be installed. See Table 1 for a listing of the recommended finished icon sizes for each density. Also, see Tips for Designers for suggestions on how to work with multiple sets of icons.

Structure

Unselected tab icons have the same fill gradient and effects as menu icons, but with no outer glow.•

Selected tab icons look just like unselected tab icons, but with a fainter inner shadow, and have the same front part gradient as dialog icons.

Tab icons have a 1 px safeframe which should only be overlapped for the edge of the anti-alias of a round shape.•

All dimensions specified on this page are based on a 32x32 px artboard size. Keep 1 px of padding around the bounding box inside the Photoshop template.

Final art must be exported as a 32x32 px transparen t PNG file.•

Templates for creating tab icons in Adobe Photoshop are available in the Icon Templates Pack.•

Figure 11. Safeframe and fill gradient for unselected tab icons. Icon size is 32x32.

Figure 12. Safeframe and fill gradient for tab icons in selected state. Icon size is 32x32.

Unselected tab icon

Light, effects, and shadows

Unselected tab icons look just like the selected tab icons, but with a fainter inner shadow, and the same front part gradient as the dialog icons.

Page 12 of 24Icon Design Guidelines, Android 2.0 | Android Developers

9/7/2010file://V:\android-sdk-windows\docs\guide\practices\ui_guidelines\icon_design.html

Page 34: Android Sdk Best Practices

Figure 13. Light, effects, and shadows for unselected tab icons.

1. Front part: gradient overlay | angle 90° bottom color: r 223 | g 223 | b 223 top color: r 249 | g 249 | b 249 bottom color location: 0% top color location: 75%

2. Inner shadow:

black | 10 % opacity | angle 90° distance 2px | size 2px

3. Inner bevel:

depth 1% | direction down | size 0px | angle 90° | altitude 10° highlight white 70% opacity shadow black 25% opacity

Step by step

Create the basic shapes using a tool like Adobe Illustrator.

1.

Import the shape to a tool like Adobe Photoshop and scale to fit an image of 32x32 px on a transparent background.

2.

Add the effects seen in Figure 13 for the unselected state filter.

3.

Export the icon at 32x32 as a PNG file with transparency enabled.

4.

Selected tab icon

The selected tab icons have the same fill gradient and effects as the menu icon, but with no outer glow.

Page 13 of 24Icon Design Guidelines, Android 2.0 | Android Developers

9/7/2010file://V:\android-sdk-windows\docs\guide\practices\ui_guidelines\icon_design.html

Page 35: Android Sdk Best Practices

Figure 14. Light, effects, and shadows for selected tab icons.

1. Front part: Use fill gradient from color palette.2. Inner

shadow:black | 20% opacity | angle 90° | distance 2px | size 2px

3. Inner bevel: depth 1% | direction down | size 0px | angle 90° | altitude 10° highlight white 70% opacity shadow black 25% opacity

Color palette

Fill gradient 1: r 163 | g 163 | b 163 2: r 120 | g 120 | b 120 Used as color fill on unselected tab icons.

Step by step

Create the basic shape using a tool like Adobe Illustrator.

1.

Import the shape into a tool like Adobe Photoshop and scale to fit a 32x32 px artboard with a transparent background.

2.

Add the effects seen in Figure 14 for the selected state filter.

3.

Export the icon at 32x32 as a PNG file with transparency enabled.

4.

Dialog icon

Dialog icons are shown in pop-up dialog boxes that prompt the user for interaction. They use a light gradient and inner shadow in order to stand out against a dark background.

As described in Providing Density-Specific Icon Sets, above, you should create separate icon sets for low-, normal, and high-density screens. This ensures that your icons will display properly across the range of devices on which your application can be installed. See Table 1 for a listing of the recommended finished icon sizes for each density. Also, see Tips for Designers for suggestions on how to work with multiple sets of icons.

Structure

Dialog icons have a 1 pixel safeframe. The base shape must fit within the safeframe, but the anti-alias of a round shape can overlap the safeframe.

Page 14 of 24Icon Design Guidelines, Android 2.0 | Android Developers

9/7/2010file://V:\android-sdk-windows\docs\guide\practices\ui_guidelines\icon_design.html

Page 36: Android Sdk Best Practices

All dimensions specified on this page are based on a 32x32 pixel artboard size in Adobe Photoshop. Keep 1 pixel of padding around the bounding box inside the Photoshop template.

Final art must be exported as a transparent PNG fil e.•

Templates for creating dialog icons in Adobe Photoshop are available in the Icon Templates Pack.•

Figure 15. Safeframe and fill gradient for dialog icons. Icon size is 32x32.

Light, effects, and shadows

Dialog icons are flat and pictured face-on. In order to stand out against a dark background, they are built up using a light gradient and inner shadow.

Page 15 of 24Icon Design Guidelines, Android 2.0 | Android Developers

9/7/2010file://V:\android-sdk-windows\docs\guide\practices\ui_guidelines\icon_design.html

Page 37: Android Sdk Best Practices

Figure 16. Light, effects, and shadows for dialog icons.

1. Front part: gradient overlay | angle 90° bottom: r 223 | g 223 | b 223 top: r 249 | g 249 | b 249 bottom color location: 0% top color location: 75%

2. Inner shadow:

black | 25% opacity | angle -90° | distance 1px | size 0px

Step by step

Create the basic shapes using a tool like Adobe Illustrator.

1.

Import the shape into a tool like Adobe Photoshop and scale to fit an image of 32x32 px on a transparent background.

2.

Add the effects seen in Figure 16 for the proper filter.3.

Export the icon at 32x32 as a PNG file with transparency enabled.

4.

List view icon

List view icons look a lot like dialog icons, but they use an inner shadow effect where the light source is above the object. They are also designed to be used only in a ListView. Examples include the Android Market application home screen and the driving directions screen in the Maps application.

As described in Providing Density-Specific Icon Sets, above, you should create separate icon sets for low-, normal, and high-density screens. This ensures that your icons will display properly across the range of devices on which your application can be installed. See Table 1 for a listing of the recommended finished icon sizes for each density. Also, see Tips for Designers for suggestions on how to work with multiple sets of icons.

Structure

A list view icon normally has a 1 px safeframe, but it is OK to use the safeframe area for the edge of the anti-alias of a round shape.

Page 16 of 24Icon Design Guidelines, Android 2.0 | Android Developers

9/7/2010file://V:\android-sdk-windows\docs\guide\practices\ui_guidelines\icon_design.html

Page 38: Android Sdk Best Practices

All dimensions specified are based on a 32x32 pixel artboard size in Photoshop. Keep 1 pixel of padding around the bounding box inside the template.

Final art must be exported as a transparent PNG fil e.•

Templates for creating list view icons in Adobe Photoshop are available in the Icon Templates Pack. •

Figure 17. Safeframe and fill gradient for list view icons. Icon size is 32x32.

Light, effects, and shadows

List view icons are flat and pictured face-on with an inner shadow. Built up by a light gradient and inner shadow, they stand out well on a dark background.

Page 17 of 24Icon Design Guidelines, Android 2.0 | Android Developers

9/7/2010file://V:\android-sdk-windows\docs\guide\practices\ui_guidelines\icon_design.html

Page 39: Android Sdk Best Practices

Figure 18. Light, effects, and shadows for list view icons.

1. Inner shadow: black | 57 % opacity | angle 120° | blend mode normal | distance 1px | size 1px

2. Background: black | standard system color These icons are displayed in list views only.

Note: The list view icon sits on 32x32 px artboard in Photoshop, without a safeframe.

Step by step

Add the effects seen in Figure 18 for the proper filter.1.

Export the icon at 32x32 as a PNG file with transparency enabled.

2.

Create the basic shapes using a tool like Adobe Illustrator.

3.

Import the shape into a tool like Adobe Photoshop and scale to fit an image of 32x32 px on a transparent background.

4.

Tips for Designers

Here are some tips that you might find useful as you develop icons or other drawable assets for your application. The tips assume that you are using Photoshop or similar raster image-editing program.

Use common naming conventions for icon assets

Try to name files so that related assets will group together inside a directory when they are sorted alphabetically. In particular, it helps to use a common prefix for each icon type. For example:

Page 18 of 24Icon Design Guidelines, Android 2.0 | Android Developers

9/7/2010file://V:\android-sdk-windows\docs\guide\practices\ui_guidelines\icon_design.html

Page 40: Android Sdk Best Practices

Asset Type Prefix Example

Icons ic_ ic_star.png

Launcher icons ic_launcher ic_launcher_calendar.png

Menu icons ic_menu ic_menu_archive.png

Status bar icons ic_stat_sys or ic_stat_notify ic_stat_notify_msg.png

Tab icons ic_tab ic_tab_recent.png

Dialog icons ic_dialog ic_dialog_info.png

Note that you are not required to use a shared prefix of any type — doing so is for your convenience only.

Set up a working space that organizes files for mul tiple densities

Developing multiple sets of assets for different screen densities means creating multiple copies of files. To help keep the multiple copies of files safe and easier to find, we recommend creating a directory structure in your working space that organizes asset files per resolution. For example:

assets/... ldpi/... _pre_production/... working_file.psd finished_asset.png mdpi/... _pre_production/... working_file.psd finished_asset.png hdpi/... _pre_production/... working_file.psd finished_asset.png

This structure parallels the density-specific structure in which you will ultimately store the finished assets in your application's resources. Because the structure in your working space is similar to that of the application, you can quickly determine which assets should be copied to each application resources directory. Separating assets by density also helps you detect any variances in filenames across densities, which is important because corresponding assets for different densities must share the same filename.

For comparison, here's the resources directory structure of a typical application:

res/... drawable-ldpi/... finished_asset.png drawable-mdpi/... finished_asset.png drawable-hdpi/... finished_asset.png

Create medium-density assets first

Since medium density is the baseline for Android, begin your designing work by creating the mdpi assets. See Table 1, above, for the actual pixel dimensions of various icon types. When possible, use vector art or paths within Photoshop layers so that it will be easier to scale the assets up or down later.

For each discreet asset, or set of like assets that share the same bounding box dimensions, create a working Photoshop file and save it in the _pre_production directory. For example: ic_tabs_phone_mdpi.psd. This will make it easier

Page 19 of 24Icon Design Guidelines, Android 2.0 | Android Developers

9/7/2010file://V:\android-sdk-windows\docs\guide\practices\ui_guidelines\icon_design.html

Page 41: Android Sdk Best Practices

to locate and edit individual assets if changes are required. It's also helpful to use a density-specific suffix in the filename for the working file, to avoid confusion when editing the files. For example: _mdpi.psd.

From the mdpi working files, save individual flattened assets to the corresponding density-specific resource directory (in this case, mdpi/) in your working space.

Create high- and low-density assets from the medium -density sources

When you are finished working with your medium-density assets, copy the working files from the your workspace's mdpi/_pre_production directory to the corresponding locations in the ldpi and hdpi directories. If any of the working files use a density-specific suffix, rename the suffix to match the intended density.

Next, open each working file in the high- and low-density directories and scale the image up or down to match the intended density. To create an hdpi asset, scale the image by 150%. To create an ldpi asset, scale the image down by 75%. To scale the images, follow these steps:

Open the working file in Photoshop or similar program.1.

Under the Image menu, choose Image Size .2.

On the Image Size panel, change the Width pop up menu to "percent."3.

Change the Width value to "150" for hdpi assets and "75" for ldpi assets.4.

Select the Scale Styles checkbox.5.

Select the Constrain Proportions checkbox.6.

Select the Resample Image checkbox and set the pop up menu to "Bicubic (Best for smooth gradients)."7.

Click OK.8.

After you scale each image, save it to the target density-specific resource directory.

If you are scaling a nine-patch image, see the section below for notes on how to handle the tick marks at the edge of the image.

After scaling, redraw bitmap layers as needed

If you scaled an image up from a bitmap layer, rather than from a vector layer, those layers may need to be redrawn manually to accommodate the higher density. For example if a 60x60 circle was painted as a bitmap for mdpi it will need to be repainted as a 90x90 circle for hdpi.

When scaling a nine-patch image, crop tick marks be fore scaling and replace them after

Nine-patch images include tick marks at the outer edge of the image. When you scale a nine-patch image, the tick marks are also scaled, which produces an inaccurate result. The recommended way to handle the scaling of nine-patch images is to remove the tick marks from the source image before scaling and then manually replace the tick marks at the proper size after scaling.

To more easily determine the tick marks after the working file has been scaled to a new resolution, first create a temporary duplicate flattened image which includes the tick marks:

Under the Select menu choose All .1.

Under the Edit menu choose Copy Merged .2.

Under the File menu choose New and then click OK on the new panel.3.

Under the Edit choose Paste .4.

After creating the temporary copy, go back to the working file and crop the tick marks out of the working file before scaling the image:

Under the Image menu, choose the Canvas Size command.1.

Page 20 of 24Icon Design Guidelines, Android 2.0 | Android Developers

9/7/2010file://V:\android-sdk-windows\docs\guide\practices\ui_guidelines\icon_design.html

Page 42: Android Sdk Best Practices

On the Canvas Size panel, subtract 2 pixels from the Width and Height values.2.

Set the Anchor to "Center."3.

Click OK4.

Scale the working file to the target density. With the working file scaled and the canvas enlarged so that the tick marks can be repainted:

Under the Image menu, choose the Canvas Size command.1.

On the Canvas Size panel, add 2 pixels to the Width and Height values.2.

Set the Anchor to "Center."3.

Click OK.4.

To determine tick marks, go back to duplicate flattened image and scale it to the target resolution.

Copy the scaled duplicate flattened image into a new layer in the working file to use as reference. Create a new layer in which to paint new tick marks at the single pixel outer edge of the image. Note tickmarks must be 100% opaque black, without transparency, and all other areas of the tick mark region must be 100% transparent, otherwise the system will not interpret the nine-patch image correctly.

Using the scaled duplicate flattened image as reference paint new tick marks in the new layer that align with the reference layer. Note round up pixels for tick marks. Any pixels that are partially opaque in the reference layer should be fully opaqe in the new layer.

Adjust stroke and drop shadow after scaling an imag e

While it is desirable to scale layer styles for the most part (such as for Gradient Overlay or Inner Glow), you may need to manually reset the Stroke and Drop Shadow in the scaled image to 1 px before saving, especially when scaling to hdpi.

Save nine-patch images with the appropriate filenam e suffix

If an asset is a nine-patch asset (with tick marks), be sure to save the asset in PNG format with a filename that includes the .9.png suffix. If the filename does not use the suffix, the system won't recognize the image as a nine-patch asset and won't resize it as intended.

When saving image assets, remove the Photoshop head er

To help keep each image asset as small as possible, make sure to remove the Photoshop headers from the file. To remove the Photoshop header, follow these steps:

Under the File menu, choose the Save for Web & Devices command 1.

On the "Save for Web & Devices" panel, set the Preset pop-up to "PNG-24," set the pop-up under Presets to "PNG-24" as well, and select the Transparency box (if the image uses transparency)

2.

Select Save.3.

Make sure that corresponding assets for different d ensities use the same filenames

Corresponding icon asset files for each density must use the same filename, but be stored in density-specific resource directories. This allows the system to look up and load the proper resource according to the screen characteristics of the device. For this reason, make sure that the set of assets in each directory is consistent and that the files do not use density-specific suffixes. For more information about density-specific resources and how the system uses them to meet the needs of different devices, see Supporting Multiple Screens.

Page 21 of 24Icon Design Guidelines, Android 2.0 | Android Developers

9/7/2010file://V:\android-sdk-windows\docs\guide\practices\ui_guidelines\icon_design.html

Page 43: Android Sdk Best Practices

Using the Android Icon Templates Pack

The Android Icon Templates Pack is a collection of template designs, filters, and settings that make it easier for you to create icons that conform to the general specifications given in this document. We recommend downloading the template pack archive before you get started with your icon design.

The icon templates are provided in Adobe Photoshop and Adobe Illustrator file formats, which preserves the layers and design treatments we used when creating the standard icons for the Android platform. You can load the template files into any compatible image-editing program, although your ability to work directly with the layers and treatments may vary based on the program you are using.

You can obtain the Icon Templates Pack archive using the link below:

Download the Icon Templates Pack »

Icon appendix

Standard launcher icons

Shown below are examples of launcher icons used by Android applications. The icons are provided for your reference only — pl ease do not reuse these icons in your applications..

Page 22 of 24Icon Design Guidelines, Android 2.0 | Android Developers

9/7/2010file://V:\android-sdk-windows\docs\guide\practices\ui_guidelines\icon_design.html

Page 44: Android Sdk Best Practices

Standard menu icons

Shown below are standard menu icons that are used i n the Android system. Because these resources can change between platform versions, you should not reference the system's copy of the resources. I f you want use any icons or other internal drawable resources, you should st ore a local copy of those icons or drawables in your application resources, t hen reference the local copy from your application code. In that way, you c an maintain control over the appearance of your icons, even if the system's copy changes. Note that the list below is not intended to be complete.

Add

Call

Camera

Clear / Close /

Cancel / Discard

Compass

Delete

Directions

Edit

Gallery

Help

Info /

details

Map

mode

My

Location

More

Preferences

Rotate

Save

Send

Search

Share

Upload

View

Zoom

Standard status bar icons

Shown below are standard status bar icons that are used in the Android platform. Because these resources can change betwee n platform versions, you should not reference the system's copy of the r esources. If you want use any icons or other internal drawable resources, you should store a local copy

Page 23 of 24Icon Design Guidelines, Android 2.0 | Android Developers

9/7/2010file://V:\android-sdk-windows\docs\guide\practices\ui_guidelines\icon_design.html

Page 45: Android Sdk Best Practices

↑ Go to top

of those icons or drawables in your application res ources, then reference the local copy from your application code. In that way, you can maintain control over the appearance of your icons, even if the syst em's copy changes. Note that the list below is not intended to be complete.

Bluetooth

Email

IM

Voicemail

Warning

Call

Call

forward

Call on

hold

Missed

call

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

Page 24 of 24Icon Design Guidelines, Android 2.0 | Android Developers

9/7/2010file://V:\android-sdk-windows\docs\guide\practices\ui_guidelines\icon_design.html

Page 46: Android Sdk Best Practices

Widget design quickview

Widgets have six standard sizes on the Homescreen

Widgets have standards for size, frames,shadows, and file format, which you can copyA few tricks make it easier to design widgetsthat fit graphically on the Home screen

In this document

Standard widget anatomy

Designing a widget

Standard widget sizes

Standard widget frames

Standard widget shadows

Widget graphics tips and tricks

Widget graphics file format

See also

AppWidgets topic in the Dev Guide

AppWidgets blog post

Widget Design Guidelines

Widgets are a feature introduced in Android 1.5. A widget displays an application's most important or timely information at a

glance, on a user's Home screen. The standard Android system image includes several examples of widgets, including widgets

for Analog Clock, Music, and other applications.

Users pick the widgets they want to display on their Home screens by touching & holding an empty area of the Home screen,

selecting Widgets from the menu, and then selecting the widget they want.

This document describes how to design a widget so it fits graphically with other widgets and with the other elements of the Android Home screen. It also describes some standards for

widget artwork and some widget graphics tips and tricks from the Android team.

For information about developing widgets, see the AppWidgets section of the Developer's Guide and the AppWidgets blog post.

Standard widget anatomy

Typical Android widgets have three main components: A bounding box, a frame, and the widget's graphical controls and other elements. Well-designed widgets leave some padding

between the edges of the bounding box and the frame, and between the inner edges of the frame and the widget's controls. Widgets designed to fit visually with other widgets on the

Home screen take cues from the other elements on the Home screen for alignment; they also use standard shading effects. All of these details are described in this document.

Standard Widget Sizes in Portrait Orientation

Widget Design Guidelines | Android Developers http://developer.android.com/guide/practices/ui_guidelines/widget_design...

1 of 7 9/7/2010 2:12 PM

Page 47: Android Sdk Best Practices

Standard Widget Sizes in Landscape Orientation

Designing a widget

Select a bounding box size for your widget.1.

The most effective widgets display your application's most useful or timely data in the smallest widget size. Users will weigh the usefulness or your widget against the portion of the

Home screen it covers, so the smaller the better.

All widgets must fit within the bounding box of one of the six supported widget sizes, or better yet, within a pair of portrait and landscape orientation sizes, so your widget looks good

when the user switches screen orientations.

Standard widget sizes illustrates the bounding dimensions of the six widget sizes (three in portrait and three in landscape orientation).

Select a matching frame.2.

Standard widget frames illustrates the standard frames for the six widget sizes, with links so you can download copies for your own use. You don't have to use these frames for your

widget, but if you do, your widgets are more likely to fit visually with other widgets.

Apply standard shadow effect to your graphics.3.

Again, you don't have to use this effect, but Standard widget shadows shows the Photoshop settings used for standard widgets.

If your widget includes buttons, draw them in three states (default, pressed, and selected).4.

You can download a Photoshop file that contains the three states of the Play button, taken from the Music widget, to analyze the Photoshop settings used for the three standard

Widget Design Guidelines | Android Developers http://developer.android.com/guide/practices/ui_guidelines/widget_design...

2 of 7 9/7/2010 2:12 PM

Page 48: Android Sdk Best Practices

button effects.

Finish drawing your artwork and then scale and align it to fit.5.

Widget alignment tips and tricks describes some techniques for aligning your widget's graphics inside the standard frames, along with a few other widget graphics tricks.

Save your widget with the correct graphics file settings.6.

Windows graphics file format describes the correct settings for your widget graphics files.

Standard widget sizes

There are six standard widget sizes, based on a Home screen grid of 4 x 4 (portrait) or 4 x 4 (landscape) cells. These dimensions are the bounding boxes for the six standard widget

sizes. The contents of typical widgets don't draw to the edge of these dimensions, but fit inside a frame withing the bounding box, as described in Designing a widget.

In portrait orientation, each cell is 80 pixels wide by 100 pixels tall (the diagram shows a cell in portrait orientation). The three supported widget sizes in portrait orientation are:

Cells Pixels

4 x 1 320 x 100

3 x 3 240 x 300

2 x 2 160 x 200

In landscape orientation, each cell is 106 pixels wide by 74 pixels tall. The three supported widget sizes in landscape orientation are:

Cells Pixels

4 x 1 424 x 74

3 x 3 318 x 222

2 x 2 212 x 148

Widget Design Guidelines | Android Developers http://developer.android.com/guide/practices/ui_guidelines/widget_design...

3 of 7 9/7/2010 2:12 PM

Page 49: Android Sdk Best Practices

Standard widget frames

For each of the six standard widget sizes there is a standard frame. You can click the images of the frames in this section to download a Photoshop file for that frame, which you can use

for your own widgets.

4x1_Widget_Frame_Portrait.psd

3x3_Widget_Frame_Portrait.psd

2x2_Widget_Frame_Portrait.psd

Widget Design Guidelines | Android Developers http://developer.android.com/guide/practices/ui_guidelines/widget_design...

4 of 7 9/7/2010 2:12 PM

Page 50: Android Sdk Best Practices

4x1_Widget_Frame_Landscape.psd

3x3_Widget_Frame_Landscape.psd

2x2_Widget_Frame_Landscape.psd

Standard widget shadows

You can apply a shadow effect to your widget's artwork, so it matches other standard Android widgets, using the following settings in the Photoshop Layer Style dialog box.

Widget graphics tips and tricks

The Android team has developed a few tricks for aligning widget artwork within standard widget bounding boxes and frames, so the widget aligns visually with other widgets and the other

elements of the Home screen, as well as other techniques for creating widgets.

Use a screen shot from the Android SDK emulator to align both the shapes and shadows of your widget controls with the Search widget and with other elements on the Home

screen.

Cut the widget artwork asset" based on the full size of a cell, including any padding you want. (That is, for a 4 x 1 widget, cut the asset at 320 by 100 pixels.)

Widget Design Guidelines | Android Developers http://developer.android.com/guide/practices/ui_guidelines/widget_design...

5 of 7 9/7/2010 2:12 PM

Page 51: Android Sdk Best Practices

To reduce banding when exporting a widget, apply the following Photoshop Add Noise setting to your graphic.

Apply 9-patch techniques to shrink the graphic and set the padding of the content area. (See the detailed guide here.)

Note: The current Android widget templates were designed using a custom gradient angle, which means the 9-patch techniques can't be used to optimize the size of the asset.

However, 9-patch techniques were used to set the content area padding.

In some cases, devices have low pixel depths that can cause visual banding and dithering issues. To solve this, application developers should pass assets through a "proxy" drawable

defined as XML:. This technique references the original artwork, in this case "background.9.png", and instructs the device to dither it as needed.

Widget graphics file format

Save your widget artwork using the appropriate bounding box size in PNG-24 format on a transparent background and in 8-bit color.

Widget Design Guidelines | Android Developers http://developer.android.com/guide/practices/ui_guidelines/widget_design...

6 of 7 9/7/2010 2:12 PM

Page 52: Android Sdk Best Practices

↑ Go to topExcept as noted, this content is licensed under Apache 2.0. For details and restrictions, see the Content License.

Android 2.2 r1 - 23 Aug 2010 18:08

Site Terms of Service - Privacy Policy - Brand Guidelines

Widget Design Guidelines | Android Developers http://developer.android.com/guide/practices/ui_guidelines/widget_design...

7 of 7 9/7/2010 2:12 PM

Page 53: Android Sdk Best Practices

Activity and task design quickview

Activities are the main building blocks ofAndroid applications.In addition to writing your own activities, youare free to re-use activities from many otherapplications through intents.

You can enable activities in your application tobe started from intents in other applications.In nearly all cases, the activity stack just worksas expected.

In a couple of cases you might need to ensure

the right thing happens by setting a string or

flag.

In this document

Applications, Activities, Activity Stack and Tasks

A Tour of Activities and Tasks

Starting an Activity from Home

Navigating Away from an Activity

Re-using an Activity

Replacing an Activity

Multitasking

Launching from Two Entry Points

Intents

Switching Between Tasks

Design Tips

Don't specify intent filters in an activity thatwon't be re-used

Handle case where no activity matches

Consider how to launch your activities

Allow activities to add to current task

Notifications should let user easily get back

Use the notification system

Don't take over BACK key unless you

absolutely need to

See also

Application Fundamentals

Activity and Task Design Guidelines

This document describes core principles of the Android application framework,

from a high-level, user-centric perspective useful to interaction and application

designers as well as application developers.

It illustrates activities and tasks with examples, and describes some of their

underlying principles and mechanisms, such as navigation, multitasking, activity

re-use, intents, and the activity stack. The document also highlights design

decisions that are available to you and what control they give you over the UI

of your application.

This document draws examples from several Android applications, including

default applications (such as Dialer) and Google applications (such as Maps).

You can try out the examples yourself in the Android emulator or on an

Android-powered device. If you are using a device, note that your device may

not offer all of the example applications used in this document.

Be sure to look at the Design Tips section for guidelines, tips, and things to

avoid. This document is a complement to Application Fundamentals, which

covers the underlying mechanics for programmers.

Applications, Activities, Activity Stack and Tasks

Four fundamental concepts in the Android system that are helpful for you to

understand are:

Applications

Activities

Activity Stack

Tasks

Applications

An Android application typically consists of one or more related, loosely bound

activities for the user to interact with, typically bundled up in a single file (with

an .apk suffix). Android ships with a rich set of applications that may include email, calendar, browser, maps, text messaging, contacts,

camera, dialer, music player, settings and others.

Android has an application launcher available at the Home screen, typically in a sliding drawer which displays applications as icons, which

the user can pick to start an application.

Activities

Activities are the main building blocks of Android applications. When you create an application, you can assemble it from activities that you

create and from activities you re-use from other applications. These activities are bound at runtime, so that newly installed applications can

take advantage of already installed activities. Once assembled, activities work together to form a cohesive user interface. An activity has a

distinct visual user interface designed around a single, well-bounded purpose, such as viewing, editing, dialing the phone, taking a photo,

searching, sending data, starting a voice command, or performing some other type of user action. Any application that presents anything

on the display must have at least one activity responsible for that display.

When using an Android device, as the user moves through the user interface they start activities one after the other, totally oblivious to the

underlying behavior — to them the experience should be seamless, activity after activity, task after task.

Activity and Task Design Guidelines | Android Developers http://developer.android.com/guide/practices/ui_guidelines/activity_task...

1 of 13 9/7/2010 2:12 PM

Page 54: Android Sdk Best Practices

An activity handles a particular type of content (data) and accepts a set of related user actions. In general, each activity has a lifecycle

that is independent of the other activities in its application or task — each activity is launched (started) independently, and the user or

system can start, run, pause, resume, stop and restart it as needed. Because of this independence, activities can be re-used and

replaced by other activities in a variety of ways.

The Dialer application is an example of an application that consists basically of four activities: dialer, contacts list, view contact, and new

contact, as shown in the following screenshots:

Dialer Contacts View Contact New Contact

Here are other examples of applications and the activities they might contain:

Email - activities to view folders, view list of messages, view a message, compose a message, and set up an account

Calendar - activities to view day, view week, view month, view agenda, edit an event, edit preferences, and view an alert

Camera - activities for running the camera, viewing the list of pictures, viewing a picture, cropping a picture, running the camcorder,

viewing the list of movies, and viewing a movie

Game - one activity to play the game, typically another for setup

Maps - one activity to view a location on a map, a second for lists (such as turn list or friend list), and a third for details (friend

location, status, photo)

An activity is the most prominent of four components of an application. The other components are service, content provider and broadcast

receiver. For more details on activities, see Activity in Application Components.

Activity Stack

As the user moves from activity to activity, across applications, the Android system keeps a linear navigation history of activities the user

has visited. This is the activity stack, also known as the back stack. In general, when a user starts a new activity, it is added to the activity

stack, so that pressing BACK displays the previous activity on the stack. However, the user cannot use the BACK key to go back further

than the last visit to Home. The adding of an activity to the current stack happens whether or not that activity begins a new task (as long

as that task was started without going Home), so going back can let the user go back to activities in previous tasks. The user can get to

tasks earlier than the most recent Home by selecting its root activity from the application launcher, a shortcut, or the "Recent tasks"

screen.

Activities are the only things that can be added to the activity stack — views, windows, menus, and dialogs cannot. That is, when

designing the navigation, if you have screen A and you want the user to be able go to a subsequent screen B and then use the BACK key

to go back to screen A, then the screen A needs to be implemented as an activity. The one exception to this rule is if your application

takes control of the BACK key and manages the navigation itself.

Tasks

A task is the sequence of activities the user follows to accomplish an objective, regardless of which applications the activities belong to.

Until a new task is explicitly specified (see "Interrupting the Task"), all activities the user starts are considered to be part of the current

task. It's notable that these activities can be in any application — that is, all in the same application or in different ones. That is, a task that

starts out in contacts can continue, by choosing an email address, to an email activity and then, by attaching a file, to a picture gallery to

pick from. Contacts, email and picture gallery are all separate applications.

The activity that starts a task is called the root activity. It is often, but not necessarily, started from the application launcher, Home screen

shortcut or "Recent tasks" switcher (a long press on Home on some devices). The user can return to a task by choosing the icon for its

Activity and Task Design Guidelines | Android Developers http://developer.android.com/guide/practices/ui_guidelines/activity_task...

2 of 13 9/7/2010 2:12 PM

Page 55: Android Sdk Best Practices

root activity the same way they started the task. Once inside a task, the BACK key goes to previous activities in that task. The activity

stack is made up of one or more tasks.

Here are some examples of tasks:

Send a text message with an attachment

View a YouTube video and share it by email with someone else

Interrupting the Task - An important property of a task is that the user can interrupt what they're doing (their task) to perform a different

task, then are able to return to where they left off to complete the original task. The idea is that users can run multiple tasks

simultaneously and switch between them. There are two primary ways to jump off to that other task — in both cases the user should be

able to return to where they were before the interruption:

User is interrupted by a notification – a notification appears and the user wants to act on it

User deciding to perform another task – user just presses Home and starts an application

Of course, there are exceptions to the rules. Beyond the two ways just mentioned, there is a third way to start a task, and that is by

starting an activity that defines itself as a new task. Maps and Browser are two applications that do this. For example, choosing an

address in an email starts the Maps activity as a new task, and choosing a link in an email starts the Browser activity as a new task. In

these cases, the BACK key will return to the previous activity in a different task (Email), because it was not started from Home.

A Tour of Activities and Tasks

The following examples illustrate basic principles for applications, activities, the activity stack, the BACK key, tasks and intents. It shows

how the system responds to user actions such as starting activities and switching between tasks. With most of these examples you can

follow along, launching activities on your device as indicated.

Starting an Activity from Home

Home is the starting place for most applications. (Some applications can be launched only from other applications.) When the user touches

an icon in the application launcher (or a shortcut on the Home screen), the main activity for that application is launched into the foreground

where it has user focus. As shown in the following figure, the user action of going Home and touching the Email icon launches the List

Messages activity of the Email application. The Home activity remains stopped in the background, ready to restart when called on by the

user.

Navigating Away from an Activity with BACK and HOME keys

An activity can keep or lose its state depending on how the user leaves the activity — by the HOME or BACK key.

By default, pressing the BACK key finishes (destroys) the current activity and displays the previous activity to the user. In the following

figure, the user starts email by touching the Email icon in the Home screen, which displays a list of email messages. The user scrolls down

the list (changing its initial state). Pressing BACK destroys the List Messages activity and returns to the previous activity, which is Home. If

the user re-launches Email, it would re-load the messages and display its initial, non-scrolled state.

Activity and Task Design Guidelines | Android Developers http://developer.android.com/guide/practices/ui_guidelines/activity_task...

3 of 13 9/7/2010 2:12 PM

Page 56: Android Sdk Best Practices

In the above example, pressing BACK goes to Home because it was the last activity the user was viewing. But if the user had gotten to

List Message from some other activity, then pressing BACK would have returned there.

By contrast, the next figure shows the user leaving List Messages by pressing HOME instead of BACK — the List Messages activity is

stopped and moved to the background rather than being destroyed. Starting Email again from its icon would simply bring the List

Messages activity to the foreground (changing it from stopped to running) in the same scrolled state the user last left it.

Exceptions. Some background activities return to their initial screen (they lose any state, such as scrolling) when they are brought to the

foreground. This is true for Contacts and Gallery. If the user chooses Home > Contacts then chooses a contact, they are viewing the

details of a contact. If they start again by choosing Home > Contacts, they are presented with the initial list of contacts rather than the

contact they were last viewing. Contacts is designed this way because this initial screen is the main entry point for the application with four

tabs for accessing the full range of features.

In addition, not all activities have the behavior that they are destroyed when BACK is pressed. When the user starts playing music in the

Music application and then presses BACK, the application overrides the normal back behavior, preventing the player activity from being

destroyed, and continues playing music, even though its activity is no longer visible — as a visual substitute, the Music application places a

notification in the status bar so the user still has an easy way to get to the application to stop or control the music. Note that you can write

an activity to stop when its screen is no longer visible, or to continue running in the background — the latter was chosen for the music

player.

Re-using an Activity

When activity A starts activity B in a different application, activity B is said to be re-used. This use case normally takes place because

activity A is lacking a capability and can find it in activity B.

Contacts Re-Uses Gallery to Get a Picture - The Contacts activity has a field for a picture of a contact, but the Gallery is normally

where pictures are kept. So Contacts can re-use the Gallery activity to get a picture. This is a good example of re-use of the Gallery

activity. The following figure illustrates the sequence of activities to do this (up to crop). This is how it's done: The user chooses Contacts,

selects the contact for viewing, chooses MENU > Edit contact and touches the picture field, which launches the Gallery activity. The user

then chooses the picture they want, crops and saves it. Saving it causes the picture to be inserted into the picture field in the contact.

Notice the Gallery returns a picture to the Contacts application that started it. The next example illustrates re-use of an activity that does

not return a result. Also notice that the following figure is illustrates the navigation history through the activities, or the activity stack — the

user can back up through each activity all the way to Home.

When designing an application, it's good to think about how it can re-use activities in other applications, and how your activities might be

re-used by other applications. If you add an activity with the same intent filter as an existing activity, then the system presents the user

Activity and Task Design Guidelines | Android Developers http://developer.android.com/guide/practices/ui_guidelines/activity_task...

4 of 13 9/7/2010 2:12 PM

Page 57: Android Sdk Best Practices

with a choice between the activities.

Gallery Re-Uses Messaging for Sharing a Picture - Sharing is another good example of one application re-using an activity from a

different application. As shown in the following figure, the user starts Gallery, picks a picture to view, chooses MENU > Share, and picks

"Messaging". This starts the Messaging activity, creates a new message and attaches the original picture to it. The user then fills in the

"To" field, writes a short message and sends it. User focus remains in the Messaging program. If the user wants to go back to the

Gallery, they must press the BACK key. (The user can back up through each activity all the way to Home.)

In contrast to the previous example, this re-use of the Messaging activity does not return anything to the Gallery activity that started it.

Both of these examples illustrate tasks — a sequence of activities that accomplish an objective. Each case uses activities from two

different applications to get the job done.

Replacing an Activity

This is the use case where activity A replaces activity B in a different application. This situation normally happens because activity A is

better at doing the job than activity B. In other words, A and B are equivalent enough that A can replace B. This case stands in contrast

with re-using an activity, where A and B are quite different activities and supplement each other.

In this example, the user has downloaded a replacement for the Phone Ringtone activity, called Rings Extended. Now when they go to

Settings, Sound & Display, Phone Ringtone, the system presents them with a choice between the Android System's ringtone activity and

the new one. This dialog box has an option to remember their choice "Use by default for this action". When they choose "Rings Extended",

that activity loads, replacing the original Android ringtone activity.

Activity and Task Design Guidelines | Android Developers http://developer.android.com/guide/practices/ui_guidelines/activity_task...

5 of 13 9/7/2010 2:12 PM

Page 58: Android Sdk Best Practices

Multitasking

As previously noted, when an activity has been launched, the user can go to Home and launch a second activity without destroying the first

activity. This scenario demonstrates launching the Maps application.

State 1 - The user launches the View Map activity and searches for a map location. Let's say the network is slow, so the map is

taking an unusually long taking time to draw.

State 2 - The user wants to do something else while they're waiting, so they press HOME, which does not interrupt the map's network

connection and allows the map to continue loading in the background.

Note that when you write an activity, you can make it stop or continue running when it is moved to the background (see onStop() in

Activity Lifecycle). For activities that download data from the network, it's recommended to let them continue downloading so the user

can multi-task.

State 3 - The map activity is now running in the background, with Home in the foreground. The user then launches the Calendar

activity, which launches into the foreground, taking user focus, where they view today's calendar (as indicated by the heavy outline).

State 4 - The user presses Home, then Maps to return to the map, which by now has fully loaded.

Activity and Task Design Guidelines | Android Developers http://developer.android.com/guide/practices/ui_guidelines/activity_task...

6 of 13 9/7/2010 2:12 PM

Page 59: Android Sdk Best Practices

The application launcher at Home has launched "View Map" and "Day View" activities into separate tasks, hence the system is multitasking

— running multiple tasks.

Launching from Two Entry Points

Every application must have at least one entry point — a way for the user or system to access activities inside the application. Each icon

in the application launcher at home represents an entry point. Applications can also be launched from another application. Each activity is a

potential entry point into the application.

The phone application has two entry points: Contacts and Dialer. A user entering from Contacts can choose a phone number to launch the

Dialer. As shown in the following figure, a user could choose the Contacts icon to launch the Contacts activity, then pick a phone number to

launch the Dialer activity and dial the phone.

Once the user is inside the application, they can access other activities, such as New Contact and Edit Contact, through tabs, menu items,

list items, onscreen buttons, or other user interface controls.

Intents

When the user takes an action on some data, such as touching a mailto:[email protected] link, they are actually initiating an Intent object,

or just an intent, which then gets resolved to a particular component (we consider only activity components here). So, the result of a user

touching a mailto: link is an Intent object that the system tries to match to an activity. If that Intent object was written explicitly naming an

activity (an explicit intent), then the system immediately launches that activity in response to the user action. However, if that Intent object

was written without naming an activity (an implicit intent), the system compares the Intent object to the intent filters of available activities.

If more than one activity can handle the action and data, the system displays an activity chooser for the user to choose from.

This example of touching the mailto: link is shown in the following figure. If the device has two email applications set up, when a user

touches a mailto: email address on a web page, the result is an Intent object which displays a dialog box with a choice between the two

activities to compose an email (Gmail and Email).

Activity and Task Design Guidelines | Android Developers http://developer.android.com/guide/practices/ui_guidelines/activity_task...

7 of 13 9/7/2010 2:12 PM

Page 60: Android Sdk Best Practices

Here are some examples of Intent objects and the activities they resolve to:

View the list of contacts - resolves to a contact list viewer activity

View a particular contact - resolves to a contact viewer activity

Edit a particular contact - resolves to a contact editor activity

Send to a particular email - resolves to an email activity

Dial a phone number - resolves to a phone dialer activity

View the list of images - resolves to an image list viewer activity

View a particular image - resolves to an image viewer activity

Crop a particular image - resolves to an image cropper activity

Notice that an Intent object specifies two things, an action and data:

A generic action to be performed. In these examples: view, edit, dial or crop

The specific data to be acted on. In these examples: the list of contacts, a particular contact, a phone number, the list of images, or a

particular image

Note that any user action to start an activity from the application launcher at Home is an explicit intent to a specific activity. Likewise, some

activities launch private activities within their application as explicit intents so no other activity can access them.

For more on intents, see Intent class and intent filters.

Switching Between Tasks

This scenario shows how the user can switch between two tasks. In this example, the user writes a text message, attaches a picture, but

before they are done they glance at their calendar. They then return to where they left off, attaching the picture and sending the message.

Start first task. You want to send a text message and attach a photo. You would choose:

Home > Messaging > New message > MENU > Attach > Pictures. This last step launches the picture gallery for picking a photo.

Notice that picture gallery is an activity in a separate application.

1.

Activity and Task Design Guidelines | Android Developers http://developer.android.com/guide/practices/ui_guidelines/activity_task...

8 of 13 9/7/2010 2:12 PM

Page 61: Android Sdk Best Practices

At this point, before you have picked a picture, you decide to stop and glance at your calendar, which is a separate task. Because the

current activity has no button to go directly to the Calendar, you need to start from Home.

Start second task. You choose Home > Calendar to look at a calendar event. Calendar launches from Home as a new task because

the application launcher creates a new task for each application it launches.

2.

Switch to first task and complete it. When done looking at the Calendar, you can return to attaching the picture by starting the root

activity again for that task: choose Home > Messaging, which takes you not to Messaging, but directly to the Picture gallery, where

you left off. You can then pick a photo, which is added to the message, you send the message and you're done with the first task.

3.

Activity and Task Design Guidelines | Android Developers http://developer.android.com/guide/practices/ui_guidelines/activity_task...

9 of 13 9/7/2010 2:12 PM

Page 62: Android Sdk Best Practices

Design Tips

The following are tips and guidelines for application designers and developers.

When writing an activity that won't be re-used, don't specify intent filters — use explicit intents

If you're writing an activity that you don't want other activities to use, be sure not to add any intent filters to that activity. This applies to an

activity that will be launched only from the application launcher or from other activities inside your application. Instead, just create intents

specifying the explicit component to launch — that is, explicit intents. In this case, there's just no need for intent filters. Intent filters are

published to all other applications, so if you make an intent filter, what you're doing is publishing access to your activity, which means you

can cause unintentional security holes.

When reusing an activity owned by others, handle the case where no activity matches

Your applications can re-use activities made available from other applications. In doing so, you cannot presume your intent will always be

resolved to a matching external activity — you must handle the case where no application installed on the device can handle the intent.

You can either test that an activity matches the intent, which you can do before starting the activity, or catch an exception if starting the

activity fails. Both approaches are described in the blog posting Can I use this Intent?.

To test whether an intent can be resolved, your code can query the package manager. The blog post provides an example in the

isIntentAvailable() helper method. You can perform this test when initializing the user interface. For instance, you could disable the user

control that initiates the Intent object, or display a message to the user that lets them go to a location, such as the Market, to download its

application. In this way, your code can start the activity (using either startActivity() or startActivityForResult()) only if the intent has tested

to resolve to an activity that is actually present.

Consider how you want your activities to be launched or used by other applications

As a designer or developer, it's up to you to determine how users start your application and the activities in it. As an application is a set of

activities, the user can start these activities from Home or from another application.

Launch your main activity from an icon at Home - If your application can run standalone, it should probably be started by the user

touching an icon in application launcher (typically implemented as a sliding drawer on the Home screen), or from a shortcut icon on

the Home screen, or from the task switcher. (The mechanism for this is for the activity to have an intent filter with action MAIN and

category LAUNCHER.)

Launch your activity from within another application - Perhaps your activities are meant for re-use. For example, many

applications have data they want to share with other users. Activities that can share data with other users include email, text

messaging and uploading to a public website.

If one or more of your activities can be an alternative to an existing activity in another application, you can make it available to users at

Activity and Task Design Guidelines | Android Developers http://developer.android.com/guide/practices/ui_guidelines/activity_task...

10 of 13 9/7/2010 2:12 PM

Page 63: Android Sdk Best Practices

the point they request that activity. For example, if your activity can send data to others (such as by email, text messaging, or

uploading), consider setting up that activity to appear as a choice to the user. To give a specific example, Gallery enables a user to

view and share pictures. When the user chooses "Share" from the menus, the system compares the "Share" request (an Intent object)

to available activities (by looking at their intent filters) and displays choices to share. In this case, it matches Email, Gmail, Messaging

and Picasa. If your activity can send a picture or upload it to a website, all it needs to do is make itself available for sharing (by

setting its intent filter).

Another activity can start your activity either with or without expecting a result back.

Start an activity expecting a result - This approach is closed loop, where the activity being started must either return a valid

result or be canceled. In the previous examples of sharing a photo from a Gallery, the user ends up back in the Gallery after

completing the send or upload procedure. These are examples of starting an activity external to the Gallery. (Such an activity is

started with startActivityForResult().)

Start an activity not expecting a result - This approach is open-ended. An example is choosing an house address in an email

message (or web page), where the Maps activity is started to map the location. No result from maps is expected to be returned

to the email message; the user can return by pressing the BACK key. (Such an activity is started with startActivity().)

Launch your activity only from within another application - The previous cases of sharing by way of Email, Gmail, Messaging

and Picasa (from within Gallery) are all activities that can also be started from icons in the application launcher at Home. In contrast,

the activities for cropping a picture and attaching a file cannot be started from Home, because they do not stand alone and require a

context.

In fact, not all applications have icons and can be started from Home. Take for example a small app that is infrequently used and

replaces existing functionality, that already has a natural entry point inside an existing application. For example, an Android phone

typically has a built-in ringtone picker that can be selected from the sound settings of the Settings application. A custom ringtone

picker application that you write could be launched by an intent identical to the built-in ringtone picker. At the point where the user

chooses "Phone ringtone", they are presented with a dialog letting them choose between "Android System" and your ringtone picker

(and letting them save their choice) as shown in the following figure. A ringtone is something you set infrequently, and already has a

well-defined starting point, so probably does not need an application icon at Home.

Launch two or more main activities within a single application from separate icon at Home - As we have defined it, all the code

in a single .apk file is considered to be one application. You can write an application that contains two main activities launchable from

Home.

The Camera.apk application is a good example of an application that contains two independent main activities — Camera and

Camcorder — that each have their own icons in application launcher, that can be launched separately, and so appear to the user as

separate applications. They both share use of the same lens, and both store their images (still and moving) in the Gallery.

In order for your application to contain two different, independent activities launchable from Home, you must define them to be

associated with different tasks. (This means setting the main activity for each task to a different task affinity — in this case,

"com.android.camera" and "com.android.videocamera".)

Contacts and Dialer are another example of two main activities launchable from Home that reside in the same application.

Making your application available as a widget - An application can also display a portion of itself as an app widget, embedded in

Home or another application, and receive periodic updates.

Allow your activities to be added to the current task

If your activities can be started from another application, allow them to be added to the current task (or an existing task it has an affinity

with). Having activities added to a task enables the user to switch between a task that contains your activities and other tasks. Exceptions

are your activities that have only one instance.

Activity and Task Design Guidelines | Android Developers http://developer.android.com/guide/practices/ui_guidelines/activity_task...

11 of 13 9/7/2010 2:12 PM

Page 64: Android Sdk Best Practices

For this behavior, your activity should have a launch mode of standard or singleTop rather than singleTask or singleInstance. These modes

also enable multiple instances of your activity to be run.

Notifications should let the user easily get back to the previous activity

Applications that are in the background or not running can have services that send out notifications to the user letting them know about

events of interest. Two examples are Calendar, which can send out notifications of upcoming events, and Email, which can send out

notifications when new messages arrive. One of the user interface guidelines is that when the user is in activity A, gets a notification for

activity B and picks that notification, when they press the BACK key, they should go back to activity A.

The following scenario shows how the activity stack should work when the user responds to a notification.

User is creating a new event in Calendar. They realize they need to copy part of an email message into this event1.

The user chooses Home > Gmail2.

While in Gmail, they receive a notification from Calendar for an upcoming meeting3.

So they choose that notification, which takes them to a dedicated Calendar activity that displays brief details of the upcoming meeting4.

The user chooses this short notice to view further details5.

When done viewing the event, the user presses the BACK key. They should be taken to Gmail, which is where they were when they

took the notification

6.

This behavior doesn't necessarily happen by default.

Notifications generally happen primarily in one of two ways:

The chosen activity is dedicated for notification only - For example, when the user receives a Calendar notification, choosing that

notification starts a special activity that displays a list of upcoming calendar events — this view is available only from the notification,

not through the Calendar's own user interface. After viewing this upcoming event, to ensure that the user pressing the BACK key will

return to the activity the user was in when they picked the notification, you would make sure this dedicated activity does not have the

same task affinity as the Calendar or any other activity. (You do this by setting task affinity to the empty string, which means it has no

affinity to anything.) The explanation for this follows.

Because of the way tasks work, if the taskAffinity of the dedicated activity is kept as its default, then pressing the BACK key (in step

6, above) would go to Calendar, rather than Gmail. The reason is that, by default, all activities in a given application have the same

task affinity. Therefore, the task affinity of the dedicated activity matches the Calendar task, which is already running in step 1. This

means in step 4, choosing the notification brings the existing Calendar event (in step 1) forward and starts the dedicated activity on

top of it. This is not what you want to have happen. Setting the dedicated activity's taskAffinity to empty string fixes this.

The chosen activity is not dedicated, but always comes to the foreground in its initial state - For example, in response to a

notification, when the Gmail application comes to the foreground, it always presents the list of conversations. You can ensure this

happens by setting a "clear top" flag in the intent that the notification triggers. This ensures that when the activity is launched, it

displays its initial activity, preventing Gmail from coming to the foreground in whatever state the user last happened to be viewing it.

(To do this, you put FLAG_ACTIVITY_CLEAR_TOP in the intent you pass to startActivity()).

There are other ways to handle notifications, such as bringing the activity to the foreground, set to display specific data, such as displaying

the text message thread for the person who just sent a new text message.

A notification always starts an activity as a new task (that is, it puts FLAG_ACTIVITY_NEW_TASK in the intent it passes to startActivity()). This is

done because interruptions to a task should not become part of that task.

Use the notification system — don't use dialog boxes in place of notifications

If your background service needs to notify a user, use the standard notification system — don't use a dialog or toast to notify them. A

dialog or toast would immediately take focus and interrupt the user, taking focus away from what they were doing: the user could be in the

middle of typing text the moment the dialog appears and could accidentally act on the dialog. Users are used to dealing with notifications

and can pull down the notification shade at their convenience to respond to your message.

Don't take over the BACK key unless you absolutely need to

As a user navigates from one activity to the next, the system adds them to the activity stack. This forms a navigation history that is

accessible with the BACK key. Most activities are relatively limited in scope, with just one set of data, such as viewing a list of contacts,

composing an email, or taking a photo. But what if your application is one big activity with several pages of content and needs finer-

grained control of the BACK key? Examples of such Google applications are the Browser, which can have several web pages open at

once, and Maps, which can have several layers of geographic data to switch between. Both of these applications take control of the

Activity and Task Design Guidelines | Android Developers http://developer.android.com/guide/practices/ui_guidelines/activity_task...

12 of 13 9/7/2010 2:12 PM

Page 65: Android Sdk Best Practices

↑ Go to top

BACK key and maintain their own internal back stacks that operate only when these applications have focus.

For example, Maps uses layers to present different information on a map to the user: displaying the location of a search result, displaying

locations of friends, and displaying a line for a street path providing direction between points. Maps stores these layers in its own history

so the BACK key can return to a previous layer.

Similarly, Browser uses browser windows to present different web pages to the user. Each window has its own navigation history,

equivalent to tabs in a browser in a desktop operating system (such as Windows, Macintosh or Linux). For example, if you did a Google

web search in one window of the Android Browser, clicking on a link in the search results displays a web page in that same window, and

then pressing BACK would to the search results page. Pressing BACK goes to a previous window only if the current window was launched

from that previous window. If the user keeps pressing back, they will eventually leave the browser activity and return Home.

Except as noted, this content is licensed under Apache 2.0. For details and restrictions, see the Content License.

Android 2.2 r1 - 23 Aug 2010 18:08

Site Terms of Service - Privacy Policy - Brand Guidelines

Activity and Task Design Guidelines | Android Developers http://developer.android.com/guide/practices/ui_guidelines/activity_task...

13 of 13 9/7/2010 2:12 PM

Page 66: Android Sdk Best Practices

Menu design quickview

An Options menu is for any commands that areglobal to the current activity.

A Context menu is for any commands that

apply to the current selection.

Place the most frequently used operationsfirst.

Put only the most important commands fixed

on the screen.The commands on the Context menu that

appears when you touch & hold on an item

should be duplicated on the activity you get toby a normal press on that item.

In this document

Tour of the Menus

Options Menu

Context Menu

Comparison of Options & Context Menus

Commands Fixed in an Activity Screen

Guidelines

Separate specific from global commands

Place most frequently used first

Don't put commands only in a Context menu

First command in Context menu should be

most intuitive

Selecting an item should perform mostintuitive operation

A Context menu should identify the selected

item

Put only most important commands fixed on

the screen

Use short names in Options icon menu

A dialog should not have Options menu

If no Options menu, don't display message

Dim or hide menu items not available

See also

Touch mode

Activity and Task Design

Menu Design Guidelines

A menu holds a set of commands (user actions) that are

normally hidden, and are accessible by a button, key, or

gesture. Menu commands provide a means for performing

operations and for navigating to other parts of your application

or other applications. Menus are useful for freeing screen

space, as an alternative to placing functionality and navigation,

in buttons or other user controls in the content area of your

application.

The Android system provides two types of menus you can use

to provide functionality or navigation. Between them, you should

be able to organize the functionality and navigation for your

application. Briefly:

The Options menu contains primary functionality that

applies globally to the current activity or starts a related

activity. It is typically invoked by a user pressing a hard

button, often labeled MENU.

The Context menu contains secondary functionality for the

currently selected item. It is typically invoked by a user's

touch & hold on an item. Like on the Options menu, the

operation can run either in the current or another activity.

All but the simplest applications have menus. The system

automatically lays the menus out and provides standard ways

for users to access them. In this sense, they are familiar and

dependable ways for users to access functionality across all

applications. All menus are panels that "float" on top of the

activity screen and are smaller than full screen, so that the

application is still visible around its edges. This is a visual

reminder that a menu is an intermediary operation that

disappears once it's used.

Let's start out with a quick tour of the menus.

Tour of the Menus

Note: Your menus and screens might not look like those shown in this document; they may vary from one version of

Android or device to another.

Options Menu

The Options menu contains commands that apply globally across the current activity, or can start another activity. They do

not apply to a selected item in the content (a Context menu does that).

On most devices, a user presses the MENU button to access the Options menu, as shown in the screenshot below. To

Menu Design Guidelines | Android Developers http://developer.android.com/guide/practices/ui_guidelines/menu_design.html

1 of 7 9/7/2010 2:13 PM

Page 67: Android Sdk Best Practices

close the menu, the user presses MENU again, or presses the BACK button. In fact, to cancel out of any menu, press the

BACK button. (Pressing the MENU button or touching outside the menu also works.) Note that how to invoke this menu may

be different on different devices.

Each activity activity has its own set of operations and therefore its own Options menu. An application with multiple

activities would have a different Options menu for each activity.

For example, in the message list view of an email program, the Options menu might let you search the messages, compose

a new message, refresh the list, or change the email settings. The compose view of an email program would have a

different Options menu, such as adding a CC field, attaching a file, or discarding the message.

In order to handle a large number of menu items, the Options menu progressively discloses them in two steps:

Options icon menu - The first press of the MENU button displays a non-scrollable grid of icons at the bottom of the

screen. (On the G1 phone, up to 6 buttons typically appear.)

Options expanded menu - If the activity has more menu items than will fit on the icon menu, then the last icon is

labeled "More" — selecting it displays a list that can contain any number of menu items and will scroll as necessary.

On some versions of Android, the user can display keyboard shortcuts in the icon menu by long pressing the MENU button

— the text in the icon menu alternates between the command names and their keyboard shortcuts (if any).

Context Menu

A Context menu is similar to a right-click context menu in a desktop operating system. It is normally a shortcut that

duplicates commands found elsewhere.

A user can touch & hold on content on the screen to access a Context menu (if one exists), as shown in the screenshot

below. A Context menu is a list of menu items (commands) that can operate on the selected content. The command can

either be part of the current activity, or the system can pass the selected content along to an operation in another activity

(by way of an intent).

For example, in an email message list, a user can touch & hold on an email message to open a Context menu containing

commands to read, archive, or delete the message.

A user can also touch & hold a location on the screen to access a Context menu. An example is when the user does touch

& hold on a blank spot on the Home screen, a Context menu appears; selecting an item from that menu inserts an icon at

that location.

Menu Design Guidelines | Android Developers http://developer.android.com/guide/practices/ui_guidelines/menu_design.html

2 of 7 9/7/2010 2:13 PM

Page 68: Android Sdk Best Practices

Context Menu is a Shortcut

In the above example, if the user performs touch & hold on the contact "Obi Wan Kenobi", a Context menu opens. The

commands provided in this Context menu are the complete set of actions that can be performed on this contact.

A normal touch on an item in the content activates the most intuitive command for that selection — in this case, "View

contact". We recommend that the most intuitive command also be listed as the first item in the Context menu. In this

example, selecting the contact "Obi Wan Kenobi" runs the same command "View contact" that is listed at the top of the

Context menu.

Also note, as shown in the following screenshot, the Context menu and the next screen both hold the same complete set of

commands that can be performed on this contact. The Context menu displays the commands in a list, while the "View

contact" activity splits them into various items in the Options menu, icon buttons and list items.

Because of this duplication, using the Context menu is considered a shortcut for going to the next screen and performing

the operation there. Context menus are less discoverable than either buttons fixed on-screen or the Options menu. Many

users never discover or use Context menus. It is for this reason that, for the most part, any command on a Context menu

should also appear on the most intuitive operation's screen. As the next section explains, text operations, such as "Select

text" might appear only on a Context menu. Also, rich applications, such as browsers, which themselves can contain web

applications, may have commands on Context menus that are not available elsewhere.

Menu Design Guidelines | Android Developers http://developer.android.com/guide/practices/ui_guidelines/menu_design.html

3 of 7 9/7/2010 2:13 PM

Page 69: Android Sdk Best Practices

Text Commands in Context Menu

Text links and text fields in the content both have system-provided operations that are common across all applications:

operations such as "Select all", "Select text", "Copy all", and "Add to dictionary". If the text field is editable, it also has other

operations, such as "Cut all" and "Input Method", and if text is also on the clipboard, it has "Paste". The system

automatically inserts the appropriate menu items into the Context menu of text links and text fields, as shown in the

following screenshot.

Comparison of Options and Context Menus

An Options menu holds commands that are global to the activity while a Context menu holds commands that apply only to

an item in the content. As shown in these diagrams, the user navigates to the menu, then touches a menu item to perform

an action or open a dialog.

Menu Design Guidelines | Android Developers http://developer.android.com/guide/practices/ui_guidelines/menu_design.html

4 of 7 9/7/2010 2:13 PM

Page 70: Android Sdk Best Practices

For more technical information on menus, see Creating Menus.

Commands Fixed in an Activity Screen

Commands can also be fixed directly on screen, typically in text buttons, graphic buttons, or list items. This placement is by

far the most discoverable location for commands — a user can immediately see the command without having to first press

a button. This increased visibility needs to be weighed against the space such user controls take up, or the sense that they

might clutter the visual design.

Guidelines

Selecting the right kind of menu to present, and using menus consistently, are critical factors in good application design.

The following guidelines should assist user experience designers and application developers toward this end.

Separate selection-specific commands from global commands

Put any commands that are global to the current activity in the Options menu or place them fixed in an activity screen; put

commands that apply to the current selection in the Context menu. (In any case, the command could either run as part of

this activity or start another activity.)

You can determine in which menu to place a command by what it operates on: If the command acts on selected content (or

a particular location) on the screen, put the command in the Context menu for that content. If the command acts on no

specific content or location, put it in the Options menu. This separation of commands is enforced by the system in the

following way. When you press the MENU button to display the Options menu, the selected content becomes unselected,

and so cannot be operated on. For an explanation of why the content becomes unselected, see the article on Touch mode.

An example of a selection-specific Context menu is when a user performs a touch & hold on a person's name in a list view

of a contacts application. The Context menu would typically contain commands "View contact", "Call contact", and "Edit

contact".

Place the most frequently used operations first

Because of limited screen height, some menus may be scrollable, so it's important to place the most important commands

so they can be viewed without scrolling. In the case of the Options menu, place the most frequently used operation on its

icon menu; the user will have to select "More" to see the rest. It's also useful to place similar commands in the same

location — for example, the Search icon might always be the first icon in the Options menu across several activities that

offer search.

In a Context menu, the most intuitive command should be first, followed by commands in order of decreasing use, with the

Menu Design Guidelines | Android Developers http://developer.android.com/guide/practices/ui_guidelines/menu_design.html

5 of 7 9/7/2010 2:13 PM

Page 71: Android Sdk Best Practices

least used command at the bottom.

Don't put commands only in a Context menu

If a user can fully access your application without using Context menus, then it's designed properly! In general, if part of

your application is inaccessible without using Context menus, then you need to duplicate those commands elsewhere.

Before opening a Context menu, it has no visual representation that identifies its presence (whereas the Options menu has

the MENU button), and so is not particularly discoverable. Therefore, in general, a Context menu should duplicate

commands found in the corresponding activity screen. For example, while it's useful to let the user call a phone number

from a Context menu invoked by touch & hold on a name in a list of contacts, that operation should also be available by the

user touching the phone number itself when viewing contact details. See shortcut for an illustration of this example.

The first command in a Context menu should be the selection's most intuitive command

As described under shortcut, touching on an item in the content should activate the same command as touching the first

item in the Context menu. Both cases should be the most intuitive operation for that item.

Selecting an item in the content should perform the most intuitive operation

In your application, when the user touches any actionable text (such as a link or list item) or image (such as a photo icon),

execute the operation most likely to be desired by the user.

Some examples of primary operations:

Selecting an image executes "View image"

Selecting a media icon or filename executes "Play"

Selecting a URL link executes "Open link"

Selecting an address executes "Go to address" (in a maps application)

Note that selecting the same item in different contexts might invoke different operations:

In a contact application, selecting a contact executes "View details"

In an IM application, selecting a contact executes "Start chat"

In an Email application, when adding a recipient to the "To" field through the contact book, selecting a contact executes

"Add to recipient list"

A Context menu should identify the selected item

When a user does touch & hold on an item, the Context menu should contain the name of the selected item. Therefore,

when creating a Context menu, be sure to include a title and the name of the selected item so that it's clear to the user

what the context is. For example, if a user selects a contact "Joan of Arc", put that name in the title of the Context menu

(using setHeaderTitle). Likewise, a command to edit the contact should be called "Edit contact", not just "Edit".

Put only the most important commands fixed on the screen

By putting commands in menus, you free up the screen to hold more content. On the other hand, fixing commands in the

content area of an activity makes them more prominent and easy to use.

Here are a number of important reasons to place commands fixed on the activity screen:

To give a command the highest prominence, ensuring the command is obvious and won't be overlooked.

Example: A "Buy" button in a store application.

When quick access to the command is important and going to the menu would be tedious or slow.

Menu Design Guidelines | Android Developers http://developer.android.com/guide/practices/ui_guidelines/menu_design.html

6 of 7 9/7/2010 2:13 PM

Page 72: Android Sdk Best Practices

↑ Go to top

Example: Next/Previous buttons or Zoom In/Out buttons in an image viewing application.

When in the middle of an operation that needs to be completed.

Example: Save/Discard buttons in an image crop activity.

Dialogs and wizards.

Example: OK/Cancel buttons

For direct manipulation.

Example: Dragging an icon in the Home screen to the trash

Use short names in the Options icon menu

If a text label in the Options icon menu is too long, the system truncates it in the middle. Thus, "Create Notification" is

truncated to something like "Create…ication". You have no control over this truncation, so the best bet is to keep the text

short. In some versions of Android, when the icon is highlighted by a navigation key (such as a trackball), the entire

descriptive text may be shown as a marquee, where the words are readable as they scroll by.

A dialog should not have an Options menu

When a dialog is displayed, pressing the MENU button should do nothing. This also holds true for activities that look like

dialogs. A dialog box is recognizable by being smaller than full-screen, having zero to three buttons, is non-scrollable, and

possibly a list of selectable items that can include checkboxes or radio buttons.

The rationale behind not having a menu is that when a dialog is displayed, the user is in the middle of a procedure and

should not be allowed to start a new global task (which is what the Option menu provides).

If an activity has no Options menu, do not display a message

When the user presses the MENU button, if there is no Options menu, the system currently does nothing. We recommend

you do not perform any action (such as displaying a message). It's a better user experience for this behavior to be

consistent across applications.

Dim or hide menu items that are not available in the current context

Sometimes a menu item's action cannot be performed — for example, the "Forward" button in a browser cannot work until

after the "Back" button has been pressed. We recommend:

In Options menu - disable the menu item, which dims the text and icon, turning it gray. This applies to menu items in

both the icon menu and the "More" menu. It would be disorienting for the icon menu to change from 6 items to 5 items,

and we treat the "More" menu the same way.

In Context menu - hide the menu item. This makes the menu shorter so the user sees only available choices (which

also reduces any scrolling).

Except as noted, this content is licensed under Apache 2.0. For details and restrictions, see the Content License.Android 2.2 r1 - 23 Aug 2010 18:08

Site Terms of Service - Privacy Policy - Brand Guidelines

Menu Design Guidelines | Android Developers http://developer.android.com/guide/practices/ui_guidelines/menu_design.html

7 of 7 9/7/2010 2:13 PM

Page 73: Android Sdk Best Practices

Designing for Performance

An Android application will run on a mobile device with limited computing power and storage, and constrained battery life.

Because of this, it should be efficient. Battery life is one reason you might want to optimize your app even if it already

seems to run "fast enough". Battery life is important to users, and Android's battery usage breakdown means users will

know if your app is responsible draining their battery.

This document covers these topics:

Introduction

Optimize Judiciously

Avoid Creating Objects

Performance Myths

Prefer Static Over Virtual

Avoid Internal Getters/Setters

Use Static Final For Constants

Use Enhanced For Loop Syntax

Avoid Enums Where You Only Need Ints

Use Package Scope with Inner Classes

Use Floating-Point Judiciously

Know And Use The Libraries

Use Native Methods Judiciously

Closing Notes

Note that although this document primarily covers micro-optimizations, these will almost never make or break your

software. Choosing the right algorithms and data structures should always be your priority, but is outside the scope of this

document.

Introduction

There are two basic rules for writing efficient code:

Don't do work that you don't need to do.

Don't allocate memory if you can avoid it.

Optimize Judiciously

As you get started thinking about how to design your application, and as you write it, consider the cautionary points about

optimization that Josh Bloch makes in his book Effective Java. Here's "Item 47: Optimize Judiciously", excerpted from the

latest edition of the book with permission. Although Josh didn't have Android application development in mind when writing

Designing for Performance | Android Developers http://developer.android.com/guide/practices/design/performance.html

1 of 9 9/7/2010 2:13 PM

Page 74: Android Sdk Best Practices

this section — for example, the java.awt.Component class referenced is not available in Android, and Android uses the

Dalvik VM, rather than a standard JVM — his points are still valid.

There are three aphorisms concerning optimization that everyone should know. They are perhaps beginning to

suffer from overexposure, but in case you aren't yet familiar with them, here they are:

More computing sins are committed in the name of efficiency (without necessarily achieving it)

than for any other single reason—including blind stupidity.

—William A. Wulf 1

We should forget about small efficiencies, say about 97% of the time: premature optimization

is the root of all evil.

—Donald E. Knuth 2

We follow two rules in the matter of optimization:

Rule 1. Don't do it.

Rule 2 (for experts only). Don't do it yet — that is, not until you have a perfectly clear and

unoptimized solution.

—M. A. Jackson 3

All of these aphorisms predate the Java programming language by two decades. They tell a deep truth about

optimization: it is easy to do more harm than good, especially if you optimize prematurely. In the process, you

may produce software that is neither fast nor correct and cannot easily be fixed.

Don't sacrifice sound architectural principles for performance. Strive to write good programs rather than

fast ones. If a good program is not fast enough, its architecture will allow it to be optimized. Good programs

embody the principle of information hiding: where possible, they localize design decisions within individual

modules, so individual decisions can be changed without affecting the remainder of the system (Item 13).

This does not mean that you can ignore performance concerns until your program is complete.

Implementation problems can be fixed by later optimization, but pervasive architectural flaws that limit

performance can be impossible to fix without rewriting the system. Changing a fundamental facet of your

design after the fact can result in an ill-structured system that is difficult to maintain and evolve. Therefore you

must think about performance during the design process.

Strive to avoid design decisions that limit performance. The components of a design that are most

difficult to change after the fact are those specifying interactions between modules and with the outside

world. Chief among these design components are APIs, wire-level protocols, and persistent data formats. Not

only are these design components difficult or impossible to change after the fact, but all of them can place

significant limitations on the performance that a system can ever achieve.

Consider the performance consequences of your API design decisions. Making a public type mutable

may require a lot of needless defensive copying (Item 39). Similarly, using inheritance in a public class where

composition would have been appropriate ties the class forever to its superclass, which can place artificial

limits on the performance of the subclass (Item 16). As a final example, using an implementation type rather

than an interface in an API ties you to a specific implementation, even though faster implementations may be

written in the future (Item 52).

The effects of API design on performance are very real. Consider the getSize method in the

java.awt.Component class. The decision that this performance-critical method was to return a

Dimension instance, coupled with the decision that Dimension instances are mutable, forces any

implementation of this method to allocate a new Dimension instance on every invocation. Even though

allocating small objects is inexpensive on a modern VM, allocating millions of objects needlessly can do real

harm to performance.

In this case, several alternatives existed. Ideally, Dimension should have been immutable (Item 15);

alternatively, the getSize method could have been replaced by two methods returning the individual primitive

Designing for Performance | Android Developers http://developer.android.com/guide/practices/design/performance.html

2 of 9 9/7/2010 2:13 PM

Page 75: Android Sdk Best Practices

components of a Dimension object. In fact, two such methods were added to the Component API in the 1.2

release for performance reasons. Preexisting client code, however, still uses the getSize method and still

suffers the performance consequences of the original API design decisions.

Luckily, it is generally the case that good API design is consistent with good performance. It is a very bad

idea to warp an API to achieve good performance. The performance issue that caused you to warp the

API may go away in a future release of the platform or other underlying software, but the warped API and the

support headaches that come with it will be with you for life.

Once you've carefully designed your program and produced a clear, concise, and well-structured

implementation, then it may be time to consider optimization, assuming you're not already satisfied with the

performance of the program.

Recall that Jackson's two rules of optimization were "Don't do it," and "(for experts only). Don't do it yet." He

could have added one more: measure performance before and after each attempted optimization. You

may be surprised by what you find. Often, attempted optimizations have no measurable effect on

performance; sometimes, they make it worse. The main reason is that it's difficult to guess where your

program is spending its time. The part of the program that you think is slow may not be at fault, in which case

you'd be wasting your time trying to optimize it. Common wisdom says that programs spend 80 percent of

their time in 20 percent of their code.

Profiling tools can help you decide where to focus your optimization efforts. Such tools give you runtime

information, such as roughly how much time each method is consuming and how many times it is invoked. In

addition to focusing your tuning efforts, this can alert you to the need for algorithmic changes. If a quadratic

(or worse) algorithm lurks inside your program, no amount of tuning will fix the problem. You must replace the

algorithm with one that is more efficient. The more code in the system, the more important it is to use a

profiler. It's like looking for a needle in a haystack: the bigger the haystack, the more useful it is to have a

metal detector. The JDK comes with a simple profiler and modern IDEs provide more sophisticated profiling

tools.

The need to measure the effects of attempted optimization is even greater on the Java platform than on more

traditional platforms, because the Java programming language does not have a strong performance model.

The relative costs of the various primitive operations are not well defined. The "semantic gap" between what

the programmer writes and what the CPU executes is far greater than in traditional statically compiled

languages, which makes it very difficult to reliably predict the performance consequences of any optimization.

There are plenty of performance myths floating around that turn out to be half-truths or outright lies.

Not only is Java's performance model ill-defined, but it varies from JVM implementation to JVM

implementation, from release to release, and from processor to processor. If you will be running your

program on multiple JVM implementations or multiple hardware platforms, it is important that you measure the

effects of your optimization on each. Occasionally you may be forced to make trade-offs between

performance on different JVM implementations or hardware platforms.

To summarize, do not strive to write fast programs — strive to write good ones; speed will follow. Do think

about performance issues while you're designing systems and especially while you're designing APIs,

wire-level protocols, and persistent data formats. When you've finished building the system, measure its

performance. If it's fast enough, you're done. If not, locate the source of the problems with the aid of a

profiler, and go to work optimizing the relevant parts of the system. The first step is to examine your choice of

algorithms: no amount of low-level optimization can make up for a poor choice of algorithm. Repeat this

process as necessary, measuring the performance after every change, until you're satisfied.

—Excerpted from Josh Bloch's Effective Java, Second Ed. (Addison-Wesley, 2008).

1 Wulf, W. A Case Against the GOTO. Proceedings of the 25th ACM National Conference 2 (1972): 791–797.

2 Knuth, Donald. Structured Programming with go to Statements. Computing Surveys 6 (1974): 261–301.

3 Jackson, M. A. Principles of Program Design, Academic Press, London, 1975. ISBN: 0123790506.

One of the trickiest problems you'll face when micro-optimizing Android apps is that the "if you will be running your program

on ... multiple hardware platforms" clause above is always true. And it's not even generally the case that you can say

Designing for Performance | Android Developers http://developer.android.com/guide/practices/design/performance.html

3 of 9 9/7/2010 2:13 PM

Page 76: Android Sdk Best Practices

"device X is a factor F faster/slower than device Y". This is especially true if one of the devices is the emulator, or one of

the devices has a JIT. If you want to know how your app performs on a given device, you need to test it on that device.

Drawing conclusions from the emulator is particularly dangerous, as is attempting to compare JIT versus non-JIT

performance: the performance profiles can differ wildly.

Avoid Creating Objects

Object creation is never free. A generational GC with per-thread allocation pools for temporary objects can make allocation

cheaper, but allocating memory is always more expensive than not allocating memory.

If you allocate objects in a user interface loop, you will force a periodic garbage collection, creating little "hiccups" in the

user experience.

Thus, you should avoid creating object instances you don't need to. Some examples of things that can help:

When extracting strings from a set of input data, try to return a substring of the original data, instead of creating a

copy. You will create a new String object, but it will share the char[] with the data.

If you have a method returning a string, and you know that its result will always be appended to a StringBuffer anyway,

change your signature and implementation so that the function does the append directly, instead of creating a

short-lived temporary object.

A somewhat more radical idea is to slice up multidimensional arrays into parallel single one-dimension arrays:

An array of ints is a much better than an array of Integers, but this also generalizes to the fact that two parallel arrays

of ints are also a lot more efficient than an array of (int,int) objects. The same goes for any combination of primitive

types.

If you need to implement a container that stores tuples of (Foo,Bar) objects, try to remember that two parallel Foo[]

and Bar[] arrays are generally much better than a single array of custom (Foo,Bar) objects. (The exception to this, of

course, is when you're designing an API for other code to access; in those cases, it's usually better to trade correct

API design for a small hit in speed. But in your own internal code, you should try and be as efficient as possible.)

Generally speaking, avoid creating short-term temporary objects if you can. Fewer objects created mean less-frequent

garbage collection, which has a direct impact on user experience.

Performance Myths

Previous versions of this document made various misleading claims. We address some of them here.

On devices without a JIT, it is true that invoking methods via a variable with an exact type rather than an interface is slightly

more efficient. (So, for example, it was cheaper to invoke methods on a HashMap map than a Map map, even though in

both cases the map was a HashMap.) It was not the case that this was 2x slower; the actual difference was more like 6%

slower. Furthermore, the JIT makes the two effectively indistinguishable.

On devices without a JIT, caching field accesses is about 20% faster than repeatedly accesssing the field. With a JIT, field

access costs about the same as local access, so this isn't a worthwhile optimization unless you feel it makes your code

easier to read. (This is true of final, static, and static final fields too.)

Prefer Static Over Virtual

If you don't need to access an object's fields, make your method static. Invocations will be about 15%-20% faster. It's also

Designing for Performance | Android Developers http://developer.android.com/guide/practices/design/performance.html

4 of 9 9/7/2010 2:13 PM

Page 77: Android Sdk Best Practices

good practice, because you can tell from the method signature that calling the method can't alter the object's state.

Avoid Internal Getters/Setters

In native languages like C++ it's common practice to use getters (e.g. i = getCount()) instead of accessing the field

directly (i = mCount). This is an excellent habit for C++, because the compiler can usually inline the access, and if you

need to restrict or debug field access you can add the code at any time.

On Android, this is a bad idea. Virtual method calls are expensive, much more so than instance field lookups. It's

reasonable to follow common object-oriented programming practices and have getters and setters in the public interface,

but within a class you should always access fields directly.

Without a JIT, direct field access is about 3x faster than invoking a trivial getter. With the JIT (where direct field access is

as cheap as accessing a local), direct field access is about 7x faster than invoking a trivial getter. This is true in Froyo, but

will improve in the future when the JIT inlines getter methods.

Use Static Final For Constants

Consider the following declaration at the top of a class:

static int intVal = 42;

static String strVal = "Hello, world!";

The compiler generates a class initializer method, called <clinit>, that is executed when the class is first used. The

method stores the value 42 into intVal, and extracts a reference from the classfile string constant table for strVal.

When these values are referenced later on, they are accessed with field lookups.

We can improve matters with the "final" keyword:

static final int intVal = 42;

static final String strVal = "Hello, world!";

The class no longer requires a <clinit> method, because the constants go into static field initializers in the dex file. Code

that refers to intVal will use the integer value 42 directly, and accesses to strVal will use a relatively inexpensive "string

constant" instruction instead of a field lookup. (Note that this optimization only applies to primitive types and String

constants, not arbitrary reference types. Still, it's good practice to declare constants static final whenever possible.)

Use Enhanced For Loop Syntax

The enhanced for loop (also sometimes known as "for-each" loop) can be used for collections that implement the Iterable

interface and for arrays. With collections, an iterator is allocated to make interface calls to hasNext() and next(). With an

ArrayList, a hand-written counted loop is about 3x faster (with or without JIT), but for other collections the enhanced for

loop syntax will be exactly equivalent to explicit iterator usage.

There are several alternatives for iterating through an array:

static class Foo {

int mSplat;

Designing for Performance | Android Developers http://developer.android.com/guide/practices/design/performance.html

5 of 9 9/7/2010 2:13 PM

Page 78: Android Sdk Best Practices

}

Foo[] mArray = ...

public void zero() {

int sum = 0;

for (int i = 0; i < mArray.length; ++i) {

sum += mArray[i].mSplat;

}

}

public void one() {

int sum = 0;

Foo[] localArray = mArray;

int len = localArray.length;

for (int i = 0; i < len; ++i) {

sum += localArray[i].mSplat;

}

}

public void two() {

int sum = 0;

for (Foo a : mArray) {

sum += a.mSplat;

}

}

zero() is slowest, because the JIT can't yet optimize away the cost of getting the array length once for every iteration

through the loop.

one() is faster. It pulls everything out into local variables, avoiding the lookups. Only the array length offers a performance

benefit.

two() is fastest for devices without a JIT, and indistinguishable from one() for devices with a JIT. It uses the enhanced for

loop syntax introduced in version 1.5 of the Java programming language.

To summarize: use the enhanced for loop by default, but consider a hand-written counted loop for performance-critical

ArrayList iteration.

(See also Effective Java item 46.)

Avoid Enums Where You Only Need Ints

Enums are very convenient, but unfortunately can be painful when size and speed matter. For example, this:

public enum Shrubbery { GROUND, CRAWLING, HANGING }

adds 740 bytes to your .dex file compared to the equivalent class with three public static final ints. On first use, the class

initializer invokes the <init> method on objects representing each of the enumerated values. Each object gets its own static

field, and the full set is stored in an array (a static field called "$VALUES"). That's a lot of code and data, just for three

integers. Additionally, this:

Shrubbery shrub = Shrubbery.GROUND;

causes a static field lookup. If "GROUND" were a static final int, the compiler would treat it as a known constant and inline

it.

Designing for Performance | Android Developers http://developer.android.com/guide/practices/design/performance.html

6 of 9 9/7/2010 2:13 PM

Page 79: Android Sdk Best Practices

The flip side, of course, is that with enums you get nicer APIs and some compile-time value checking. So, the usual

trade-off applies: you should by all means use enums for public APIs, but try to avoid them when performance matters.

If you're using Enum.ordinal, that's usually a sign that you should be using ints instead. As a rule of thumb, if an enum

doesn't have a constructor and doesn't define its own methods, and it's used in performance-critical code, you should

consider static final int constants instead.

Use Package Scope with Inner Classes

Consider the following class definition:

public class Foo {

private int mValue;

public void run() {

Inner in = new Inner();

mValue = 27;

in.stuff();

}

private void doStuff(int value) {

System.out.println("Value is " + value);

}

private class Inner {

void stuff() {

Foo.this.doStuff(Foo.this.mValue);

}

}

}

The key things to note here are that we define an inner class (Foo$Inner) that directly accesses a private method and a

private instance field in the outer class. This is legal, and the code prints "Value is 27" as expected.

The problem is that the VM considers direct access to Foo's private members from Foo$Inner to be illegal because Foo

and Foo$Inner are different classes, even though the Java language allows an inner class to access an outer class' private

members. To bridge the gap, the compiler generates a couple of synthetic methods:

/*package*/ static int Foo.access$100(Foo foo) {

return foo.mValue;

}

/*package*/ static void Foo.access$200(Foo foo, int value) {

foo.doStuff(value);

}

The inner-class code calls these static methods whenever it needs to access the "mValue" field or invoke the "doStuff"

method in the outer class. What this means is that the code above really boils down to a case where you're accessing

member fields through accessor methods instead of directly. Earlier we talked about how accessors are slower than direct

field accesses, so this is an example of a certain language idiom resulting in an "invisible" performance hit.

We can avoid this problem by declaring fields and methods accessed by inner classes to have package scope, rather than

private scope. This runs faster and removes the overhead of the generated methods. (Unfortunately it also means the fields

could be accessed directly by other classes in the same package, which runs counter to the standard practice of making all

fields private. Once again, if you're designing a public API you might want to carefully consider using this optimization.)

Designing for Performance | Android Developers http://developer.android.com/guide/practices/design/performance.html

7 of 9 9/7/2010 2:13 PM

Page 80: Android Sdk Best Practices

Use Floating-Point Judiciously

As a rule of thumb, floating-point is about 2x slower than integer on Android devices. This is true on a FPU-less, JIT-less

G1 and a Nexus One with an FPU and the JIT. (Of course, absolute speed difference between those two devices is about

10x for arithmetic operations.)

In speed terms, there's no difference between float and double on the more modern hardware. Space-wise, double is

2x larger. As with desktop machines, assuming space isn't an issue, you should prefer double to float.

Also, even for integers, some chips have hardware multiply but lack hardware divide. In such cases, integer division and

modulus operations are performed in software — something to think about if you're designing a hash table or doing lots of

math.

Know And Use The Libraries

In addition to all the usual reasons to prefer library code over rolling your own, bear in mind that the system is at liberty to

replace calls to library methods with hand-coded assembler, which may be better than the best code the JIT can produce

for the equivalent Java. The typical example here is String.indexOf and friends, which Dalvik replaces with an inlined

intrinsic. Similarly, the System.arraycopy method is about 9x faster than a hand-coded loop on a Nexus One with the

JIT.

(See also Effective Java item 47.)

Use Native Methods Judiciously

Native code isn't necessarily more efficient than Java. For one thing, there's a cost associated with the Java-native

transition, and the JIT can't optimize across these boundaries. If you're allocating native resources (memory on the native

heap, file descriptors, or whatever), it can be significantly more difficult to arrange timely collection of these resources. You

also need to compile your code for each architecture you wish to run on (rather than rely on it having a JIT). You may even

have to compile multiple versions for what you consider the same architecture: native code compiled for the ARM

processor in the G1 can't take full advantage of the ARM in the Nexus One, and code compiled for the ARM in the Nexus

One won't run on the ARM in the G1.

Native code is primarily useful when you have an existing native codebase that you want to port to Android, not for

"speeding up" parts of a Java app.

(See also Effective Java item 54.)

Closing Notes

One last thing: always measure. Before you start optimizing, make sure you have a problem. Make sure you can accurately

measure your existing performance, or you won't be able to measure the benefit of the alternatives you try.

Every claim made in this document is backed up by a benchmark. The source to these benchmarks can be found in the

code.google.com "dalvik" project.

The benchmarks are built with the Caliper microbenchmarking framework for Java. Microbenchmarks are hard to get right,

so Caliper goes out of its way to do the hard work for you, and even detect some cases where you're not measuring what

you think you're measuring (because, say, the VM has managed to optimize all your code away). We highly recommend

you use Caliper to run your own microbenchmarks.

Designing for Performance | Android Developers http://developer.android.com/guide/practices/design/performance.html

8 of 9 9/7/2010 2:13 PM

Page 81: Android Sdk Best Practices

↑ Go to top

Except as noted, this content is licensed under Apache 2.0. For details and restrictions, see the Content License.Android 2.2 r1 - 23 Aug 2010 18:08

Site Terms of Service - Privacy Policy - Brand Guidelines

Designing for Performance | Android Developers http://developer.android.com/guide/practices/design/performance.html

9 of 9 9/7/2010 2:13 PM

Page 82: Android Sdk Best Practices

An ANR dialog displayed to the user.

Designing for Responsiveness

It's possible to write code that wins every performance test in the world, but still sends users in a fiery rage when they try

to use the application. These are the applications that aren't responsive enough — the ones that feel sluggish, hang or

freeze for significant periods, or take too long to process input.

In Android, the system guards against applications that are insufficiently responsive for a period of time by displaying a

dialog to the user, called the Application Not Responding (ANR) dialog. The user can choose to let the application continue,

but the user won't appreciate having to act on this dialog every time he or she uses your application. So it's important to

design responsiveness into your application, so that the system never has cause to display an ANR to the user.

Generally, the system displays an ANR if an application cannot respond to user input. For example, if an application blocks

on some I/O operation (frequently a network access), then the main application thread won't be able to process incoming

user input events. After a time, the system concludes that the application has hung, and displays the ANR to give the user

the option to kill it.

Similarly, if your application spends too much time building an elaborate in-memory structure, or perhaps computing the

next move in a game, the system will conclude that your application has hung. It's always important to make sure these

computations are efficient using the techniques above, but even the most efficient code still takes time to run.

In both of these cases, the fix is usually to create a child thread, and do most of your work there. This keeps the main

thread (which drives the user interface event loop) running, and prevents the system from concluding your code has frozen.

Since such threading usually is accomplished at the class level, you can think of responsiveness as a class problem.

(Compare this with basic performance, which was described above as a method-level concern.)

This document discusses how the Android system determines

whether an application is not responding and provides guidelines

for ensuring that your application is responsive.

This document covers these topics:

What Triggers ANR?

How to Avoid ANR

Reinforcing Responsiveness

What Triggers ANR?

In Android, application responsiveness is monitored by the

Activity Manager and Window Manager system services.

Android will display the ANR dialog for a particular application

when it detects one of the following conditions:

No response to an input event (e.g. key press, screen

touch) within 5 seconds

A BroadcastReceiver hasn't finished executing within 10

seconds

Designing for Responsiveness | Android Developers http://developer.android.com/guide/practices/design/responsiveness.html

1 of 2 9/7/2010 2:13 PM

Page 83: Android Sdk Best Practices

↑ Go to top

How to Avoid ANR

Given the above definition for ANR, let's examine why this can occur in Android applications and how best to structure your

application to avoid ANR.

Android applications normally run entirely on a single (i.e. main) thread. This means that anything your application is doing in

the main thread that takes a long time to complete can trigger the ANR dialog because your application is not giving itself a

chance to handle the input event or Intent broadcast.

Therefore any method that runs in the main thread should do as little work as possible. In particular, Activities should do as

little as possible to set up in key life-cycle methods such as onCreate() and onResume(). Potentially long running

operations such as network or database operations, or computationally expensive calculations such as resizing bitmaps

should be done in a child thread (or in the case of databases operations, via an asynchronous request). However, this does

not mean that your main thread should block while waiting for the child thread to complete — nor should you call

Thread.wait() or Thread.sleep(). Instead of blocking while waiting for a child thread to complete, your main thread

should provide a Handler for child threads to post back to upon completion. Designing your application in this way will

allow your main thread to remain responsive to input and thus avoid ANR dialogs caused by the 5 second input event

timeout. These same practices should be followed for any other threads that display UI, as they are also subject to the

same timeouts.

The specific constraint on IntentReceiver execution time emphasizes what they were meant to do: small, discrete amounts

of work in the background such as saving a setting or registering a Notification. So as with other methods called in the main

thread, applications should avoid potentially long-running operations or calculations in BroadcastReceivers. But instead of

doing intensive tasks via child threads (as the life of a BroadcastReceiver is short), your application should start a Service

if a potentially long running action needs to be taken in response to an Intent broadcast. As a side note, you should also

avoid starting an Activity from an Intent Receiver, as it will spawn a new screen that will steal focus from whatever

application the user is currently has running. If your application has something to show the user in response to an Intent

broadcast, it should do so using the Notification Manager.

Reinforcing Responsiveness

Generally, 100 to 200ms is the threshold beyond which users will perceive lag (or lack of "snappiness," if you will) in an

application. As such, here are some additional tips beyond what you should do to avoid ANR that will help make your

application seem responsive to users.

If your application is doing work in the background in response to user input, show that progress is being made

(ProgressBar and ProgressDialog are useful for this).

For games specifically, do calculations for moves in a child thread.

If your application has a time-consuming initial setup phase, consider showing a splash screen or rendering the main

view as quickly as possible and filling in the information asynchronously. In either case, you should indicate somehow

that progress is being made, lest the user perceive that the application is frozen.

Except as noted, this content is licensed under Apache 2.0. For details and restrictions, see the Content License.

Android 2.2 r1 - 23 Aug 2010 18:08

Site Terms of Service - Privacy Policy - Brand Guidelines

Designing for Responsiveness | Android Developers http://developer.android.com/guide/practices/design/responsiveness.html

2 of 2 9/7/2010 2:13 PM

Page 84: Android Sdk Best Practices

Designing for Seamlessness

Even if your application is fast and responsive, certain design decisions can still cause problems for users — because of

unplanned interactions with other applications or dialogs, inadvertent loss of data, unintended blocking, and so on. To avoid

these problems, it helps to understand the context in which your applications run and the system interactions that can affect

your application. In short, you should strive to develop an application that interacts seamlessly with the system and with

other applications.

A common seamlessness problem is when an application's background process — for example, a service or broadcast

receiver — pops up a dialog in response to some event. This may seem like harmless behavior, especially when you are

building and testing your application in isolation, on the emulator. However, when your application is run on an actual device,

your application may not have user focus at the time your background process displays the dialog. So it could end up that

your application would display it's dialog behind the active application, or it could take focus from the current application and

display the dialog in front of whatever the user was doing (such as dialing a phone call, for example). That behavior would

not work for your application or for the user.

To avoid these problems, your application should use the proper system facility for notifying the user — the

Notification classes. Using notifications, your application can signal the user that an event has taken place, by

displaying an icon in the status bar rather than taking focus and interrupting the user.

Another example of a seamlessness problem is when an activity inadvertently loses state or user data because it doesn't

correctly implement the onPause() and other lifecycle methods. Or, if your application exposes data intended to be used by

other applications, you should expose it via a ContentProvider, rather than (for example) doing so through a world-readable

raw file or database.

What those examples have in common is that they involve cooperating nicely with the system and other applications. The

Android system is designed to treat applications as a sort of federation of loosely-coupled components, rather than chunks

of black-box code. This allows you as the developer to view the entire system as just an even-larger federation of these

components. This benefits you by allowing you to integrate cleanly and seamlessly with other applications, and so you

should design your own code to return the favor.

This document discusses common seamlessness problems and how to avoid them. It covers these topics:

Don't Drop Data

Don't Expose Raw Data

Don't Interrupt the User

Got a Lot to Do? Do it in a Thread

Don't Overload a Single Activity Screen

Extend System Themes

Design Your UI to Work with Multiple Screen Resolutions

Assume the Network is Slow

Don't Assume Touchscreen or Keyboard

Do Conserve the Device Battery

Don't Drop Data

Designing for Seamlessness | Android Developers http://developer.android.com/guide/practices/design/seamlessness.html

1 of 4 9/7/2010 2:14 PM

Page 85: Android Sdk Best Practices

Always keep in mind that Android is a mobile platform. It may seem obvious to say it, but it's important to remember that

another Activity (such as the "Incoming Phone Call" app) can pop up over your own Activity at any moment. This will fire the

onSaveInstanceState() and onPause() methods, and will likely result in your application being killed.

If the user was editing data in your application when the other Activity appeared, your application will likely lose that data

when your application is killed. Unless, of course, you save the work in progress first. The "Android Way" is to do just that:

Android applications that accept or edit input should override the onSaveInstanceState() method and save their state in

some appropriate fashion. When the user revisits the application, she should be able to retrieve her data.

A classic example of a good use of this behavior is a mail application. If the user was composing an email when another

Activity started up, the application should save the in-process email as a draft.

Don't Expose Raw Data

If you wouldn't walk down the street in your underwear, neither should your data. While it's possible to expose certain kinds

of application to the world to read, this is usually not the best idea. Exposing raw data requires other applications to

understand your data format; if you change that format, you'll break any other applications that aren't similarly updated.

The "Android Way" is to create a ContentProvider to expose your data to other applications via a clean, well-thought-out,

and maintainable API. Using a ContentProvider is much like inserting a Java language interface to split up and

componentize two tightly-coupled pieces of code. This means you'll be able to modify the internal format of your data

without changing the interface exposed by the ContentProvider, and this without affecting other applications.

Don't Interrupt the User

If the user is running an application (such as the Phone application during a call) it's a pretty safe bet he did it on purpose.

That's why you should avoid spawning activities except in direct response to user input from the current Activity.

That is, don't call startActivity() from BroadcastReceivers or Services running in the background. Doing so will interrupt

whatever application is currently running, and result in an annoyed user. Perhaps even worse, your Activity may become a

"keystroke bandit" and receive some of the input the user was in the middle of providing to the previous Activity. Depending

on what your application does, this could be bad news.

Instead of spawning Activity UIs directly from the background, you should instead use the NotificationManager to set

Notifications. These will appear in the status bar, and the user can then click on them at his leisure, to see what your

application has to show him.

(Note that all this doesn't apply to cases where your own Activity is already in the foreground: in that case, the user expects

to see your next Activity in response to input.)

Got a Lot to Do? Do it in a Thread

If your application needs to perform some expensive or long-running computation, you should probably move it to a thread.

This will prevent the dreaded "Application Not Responding" dialog from being displayed to the user, with the ultimate result

being the fiery demise of your application.

By default, all code in an Activity as well as all its Views run in the same thread. This is the same thread that also handles

UI events. For example, when the user presses a key, a key-down event is added to the Activity's main thread's queue.

The event handler system needs to dequeue and handle that event quickly; if it doesn't, the system concludes after a few

seconds that the application is hung and offers to kill it for the user.

Designing for Seamlessness | Android Developers http://developer.android.com/guide/practices/design/seamlessness.html

2 of 4 9/7/2010 2:14 PM

Page 86: Android Sdk Best Practices

If you have long-running code, running it inline in your Activity will run it on the event handler thread, effectively blocking the

event handler. This will delay input processing, and result in the ANR dialogs. To avoid this, move your computations to a

thread. This Design for Responsiveness document discusses how to do that..

Don't Overload a Single Activity Screen

Any application worth using will probably have several different screens. When designing the screens of your UI, be sure to

make use of multiple Activity object instances.

Depending on your development background, you may interpret an Activity as similar to something like a Java Applet, in

that it is the entry point for your application. However, that's not quite accurate: where an Applet subclass is the single entry

point for a Java Applet, an Activity should be thought of as one of potentially several entry points to your application. The

only difference between your "main" Activity and any others you might have is that the "main" one just happens to be the

only one that expressed an interest in the "android.intent.action.MAIN" action in your AndroidManifest..xml file.

So, when designing your application, think of your application as a federation of Activity objects. This will make your code a

lot more maintainable in the long run, and as a nice side effect also plays nicely with Android's application history and

"backstack" model.

Extend System Themes

When it comes to the look-and-feel of the user interface, it's important to blend in nicely. Users are jarred by applications

which contrast with the user interface they've come to expect. When designing your UIs, you should try and avoid rolling

your own as much as possible. Instead, use a Theme. You can override or extend those parts of the theme that you need

to, but at least you're starting from the same UI base as all the other applications. For all the details, read Applying Styles

and Themes.

Design Your UI to Work with Multiple Screen Resolutions

Different Android-powered devices will support different screen resolutions. Some will even be able to change resolutions

on the fly, such as by switching to landscape mode. It's important to make sure your layouts and drawables are flexible

enough to display properly on a variety of device screens.

Fortunately, this is very easy to do. In brief, what you must do is provide different versions of your artwork (if you use any)

for the key resolutions, and then design your layout to accommodate various dimensions. (For example, avoid using

hard-coded positions and instead use relative layouts.) If you do that much, the system handles the rest, and your

application looks great on any device.

Assume the Network is Slow

Android devices will come with a variety of network-connectivity options. All will have some data-access provision, though

some will be faster than others. The lowest common denominator, however, is GPRS, the non-3G data service for GSM

networks. Even 3G-capable devices will spend lots of time on non-3G networks, so slow networks will remain a reality for

quite a long time to come.

That's why you should always code your applications to minimize network accesses and bandwidth. You can't assume the

network is fast, so you should always plan for it to be slow. If your users happen to be on faster networks, then that's great

— their experience will only improve. You want to avoid the inverse case though: applications that are usable some of the

Designing for Seamlessness | Android Developers http://developer.android.com/guide/practices/design/seamlessness.html

3 of 4 9/7/2010 2:14 PM

Page 87: Android Sdk Best Practices

↑ Go to top

time, but frustratingly slow the rest based on where the user is at any given moment are likely to be unpopular.

One potential gotcha here is that it's very easy to fall into this trap if you're using the emulator, since the emulator uses your

desktop computer's network connection. That's almost guaranteed to be much faster than a cell network, so you'll want to

change the settings on the emulator that simulate slower network speeds. You can do this in Eclipse, in the "Emulator

Settings" tab of your launch configuration or via a command-line option when starting the emulator.

Don't Assume Touchscreen or Keyboard

Android will support a variety of handset form-factors. That's a fancy way of saying that some Android devices will have full

"QWERTY" keyboards, while others will have 40-key, 12-key, or even other key configurations. Similarly, some devices will

have touch-screens, but many won't.

When building your applications, keep that in mind. Don't make assumptions about specific keyboard layouts -- unless, of

course, you're really interested in restricting your application so that it can only be used on those devices.

Do Conserve the Device Battery

A mobile device isn't very mobile if it's constantly plugged into the wall. Mobile devices are battery-powered, and the longer

we can make that battery last on a charge, the happier everyone is — especially the user. Two of the biggest consumers

of battery power are the processor, and the radio; that's why it's important to write your applications to do as little work as

possible, and use the network as infrequently as possible.

Minimizing the amount of processor time your application uses really comes down to writing efficient code. To minimize the

power drain from using the radio, be sure to handle error conditions gracefully, and only fetch what you need. For example,

don't constantly retry a network operation if one failed. If it failed once, it's likely because the user has no reception, so it's

probably going to fail again if you try right away; all you'll do is waste battery power.

Users are pretty smart: if your program is power-hungry, you can count on them noticing. The only thing you can be sure of

at that point is that your program won't stay installed very long.

Except as noted, this content is licensed under Apache 2.0. For details and restrictions, see the Content License.Android 2.2 r1 - 23 Aug 2010 18:08

Site Terms of Service - Privacy Policy - Brand Guidelines

Designing for Seamlessness | Android Developers http://developer.android.com/guide/practices/design/seamlessness.html

4 of 4 9/7/2010 2:14 PM