Documenti di Didattica
Documenti di Professioni
Documenti di Cultura
Page 1 of 3
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.
See also
Market Filters Providing Alternative Resources Supporting Multiple Screens <supports-screens> <uses-configuration> <uses-feature> <uses-library> <uses-permission> <uses-sdk>
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 cant run your app will never see it in the Android Market, and will not get in trouble by downloading it. This page explains how you can control which devices have access to your apps, and how to prepare your apps to make sure they reach the right audience.
file://V:\android-sdk-windows\docs\guide\practices\compatibility.html
9/7/2010
Page 2 of 3
web developers get better fine-grained control. Thats the same approach Android uses: since its impossible to keep up with all the Android devices being released, you instead use the fine-grained controls Android provides.
Filtering on Android Market Android Market filters the applications that are visible to users, so that users can see and download only those applications that are compatible with their devices. 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.
When you write your application, you specify which features your app requires by listing their feature IDs in <usesfeature> 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 wont be shown to devices that dont support Live Wallpapers. This puts you in total control of your app because you dont have to declare these features. Consider an example involving cameras. If youre building a really impressive next-generation augmented-reality app, your app wont function at all without a camera. However, if youre building a shopping app that only uses the camera for barcode scanning, users without cameras might still find it useful even if they cant scan barcodes. While both apps need to acquire the permission to access the camera, only the first app needs to state that it requires a camera. (The shopping app can simply check at runtime and disable the camera-related features if theres no camera present.) 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.
file://V:\android-sdk-windows\docs\guide\practices\compatibility.html
9/7/2010
Page 3 of 3
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
Theres one additional quirk that we havent yet addressed: protecting apps from changes made to future versions of Android. If the Android platform introduces a new feature or changes how existing features are handled, what happens to existing apps that were written without any knowledge of the new behavior? Simply put, Android commits to not making existing apps available to devices where they wont work properly, even when the platform changes. The best way to explain this is through examples, so here are two: 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 doesnt strictly need it, you can explicitly state that you dont require it; but unless you do that, your app wont be shown to devices without microphones. In other words, whenever Android introduces new features or changes existing ones, we will always take steps to protect existing applications so that they dont end up being available to devices where they wont work.
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. Weve built in tools to the SDK and set up policies and requirements to ensure that developers remain in control of their apps, today and in the future. With the information you just read, and the resources listed in the sidebar of this document, you can publish your app with the confidence that only users who can run it will see it.
Except as noted, this content is licensed under Apache 2.0. For details and restrictions, see the Content License. Android 2.2 r1 - 14 May 2010 15:20 Site Terms of Service - Privacy Policy - Brand Guidelines
Go to top
file://V:\android-sdk-windows\docs\guide\practices\compatibility.html
9/7/2010
Page 1 of 17
In this document
Overview 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
file://V:\android-sdk-windows\docs\guide\practices\screens_support.html
9/7/2010
Page 2 of 17
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. Resolution The 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. Density Based 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 densityindependent 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.
file://V:\android-sdk-windows\docs\guide\practices\screens_support.html
9/7/2010
Page 3 of 17
Large screen
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.
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: 1. Pre-scaling of resources (such as image assets)
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
file://V:\android-sdk-windows\docs\guide\practices\screens_support.html
9/7/2010
Page 4 of 17
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. 2. Auto-scaling of pixel dimensions and coordinates 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 lowerdensity screen, coordinates are scaled down. For more information, see the android:anyDensity attribute in Manifest attributes for screens support. 3. Compatibility-mode display on larger screen-sizes 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. Publishing to Small Screen Devices To 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.
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.
file://V:\android-sdk-windows\docs\guide\practices\screens_support.html
9/7/2010
Page 5 of 17
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 densityrelated 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.
file://V:\android-sdk-windows\docs\guide\practices\screens_support.html
9/7/2010
Page 6 of 17
android:normalScreens android:largeScreens
android:anyDensity
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
file://V:\android-sdk-windows\docs\guide\practices\screens_support.html
9/7/2010
Page 7 of 17
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>
file://V:\android-sdk-windows\docs\guide\practices\screens_support.html
9/7/2010
Page 8 of 17
Description Resources for small screens, such as QVGA low density. Resources for normal (baseline configuration) screens, such as T-Mobile G1/HTC Magic screen size, or equivalent. Resources for large screens. Typical example is a tablet like device. Low-density resources, for 100 to 140 dpi screens. Medium-density resources for 140 to 180 dpi screens. High-density resources for 190 to 250 dpi screens. Density-independent resources. The platform does not auto-scale resources tagged with this qualifier, regardless of the current screen's density. 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. Resources for use only on screens that have an aspect ratio that is similar to the baseline screen configuration. 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).
Density
Aspect ratio
long
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 TMobile 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 res/layout-small/my_layout.xml res/layout-large/my_layout.xml res/layout-large-land/my_layout.xml res/drawable-ldpi/my_icon.png res/drawable-mdpi/dpi/my_icon.png res/drawable-hdpi/my_icon.png res/drawable-nodpi/composite.xml // // // // layout layout layout layout for for for for normal screen size small screen size large screen size large screen size in landscape mode
// icon image for low density // icon for medium density // icon image for high density // density independent resource
For more information about how to use resource qualifiers or how the platform selects them, please read Alternative Resources.
file://V:\android-sdk-windows\docs\guide\practices\screens_support.html
9/7/2010
Page 9 of 17
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.
file://V:\android-sdk-windows\docs\guide\practices\screens_support.html
9/7/2010
Page 10 of 17
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.
//
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.
file://V:\android-sdk-windows\docs\guide\practices\screens_support.html
9/7/2010
Page 11 of 17
file://V:\android-sdk-windows\docs\guide\practices\screens_support.html
9/7/2010
Page 12 of 17
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: 1. 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. 2. 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. 3. 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. 4. 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. 5. 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. 6. 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. 7. 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. 8. 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. 9. For resource-related issues, you can try resolving them by: 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. 10. 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. 11. 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. 12. Continue testing and debugging until your application performs as expected on all of the platforms and screen sizes your application will support. 13. 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.
file://V:\android-sdk-windows\docs\guide\practices\screens_support.html
9/7/2010
Page 13 of 17
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.
file://V:\android-sdk-windows\docs\guide\practices\screens_support.html
9/7/2010
Page 14 of 17
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 sizedensity 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.
file://V:\android-sdk-windows\docs\guide\practices\screens_support.html
9/7/2010
Page 15 of 17
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.
Figure 4. Resolution and density options that you can use, when creating an AVD using the AVD Manager.
In the android tool, follow these steps to create an AVD with a custom resolution or density: 1. 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: android create avd -n <name> -t <targetID> --skin WVGA800 2. 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. 3. 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. 4. Set any other hardware options and complete the AVD creation. 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.
file://V:\android-sdk-windows\docs\guide\practices\screens_support.html
9/7/2010
Page 16 of 17
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 ] SVGA, large size, high density [ emulator -skin 800x600 -dpi-device 240]
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:
file://V:\android-sdk-windows\docs\guide\practices\screens_support.html
9/7/2010
Page 17 of 17
Go to top
Except as noted, this content is licensed under Apache 2.0. For details and restrictions, see the Content License. Android 2.2 r1 - 14 May 2010 15:20 Site Terms of Service - Privacy Policy - Brand Guidelines
file://V:\android-sdk-windows\docs\guide\practices\screens_support.html
9/7/2010
Page 1 of 1
Go to top
file://V:\android-sdk-windows\docs\guide\practices\ui_guidelines\index.html
9/7/2010
Page 1 of 24
In this document
Launcher 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 also
Supporting Multiple Screens Android Icon Templates Pack, v2.0
Older versions
Icon Design Guidelines, Android 1.0 Android Icon Templates Pack, v1.0
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: 1. Design the icons for the baseline density first (see Table 1 for the actual pixel dimensions at which to design the icons). 2. 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. 3. Test and adjust your baseline icons as needed. 4. When you are satisfied with the icons you've developed at the baseline density, create scaled copies for the other densities.
file://V:\android-sdk-windows\docs\guide\practices\ui_guidelines\icon_design.html
9/7/2010
Page 2 of 24
Scale the baseline icons up 150% to create the high-density assets. Scale the baseline icons down 75% to create the low-density assets. 5. Place the icons in density-specific resource directories in your application. For example: 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. 6. Test and adjust the high- and low-density icons if needed 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 Generalized Screen Densities Low density screen (ldpi) Medium density screen (mdpi)
48 x 48 px 48 x 48 px 32 x 32 px 32 x 32 px 32 x 32 px 32 x 32 px
36 x 36 px 36 x 36 px 24 x 24 px 24 x 24 px 24 x 24 px 24 x 24 px
Launcher Icon
A Launcher icon is a graphic that represents your application on the devices 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:
file://V:\android-sdk-windows\docs\guide\practices\ui_guidelines\icon_design.html
9/7/2010
Page 3 of 24
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. Figure 1. Illustration of Launcher icon style.
file://V:\android-sdk-windows\docs\guide\practices\ui_guidelines\icon_design.html
9/7/2010
Page 4 of 24
Figure 2. Side-by-side examples of "do's and don'ts" for Android launcher icons.
Figure 3. Example materials that you can use to create your icons.
file://V:\android-sdk-windows\docs\guide\practices\ui_guidelines\icon_design.html
9/7/2010
Page 5 of 24
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.
file://V:\android-sdk-windows\docs\guide\practices\ui_guidelines\icon_design.html
9/7/2010
Page 6 of 24
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 mediumdensity (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.
file://V:\android-sdk-windows\docs\guide\practices\ui_guidelines\icon_design.html
9/7/2010
Page 7 of 24
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.
file://V:\android-sdk-windows\docs\guide\practices\ui_guidelines\icon_design.html
9/7/2010
Page 8 of 24
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 file. 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.
file://V:\android-sdk-windows\docs\guide\practices\ui_guidelines\icon_design.html
9/7/2010
Page 9 of 24
Figure 8. Light, effects, and shadows for menu icons. 1. Front part: Use fill gradient from primary color palette 2. Inner black | 20 % opacity shadow: 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.
Step by step
1. Create the basic shapes using a tool like Adobe Illustrator. 2. 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. 3. Add the effects seen as described in Figure 8. 4. Export the icon at 48x48 as a PNG file with transparency enabled.
Fill gradient 1: r 163 | g 163 | b 163 2: r 120 | g 120 | b 120 Used as color fill. Black r0|g0|b0 Used for inner shadow and bevel shadow.
file://V:\android-sdk-windows\docs\guide\practices\ui_guidelines\icon_design.html
9/7/2010
Page 10 of 24
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 file. 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.
file://V:\android-sdk-windows\docs\guide\practices\ui_guidelines\icon_design.html
9/7/2010
Page 11 of 24
Figure 10. Light, effects, and shadows for status bar icons. 1. Front part: Use fill gradient from primary color palette 2. Inner depth 100% | direction down bevel: size 0px | angle 90 | altitude 30 highlight white 75% opacity shadow black 75% opacity 3. Detail: white 4. Disabled grey gradient from palette detail: + 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 r0|g0|b0 Used for bevel shadow.
Step by step
1. 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. 2. Add rounded corners as specified in Figure 9. 3. Add light, effects, and shadows as specified in Figure 10. 4. Export the icon at 25x25 as a PNG file with transparency enabled.
file://V:\android-sdk-windows\docs\guide\practices\ui_guidelines\icon_design.html
9/7/2010
Page 12 of 24
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 transparent 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.
file://V:\android-sdk-windows\docs\guide\practices\ui_guidelines\icon_design.html
9/7/2010
Page 13 of 24
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 black | 10 % opacity | angle 90 shadow: distance 2px | size 2px 3. Inner depth 1% | direction down | size 0px bevel: | angle 90 | altitude 10 highlight white 70% opacity shadow black 25% opacity
Step by step
1. Create the basic shapes using a tool like Adobe Illustrator. 2. Import the shape to a tool like Adobe Photoshop and scale to fit an image of 32x32 px on a transparent background. 3. Add the effects seen in Figure 13 for the unselected state filter. 4. Export the icon at 32x32 as a PNG file with transparency enabled.
file://V:\android-sdk-windows\docs\guide\practices\ui_guidelines\icon_design.html
9/7/2010
Page 14 of 24
Figure 14. Light, effects, and shadows for selected tab icons. 1. Front part: 2. Inner shadow: Use fill gradient from color palette. 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
1. Create the basic shape using a tool like Adobe Illustrator. 2. Import the shape into a tool like Adobe Photoshop and scale to fit a 32x32 px artboard with a transparent background. 3. Add the effects seen in Figure 14 for the selected state filter. 4. Export the icon at 32x32 as a PNG file with transparency enabled.
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.
file://V:\android-sdk-windows\docs\guide\practices\ui_guidelines\icon_design.html
9/7/2010
Page 15 of 24
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 file. 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.
file://V:\android-sdk-windows\docs\guide\practices\ui_guidelines\icon_design.html
9/7/2010
Page 16 of 24
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% black | 25% opacity | angle -90 | distance 1px | size 0px
2. Inner shadow:
Step by step
1. Create the basic shapes using a tool like Adobe Illustrator. 2. Import the shape into a tool like Adobe Photoshop and scale to fit an image of 32x32 px on a transparent background. 3. Add the effects seen in Figure 16 for the proper filter. 4. Export the icon at 32x32 as a PNG file with transparency enabled.
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.
file://V:\android-sdk-windows\docs\guide\practices\ui_guidelines\icon_design.html
9/7/2010
Page 17 of 24
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 file. 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.
file://V:\android-sdk-windows\docs\guide\practices\ui_guidelines\icon_design.html
9/7/2010
Page 18 of 24
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 black | standard system color These icons are displayed in list views only.
2.
Background:
Note: The list view icon sits on 32x32 px artboard in Photoshop, without a safeframe.
Step by step
1. Add the effects seen in Figure 18 for the proper filter. 2. Export the icon at 32x32 as a PNG file with transparency enabled. 3. Create the basic shapes using a tool like Adobe Illustrator. 4. Import the shape into a tool like Adobe Photoshop and scale to fit an image of 32x32 px on a transparent background.
file://V:\android-sdk-windows\docs\guide\practices\ui_guidelines\icon_design.html
9/7/2010
Page 19 of 24
Asset Type Icons Launcher icons Menu icons Status bar icons Tab icons Dialog icons
Note that you are not required to use a shared prefix of any type doing so is for your convenience only.
file://V:\android-sdk-windows\docs\guide\practices\ui_guidelines\icon_design.html
9/7/2010
Page 20 of 24
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.
When scaling a nine-patch image, crop tick marks before 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: 1. Under the Select menu choose All. 2. Under the Edit menu choose Copy Merged. 3. Under the File menu choose New and then click OK on the new panel. 4. Under the Edit choose Paste. 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: 1. Under the Image menu, choose the Canvas Size command.
file://V:\android-sdk-windows\docs\guide\practices\ui_guidelines\icon_design.html
9/7/2010
Page 21 of 24
2. On the Canvas Size panel, subtract 2 pixels from the Width and Height values. 3. Set the Anchor to "Center." 4. Click OK 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: 1. Under the Image menu, choose the Canvas Size command. 2. On the Canvas Size panel, add 2 pixels to the Width and Height values. 3. Set the Anchor to "Center." 4. Click OK. 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.
Make sure that corresponding assets for different densities 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.
file://V:\android-sdk-windows\docs\guide\practices\ui_guidelines\icon_design.html
9/7/2010
Page 22 of 24
Icon appendix
file://V:\android-sdk-windows\docs\guide\practices\ui_guidelines\icon_design.html
9/7/2010
Page 23 of 24
Add
Call
Camera
Compass
Delete
Directions
Edit
Gallery
Help
Info / details
Map mode
My Location
More
Preferences
Rotate
Save
Send
Search
Share
Upload
View
Zoom
file://V:\android-sdk-windows\docs\guide\practices\ui_guidelines\icon_design.html
9/7/2010
Page 24 of 24
of those icons or drawables in your application resources, then reference the local copy from your application code. In that way, you can maintain control over the appearance of your icons, even if the system's copy changes. Note that the list below is not intended to be complete.
Bluetooth Email
IM
Voicemail Warning
Call
Call forward
Call on hold
Missed call
Go to top
Except as noted, this content is licensed under Apache 2.0. For details and restrictions, see the Content License. Android 2.2 r1 - 14 May 2010 15:20 Site Terms of Service - Privacy Policy - Brand Guidelines
file://V:\android-sdk-windows\docs\guide\practices\ui_guidelines\icon_design.html
9/7/2010
http://developer.android.com/guide/practices/ui_guidelines/widget_design...
Widget design quickview Widgets have six standard sizes on the Home screen Widgets have standards for size, frames, shadows, and file format, which you can copy A few tricks make it easier to design widgets that 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
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.
1 of 7
9/7/2010 2:12 PM
http://developer.android.com/guide/practices/ui_guidelines/widget_design...
Designing a widget
1. Select a bounding box size for your widget. 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). 2. Select a matching frame. 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. 3. Apply standard shadow effect to your graphics. Again, you don't have to use this effect, but Standard widget shadows shows the Photoshop settings used for standard widgets. 4. If your widget includes buttons, draw them in three states (default, pressed, and selected). 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
2 of 7
9/7/2010 2:12 PM
http://developer.android.com/guide/practices/ui_guidelines/widget_design...
button effects.
5. Finish drawing your artwork and then scale and align it to fit. 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. 6. Save your widget with the correct graphics file settings. Windows graphics file format describes the correct settings for your widget graphics files.
In landscape orientation, each cell is 106 pixels wide by 74 pixels tall. The three supported widget sizes in landscape orientation are: Cells 4x1 3x3 2x2 Pixels 424 x 74 318 x 222 212 x 148
3 of 7
9/7/2010 2:12 PM
http://developer.android.com/guide/practices/ui_guidelines/widget_design...
4x1_Widget_Frame_Portrait.psd
3x3_Widget_Frame_Portrait.psd
2x2_Widget_Frame_Portrait.psd
4 of 7
9/7/2010 2:12 PM
http://developer.android.com/guide/practices/ui_guidelines/widget_design...
4x1_Widget_Frame_Landscape.psd
3x3_Widget_Frame_Landscape.psd
2x2_Widget_Frame_Landscape.psd
5 of 7
9/7/2010 2:12 PM
http://developer.android.com/guide/practices/ui_guidelines/widget_design...
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.
6 of 7
9/7/2010 2:12 PM
http://developer.android.com/guide/practices/ui_guidelines/widget_design...
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
Go to top
7 of 7
9/7/2010 2:12 PM
http://developer.android.com/guide/practices/ui_guidelines/activity_task...
Activity and task design quickview Activities are the main building blocks of Android applications. In addition to writing your own activities, you are free to re-use activities from many other applications through intents. You can enable activities in your application to be started from intents in other applications. In nearly all cases, the activity stack just works as 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 that won'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
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.
1 of 13
9/7/2010 2:12 PM
http://developer.android.com/guide/practices/ui_guidelines/activity_task...
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
2 of 13
9/7/2010 2:12 PM
http://developer.android.com/guide/practices/ui_guidelines/activity_task...
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.
3 of 13
9/7/2010 2:12 PM
http://developer.android.com/guide/practices/ui_guidelines/activity_task...
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
4 of 13
9/7/2010 2:12 PM
http://developer.android.com/guide/practices/ui_guidelines/activity_task...
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.
5 of 13
9/7/2010 2:12 PM
http://developer.android.com/guide/practices/ui_guidelines/activity_task...
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.
6 of 13
9/7/2010 2:12 PM
http://developer.android.com/guide/practices/ui_guidelines/activity_task...
The application launcher at Home has launched "View Map" and "Day View" activities into separate tasks, hence the system is multitasking running multiple tasks.
Intents
When the user takes an action on some data, such as touching a mailto:info@example.com 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).
7 of 13
9/7/2010 2:12 PM
http://developer.android.com/guide/practices/ui_guidelines/activity_task...
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.
8 of 13
9/7/2010 2:12 PM
http://developer.android.com/guide/practices/ui_guidelines/activity_task...
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. 2. 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.
3. 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.
9 of 13
9/7/2010 2:12 PM
http://developer.android.com/guide/practices/ui_guidelines/activity_task...
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
10 of 13
9/7/2010 2:12 PM
http://developer.android.com/guide/practices/ui_guidelines/activity_task...
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.
11 of 13
9/7/2010 2:12 PM
http://developer.android.com/guide/practices/ui_guidelines/activity_task...
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. 1. User is creating a new event in Calendar. They realize they need to copy part of an email message into this event 2. The user chooses Home > Gmail 3. While in Gmail, they receive a notification from Calendar for an upcoming meeting 4. So they choose that notification, which takes them to a dedicated Calendar activity that displays brief details of the upcoming meeting 5. The user chooses this short notice to view further details 6. 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 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 finergrained 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
12 of 13
9/7/2010 2:12 PM
http://developer.android.com/guide/practices/ui_guidelines/activity_task...
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
Go to top
13 of 13
9/7/2010 2:12 PM
http://developer.android.com/guide/practices/ui_guidelines/menu_design.html
Menu design quickview An Options menu is for any commands that are global to the current activity. A Context menu is for any commands that apply to the current selection. Place the most frequently used operations first. 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 to by 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 most intuitive 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
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
1 of 7
9/7/2010 2:13 PM
http://developer.android.com/guide/practices/ui_guidelines/menu_design.html
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.
2 of 7
9/7/2010 2:13 PM
http://developer.android.com/guide/practices/ui_guidelines/menu_design.html
3 of 7
9/7/2010 2:13 PM
http://developer.android.com/guide/practices/ui_guidelines/menu_design.html
4 of 7
9/7/2010 2:13 PM
http://developer.android.com/guide/practices/ui_guidelines/menu_design.html
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.
5 of 7
9/7/2010 2:13 PM
http://developer.android.com/guide/practices/ui_guidelines/menu_design.html
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"
6 of 7
9/7/2010 2:13 PM
http://developer.android.com/guide/practices/ui_guidelines/menu_design.html
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
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
Go to top
7 of 7
9/7/2010 2:13 PM
http://developer.android.com/guide/practices/design/performance.html
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
1 of 9
9/7/2010 2:13 PM
http://developer.android.com/guide/practices/design/performance.html
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 reasonincluding 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
2 of 9
9/7/2010 2:13 PM
http://developer.android.com/guide/practices/design/performance.html
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 2 3
Wulf, W. A Case Against the GOTO. Proceedings of the 25th ACM National Conference 2 (1972): 791797. Knuth, Donald. Structured Programming with go to Statements. Computing Surveys 6 (1974): 261301. 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
3 of 9
9/7/2010 2:13 PM
http://developer.android.com/guide/practices/design/performance.html
"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.
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.)
4 of 9
9/7/2010 2:13 PM
http://developer.android.com/guide/practices/design/performance.html
good practice, because you can tell from the method signature that calling the method can't alter the object's state.
5 of 9
9/7/2010 2:13 PM
http://developer.android.com/guide/practices/design/performance.html
} 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.)
6 of 9
9/7/2010 2:13 PM
http://developer.android.com/guide/practices/design/performance.html
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.
7 of 9
9/7/2010 2:13 PM
http://developer.android.com/guide/practices/design/performance.html
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.
8 of 9
9/7/2010 2:13 PM
http://developer.android.com/guide/practices/design/performance.html
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
9 of 9
9/7/2010 2:13 PM
http://developer.android.com/guide/practices/design/responsiveness.html
1 of 2
9/7/2010 2:13 PM
http://developer.android.com/guide/practices/design/responsiveness.html
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
Go to top
2 of 2
9/7/2010 2:13 PM
http://developer.android.com/guide/practices/design/seamlessness.html
9/7/2010 2:14 PM
http://developer.android.com/guide/practices/design/seamlessness.html
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.
2 of 4
9/7/2010 2:14 PM
http://developer.android.com/guide/practices/design/seamlessness.html
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..
3 of 4
9/7/2010 2:14 PM
http://developer.android.com/guide/practices/design/seamlessness.html
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.
Go to top
4 of 4
9/7/2010 2:14 PM